contracttrait

Attribute Macro contracttrait 

Source
#[contracttrait]
Expand description

Defines a contract trait with default function implementations that can be used by contracts.

The contracttrait macro generates a trait that contracts can implement using contractimpl. Functions defined with default implementations in the trait will be automatically exported as contract functions when a contract implements the trait using #[contractimpl(contracttrait)].

This is useful for defining standard interfaces where some functions have default implementations that can be optionally overridden.

Note: The contracttrait macro is not required on traits, but without it default functions will not be exported by contracts that implement the trait.

§Macro Arguments

  • crate_path - The path to the soroban-sdk crate. Defaults to soroban_sdk.
  • spec_name - The name for the spec type. Defaults to {TraitName}Spec.
  • spec_export - Whether to export the spec for default functions. Defaults to false.
  • args_name - The name for the args type. Defaults to {TraitName}Args.
  • client_name - The name for the client type. Defaults to {TraitName}Client.

§Examples

Define a trait with a default function and implement it in a contract:

use soroban_sdk::{contract, contractimpl, contracttrait, Address, Env};

#[contracttrait]
pub trait Token {
    fn balance(env: &Env, id: Address) -> i128 {
        // ...
    }

    // Default function.
    fn transfer(env: &Env, from: Address, to: Address, amount: i128) {
        // ...
    }
}

#[contract]
pub struct TokenContract;

#[contractimpl(contracttrait)]
impl Token for TokenContract {
    fn balance(env: &Env, id: Address) -> i128 {
        // Provide a custom impl of balance.
        // ...
    }
}