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
| Function | Description |
|---|---|
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
- Minimize Gas: Optimize loops and storage access
- Validate Inputs: Always check parameters before use
- Handle Errors: Use try/catch for external calls
- Event Logging: Emit events for important state changes
- 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
Related APIs
uploadContractFile- Deploy contract binarydownloadContractFile- Retrieve contractverifyContract- Verify contract integritysetContractReference- Link account to contractgetContractReferences- List account contractsgetContractRunnerStatus- Check runner state