Call a Contract

A common blockchain operation is communication between smart contracts.

Example

To perform a call there are three steps that we must take:

  1. Provide an interface to call
  2. Create a type that allows us to make a call
  3. Call a function on our interface

Defining the Interface

Let's take the example of a Vault to demonstrate how a call can be performed.

library;

abi Vault {
    #[payable]
    fn deposit();
    fn withdraw(amount: u64, asset: ContractId);
}

Creating a Callable Type

To call a function on our Vault we must create a type that can perform calls. The syntax for creating a callable type is: abi(<interface-name>, <b256-address>).

Calling a Contract

The following snippet uses a script to call our Vault contract.

script;

use contract_interface::Vault;

fn main(amount: u64, asset_id: ContractId, vault_id: b256) -> bool {
    let caller = abi(Vault, vault_id);

    // Optional arguments are wrapped in `{}`
    caller.deposit {
        // `u64` that represents the gas being forwarded to the contract
        gas: 10000,
        // `u64` that represents how many coins are being forwarded
        coins: amount,
        // `b256` that represents the asset ID of the forwarded coins 
        asset_id: asset_id.into(),
    }();

    caller.withdraw(amount, asset_id);

    true
}

The deposit() function uses pre-defined optional arguments provided by the Sway language.