var img = document.createElement('img'); img.src = "https://terradocs.matomo.cloud//piwik.php?idsite=1&rec=1&url=https://docs.terra.money" + location.pathname; img.style = "border:0"; img.alt = "tracker"; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(img,s);
Skip to main content

Wasm

The Wasm module implements the execution environment for WebAssembly smart contracts, powered by CosmWasm.

Concepts

Smart contracts

Smart contracts are autonomous agents that can interact with other entities on the Terra blockchain, such as human-owned accounts, validators, and other smart contracts. Each smart contract has:

  • A unique contract address with an account that holds funds.
  • A code ID, where its logic is defined.
  • Its own key-value store, where it can persist and retrieve data.

Contract address

Upon instantiation, each contract is automatically assigned a Terra account address called the contract address. The address is procedurally generated on-chain without an accompanying private and public key pair, and it can be completely determined by the contract's number order of existence. For instance, on two separate Terra networks, the first contract will always be assigned the address terra18vd8fpwxzck93qlwghaj6arh4p7c5n896xzem5, and similarly for the second, third, and so on.

Code ID

On Terra, code upload and contract creation are separate events. A smart contract writer first uploads WASM bytecode onto the blockchain to obtain a code ID, which they then can use to initialize an instance of that contract. This scheme promotes efficient storage because most contracts share the same underlying logic and vary only in their initial configuration. Vetted, high-quality contracts for common use cases like fungible tokens and multisig wallets can be easily reused without the need to upload new code.

Key-value store

Each smart contract is given its own dedicated keyspace in LevelDB, prefixed by the contract address. Contract code is safely sandboxed and can only set and delete new keys and values within its assigned keyspace.

Interaction

You can interact with smart contracts in several ways.

Instantiation

You can instantiate a new smart contract by sending a MsgInstantiateContract. In it, you can:

  • Assign an owner to the contract.
  • Specify code that will be used for the contract via a code ID.
  • Define the initial parameters / configuration through an InitMsg.
  • Provide the new contract's account with some initial funds.
  • Denote whether the contract is migratable (i.e. can change code IDs).

The InitMsg is a JSON message whose expected format is defined in the contract's code. Every contract contains a section that defines how to set up the initial state depending on the provided InitMsg.

Execution

You can execute a smart contract to invoke one of its defined functions by sending a MsgExecuteContract. In it, you can:

  • Specify which function to call with a HandleMsg.
  • Send funds to the contract, which may be expected during execution.

The HandleMsg is a JSON message that contains function call arguments and gets routed to the appropriate handling logic. From there, the contract executes the function's instructions during which the contract's own state can be modified. The contract can only modify outside state, such as state in other contracts or modules, after its own execution has ended, by returning a list of blockchain messages, such as MsgSend and MsgExecuteContract. These messages are appended to the same transaction as the MsgExecuteContract and if any of the messages are invalid, the whole transaction is invalidated.

Migration

If a user is the contract's owner and a contract is instantiated as migratable, they can issue a MsgMigrateContract to reset its code ID to a new one. The migration can be parameterized with a MigrateMsg, a JSON message.

Transfer of ownership

The current owner of the smart contract can reassign a new owner to the contract with MsgUpdateContractOwner.

Query

Contracts can define query functions, or read-only operations meant for data-retrieval. Doing so allows contracts to expose rich, custom data endpoints with JSON responses instead of raw bytes from the low-level key-value store. Because the blockchain state cannot be changed, the node can directly run the query without a transaction.

Users can specify which query function to use alongside any arguments with a JSON QueryMsg. Even though there is no gas fee, the query function's execution is capped by gas determined by metered execution, which is not charged, as a form of spam protection.

Wasmer VM

The actual execution of WASM bytecode is performed by wasmer, which provides a lightweight, sandboxed runtime with metered execution to account for the resource cost of computation.

Gas meter

In addition to the regular gas fees incurred from creating the transaction, Terra also calculates a separate gas when executing smart contract code. This is tracked by the gas meter during the execution of every opcode. The result is then translated back to native Terra gas via a constant multiplier (currently set to 100).

Gas fees

WASM data and event spend gas up to 1 * bytes. Passing the event and data to another contract also spends gas in reply.

Data

CodeInfo


_5
type CodeInfo struct {
_5
CodeID uint64 `json:"code_id"`
_5
CodeHash core.Base64Bytes `json:"code_hash"`
_5
Creator sdk.AccAddress `json:"creator"`
_5
}

ContractInfo


_7
type ContractInfo struct {
_7
Address sdk.AccAddress `json:"address"`
_7
Owner sdk.AccAddress `json:"owner"`
_7
CodeID uint64 `json:"code_id"`
_7
InitMsg core.Base64Bytes `json:"init_msg"`
_7
Migratable bool `json:"migratable"`
_7
}

