# Lifecycle of a Contract
# What is a smart contract?
A CosmWasm contract is simply wasm bytecode uploaded to the chain. The contract itself is not its "state". Think of the contract as a class. Contracts are immutable because their code/logic is fixed.
Upon contract instantiation, there exists an instance of the contract. The
instance contains a reference to the contract and some state in a uniquely
prefixed data store, which is created upon contract instantiation. Concisely,
we might say, contract (instance) = code + state
. In other words, an instance
of a contract is uniquely defined by a reference to wasm bytecode and a
reference to a prefixed key-value store. Instances are mutable because of state
changes.
# Lifecycle of a Contract:
- Create contract code.
- Instantiate a contract instance.
- Invoke the instance.
NOTE: Often, when we say "the contract", what is really intended is "a particular instance of the contract". For brevity's sake, if we say something like "contract state", "contract call", or "contract account", keep in mind that it really means "contract instance state", "contract instance call", or "contract instance account."
# Contract State
Contract state, or instance state, is mutable only by the one instance of the contract but may be immutably read by any instance of the contract. This state is a key-value store with one or more keys. State is born upon contract instantiation.
- State is not "stored in" the contract, although it may feel this way during smart contract development. State comes from the Golang runtime (the chain).
- State is mutable only from the corresponding instance.
# EVM Tooling Analogs
Ethereum | Wasm | Description |
---|---|---|
Solidity, Vyper | CosmWasm-std + Rust | Smart contract languages |
Open Zepplin contracts | cw-plus | Smart contract libraries with reusable components. |
EVM | CosmWasm VM | Virtual machines that execute smart contract bytecode. |
Web3.js | CosmJS | Client-side JavaScript libraries for interacting with blockchains. |
The cosmwasm-std
crate (opens new window)
is the standard library for building contracts in CosmWasm. It is compiled as
part of the contract to Wasm. When creating a dependency to cosmwasm-std, the
required Wasm imports and exports are created implicitely via C interfaces.