Import a contract from its WASM file, generating a client, types, and constant holding the contract file.
The path given is relative to the workspace root, and not the current file.
Syntax
mod contract_name {
soroban_sdk::contractimport!(file = "path/to/contract.wasm");
}
Parameters
Path to the WASM file, relative to the workspace root.
Optional SHA-256 hash of the WASM file for verification. If provided, the macro will verify the file contents match this hash at compile time.
Generated Code
The macro generates in the current module:
- A
Contract trait that matches the contract’s interface
- A
ContractClient struct that has functions for each function in the contract
- Types for all contract types defined in the contract
- A
WASM constant containing the contract’s WASM bytes
Example
Importing and Using an External Contract
use soroban_sdk::{contractimpl, BytesN, Env, Symbol};
mod contract_a {
soroban_sdk::contractimport!(file = "contract_a.wasm");
}
pub struct ContractB;
#[contractimpl]
impl ContractB {
pub fn add_with(env: Env, contract_id: BytesN<32>, x: u32, y: u32) -> u32 {
let client = contract_a::ContractClient::new(&env, contract_id);
client.add(&x, &y)
}
}
#[test]
fn test() {
let env = Env::default();
// Register contract A using the imported WASM.
let contract_a_id = env.register_contract_wasm(None, contract_a::WASM);
// Register contract B defined in this crate.
let contract_b_id = env.register(ContractB, ());
// Create a client for calling contract B.
let client = ContractBClient::new(&env, &contract_b_id);
// Invoke contract B via its client.
let sum = client.add_with(&contract_a_id, &5, &7);
assert_eq!(sum, 12);
}
Using SHA-256 Verification
mod contract_a {
soroban_sdk::contractimport!(
file = "contract_a.wasm",
sha256 = "a1b2c3d4e5f6..."
);
}
If the SHA-256 hash doesn’t match the file contents, compilation will fail with an error message showing the expected hash.
Use Cases
Cross-Contract Calls
Use contractimport! to call functions on other deployed contracts:
mod token {
soroban_sdk::contractimport!(file = "soroban_token_contract.wasm");
}
#[contractimpl]
impl MyContract {
pub fn transfer_tokens(
env: Env,
token_id: BytesN<32>,
from: Address,
to: Address,
amount: i128
) {
let token = token::ContractClient::new(&env, token_id);
token.transfer(&from, &to, &amount);
}
}
Testing with External Contracts
Use imported contracts in tests:
#[test]
fn test_with_external_contract() {
let env = Env::default();
// Deploy the imported contract
let external_id = env.register_contract_wasm(None, external::WASM);
let external_client = external::ContractClient::new(&env, &external_id);
// Test interactions
let result = external_client.some_function(&arg);
assert_eq!(result, expected);
}
See Also
#[contract] - Define a contract in the current crate
Env - Environment type with contract registration methods
- Cross-Contract Calls - Complete guide to calling external contracts