Cadence

Contracts

A contract is a collection of type definitions, data (its state), and code (its functions) that is stored in the contract storage area of an account.

Contracts also:

  • are where all composite types' interfaces for these types must be defined. Therefore, an object of one of these types cannot exist without having been defined in a deployed Cadence contract.
  • can be deployed to accounts, updated, and removed from accounts using the contracts object of authorized accounts. See the account contracts section below for more information about these operations.
  • are types. They are similar to composite types, but are stored differently than structs or resources and cannot be used as values, copied, or moved like resources or structs.

Contracts stay in an account's contract storage area and can only be added, updated, or removed by the account owner with special commands.

Contracts are declared using the contract keyword. The keyword is followed by the name of the contract:

access(all)
contract SomeContract {
    // ...
}

Contracts cannot be nested in each other:

access(all)
contract Invalid {

    // Invalid: Contracts cannot be nested in any other type.
    //
    access(all)
    contract Nested {
        // ...
    }
}

One of the simplest forms of a contract is one with a state field, a function, and an initializer that initializes the field:

access(all)
contract HelloWorld {

    // Declare a stored state field in HelloWorld
    //
    access(all)
    let greeting: String

    // Declare a function that can be called by anyone
    // who imports the contract
    //
    access(all)
    fun hello(): String {
        return self.greeting
    }

    init() {
        self.greeting = "Hello World!"
    }
}

Transactions and other contracts can interact with contracts by importing them at the beginning of a transaction or contract definition.

Anyone can call the above contract's hello function by importing the contract from the account it was deployed to and using the imported object to call the hello function:

import HelloWorld from 0x42

// Invalid: The contract does not know where hello comes from
//
log(hello())        // Error

// Valid: Using the imported contract object to call the hello
// function
//
log(HelloWorld.hello())    // prints "Hello World!"

// Valid: Using the imported contract object to read the greeting
// field
log(HelloWorld.greeting)   // prints "Hello World!"

// Invalid: Cannot call the init function after the contract has been created.
//
HelloWorld.init()    // Error

There can be any number of contracts per account, and they can include an arbitrary amount of data. This means that a contract can have any number of fields, functions, and type definitions, but they must be in the contract and not another top-level definition:

// Invalid: Top-level declarations are restricted to only be contracts
//          or contract interfaces. Therefore, all of these would be invalid
//          if they were deployed to the account contract storage and
//          the deployment would be rejected.
//
access(all)
resource Vault {}

access(all)
struct Hat {}

access(all)
fun helloWorld(): String {}
let num: Int

Another important feature of contracts is that instances of resources and events that are declared in contracts can only be created/emitted within functions or types that are declared in the same contract.

It is not possible to create instances of resources and events outside the contract.

The following contract defines a resource interface Receiver, and a resource Vault that implements that interface. Due to how this example is written, there is no way to create this resource, so it would not be usable:

// Valid
access(all)
contract FungibleToken {

    access(all)
    resource interface Receiver {

        access(all)
        balance: Int

        access(all)
        fun deposit(from: @{Receiver}) {
            pre {
                from.balance > 0:
                    "Deposit balance needs to be positive!"
            }
            post {
                self.balance == before(self.balance) + before(from.balance):
                    "Incorrect amount removed"
            }
        }
    }

    access(all)
    resource Vault: Receiver {

        // keeps track of the total balance of the accounts tokens
        access(all)
        var balance: Int

        init(balance: Int) {
            self.balance = balance
        }

        // withdraw subtracts amount from the vaults balance and
        // returns a vault object with the subtracted balance
        access(all)
        fun withdraw(amount: Int): @Vault {
            self.balance = self.balance - amount
            return <-create Vault(balance: amount)
        }

        // deposit takes a vault object as a parameter and adds
        // its balance to the balance of the Account's vault, then
        // destroys the sent vault because its balance has been consumed
        access(all)
        fun deposit(from: @{Receiver}) {
            self.balance = self.balance + from.balance
            destroy from
        }
    }
}

If a user tried to run a transaction that created an instance of the Vault type, the type checker would not allow it because only code in the FungibleToken contract can create new Vaults:

import FungibleToken from 0x42

// Invalid: Cannot create an instance of the `Vault` type outside
// of the contract that defines `Vault`
//
let newVault <- create FungibleToken.Vault(balance: 10)

Account access

Contracts can access the account they are deployed to — contracts have the implicit field named account, which is only accessible within the contract:

