Skip to main content

Smart Contracts

Shamwari supports WebAssembly (WASM) smart contracts for extensible blockchain logic.

Contract Model

Smart contracts in Shamwari run in a deterministic WASM runtime with:

  • Sandboxed execution: Isolated memory and resources
  • Gas metering: Computation cost limits
  • Deterministic: Same input always produces same output
  • Stateful: Persistent contract storage on-chain

Writing Contracts

Basic Structure

export function init(context) {
context.set("owner", context.sender());
context.set("balance", 0);
}

export function transfer(context, amount, to) {
let sender = context.sender();
let balance = context.get("balance");

require(balance >= amount, "Insufficient balance");
require(sender !== to, "Cannot transfer to self");

context.sub("balance", amount);
context.set(to, context.get(to) + amount);
}

Available APIs

FunctionDescription
context.sender()Get transaction sender account
context.get(key)Read contract storage
context.set(key, value)Write contract storage
context.add(key, amount)Add to numeric storage
context.sub(key, amount)Subtract from numeric storage
context.require(cond, msg)Conditional abort
context.emit(event, data)Emit contract event

Deployment

# Compile contract
shamwari contract compile my_contract.js

# Deploy to chain
curl -X POST http://localhost:6876/nxt \
-d "requestType=uploadContractFile" \
-d "contractName=MyContract" \
-d "contract=@my_contract.wasm" \
-d "secretPhrase=your_secret_phrase"

Contract References

# Set contract reference (link account to contract)
curl -X POST http://localhost:6876/nxt \
-d "requestType=setContractReference" \
-d "account=NXT-account" \
-d "contract=1234567890123456789" \
-d "secretPhrase=your_secret_phrase"

Verification

# Verify contract integrity
curl "http://localhost:6876/nxt?requestType=verifyContract&contract=1234567890123456789"

Contract Runner Status

# Check contract execution state
curl "http://localhost:6876/nxt?requestType=getContractRunnerStatus"

Best Practices

  1. Minimize Gas: Optimize loops and storage access
  2. Validate Inputs: Always check parameters before use
  3. Handle Errors: Use try/catch for external calls
  4. Event Logging: Emit events for important state changes
  5. Upgrade Path: Design contracts for future upgrades

Limitations

  • Contract size: Maximum 128 KB
  • Execution time: 100 ms timeout
  • Storage: 1 MB per contract
  • Gas per block: Limited by block size
  • uploadContractFile - Deploy contract binary
  • downloadContractFile - Retrieve contract
  • verifyContract - Verify contract integrity
  • setContractReference - Link account to contract
  • getContractReferences - List account contracts
  • getContractRunnerStatus - Check runner state