State

Last Code ID

  • type: uint64

A counter for the last uploaded code ID.

Last Instance ID

  • type: uint64

A counter for the last instantiated contract number.

Code

  • type: map[uint64]CodeInfo

Maps a code ID to CodeInfo entry.

Contract Info

  • type: map[bytes]ContractInfo

Maps contract address to its corresponding ContractInfo.

Contract Store

  • type: map[bytes]KVStore

Maps contract address to its dedicated KVStore.

Message types

MsgStoreCode

Uploads new code to the blockchain and results in a new code ID, if successful. WASMByteCode is accepted as either uncompressed or gzipped binary data encoded as Base64.


_5
type MsgStoreCode struct {
_5
Sender sdk.AccAddress `json:"sender" yaml:"sender"`
_5
// WASMByteCode can be raw or gzip compressed
_5
WASMByteCode core.Base64Bytes `json:"wasm_byte_code" yaml:"wasm_byte_code"`
_5
}

MsgInstantiateContract

Creates a new instance of a smart contract. Initial configuration is provided in the InitMsg, which is a JSON message encoded in Base64. If Migratable is set to true, the owner of the contract is permitted to reset the contract's code ID to a new one.


_12
type MsgInstantiateContract struct {
_12
// Sender is an sender address
_12
Sender string `protobuf:"bytes,1,opt,name=sender,proto3" json:"sender,omitempty" yaml:"sender"`
_12
// Admin is an optional admin address who can migrate the contract
_12
Admin string `protobuf:"bytes,2,opt,name=admin,proto3" json:"admin,omitempty" yaml:"admin"`
_12
// CodeID is the reference to the stored WASM code
_12
CodeID uint64 `protobuf:"varint,3,opt,name=code_id,json=codeId,proto3" json:"code_id,omitempty" yaml:"code_id"`
_12
// InitMsg json encoded message to be passed to the contract on instantiation
_12
InitMsg encoding_json.RawMessage `protobuf:"bytes,4,opt,name=init_msg,json=initMsg,proto3,casttype=encoding/json.RawMessage" json:"init_msg,omitempty" yaml:"init_msg"`
_12
// InitCoins that are transferred to the contract on execution
_12
InitCoins github_com_cosmos_cosmos_sdk_types.Coins `protobuf:"bytes,5,rep,name=init_coins,json=initCoins,proto3,castrepeated=github.com/cosmos/cosmos-sdk/types.Coins" json:"init_coins" yaml:"init_coins"`
_12
}

MsgExecuteContract

Invokes a function defined within the smart contract. Function and parameters are encoded in ExecuteMsg, which is a JSON message encoded in Base64.


_6
type MsgExecuteContract struct {
_6
Sender sdk.AccAddress `json:"sender" yaml:"sender"`
_6
Contract sdk.AccAddress `json:"contract" yaml:"contract"`
_6
ExecuteMsg core.Base64Bytes `json:"execute_msg" yaml:"execute_msg"`
_6
Coins sdk.Coins `json:"coins" yaml:"coins"`
_6
}

MsgMigrateContract

Can be issued by the owner of a migratable smart contract to reset its code ID to another one. MigrateMsg is a JSON message encoded in Base64.


_6
type MsgMigrateContract struct {
_6
Owner sdk.AccAddress `json:"owner" yaml:"owner"`
_6
Contract sdk.AccAddress `json:"contract" yaml:"contract"`
_6
NewCodeID uint64 `json:"new_code_id" yaml:"new_code_id"`
_6
MigrateMsg core.Base64Bytes `json:"migrate_msg" yaml:"migrate_msg"`
_6
}

MsgUpdateContractOwner

Can be issued by the smart contract's owner to transfer ownership.


_5
type MsgUpdateContractOwner struct {
_5
Owner sdk.AccAddress `json:"owner" yaml:"owner"`
_5
NewOwner sdk.AccAddress `json:"new_owner" yaml:"new_owner"`
_5
Contract sdk.AccAddress `json:"contract" yaml:"contract"`
_5
}

Parameters

The subspace for the WASM module is wasm.


_5
type Params struct {
_5
MaxContractSize uint64 `json:"max_contract_size" yaml:"max_contract_size"`
_5
MaxContractGas uint64 `json:"max_contract_gas" yaml:"max_contract_gas"`
_5
MaxContractMsgSize uint64 `json:"max_contract_msg_size" yaml:"max_contract_msg_size"`
_5
}

MaxContractSize

  • type: uint64

Maximum contract bytecode size in bytes.

MaxContractGas

  • type: uint64

Maximum contract gas consumption during any execution.

MaxContractMsgSize

  • type: uint64

Maximum contract message size in bytes.