WASM Smart Contract Stack

Smart Contract Runtime Environment

Mandala Chain runtimes are based on Substrate, and both networks incorporate pallet-contracts,a sandboxed environment used to deploy and execute WebAssembly (WASM) smart contracts. Any language that compiles to WASM may be deployed and run on this Wasm Virtual Machine. However, the code should be compatible with the pallet-contracts API.

To avoid unnecessary complexity, and writing boilerplate code, the most appropriate method of building will involve the use of an eDSL specifically targeting pallet-contracts, such as ink! (based on Rust), or ask! (based on AssemblyScript), or possibly others as the ecosystem grows.

After compilation, a WASM blob can then be deployed and stored on-chain.

Execution Engine

Pallet-contracts uses wasmi as a Wasm interpreter to execute WASM smart contract blobs. Although there is a faster JIT interpreter such as wasmtime available in the native runtime, smart contracts are an untrusted environment that requires a higher degree of correctness of interpretation, which makes wasmi a more suitable option.

Two-step Deployment of Contracts

The contract code (WASM blob), and contract address and storage are decoupled from one another, so we require two steps to deploy a new contract on-chain:

  1. First, upload the Wasm contract on-chain (every contract Wasm code has a code_hash as an identifier).

  2. Second, instantiate the contract - it will create an address and storage for that contract.

  3. Anyone can instantiate a contract based on its code_hash.

There are several benefits of decoupling the contract code from the address/storage:

  • To save space on-chain. Since a contract can have several constructors and instantiations, a redeployment will create a new instance based on the same underlying code. Think about standardized tokens, like PSP22 & PSP34, that will have one code_hash & blob living on-chain, and as many instantiations as needed, rather than uploading code with each new instantiation (for example, on Ethereum).

  • To instantiate a new contract using code within an existing smart contract (see the delegator example), code_hash is all that is needed.

  • Some standard contracts, such as (PSP22 and PSP34) will only be uploaded on-chain once, preventing users from having to pay gas costs for uploading new code.

  • Update contract code for an address: replace the contract code at the specified address with a new code (see set_code_hash). Storage and balances will be preserved.

For More Information About pallet-contracts​

Client APIs

The only library available to communicate with smart contracts is Polkadot.js API.

INFO

This API provides application developers the ability to query a node and interact with the Polkadot or Substrate chains using Javascript.

Parity also developed a web application to interact with contracts called contracts-ui.

The Wasm Stack vs. Ethereum

Last updated