soroban-project) and then initialize a project workspace with a single contract named add_contract.
Adding one more contract template to the project can be done using the same command:
soroban-project directory will look like this:
stellar contract init command created a new contract, located in ./contracts, each containing:
- Cargo.toml file with the
soroban-sdkdependency srcdirectory with an example hello-world contract and a test.
soroban-project first before running it), and check the build directory target/wasm32v1-none/release/ for the compiled .wasm files.
Integrating Contracts in the Same Workspace
With the given project structure, cross-contract calls can be easily made. Starting with modifying the sample hello world contract into an add contract:contracts/add_contract/src/lib.rs
ContractAdd from another contract, it’s necessary to add a workspace dependency:
./contracts/main_contract/Cargo.toml
ContractAdd can now be referenced and used from another contracts using ContractAddClient:
contracts/main_contract/src/lib.rs
ContractAdd’s add function to calculate the sum of 2 numbers. It’s a good idea to update tests for our main contract as well:
contracts/main_contract/src/test.rs
contracts/main_contract:
Adding contract interfaces
As the next step, we can abstract away add contract and allow it to have multiple implementations. Main contract will in turn use the contract interface that is not bound to its implementation.contracts/adder_interface/src/lib.rs
adder_interface as a dependency:
./Cargo.toml
./contracts/add_contract/Cargo.toml
./contracts/main_contract/Cargo.toml
./contracts/add_extra_contract/Cargo.toml
adder_interface crate:
./contracts/adder_interface/Cargo.toml
./contracts/adder_interface/src/lib.rs
contracts/add_contract/src/lib.rs
contracts/main_contract/src/lib.rs
Adder implementation that adds an extra 1:
contracts/add_extra_contract/src/lib.rs