Calling other contracts

Hay dos formas diferentes de llamar a otros contratos en Cairo.

The easiest way to call other contracts is by using the dispatcher of the contract you want to call. You can read more about Dispatchers in the Cairo Book

La otra forma es utilizar la llamada al sistema starknet::call_contract_syscall. Sin embargo, este método no es recomendable.

Para llamar a otros contratos utilizando dispatchers, tendrás que definir la interfaz del contrato llamado como un trait anotado con el atributo #[starknet::interface], y luego importar los elementos IContractDispatcher e IContractDispatcherTrait en tu contrato.

#[starknet::interface] trait ICallee<TContractState> { fn set_value(ref self: TContractState, value: u128) -> u128; } #[starknet::contract] mod Callee { #[storage] struct Storage { value: u128, } #[abi(embed_v0)] impl ICalleeImpl of super::ICallee<ContractState> { fn set_value(ref self: ContractState, value: u128) -> u128 { self.value.write(value); value } } }

Visita el contrato en Voyager o juega con él en Remix.

use starknet::ContractAddress; // We need to have the interface of the callee contract defined // so that we can import the Dispatcher. #[starknet::interface] trait ICallee<TContractState> { fn set_value(ref self: TContractState, value: u128) -> u128; } #[starknet::interface] trait ICaller<TContractState> { fn set_value_from_address(ref self: TContractState, addr: ContractAddress, value: u128); } #[starknet::contract] mod Caller { // We import the Dispatcher of the called contract use super::{ICalleeDispatcher, ICalleeDispatcherTrait}; use starknet::ContractAddress; #[storage] struct Storage {} #[abi(embed_v0)] impl ICallerImpl of super::ICaller<ContractState> { fn set_value_from_address(ref self: ContractState, addr: ContractAddress, value: u128) { ICalleeDispatcher { contract_address: addr }.set_value(value); } } }

Visita el contrato en Voyager o juega con él en Remix.

Last change: 2023-11-30, commit: fec6527