WASM Contract Deployment
Last updated
Last updated
Magnet runtimes are based on Substrate, incorporate pallet-contracts
, a sandboxed environment used to deploy and execute WebAssembly 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 which require 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 other, so require two steps to deploy a new contract on-chain:
First, upload the Wasm contract on-chain (every contract Wasm code has a code_hash
as an identifier).
Second, instantiate the contract - it will create an address and storage for that contract.
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, that will have one code_hash
& blob
living on-chain, and as many instantiations as are needed, rather than having to upload 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 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 new code. Storage and balances will be preserved.