Overview
This tutorial teaches you how to:- Make simple cross-contract calls
- Handle callbacks from other contracts
- Work with promises
- Handle errors in cross-contract interactions
Simple cross-contract call
The simplest example calls the Hello NEAR contract to set and retrieve a greeting.GitHub Repository
View the complete example on GitHub
How it works
Make the cross-contract call
Your contract creates a promise to call another contract’s method:
- Rust
- JavaScript
Key concepts
Promises
Promises
Cross-contract calls use promises to handle asynchronous operations:
- Promise creation: Initiates a call to another contract
- Promise chaining: Sequences multiple calls with
.then() - Promise results: Access results in callback functions
Callbacks
Callbacks
Callbacks handle the results of cross-contract calls:
- Must be marked as
#[private](Rust) orprivateFunction: true(JS) - Only callable by the contract itself
- Access promise results via
env::promise_result()ornear.promiseResult()
Gas considerations
Gas considerations
Cross-contract calls require careful gas management:
- Allocate sufficient gas for the external call
- Reserve gas for the callback
- Total gas = call gas + callback gas
- Failed calls due to insufficient gas cannot be recovered
Error handling
Error handling
Handle errors gracefully:
- Check promise results in callbacks
- Provide fallback behavior for failed calls
- Log errors for debugging
- Consider refund logic for failed operations
Common patterns
Sequential calls
Make multiple calls in sequence:Batch calls
Make multiple independent calls:Testing cross-contract calls
Use NEAR Workspaces to test cross-contract interactions:- Rust
- JavaScript
Next steps
Advanced cross-contract calls
Learn about parallel and batch cross-contract calls
Factory contracts
Deploy contracts from contracts
NFT marketplace
Build a marketplace using cross-contract calls
Contract security
Secure your cross-contract interactions