let account: auth(Storage, Keys, Contracts, Inbox, Capabilities) &Account`,

The account reference is fully entitled, so it grants access to the account's storage, keys, contracts, and so on.

For example, the following gives the contract the ability to write to the account's storage when the contract is initialized:

init(balance: Int) {
    self.account.storage.save(
        <-create Vault(balance: 1000),
        to: /storage/initialVault
    )
}

Contract interfaces

Like composite types, contracts can have interfaces that specify rules about their behavior, their types, and the behavior of their types.

Contract interfaces have to be declared globally. Declarations cannot be nested in other types.

Contract interfaces may not declare concrete types (other than events), but they can declare interfaces. If a contract interface declares an interface type, the implementing contract does not have to also define that interface. They can refer to that nested interface by saying {ContractInterfaceName}.{NestedInterfaceName}:

// Declare a contract interface that declares an interface and a resource
// that needs to implement that interface in the contract implementation.
//
access(all)
contract interface InterfaceExample {

    // Implementations do not need to declare this
    // They refer to it as InterfaceExample.NestedInterface
    //
    access(all)
    resource interface NestedInterface {}

    // Implementations must declare this type
    //
    access(all)
    resource Composite: NestedInterface {}
}

access(all)
contract ExampleContract: InterfaceExample {

    // The contract doesn't need to redeclare the `NestedInterface` interface
    // because it is already declared in the contract interface

    // The resource has to refer to the resource interface using the name
    // of the contract interface to access it
    //
    access(all)
    resource Composite: InterfaceExample.NestedInterface {
    }
}

Account.Contracts

An account exposes its inbox through the contracts field, which has the type Account.Contracts:

access(all)
struct Contracts {

    /// The names of all contracts deployed in the account.
    access(all)
    let names: [String]

    /// Returns the deployed contract for the contract/contract interface with the given name in the account, if any.
    ///
    /// Returns nil if no contract/contract interface with the given name exists in the account.
    access(all)
    view fun get(name: String): DeployedContract?

    /// Returns a reference of the given type to the contract with the given name in the account, if any.
    ///
    /// Returns nil if no contract with the given name exists in the account,
    /// or if the contract does not conform to the given type.
    access(all)
    view fun borrow<T: &Any>(name: String): T?

    /// Adds the given contract to the account.
    ///
    /// The `code` parameter is the UTF-8 encoded representation of the source code.
    /// The code must contain exactly one contract or contract interface,
    /// which must have the same name as the `name` parameter.
    ///
    /// All additional arguments that are given are passed further to the initializer
    /// of the contract that is being deployed.
    ///
    /// The function fails if a contract/contract interface with the given name already exists in the account,
    /// if the given code does not declare exactly one contract or contract interface,
    /// or if the given name does not match the name of the contract/contract interface declaration in the code.
    ///
    /// Returns the deployed contract.
    access(Contracts | AddContract)
    fun add(
        name: String,
        code: [UInt8]
    ): DeployedContract

    /// Updates the code for the contract/contract interface in the account.
    ///
    /// The `code` parameter is the UTF-8 encoded representation of the source code.
    /// The code must contain exactly one contract or contract interface,
    /// which must have the same name as the `name` parameter.
    ///
    /// Does **not** run the initializer of the contract/contract interface again.
    /// The contract instance in the world state stays as is.
    ///
    /// Fails if no contract/contract interface with the given name exists in the account,
    /// if the given code does not declare exactly one contract or contract interface,
    /// or if the given name does not match the name of the contract/contract interface declaration in the code.
    ///
    /// Returns the deployed contract for the updated contract.
    access(Contracts | UpdateContract)
    fun update(name: String, code: [UInt8]): DeployedContract

    /// Removes the contract/contract interface from the account which has the given name, if any.
    ///
    /// Returns the removed deployed contract, if any.
    ///
    /// Returns nil if no contract/contract interface with the given name exists in the account.
    access(Contracts | RemoveContract)
    fun remove(name: String): DeployedContract?
}

entitlement Contracts

entitlement AddContract
entitlement UpdateContract
entitlement RemoveContract

Deployed contract

Accounts store deployed contracts, which is the code of the contract:

access(all)
struct DeployedContract {
    /// The address of the account where the contract is deployed at.
    access(all)
    let address: Address

    /// The name of the contract.
    access(all)
    let name: String

    /// The code of the contract.
    access(all)
    let code: [UInt8]

    /// Returns an array of `Type` objects representing all the public type declarations in this contract
    /// (e.g. structs, resources, enums).
    ///
    /// For example, given a contract
    /// ```
    /// contract Foo {
    ///
    ///       access(all)
    ///       struct Bar {...}
    ///
    ///       access(all)
    ///       resource Qux {...}
    /// }
    /// ```
    /// then `.publicTypes()` will return an array equivalent to the expression `[Type<Bar>(), Type<Qux>()]`
    access(all)
    view fun publicTypes(): [Type]
}

