contract-call?
Executing public functions in other smart contracts from within a Clarity smart contract.
Function Signature
- Input:
.contract-name
: The name of the contract to callfunction-name
: The name of the public function to executearg0, arg1, ...
: Arguments to pass to the function
- Output:
(response A B)
where A and B are the types returned by the called function
Why it matters
The contract-call?
function is crucial for:
- Enabling inter-contract communication and composability.
- Allowing contracts to leverage functionality from other contracts.
- Building complex systems of interacting smart contracts.
- Implementing upgradeable contract patterns.
When to use it
Use the contract-call?
function when you need to:
- Call a public function in another contract.
- Interact with standardized contracts (e.g., token contracts).
- Split complex logic across multiple contracts for better organization.
- Implement upgradeable systems by calling into newer contract versions.
Best Practices
- Always check the return value of
contract-call?
as it returns a response type. - Be aware that
contract-call?
cannot be used to call functions within the same contract. - Consider the gas costs of external contract calls in your overall transaction budget.
- Use
as-contract
when appropriate to make calls with the contract's own principal.
Practical Example: Interacting with a Token Contract
Let's implement a function that transfers tokens using a standard token contract:
This example demonstrates:
- Using
contract-call?
to interact with another contract (.token-contract
). - Passing arguments to the called function, including the current
tx-sender
. - Returning the response from the called function directly.
Common Pitfalls
- Forgetting to handle the response from
contract-call?
, which can lead to unexpected behavior. - Attempting to use
contract-call?
to call functions within the same contract, which is not allowed. - Not considering the possibility of the called contract changing or being upgraded.
Related Functions
as-contract
: Often used in combination withcontract-call?
to make calls as the contract principal.try!
: Useful for handling the response fromcontract-call?
and propagating errors.unwrap!
: Can be used to extract the success value from acontract-call?
response or return an error.
Conclusion
The contract-call?
function is a fundamental building block for creating complex, interacting systems of smart contracts on the Stacks blockchain. By enabling contracts to call functions in other contracts, it promotes code reuse, modularity, and upgradability. However, developers must be careful to handle responses correctly and consider the implications of external calls on their contract's behavior and gas usage.