An example project for writing Arbitrum Stylus programs in Rust using the stylus-sdk. It includes a Rust implementation of a vending machine Ethereum smart contract. Below is the interface for the VendingMachine contract:
interface IVendingMachine {
// Function to distribute a cupcake to a user
function giveCupcakeTo(address userAddress) external returns (bool);
// Getter function for the cupcake balance of a user
function getCupcakeBalanceFor(address userAddress) external view returns (uint);
}
You can export the Solidity ABI for your program by using the cargo stylus
tool as follows:
cargo stylus export-abi
which outputs:
/**
* This file was automatically generated by Stylus and represents a Rust program.
* For more information, please see [The Stylus SDK](https://github.com/OffchainLabs/stylus-sdk-rs).
*/
interface VendingMachine {
function giveCupcakeTo(address user_address) external returns (bool);
function getCupcakeBalanceFor(address user_address) external view returns (uint256);
}
You can use the cargo stylus
command to also deploy your program to the Stylus testnet. We can use the tool to first check
our program compiles to valid WASM for Stylus and will succeed a deployment onchain without transacting. By default, this will use the Stylus testnet public RPC endpoint. See here for Stylus testnet information.
cargo stylus check
Next, we deploy:
cargo stylus deploy \
--private-key-path=<PRIVKEY_FILE_PATH>
This example includes how to call and transact with your program in Rust using ethers-rs under examples/vending_machine.rs
. Your programs are also Ethereum ABI equivalent if using the Stylus SDK, meaning they can be called and transacted with using any other Ethereum tooling.
By using the program address from your deployment step above and your wallet, you can attempt to call the vending machine program and interact with it.
To run the example, set the following env vars or place them in a .env
file this project, then:
STYLUS_PROGRAM_ADDRESS=<the onchain address of your deployed program>
PRIV_KEY_PATH=<the file path for your priv key to transact with>
RPC_URL=https://stylus-testnet.arbitrum.io/rpc
USER_ADDRESS=<the address of the user you want to interact with>
Alternatively, you can copy the .env-sample
into a .env
file:
cp .env-sample .env
Next, run:
cargo run --example vending_machine --target=<YOUR_ARCHITECTURE>
Where you can find YOUR_ARCHITECTURE
by running rustc -vV | grep host
. For M1 Apple computers, for example, this is aarch64-apple-darwin
and for most Linux x86 it is x86_64-unknown-linux-gnu
.