This example is type only, which provides information about a deployed contract. it is not the contract instance, which is the result of importing a contract.

Getting a deployed contract

The function contracts.get retrieves a deployed contract:

access(all)
view fun get(name: String): DeployedContract?

The function returns the deployed contract with the given name, if any. If no contract with the given name exists in the account, the function returns nil.

For example, assuming that an account has a contract named Test deployed to it, the contract can be retrieved as follows:

let account = getAccount(0x1)
let contract = account.contracts.get(name: "Test")

Borrowing a deployed contract

Contracts can be borrowed to effectively perform a dynamic import dependent on a specific execution path.

This is in contrast to a typical import statement (e.g., import T from 0x1), which statically imports a contract.

The contracts.borrow function obtains a reference to a contract instance:

access(all)
view fun borrow<T: &Any>(name: String): T?

The functions returns a reference to the contract instance stored with that name on the account, if it exists, and if it has the provided type T. If no contract with the given name exists in the account, the function returns nil.

For example, assuming that a contract named Test, which conforms to the TestInterface interface is deployed to an account, a reference to the contract instance can be obtained as follows:

let account = getAccount(0x1)
let contract: &TestInterface = account.contracts.borrow<&TestInterface>(name: "Test")

This is similar to the import statement:

import Test from 0x1

Deploying a new contract

The contracts.add function deploys a new contract to an account:

access(Contracts | AddContract)
fun add(
    name: String,
    code: [UInt8],
    ... contractInitializerArguments
): DeployedContract

Calling the add function requires access to an account via a reference that is authorized with the coarse-grained Contracts entitlement (auth(Contracts) &Account), or the fine-grained AddContract entitlement (auth(AddContract) &Account).

The code parameter is the UTF-8 encoded representation of the source code. The code must contain exactly one contract or contract interface, which must have the same name as the name parameter.

The add function passes all extra arguments of the call (contractInitializerArguments) to the initializer of the contract.

If a contract with the given name already exists in the account, if the given code does not declare exactly one contract or contract interface, or if the given name does not match the name of the contract declaration in the code, then the function aborts the program.

When the deployment succeeds, the function returns the deployed contract.

For example, assume the following contract code should be deployed:

access(all)
contract Test {

    access(all)
    let message: String

    init(message: String) {
        self.message = message
    }
}

The contract can then be deployed as follows:

transaction(code: String) {
    prepare(signer: auth(AddContract) &Account) {
        signer.contracts.add(
            name: "Test",
            code: code.utf8,
            message: "I'm a new contract in an existing account"
        )
    }
}

Updating a deployed contract

The contracts.update function updates the code of an existing contract:

access(Contracts | UpdateContract)
fun update(name: String, code: [UInt8]): DeployedContract

Calling the update function requires access to an account via a reference that is authorized with the coarse-grained Contracts entitlement (auth(Contracts) &Account), or the fine-grained UpdateContract entitlement (auth(UpdateContract) &Account).

The code parameter is the UTF-8 encoded representation of the source code. The code must contain exactly one contract or contract interface, which must have the same name as the name parameter.

If no contract with the given name exists in the account, if the given code does not declare exactly one contract or contract interface, or if the given name does not match the name of the contract declaration in the code, then the function aborts the program.

When the update succeeds, the function returns the deployed contract.

The update function does not run the initializer of the contract again.

Updating a contract does not change the contract instance and its existing stored data. A contract update only changes the code of a contract.

It is only possible to update contracts in ways that keep data consistency. Certain restrictions apply.

For example, assume that a contract named Test is already deployed to the account, and it should be updated with the following contract code:

access(all)
contract Test {
    
    access(all)
    let message: String

    init(message: String) {
        self.message = message
    }
}

The contract can be updated as follows:

transaction(code: String) {
    prepare(signer: auth(UpdateContract) &Account) {
        signer.contracts.update(
            name: "Test",
            code: code
        )
    }
}

Removing a deployed contract

The contracts.remove function removes a deployed contract from an account:

access(Contracts | RemoveContract)
fun remove(name: String): DeployedContract?

Calling the remove function requires access to an account via a reference that is authorized with the coarse-grained Contracts entitlement (auth(Contracts) &Account), or the fine-grained RemoveContract entitlement (auth(RemoveContract) &Account).

The function removes the contract from the account that has the given name and returns it. If no contract with the given name exists in the account, the function returns nil.

For example, assuming that a contract named Test is deployed to an account, the contract can be removed as follows:

transaction(code: String) {
    prepare(signer: auth(RemoveContract) &Account) {
        signer.contracts.remove(name: "Test",)
    }
}

On this page