diff --git a/.github/workflows/check-publish.yml b/.github/workflows/check-publish.yml index 67bbb311..132eb00c 100644 --- a/.github/workflows/check-publish.yml +++ b/.github/workflows/check-publish.yml @@ -37,6 +37,9 @@ jobs: - name: check openzeppelin-crypto run: cargo publish -p openzeppelin-crypto --target wasm32-unknown-unknown --dry-run + - name: check openzeppelin-stylus-proc + run: cargo publish -p openzeppelin-stylus-proc --target wasm32-unknown-unknown --dry-run + # TODO: https://github.com/OpenZeppelin/rust-contracts-stylus/issues/291 # - name: check openzeppelin-stylus # run: cargo publish -p openzeppelin-stylus --target wasm32-unknown-unknown --dry-run diff --git a/.github/workflows/gas-bench.yml b/.github/workflows/gas-bench.yml index 67a6f127..a14bf25c 100644 --- a/.github/workflows/gas-bench.yml +++ b/.github/workflows/gas-bench.yml @@ -31,6 +31,9 @@ jobs: with: key: "gas-bench" + - name: install cargo-stylus + run: cargo install cargo-stylus@0.5.1 + - name: install solc run: | curl -LO https://github.com/ethereum/solidity/releases/download/v0.8.24/solc-static-linux diff --git a/Cargo.lock b/Cargo.lock index df6ba222..881f9b29 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -822,6 +822,7 @@ dependencies = [ "alloy-primitives", "e2e", "eyre", + "futures", "keccak-const", "koba", "openzeppelin-stylus", @@ -2591,11 +2592,22 @@ dependencies = [ "keccak-const", "mini-alloc", "motsu", + "openzeppelin-stylus-proc", "rand", "stylus-proc", "stylus-sdk", ] +[[package]] +name = "openzeppelin-stylus-proc" +version = "0.1.0-rc" +dependencies = [ + "convert_case 0.6.0", + "proc-macro2", + "quote", + "syn 2.0.68", +] + [[package]] name = "ownable-example" version = "0.0.0" diff --git a/Cargo.toml b/Cargo.toml index 3f76e904..7f696c6e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,7 @@ [workspace] members = [ "contracts", + "contracts-proc", "lib/crypto", "lib/motsu", "lib/motsu-proc", @@ -22,6 +23,7 @@ members = [ ] default-members = [ "contracts", + "contracts-proc", "lib/crypto", "lib/motsu", "lib/motsu-proc", @@ -48,7 +50,6 @@ resolver = "2" authors = ["OpenZeppelin"] edition = "2021" license = "MIT" -keywords = ["arbitrum", "ethereum", "stylus"] repository = "https://github.com/OpenZeppelin/rust-contracts-stylus" version = "0.1.0-rc" @@ -92,6 +93,7 @@ rand = "0.8.5" regex = "1.10.4" tiny-keccak = { version = "2.0.2", features = ["keccak"] } tokio = { version = "1.12.0", features = ["full"] } +futures = "0.3.30" # procedural macros syn = { version = "2.0.58", features = ["full"] } @@ -100,6 +102,7 @@ quote = "1.0.35" # members openzeppelin-stylus = { path = "contracts" } +openzeppelin-stylus-proc = { path = "contracts-proc" } openzeppelin-crypto = { path = "lib/crypto" } motsu = { path = "lib/motsu"} motsu-proc = { path = "lib/motsu-proc", version = "0.1.0" } diff --git a/benches/Cargo.toml b/benches/Cargo.toml index f16effd4..5cb17d8e 100644 --- a/benches/Cargo.toml +++ b/benches/Cargo.toml @@ -11,6 +11,7 @@ openzeppelin-stylus.workspace = true alloy-primitives = { workspace = true, features = ["tiny-keccak"] } alloy.workspace = true tokio.workspace = true +futures.workspace = true eyre.workspace = true koba.workspace = true e2e.workspace = true diff --git a/benches/src/access_control.rs b/benches/src/access_control.rs index 7c9b7978..12ccfaa8 100644 --- a/benches/src/access_control.rs +++ b/benches/src/access_control.rs @@ -8,7 +8,10 @@ use alloy::{ }; use e2e::{receipt, Account}; -use crate::report::Report; +use crate::{ + report::{ContractReport, FunctionReport}, + CacheOpt, +}; sol!( #[sol(rpc)] @@ -33,7 +36,22 @@ const ROLE: [u8; 32] = const NEW_ADMIN_ROLE: [u8; 32] = hex!("879ce0d4bfd332649ca3552efe772a38d64a315eb70ab69689fd309c735946b5"); -pub async fn bench() -> eyre::Result { +pub async fn bench() -> eyre::Result { + let receipts = run_with(CacheOpt::None).await?; + let report = receipts + .into_iter() + .try_fold(ContractReport::new("AccessControl"), ContractReport::add)?; + + let cached_receipts = run_with(CacheOpt::Bid(0)).await?; + let report = cached_receipts + .into_iter() + .try_fold(report, ContractReport::add_cached)?; + + Ok(report) +} +pub async fn run_with( + cache_opt: CacheOpt, +) -> eyre::Result> { let alice = Account::new().await?; let alice_addr = alice.address(); let alice_wallet = ProviderBuilder::new() @@ -50,7 +68,8 @@ pub async fn bench() -> eyre::Result { .wallet(EthereumWallet::from(bob.signer.clone())) .on_http(bob.url().parse()?); - let contract_addr = deploy(&alice).await; + let contract_addr = deploy(&alice, cache_opt).await?; + let contract = AccessControl::new(contract_addr, &alice_wallet); let contract_bob = AccessControl::new(contract_addr, &bob_wallet); @@ -66,14 +85,17 @@ pub async fn bench() -> eyre::Result { (setRoleAdminCall::SIGNATURE, receipt!(contract.setRoleAdmin(ROLE.into(), NEW_ADMIN_ROLE.into()))?), ]; - let report = receipts + receipts .into_iter() - .try_fold(Report::new("AccessControl"), Report::add)?; - Ok(report) + .map(FunctionReport::new) + .collect::>>() } -async fn deploy(account: &Account) -> Address { +async fn deploy( + account: &Account, + cache_opt: CacheOpt, +) -> eyre::Result
{ let args = AccessControl::constructorCall {}; let args = alloy::hex::encode(args.abi_encode()); - crate::deploy(account, "access-control", Some(args)).await + crate::deploy(account, "access-control", Some(args), cache_opt).await } diff --git a/benches/src/erc20.rs b/benches/src/erc20.rs index 22f2aff0..bcf63435 100644 --- a/benches/src/erc20.rs +++ b/benches/src/erc20.rs @@ -9,7 +9,10 @@ use alloy::{ use alloy_primitives::U256; use e2e::{receipt, Account}; -use crate::report::Report; +use crate::{ + report::{ContractReport, FunctionReport}, + CacheOpt, +}; sol!( #[sol(rpc)] @@ -39,7 +42,23 @@ const TOKEN_NAME: &str = "Test Token"; const TOKEN_SYMBOL: &str = "TTK"; const CAP: U256 = uint!(1_000_000_U256); -pub async fn bench() -> eyre::Result { +pub async fn bench() -> eyre::Result { + let reports = run_with(CacheOpt::None).await?; + let report = reports + .into_iter() + .try_fold(ContractReport::new("Erc20"), ContractReport::add)?; + + let cached_reports = run_with(CacheOpt::Bid(0)).await?; + let report = cached_reports + .into_iter() + .try_fold(report, ContractReport::add_cached)?; + + Ok(report) +} + +pub async fn run_with( + cache_opt: CacheOpt, +) -> eyre::Result> { let alice = Account::new().await?; let alice_addr = alice.address(); let alice_wallet = ProviderBuilder::new() @@ -56,7 +75,8 @@ pub async fn bench() -> eyre::Result { .wallet(EthereumWallet::from(bob.signer.clone())) .on_http(bob.url().parse()?); - let contract_addr = deploy(&alice).await; + let contract_addr = deploy(&alice, cache_opt).await?; + let contract = Erc20::new(contract_addr, &alice_wallet); let contract_bob = Erc20::new(contract_addr, &bob_wallet); @@ -79,17 +99,21 @@ pub async fn bench() -> eyre::Result { (transferFromCall::SIGNATURE, receipt!(contract_bob.transferFrom(alice_addr, bob_addr, uint!(4_U256)))?), ]; - let report = - receipts.into_iter().try_fold(Report::new("Erc20"), Report::add)?; - Ok(report) + receipts + .into_iter() + .map(FunctionReport::new) + .collect::>>() } -async fn deploy(account: &Account) -> Address { +async fn deploy( + account: &Account, + cache_opt: CacheOpt, +) -> eyre::Result
{ let args = Erc20Example::constructorCall { name_: TOKEN_NAME.to_owned(), symbol_: TOKEN_SYMBOL.to_owned(), cap_: CAP, }; let args = alloy::hex::encode(args.abi_encode()); - crate::deploy(account, "erc20", Some(args)).await + crate::deploy(account, "erc20", Some(args), cache_opt).await } diff --git a/benches/src/erc721.rs b/benches/src/erc721.rs index b5dc4bb2..b00729a1 100644 --- a/benches/src/erc721.rs +++ b/benches/src/erc721.rs @@ -8,7 +8,10 @@ use alloy::{ }; use e2e::{receipt, Account}; -use crate::report::Report; +use crate::{ + report::{ContractReport, FunctionReport}, + CacheOpt, +}; sol!( #[sol(rpc)] @@ -29,7 +32,23 @@ sol!( sol!("../examples/erc721/src/constructor.sol"); -pub async fn bench() -> eyre::Result { +pub async fn bench() -> eyre::Result { + let reports = run_with(CacheOpt::None).await?; + let report = reports + .into_iter() + .try_fold(ContractReport::new("Erc721"), ContractReport::add)?; + + let cached_reports = run_with(CacheOpt::Bid(0)).await?; + let report = cached_reports + .into_iter() + .try_fold(report, ContractReport::add_cached)?; + + Ok(report) +} + +pub async fn run_with( + cache_opt: CacheOpt, +) -> eyre::Result> { let alice = Account::new().await?; let alice_addr = alice.address(); let alice_wallet = ProviderBuilder::new() @@ -41,7 +60,8 @@ pub async fn bench() -> eyre::Result { let bob = Account::new().await?; let bob_addr = bob.address(); - let contract_addr = deploy(&alice).await; + let contract_addr = deploy(&alice, cache_opt).await?; + let contract = Erc721::new(contract_addr, &alice_wallet); let token_1 = uint!(1_U256); @@ -70,13 +90,17 @@ pub async fn bench() -> eyre::Result { (burnCall::SIGNATURE, receipt!(contract.burn(token_1))?), ]; - let report = - receipts.into_iter().try_fold(Report::new("Erc721"), Report::add)?; - Ok(report) + receipts + .into_iter() + .map(FunctionReport::new) + .collect::>>() } -async fn deploy(account: &Account) -> Address { +async fn deploy( + account: &Account, + cache_opt: CacheOpt, +) -> eyre::Result
{ let args = Erc721Example::constructorCall {}; let args = alloy::hex::encode(args.abi_encode()); - crate::deploy(account, "erc721", Some(args)).await + crate::deploy(account, "erc721", Some(args), cache_opt).await } diff --git a/benches/src/lib.rs b/benches/src/lib.rs index 85a37ca0..c884bcdb 100644 --- a/benches/src/lib.rs +++ b/benches/src/lib.rs @@ -1,3 +1,5 @@ +use std::process::Command; + use alloy::{ primitives::Address, rpc::types::{ @@ -7,6 +9,7 @@ use alloy::{ }; use alloy_primitives::U128; use e2e::{Account, ReceiptExt}; +use eyre::WrapErr; use koba::config::{Deploy, Generate, PrivateKey}; use serde::Deserialize; @@ -16,8 +19,6 @@ pub mod erc721; pub mod merkle_proofs; pub mod report; -const RPC_URL: &str = "http://localhost:8547"; - #[derive(Debug, Deserialize)] struct ArbOtherFields { #[serde(rename = "gasUsedForL1")] @@ -27,23 +28,24 @@ struct ArbOtherFields { l1_block_number: String, } +/// Cache options for the contract. +/// `Bid(0)` will likely cache the contract on the nitro test node. +pub enum CacheOpt { + None, + Bid(u32), +} + type ArbTxReceipt = WithOtherFields>>; -fn get_l2_gas_used(receipt: &ArbTxReceipt) -> eyre::Result { - let l2_gas = receipt.gas_used; - let arb_fields: ArbOtherFields = receipt.other.deserialize_as()?; - let l1_gas = arb_fields.gas_used_for_l1.to::(); - Ok(l2_gas - l1_gas) -} - async fn deploy( account: &Account, contract_name: &str, args: Option, -) -> Address { + cache_opt: CacheOpt, +) -> eyre::Result
{ let manifest_dir = - std::env::current_dir().expect("should get current dir from env"); + std::env::current_dir().context("should get current dir from env")?; let wasm_path = manifest_dir .join("target") @@ -53,7 +55,7 @@ async fn deploy( let sol_path = args.as_ref().map(|_| { manifest_dir .join("examples") - .join(format!("{}", contract_name)) + .join(contract_name) .join("src") .join("constructor.sol") }); @@ -72,14 +74,46 @@ async fn deploy( keystore_path: None, keystore_password_path: None, }, - endpoint: RPC_URL.to_owned(), + endpoint: env("RPC_URL")?, deploy_only: false, quiet: true, }; - koba::deploy(&config) + let address = koba::deploy(&config) .await .expect("should deploy contract") - .address() - .expect("should return contract address") + .address()?; + + if let CacheOpt::Bid(bid) = cache_opt { + cache_contract(account, address, bid)?; + } + + Ok(address) +} + +/// Try to cache a contract on the stylus network. +/// Already cached contracts won't be cached, and this function will not return +/// an error. +/// Output will be forwarded to the child process. +fn cache_contract( + account: &Account, + contract_addr: Address, + bid: u32, +) -> eyre::Result<()> { + // We don't need a status code. + // Since it is not zero when the contract is already cached. + let _ = Command::new("cargo") + .args(["stylus", "cache", "bid"]) + .args(["-e", &env("RPC_URL")?]) + .args(["--private-key", &format!("0x{}", account.pk())]) + .arg(contract_addr.to_string()) + .arg(bid.to_string()) + .status() + .context("failed to execute `cargo stylus cache bid` command")?; + Ok(()) +} + +/// Load the `name` environment variable. +fn env(name: &str) -> eyre::Result { + std::env::var(name).wrap_err(format!("failed to load {name}")) } diff --git a/benches/src/main.rs b/benches/src/main.rs index cd4e0e38..52278d77 100644 --- a/benches/src/main.rs +++ b/benches/src/main.rs @@ -1,18 +1,21 @@ -use benches::{access_control, erc20, erc721, merkle_proofs, report::Reports}; +use benches::{ + access_control, erc20, erc721, merkle_proofs, report::BenchmarkReport, +}; +use futures::FutureExt; #[tokio::main] async fn main() -> eyre::Result<()> { - let reports = tokio::join!( - access_control::bench(), - erc20::bench(), - erc721::bench(), - merkle_proofs::bench() - ); - - let reports = [reports.0?, reports.1?, reports.2?, reports.3?]; - let report = - reports.into_iter().fold(Reports::default(), Reports::merge_with); + let report = futures::future::try_join_all([ + access_control::bench().boxed(), + erc20::bench().boxed(), + erc721::bench().boxed(), + merkle_proofs::bench().boxed(), + ]) + .await? + .into_iter() + .fold(BenchmarkReport::default(), BenchmarkReport::merge_with); + println!(); println!("{report}"); Ok(()) diff --git a/benches/src/merkle_proofs.rs b/benches/src/merkle_proofs.rs index 92a7d55e..fd986520 100644 --- a/benches/src/merkle_proofs.rs +++ b/benches/src/merkle_proofs.rs @@ -8,7 +8,10 @@ use alloy::{ }; use e2e::{receipt, Account}; -use crate::report::Report; +use crate::{ + report::{ContractReport, FunctionReport}, + CacheOpt, +}; sol!( #[sol(rpc)] @@ -57,7 +60,23 @@ const PROOF: [[u8; 32]; 16] = bytes_array! { "fd47b6c292f51911e8dfdc3e4f8bd127773b17f25b7a554beaa8741e99c41208", }; -pub async fn bench() -> eyre::Result { +pub async fn bench() -> eyre::Result { + let reports = run_with(CacheOpt::None).await?; + let report = reports + .into_iter() + .try_fold(ContractReport::new("MerkleProofs"), ContractReport::add)?; + + let cached_reports = run_with(CacheOpt::Bid(0)).await?; + let report = cached_reports + .into_iter() + .try_fold(report, ContractReport::add_cached)?; + + Ok(report) +} + +pub async fn run_with( + cache_opt: CacheOpt, +) -> eyre::Result> { let alice = Account::new().await?; let alice_wallet = ProviderBuilder::new() .network::() @@ -65,7 +84,8 @@ pub async fn bench() -> eyre::Result { .wallet(EthereumWallet::from(alice.signer.clone())) .on_http(alice.url().parse()?); - let contract_addr = deploy(&alice).await; + let contract_addr = deploy(&alice, cache_opt).await?; + let contract = Verifier::new(contract_addr, &alice_wallet); let proof = PROOF.map(|h| h.into()).to_vec(); @@ -75,12 +95,15 @@ pub async fn bench() -> eyre::Result { receipt!(contract.verify(proof, ROOT.into(), LEAF.into()))?, )]; - let report = receipts + receipts .into_iter() - .try_fold(Report::new("MerkleProofs"), Report::add)?; - Ok(report) + .map(FunctionReport::new) + .collect::>>() } -async fn deploy(account: &Account) -> Address { - crate::deploy(account, "merkle-proofs", None).await +async fn deploy( + account: &Account, + cache_opt: CacheOpt, +) -> eyre::Result
{ + crate::deploy(account, "merkle-proofs", None, cache_opt).await } diff --git a/benches/src/report.rs b/benches/src/report.rs index 3a1184b2..49b5fe70 100644 --- a/benches/src/report.rs +++ b/benches/src/report.rs @@ -1,64 +1,157 @@ -use std::fmt::Display; +use std::{collections::HashMap, fmt::Display}; -use crate::{get_l2_gas_used, ArbTxReceipt}; +use crate::{ArbOtherFields, ArbTxReceipt}; const SEPARATOR: &str = "::"; #[derive(Debug)] -pub struct Report { +pub struct FunctionReport { + sig: String, + gas: u128, +} + +impl FunctionReport { + pub(crate) fn new(receipt: (&str, ArbTxReceipt)) -> eyre::Result { + Ok(FunctionReport { + sig: receipt.0.to_owned(), + gas: get_l2_gas_used(&receipt.1)?, + }) + } +} + +#[derive(Debug)] +pub struct ContractReport { contract: String, - fns: Vec<(String, u128)>, + functions: Vec, + functions_cached: Vec, } -impl Report { +impl ContractReport { pub fn new(contract: &str) -> Self { - Report { contract: contract.to_owned(), fns: vec![] } + ContractReport { + contract: contract.to_owned(), + functions: vec![], + functions_cached: vec![], + } + } + + pub fn add(mut self, fn_report: FunctionReport) -> eyre::Result { + self.functions.push(fn_report); + Ok(self) } - pub fn add(mut self, receipt: (&str, ArbTxReceipt)) -> eyre::Result { - let gas = get_l2_gas_used(&receipt.1)?; - self.fns.push((receipt.0.to_owned(), gas)); + pub fn add_cached( + mut self, + fn_report: FunctionReport, + ) -> eyre::Result { + self.functions_cached.push(fn_report); Ok(self) } - fn get_longest_signature(&self) -> usize { + fn signature_max_len(&self) -> usize { let prefix_len = self.contract.len() + SEPARATOR.len(); - self.fns + self.functions + .iter() + .map(|FunctionReport { sig: name, .. }| prefix_len + name.len()) + .max() + .unwrap_or_default() + } + + fn gas_max_len(&self) -> usize { + self.functions + .iter() + .map(|FunctionReport { gas, .. }| gas.to_string().len()) + .max() + .unwrap_or_default() + } + + fn gas_cached_max_len(&self) -> usize { + self.functions_cached .iter() - .map(|(sig, _)| prefix_len + sig.len()) + .map(|FunctionReport { gas, .. }| gas.to_string().len()) .max() .unwrap_or_default() } } #[derive(Debug, Default)] -pub struct Reports(Vec); +pub struct BenchmarkReport(Vec); -impl Reports { - pub fn merge_with(mut self, report: Report) -> Self { +impl BenchmarkReport { + pub fn merge_with(mut self, report: ContractReport) -> Self { self.0.push(report); self } -} -impl Display for Reports { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - let reports = &self.0; - let width = reports + pub fn column_width( + &self, + column_value: impl FnMut(&ContractReport) -> usize, + header: &str, + ) -> usize { + self.0 .iter() - .map(Report::get_longest_signature) + .map(column_value) + .chain(std::iter::once(header.len())) .max() - .unwrap_or_default(); + .unwrap_or_default() + } +} + +impl Display for BenchmarkReport { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + const HEADER_SIG: &str = "Contract::function"; + const HEADER_GAS_CACHED: &str = "Cached"; + const HEADER_GAS: &str = "Not Cached"; + + // Calculating the width of table columns. + let width1 = + self.column_width(ContractReport::signature_max_len, HEADER_SIG); + let width2 = self.column_width( + ContractReport::gas_cached_max_len, + HEADER_GAS_CACHED, + ); + let width3 = self.column_width(ContractReport::gas_max_len, HEADER_GAS); - for report in reports { + // Print headers for the table columns. + writeln!( + f, + "| {HEADER_SIG:width2$} | {HEADER_GAS:>width3$} |" + )?; + writeln!( + f, + "| {:->width1$} | {:->width2$} | {:->width3$} |", + "", "", "" + )?; + + // Merging a non-cached gas report with a cached one. + for report in &self.0 { let prefix = format!("{}{SEPARATOR}", report.contract); + let gas: HashMap<_, _> = report + .functions + .iter() + .map(|func| (&*func.sig, func.gas)) + .collect(); + + for report_cached in &report.functions_cached { + let sig = &*report_cached.sig; + let gas_cached = &report_cached.gas; + let gas = gas[sig]; - for (sig, gas) in &report.fns { - let signature = format!("{prefix}{sig}"); - writeln!(f, "{signature:10}")?; + let full_sig = format!("{prefix}{sig}"); + writeln!( + f, + "| {full_sig:width2$} | {gas:>width3$} |" + )?; } } Ok(()) } } + +fn get_l2_gas_used(receipt: &ArbTxReceipt) -> eyre::Result { + let l2_gas = receipt.gas_used; + let arb_fields: ArbOtherFields = receipt.other.deserialize_as()?; + let l1_gas = arb_fields.gas_used_for_l1.to::(); + Ok(l2_gas - l1_gas) +} diff --git a/contracts-proc/Cargo.toml b/contracts-proc/Cargo.toml new file mode 100644 index 00000000..3372da2c --- /dev/null +++ b/contracts-proc/Cargo.toml @@ -0,0 +1,23 @@ +[package] +name = "openzeppelin-stylus-proc" +description = "Procedural macros for OpenZeppelin Stylus contracts" +version.workspace = true +authors.workspace = true +edition.workspace = true +license.workspace = true +categories = ["cryptography::cryptocurrencies", "no-std", "wasm"] +keywords = ["arbitrum", "ethereum", "stylus", "smart-contracts", "standards"] +repository.workspace = true + + +[dependencies] +proc-macro2.workspace = true +quote.workspace = true +syn.workspace = true +convert_case = "0.6.0" + +[lints] +workspace = true + +[lib] +proc-macro = true diff --git a/contracts-proc/src/interface_id.rs b/contracts-proc/src/interface_id.rs new file mode 100644 index 00000000..c2347caf --- /dev/null +++ b/contracts-proc/src/interface_id.rs @@ -0,0 +1,102 @@ +//! Defines the `#[interface_id]` procedural macro. + +use std::mem; + +use convert_case::{Case, Casing}; +use proc_macro::TokenStream; +use proc_macro2::Ident; +use quote::quote; +use syn::{ + parse::{Parse, ParseStream}, + parse_macro_input, FnArg, ItemTrait, LitStr, Result, Token, TraitItem, +}; + +/// Computes an interface id as an associated constant for the trait. +pub(crate) fn interface_id( + _attr: &TokenStream, + input: TokenStream, +) -> TokenStream { + let mut input = parse_macro_input!(input as ItemTrait); + + let mut selectors = Vec::new(); + for item in &mut input.items { + let TraitItem::Fn(func) = item else { + continue; + }; + + let mut override_fn_name = None; + for attr in mem::take(&mut func.attrs) { + if attr.path().is_ident("selector") { + if override_fn_name.is_some() { + error!(attr.path(), "more than one selector attribute"); + } + let args: SelectorArgs = match attr.parse_args() { + Ok(args) => args, + Err(error) => error!(attr.path(), "{}", error), + }; + override_fn_name = Some(args.name); + } else { + // Put back any other attributes. + func.attrs.push(attr); + } + } + + let solidity_fn_name = override_fn_name.unwrap_or_else(|| { + let rust_fn_name = func.sig.ident.to_string(); + rust_fn_name.to_case(Case::Camel) + }); + + let arg_types = func.sig.inputs.iter().filter_map(|arg| match arg { + FnArg::Typed(t) => Some(t.ty.clone()), + // Opt out any `self` arguments. + FnArg::Receiver(_) => None, + }); + + // Store selector expression from every function in the trait. + selectors.push( + quote! { u32::from_be_bytes(stylus_sdk::function_selector!(#solidity_fn_name #(, #arg_types )*)) } + ); + } + + let name = input.ident; + let vis = input.vis; + let attrs = input.attrs; + let trait_items = input.items; + let (_impl_generics, ty_generics, where_clause) = + input.generics.split_for_impl(); + + // Keep the same trait with an additional associated constant + // `INTERFACE_ID`. + quote! { + #(#attrs)* + #vis trait #name #ty_generics #where_clause { + #(#trait_items)* + + #[doc = concat!("Solidity interface id associated with ", stringify!(#name), " trait.")] + #[doc = "Computed as a XOR of selectors for each function in the trait."] + const INTERFACE_ID: u32 = { + #(#selectors)^* + }; + } + } + .into() +} + +/// Contains arguments of the `#[selector(..)]` attribute. +struct SelectorArgs { + name: String, +} + +impl Parse for SelectorArgs { + fn parse(input: ParseStream) -> Result { + let ident: Ident = input.parse()?; + + if ident == "name" { + let _: Token![=] = input.parse()?; + let lit: LitStr = input.parse()?; + Ok(SelectorArgs { name: lit.value() }) + } else { + error!(@ident, "expected identifier 'name'") + } + } +} diff --git a/contracts-proc/src/lib.rs b/contracts-proc/src/lib.rs new file mode 100644 index 00000000..0d174638 --- /dev/null +++ b/contracts-proc/src/lib.rs @@ -0,0 +1,64 @@ +//! Procedural macro definitions used in `openzeppelin-stylus` smart contracts +//! library. + +extern crate proc_macro; +use proc_macro::TokenStream; + +/// Shorthand to print nice errors. +/// +/// Note that it's defined before the module declarations. +macro_rules! error { + ($tokens:expr, $($msg:expr),+ $(,)?) => {{ + let error = syn::Error::new(syn::spanned::Spanned::span(&$tokens), format!($($msg),+)); + return error.to_compile_error().into(); + }}; + (@ $tokens:expr, $($msg:expr),+ $(,)?) => {{ + return Err(syn::Error::new(syn::spanned::Spanned::span(&$tokens), format!($($msg),+))) + }}; +} + +mod interface_id; + +/// Computes the interface id as an associated constant `INTERFACE_ID` for the +/// trait that describes contract's abi. +/// +/// Selector collision should be handled with +/// macro `#[selector(name = "actualSolidityMethodName")]` on top of the method. +/// +/// # Examples +/// +/// ```rust,ignore +/// #[interface_id] +/// pub trait IErc721 { +/// fn balance_of(&self, owner: Address) -> Result>; +/// +/// fn owner_of(&self, token_id: U256) -> Result>; +/// +/// fn safe_transfer_from( +/// &mut self, +/// from: Address, +/// to: Address, +/// token_id: U256, +/// ) -> Result<(), Vec>; +/// +/// #[selector(name = "safeTransferFrom")] +/// fn safe_transfer_from_with_data( +/// &mut self, +/// from: Address, +/// to: Address, +/// token_id: U256, +/// data: Bytes, +/// ) -> Result<(), Vec>; +/// } +/// +/// impl IErc165 for Erc721 { +/// fn supports_interface(interface_id: FixedBytes<4>) -> bool { +/// ::INTERFACE_ID == u32::from_be_bytes(*interface_id) +/// || Erc165::supports_interface(interface_id) +/// } +/// } +/// ``` +#[proc_macro_attribute] +pub fn interface_id(attr: TokenStream, input: TokenStream) -> TokenStream { + interface_id::interface_id(&attr, input) +} diff --git a/contracts/Cargo.toml b/contracts/Cargo.toml index f079ce0e..13054d80 100644 --- a/contracts/Cargo.toml +++ b/contracts/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "openzeppelin-stylus" -categories = ["no-std", "wasm"] description = "OpenZeppelin Contracts for Stylus" edition.workspace = true -keywords.workspace = true +categories = ["cryptography::cryptocurrencies", "no-std", "wasm"] +keywords = ["arbitrum", "ethereum", "stylus", "smart-contracts", "standards"] license.workspace = true repository.workspace = true version.workspace = true @@ -15,6 +15,7 @@ stylus-sdk.workspace = true stylus-proc.workspace = true mini-alloc.workspace = true keccak-const.workspace = true +openzeppelin-stylus-proc.workspace = true [dev-dependencies] alloy-primitives = { workspace = true, features = ["arbitrary"] } diff --git a/contracts/src/token/erc20/extensions/metadata.rs b/contracts/src/token/erc20/extensions/metadata.rs index 4035f558..ea8680cb 100644 --- a/contracts/src/token/erc20/extensions/metadata.rs +++ b/contracts/src/token/erc20/extensions/metadata.rs @@ -2,8 +2,12 @@ use alloc::string::String; +use alloy_primitives::FixedBytes; +use openzeppelin_stylus_proc::interface_id; use stylus_proc::{public, sol_storage}; +use crate::utils::introspection::erc165::IErc165; + /// Number of decimals used by default on implementors of [`Metadata`]. pub const DEFAULT_DECIMALS: u8 = 18; @@ -20,6 +24,7 @@ sol_storage! { } /// Interface for the optional metadata functions from the ERC-20 standard. +#[interface_id] pub trait IErc20Metadata { /// Returns the name of the token. /// @@ -76,3 +81,22 @@ impl IErc20Metadata for Erc20Metadata { DEFAULT_DECIMALS } } + +impl IErc165 for Erc20Metadata { + fn supports_interface(interface_id: FixedBytes<4>) -> bool { + ::INTERFACE_ID + == u32::from_be_bytes(*interface_id) + } +} + +#[cfg(all(test, feature = "std"))] +mod tests { + use crate::token::erc20::extensions::{Erc20Metadata, IErc20Metadata}; + + #[motsu::test] + fn interface_id() { + let actual = ::INTERFACE_ID; + let expected = 0xa219a025; + assert_eq!(actual, expected); + } +} diff --git a/contracts/src/token/erc20/mod.rs b/contracts/src/token/erc20/mod.rs index b3554b64..4f53c67a 100644 --- a/contracts/src/token/erc20/mod.rs +++ b/contracts/src/token/erc20/mod.rs @@ -4,8 +4,9 @@ //! revert instead of returning `false` on failure. This behavior is //! nonetheless conventional and does not conflict with the expectations of //! [`Erc20`] applications. -use alloy_primitives::{Address, U256}; +use alloy_primitives::{Address, FixedBytes, U256}; use alloy_sol_types::sol; +use openzeppelin_stylus_proc::interface_id; use stylus_proc::SolidityError; use stylus_sdk::{ call::MethodError, @@ -13,6 +14,8 @@ use stylus_sdk::{ stylus_proc::{public, sol_storage}, }; +use crate::utils::introspection::erc165::{Erc165, IErc165}; + pub mod extensions; pub mod utils; @@ -112,6 +115,7 @@ sol_storage! { } /// Required interface of an [`Erc20`] compliant contract. +#[interface_id] pub trait IErc20 { /// The error type associated to this ERC-20 trait implementation. type Error: Into>; @@ -287,6 +291,13 @@ impl IErc20 for Erc20 { } } +impl IErc165 for Erc20 { + fn supports_interface(interface_id: FixedBytes<4>) -> bool { + ::INTERFACE_ID == u32::from_be_bytes(*interface_id) + || Erc165::supports_interface(interface_id) + } +} + impl Erc20 { /// Sets a `value` number of tokens as the allowance of `spender` over the /// caller's tokens. @@ -551,6 +562,10 @@ mod tests { use stylus_sdk::msg; use super::{Erc20, Error, IErc20}; + use crate::{ + token::erc721::{Erc721, IErc721}, + utils::introspection::erc165::IErc165, + }; #[motsu::test] fn reads_balance(contract: Erc20) { @@ -883,4 +898,15 @@ mod tests { let result = contract.approve(Address::ZERO, one); assert!(matches!(result, Err(Error::InvalidSpender(_)))); } + + #[motsu::test] + fn interface_id() { + let actual = ::INTERFACE_ID; + let expected = 0x36372b07; + assert_eq!(actual, expected); + + let actual = ::INTERFACE_ID; + let expected = 0x01ffc9a7; + assert_eq!(actual, expected); + } } diff --git a/contracts/src/token/erc721/extensions/consecutive.rs b/contracts/src/token/erc721/extensions/consecutive.rs index 35a88440..d5f173a2 100644 --- a/contracts/src/token/erc721/extensions/consecutive.rs +++ b/contracts/src/token/erc721/extensions/consecutive.rs @@ -801,13 +801,16 @@ mod tests { ERC721ExceededMaxBatchMint, Erc721Consecutive, Error, }, tests::random_token_id, - ERC721InvalidReceiver, ERC721NonexistentToken, IErc721, + ERC721IncorrectOwner, ERC721InvalidApprover, + ERC721InvalidReceiver, ERC721InvalidSender, + ERC721NonexistentToken, IErc721, }, }, utils::structs::checkpoints::U96, }; const BOB: Address = address!("F4EaCDAbEf3c8f1EdE91b6f2A6840bc2E4DD3526"); + const DAVE: Address = address!("0BB78F7e7132d1651B4Fd884B7624394e92156F1"); fn init( contract: &mut Erc721Consecutive, @@ -858,6 +861,43 @@ mod tests { assert_eq!(balance2, balance1 + uint!(1_U256)); } + #[motsu::test] + fn error_when_minting_token_id_twice(contract: Erc721Consecutive) { + let alice = msg::sender(); + let token_id = random_token_id(); + contract + ._mint(alice, token_id) + .expect("should mint the token a first time"); + let err = contract + ._mint(alice, token_id) + .expect_err("should not mint a token with `token_id` twice"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::InvalidSender(ERC721InvalidSender { + sender: Address::ZERO + })) + )); + } + + #[motsu::test] + fn error_when_minting_token_invalid_receiver(contract: Erc721Consecutive) { + let invalid_receiver = Address::ZERO; + + let token_id = random_token_id(); + + let err = contract + ._mint(invalid_receiver, token_id) + .expect_err("should not mint a token for invalid receiver"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::InvalidReceiver(ERC721InvalidReceiver { + receiver + })) if receiver == invalid_receiver + )); + } + #[motsu::test] fn error_when_to_is_zero(contract: Erc721Consecutive) { let err = contract @@ -994,5 +1034,300 @@ mod tests { Error::Erc721(erc721::Error::NonexistentToken(ERC721NonexistentToken { token_id })) if token_id == U256::from(non_consecutive_token_id) )); + + // After being burnt the token should not be burnt again. + let non_existent_token = non_consecutive_token_id; + let err = contract + ._burn(non_existent_token) + .expect_err("should return Error::NonexistentToken"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::NonexistentToken (ERC721NonexistentToken{ + token_id: t_id + })) if t_id == non_existent_token + )); + } + + #[motsu::test] + fn safe_transfer_from(contract: Erc721Consecutive) { + let alice = msg::sender(); + let token_id = random_token_id(); + contract._mint(alice, token_id).expect("should mint a token to Alice"); + + contract + .safe_transfer_from(alice, BOB, token_id) + .expect("should transfer a token from Alice to Bob"); + + let owner = contract + .owner_of(token_id) + .expect("should return the owner of the token"); + + assert_eq!(owner, BOB); + } + + #[motsu::test] + fn safe_transfers_from_approved_token(contract: Erc721Consecutive) { + let alice = msg::sender(); + let token_id = random_token_id(); + contract._mint(BOB, token_id).expect("should mint token to Bob"); + contract.erc721._token_approvals.setter(token_id).set(alice); + contract + .safe_transfer_from(BOB, alice, token_id) + .expect("should transfer Bob's token to Alice"); + let owner = contract + .owner_of(token_id) + .expect("should return the owner of the token"); + assert_eq!(owner, alice); + } + + #[motsu::test] + fn error_when_safe_transfer_from_incorrect_owner( + contract: Erc721Consecutive, + ) { + let alice = msg::sender(); + let token_id = random_token_id(); + + contract._mint(alice, token_id).expect("should mint a token to Alice"); + + let err = contract + .safe_transfer_from(DAVE, BOB, token_id) + .expect_err("should not transfer from incorrect owner"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::IncorrectOwner(ERC721IncorrectOwner { + sender, + token_id: t_id, + owner + })) if sender == DAVE && t_id == token_id && owner == alice + )); + } + + #[motsu::test] + fn error_when_internal_safe_transfer_nonexistent_token( + contract: Erc721Consecutive, + ) { + let alice = msg::sender(); + let token_id = random_token_id(); + let err = contract + ._safe_transfer(alice, BOB, token_id, vec![0, 1, 2, 3].into()) + .expect_err("should not transfer a non-existent token"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::NonexistentToken(ERC721NonexistentToken { + token_id: t_id, + })) if t_id == token_id + )); + } + + #[motsu::test] + fn error_when_safe_transfer_to_invalid_receiver( + contract: Erc721Consecutive, + ) { + let alice = msg::sender(); + let token_id = random_token_id(); + let invalid_receiver = Address::ZERO; + + contract._mint(alice, token_id).expect("should mint a token to Alice"); + + let err = contract + .safe_transfer_from(alice, invalid_receiver, token_id) + .expect_err("should not transfer the token to invalid receiver"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::InvalidReceiver(ERC721InvalidReceiver { + receiver + })) if receiver == invalid_receiver + )); + + let owner = contract + .owner_of(token_id) + .expect("should return the owner of the token"); + assert_eq!(alice, owner); + } + + #[motsu::test] + fn safe_transfers_from_with_data(contract: Erc721Consecutive) { + let alice = msg::sender(); + let token_id = random_token_id(); + contract._mint(alice, token_id).expect("should mint a token to Alice"); + + contract + .safe_transfer_from_with_data( + alice, + BOB, + token_id, + vec![0, 1, 2, 3].into(), + ) + .expect("should transfer a token from Alice to Bob"); + + let owner = contract + .owner_of(token_id) + .expect("should return the owner of the token"); + + assert_eq!(owner, BOB); + } + + #[motsu::test] + fn error_when_internal_safe_transfer_to_invalid_receiver( + contract: Erc721Consecutive, + ) { + let alice = msg::sender(); + let token_id = random_token_id(); + let invalid_receiver = Address::ZERO; + + contract._mint(alice, token_id).expect("should mint a token to Alice"); + + let err = contract + ._safe_transfer( + alice, + invalid_receiver, + token_id, + vec![0, 1, 2, 3].into(), + ) + .expect_err("should not transfer the token to invalid receiver"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::InvalidReceiver(ERC721InvalidReceiver { + receiver + })) if receiver == invalid_receiver + )); + + let owner = contract + .owner_of(token_id) + .expect("should return the owner of the token"); + assert_eq!(alice, owner); + } + + #[motsu::test] + fn error_when_internal_safe_transfer_from_incorrect_owner( + contract: Erc721Consecutive, + ) { + let alice = msg::sender(); + let token_id = random_token_id(); + + contract._mint(alice, token_id).expect("should mint a token to Alice"); + + let err = contract + ._safe_transfer(DAVE, BOB, token_id, vec![0, 1, 2, 3].into()) + .expect_err("should not transfer the token from incorrect owner"); + assert!(matches!( + err, + Error::Erc721(erc721::Error::IncorrectOwner(ERC721IncorrectOwner { + sender, + token_id: t_id, + owner + })) if sender == DAVE && t_id == token_id && owner == alice + )); + } + + #[motsu::test] + fn safe_mints(contract: Erc721Consecutive) { + let alice = msg::sender(); + let token_id = random_token_id(); + + let initial_balance = contract + .balance_of(alice) + .expect("should return the balance of Alice"); + + contract + ._safe_mint(alice, token_id, vec![0, 1, 2, 3].into()) + .expect("should mint a token for Alice"); + + let owner = contract + .owner_of(token_id) + .expect("should return the owner of the token"); + assert_eq!(owner, alice); + + let balance = contract + .balance_of(alice) + .expect("should return the balance of Alice"); + + assert_eq!(initial_balance + uint!(1_U256), balance); + } + + #[motsu::test] + fn approves(contract: Erc721Consecutive) { + let alice = msg::sender(); + let token_id = random_token_id(); + contract._mint(alice, token_id).expect("should mint a token"); + contract + .approve(BOB, token_id) + .expect("should approve Bob for operations on token"); + assert_eq!(contract.erc721._token_approvals.get(token_id), BOB); + } + + #[motsu::test] + fn error_when_approve_for_nonexistent_token(contract: Erc721Consecutive) { + let token_id = random_token_id(); + let err = contract + .approve(BOB, token_id) + .expect_err("should not approve for a non-existent token"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::NonexistentToken(ERC721NonexistentToken { + token_id: t_id + })) if token_id == t_id + )); + } + + #[motsu::test] + fn error_when_approve_by_invalid_approver(contract: Erc721Consecutive) { + let token_id = random_token_id(); + contract._mint(BOB, token_id).expect("should mint a token"); + + let err = contract + .approve(DAVE, token_id) + .expect_err("should not approve when invalid approver"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::InvalidApprover(ERC721InvalidApprover { + approver + })) if approver == msg::sender() + )); + } + + #[motsu::test] + fn approval_for_all(contract: Erc721Consecutive) { + let alice = msg::sender(); + contract + .erc721 + ._operator_approvals + .setter(alice) + .setter(BOB) + .set(false); + + contract + .set_approval_for_all(BOB, true) + .expect("should approve Bob for operations on all Alice's tokens"); + assert_eq!(contract.is_approved_for_all(alice, BOB), true); + + contract.set_approval_for_all(BOB, false).expect( + "should disapprove Bob for operations on all Alice's tokens", + ); + assert_eq!(contract.is_approved_for_all(alice, BOB), false); + } + + #[motsu::test] + fn error_when_get_approved_of_nonexistent_token( + contract: Erc721Consecutive, + ) { + let token_id = random_token_id(); + let err = contract + .get_approved(token_id) + .expect_err("should not return approved for a non-existent token"); + + assert!(matches!( + err, + Error::Erc721(erc721::Error::NonexistentToken(ERC721NonexistentToken { + token_id: t_id + })) if token_id == t_id + )); } } diff --git a/contracts/src/token/erc721/extensions/enumerable.rs b/contracts/src/token/erc721/extensions/enumerable.rs index 263f676a..2c5095aa 100644 --- a/contracts/src/token/erc721/extensions/enumerable.rs +++ b/contracts/src/token/erc721/extensions/enumerable.rs @@ -10,11 +10,15 @@ //! [`Erc721Enumerable`]. // TODO: Add link for `Erc721Consecutive` to module docs. -use alloy_primitives::{uint, Address, U256}; +use alloy_primitives::{uint, Address, FixedBytes, U256}; use alloy_sol_types::sol; +use openzeppelin_stylus_proc::interface_id; use stylus_proc::{public, sol_storage, SolidityError}; -use crate::token::{erc721, erc721::IErc721}; +use crate::{ + token::{erc721, erc721::IErc721}, + utils::introspection::erc165::IErc165, +}; sol! { /// Indicates an error when an `owner`'s token query @@ -63,6 +67,7 @@ sol_storage! { /// This is the interface of the optional `Enumerable` extension /// of the ERC-721 standard. +#[interface_id] pub trait IErc721Enumerable { /// The error type associated to this ERC-721 enumerable trait /// implementation. @@ -144,6 +149,13 @@ impl IErc721Enumerable for Erc721Enumerable { } } +impl IErc165 for Erc721Enumerable { + fn supports_interface(interface_id: FixedBytes<4>) -> bool { + ::INTERFACE_ID + == u32::from_be_bytes(*interface_id) + } +} + impl Erc721Enumerable { /// Function to add a token to this extension's /// ownership-tracking data structures. @@ -547,4 +559,11 @@ mod tests { contract.token_of_owner_by_index(alice, U256::ZERO).unwrap_err(); assert!(matches!(err, Error::OutOfBoundsIndex(_))); } + + #[motsu::test] + fn interface_id() { + let actual = ::INTERFACE_ID; + let expected = 0x780e9d63; + assert_eq!(actual, expected); + } } diff --git a/contracts/src/token/erc721/extensions/metadata.rs b/contracts/src/token/erc721/extensions/metadata.rs index 5b315bf4..634d0eda 100644 --- a/contracts/src/token/erc721/extensions/metadata.rs +++ b/contracts/src/token/erc721/extensions/metadata.rs @@ -2,9 +2,11 @@ use alloc::string::String; +use alloy_primitives::FixedBytes; +use openzeppelin_stylus_proc::interface_id; use stylus_proc::{public, sol_storage}; -use crate::utils::Metadata; +use crate::utils::{introspection::erc165::IErc165, Metadata}; sol_storage! { /// Metadata of an [`crate::token::erc721::Erc721`] token. @@ -17,6 +19,7 @@ sol_storage! { } /// Interface for the optional metadata functions from the ERC-721 standard. +#[interface_id] pub trait IErc721Metadata { /// Returns the token collection name. /// @@ -58,3 +61,24 @@ impl IErc721Metadata for Erc721Metadata { self._base_uri.get_string() } } + +impl IErc165 for Erc721Metadata { + fn supports_interface(interface_id: FixedBytes<4>) -> bool { + ::INTERFACE_ID + == u32::from_be_bytes(*interface_id) + } +} + +#[cfg(all(test, feature = "std"))] +mod tests { + // use crate::token::erc721::extensions::{Erc721Metadata, IErc721Metadata}; + + // TODO: IErc721Metadata should be refactored to have same api as solidity + // has: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/4764ea50750d8bda9096e833706beba86918b163/contracts/token/ERC721/extensions/IERC721Metadata.sol#L12 + // [motsu::test] + // fn interface_id() { + // let actual = ::INTERFACE_ID; + // let expected = 0x5b5e139f; + // assert_eq!(actual, expected); + // } +} diff --git a/contracts/src/token/erc721/mod.rs b/contracts/src/token/erc721/mod.rs index 119422f1..84692aef 100644 --- a/contracts/src/token/erc721/mod.rs +++ b/contracts/src/token/erc721/mod.rs @@ -2,6 +2,7 @@ use alloc::vec; use alloy_primitives::{fixed_bytes, uint, Address, FixedBytes, U128, U256}; +use openzeppelin_stylus_proc::interface_id; use stylus_sdk::{ abi::Bytes, alloy_sol_types::sol, @@ -10,7 +11,10 @@ use stylus_sdk::{ prelude::*, }; -use crate::utils::math::storage::{AddAssignUnchecked, SubAssignUnchecked}; +use crate::utils::{ + introspection::erc165::{Erc165, IErc165}, + math::storage::{AddAssignUnchecked, SubAssignUnchecked}, +}; pub mod extensions; @@ -198,6 +202,7 @@ sol_storage! { unsafe impl TopLevelStorage for Erc721 {} /// Required interface of an [`Erc721`] compliant contract. +#[interface_id] pub trait IErc721 { /// The error type associated to this ERC-721 trait implementation. type Error: Into>; @@ -317,6 +322,7 @@ pub trait IErc721 { /// # Events /// /// Emits a [`Transfer`] event. + #[selector(name = "safeTransferFrom")] fn safe_transfer_from_with_data( &mut self, from: Address, @@ -549,6 +555,13 @@ impl IErc721 for Erc721 { } } +impl IErc165 for Erc721 { + fn supports_interface(interface_id: FixedBytes<4>) -> bool { + ::INTERFACE_ID == u32::from_be_bytes(*interface_id) + || Erc165::supports_interface(interface_id) + } +} + impl Erc721 { /// Returns the owner of the `token_id`. Does NOT revert if the token /// doesn't exist. @@ -1153,6 +1166,7 @@ mod tests { ERC721InvalidReceiver, ERC721InvalidSender, ERC721NonexistentToken, Erc721, Error, IErc721, }; + use crate::utils::introspection::erc165::IErc165; const BOB: Address = address!("F4EaCDAbEf3c8f1EdE91b6f2A6840bc2E4DD3526"); const DAVE: Address = address!("0BB78F7e7132d1651B4Fd884B7624394e92156F1"); @@ -1511,9 +1525,7 @@ mod tests { } #[motsu::test] - fn error_when_safe_transfer_from_transfers_to_invalid_receiver( - contract: Erc721, - ) { + fn error_when_safe_transfer_to_invalid_receiver(contract: Erc721) { let alice = msg::sender(); let token_id = random_token_id(); let invalid_receiver = Address::ZERO; @@ -2306,9 +2318,7 @@ mod tests { } #[motsu::test] - fn error_when_safe_transfer_internal_ransfers_to_invalid_receiver( - contract: Erc721, - ) { + fn error_when_internal_safe_transfer_to_invalid_receiver(contract: Erc721) { let alice = msg::sender(); let token_id = random_token_id(); let invalid_receiver = Address::ZERO; @@ -2338,7 +2348,7 @@ mod tests { } #[motsu::test] - fn error_when_safe_transfer_internal_transfers_from_incorrect_owner( + fn error_when_internal_safe_transfer_from_incorrect_owner( contract: Erc721, ) { let alice = msg::sender(); @@ -2366,9 +2376,7 @@ mod tests { } #[motsu::test] - fn error_when_safe_transfer_internal_transfers_nonexistent_token( - contract: Erc721, - ) { + fn error_when_internal_safe_transfer_nonexistent_token(contract: Erc721) { let alice = msg::sender(); let token_id = random_token_id(); let err = contract @@ -2487,4 +2495,15 @@ mod tests { }) if token_id == t_id )); } + + #[motsu::test] + fn interface_id() { + let actual = ::INTERFACE_ID; + let expected = 0x80ac58cd; + assert_eq!(actual, expected); + + let actual = ::INTERFACE_ID; + let expected = 0x01ffc9a7; + assert_eq!(actual, expected); + } } diff --git a/contracts/src/utils/introspection/erc165.rs b/contracts/src/utils/introspection/erc165.rs new file mode 100644 index 00000000..bace2799 --- /dev/null +++ b/contracts/src/utils/introspection/erc165.rs @@ -0,0 +1,64 @@ +//! Trait and implementation of the ERC-165 standard, as defined in the [ERC]. +//! +//! [ERC]: https://eips.ethereum.org/EIPS/eip-165 + +use alloy_primitives::FixedBytes; +use openzeppelin_stylus_proc::interface_id; + +/// Interface of the ERC-165 standard, as defined in the [ERC]. +/// +/// Implementers can declare support of contract interfaces, which others can +/// query. +/// +/// For an implementation, see [`Erc165`]. +/// +/// [ERC]: https://eips.ethereum.org/EIPS/eip-165 +#[interface_id] +pub trait IErc165 { + /// Returns true if this contract implements the interface defined by + /// `interface_id`. See the corresponding [ERC section] + /// to learn more about how these ids are created. + /// + /// Method [`IErc165::supports_interface`] should be reexported with + /// `#[public]` macro manually like this: + /// + /// ```rust,ignore + /// #[public] + /// impl Erc20Example { + /// fn supports_interface(interface_id: FixedBytes<4>) -> bool { + /// Erc20::supports_interface(interface_id) + /// || Erc20Metadata::supports_interface(interface_id) + /// } + /// } + /// ``` + /// + /// # Arguments + /// + /// * `interface_id` - The interface identifier, as specified in [ERC + /// section] + /// + /// [ERC section]: https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified + fn supports_interface(interface_id: FixedBytes<4>) -> bool; +} + +/// Implementation of the [`IErc165`] trait. +/// +/// Contracts that want to support ERC-165 should implement the [`IErc165`] +/// trait for the additional interface id that will be supported and call +/// [`Erc165::supports_interface`] like: +/// +/// ```rust,ignore +/// impl IErc165 for Erc20 { +/// fn supports_interface(interface_id: FixedBytes<4>) -> bool { +/// crate::token::erc20::INTERFACE_ID == u32::from_be_bytes(*interface_id) +/// || Erc165::supports_interface(interface_id) +/// } +/// } +/// ``` +pub struct Erc165; + +impl IErc165 for Erc165 { + fn supports_interface(interface_id: FixedBytes<4>) -> bool { + Self::INTERFACE_ID == u32::from_be_bytes(*interface_id) + } +} diff --git a/contracts/src/utils/introspection/mod.rs b/contracts/src/utils/introspection/mod.rs new file mode 100644 index 00000000..72077bf5 --- /dev/null +++ b/contracts/src/utils/introspection/mod.rs @@ -0,0 +1,2 @@ +//! Stylus contract's introspection helpers library. +pub mod erc165; diff --git a/contracts/src/utils/mod.rs b/contracts/src/utils/mod.rs index 7c24bc20..b8f56cef 100644 --- a/contracts/src/utils/mod.rs +++ b/contracts/src/utils/mod.rs @@ -1,5 +1,6 @@ //! Common Smart Contracts utilities. pub mod cryptography; +pub mod introspection; pub mod math; pub mod metadata; pub mod nonces; diff --git a/examples/erc20/src/lib.rs b/examples/erc20/src/lib.rs index 407e87d0..ace37b5f 100644 --- a/examples/erc20/src/lib.rs +++ b/examples/erc20/src/lib.rs @@ -3,13 +3,13 @@ extern crate alloc; use alloc::vec::Vec; -use alloy_primitives::{Address, U256}; +use alloy_primitives::{Address, FixedBytes, U256}; use openzeppelin_stylus::{ token::erc20::{ extensions::{capped, Capped, Erc20Metadata, IErc20Burnable}, Erc20, IErc20, }, - utils::Pausable, + utils::{introspection::erc165::IErc165, Pausable}, }; use stylus_sdk::prelude::{entrypoint, public, sol_storage}; @@ -105,4 +105,9 @@ impl Erc20Example { self.pausable.when_not_paused()?; self.erc20.transfer_from(from, to, value).map_err(|e| e.into()) } + + fn supports_interface(interface_id: FixedBytes<4>) -> bool { + Erc20::supports_interface(interface_id) + || Erc20Metadata::supports_interface(interface_id) + } } diff --git a/examples/erc20/tests/abi/mod.rs b/examples/erc20/tests/abi/mod.rs index 0e652d26..f042e396 100644 --- a/examples/erc20/tests/abi/mod.rs +++ b/examples/erc20/tests/abi/mod.rs @@ -29,6 +29,8 @@ sol!( #[derive(Debug)] function whenNotPaused() external view; + function supportsInterface(bytes4 interface_id) external view returns (bool supportsInterface); + error EnforcedPause(); error ExpectedPause(); diff --git a/examples/erc20/tests/erc20.rs b/examples/erc20/tests/erc20.rs index cc82c8de..a1301939 100644 --- a/examples/erc20/tests/erc20.rs +++ b/examples/erc20/tests/erc20.rs @@ -1340,3 +1340,50 @@ async fn error_when_transfer_from(alice: Account, bob: Account) -> Result<()> { Ok(()) } + +// ============================================================================ +// Integration Tests: ERC-165 Support Interface +// ============================================================================ + +#[e2e::test] +async fn support_interface(alice: Account) -> Result<()> { + let contract_addr = alice + .as_deployer() + .with_default_constructor::() + .deploy() + .await? + .address()?; + let contract = Erc20::new(contract_addr, &alice.wallet); + let invalid_interface_id: u32 = 0xffffffff; + let Erc20::supportsInterfaceReturn { + supportsInterface: supports_interface, + } = contract.supportsInterface(invalid_interface_id.into()).call().await?; + + assert_eq!(supports_interface, false); + + let erc20_interface_id: u32 = 0x36372b07; + let Erc20::supportsInterfaceReturn { + supportsInterface: supports_interface, + } = contract.supportsInterface(erc20_interface_id.into()).call().await?; + + assert_eq!(supports_interface, true); + + let erc165_interface_id: u32 = 0x01ffc9a7; + let Erc20::supportsInterfaceReturn { + supportsInterface: supports_interface, + } = contract.supportsInterface(erc165_interface_id.into()).call().await?; + + assert_eq!(supports_interface, true); + + let erc20_metadata_interface_id: u32 = 0xa219a025; + let Erc20::supportsInterfaceReturn { + supportsInterface: supports_interface, + } = contract + .supportsInterface(erc20_metadata_interface_id.into()) + .call() + .await?; + + assert_eq!(supports_interface, true); + + Ok(()) +} diff --git a/examples/erc721/src/lib.rs b/examples/erc721/src/lib.rs index 8d2a4d62..3b1c22ef 100644 --- a/examples/erc721/src/lib.rs +++ b/examples/erc721/src/lib.rs @@ -3,13 +3,13 @@ extern crate alloc; use alloc::vec::Vec; -use alloy_primitives::{Address, U256}; +use alloy_primitives::{Address, FixedBytes, U256}; use openzeppelin_stylus::{ token::erc721::{ extensions::{Erc721Enumerable as Enumerable, IErc721Burnable}, Erc721, IErc721, }, - utils::Pausable, + utils::{introspection::erc165::IErc165, Pausable}, }; use stylus_sdk::{ abi::Bytes, @@ -151,4 +151,9 @@ impl Erc721Example { Ok(()) } + + pub fn supports_interface(interface_id: FixedBytes<4>) -> bool { + Erc721::supports_interface(interface_id) + || Enumerable::supports_interface(interface_id) + } } diff --git a/examples/erc721/tests/abi/mod.rs b/examples/erc721/tests/abi/mod.rs index b02f4448..796f4174 100644 --- a/examples/erc721/tests/abi/mod.rs +++ b/examples/erc721/tests/abi/mod.rs @@ -18,8 +18,10 @@ sol!( function setApprovalForAll(address operator, bool approved) external; function totalSupply() external view returns (uint256 totalSupply); function transferFrom(address from, address to, uint256 tokenId) external; + function mint(address to, uint256 tokenId) external; function burn(uint256 tokenId) external; + function paused() external view returns (bool paused); function pause() external; function unpause() external; @@ -27,11 +29,14 @@ sol!( function whenPaused() external view; #[derive(Debug)] function whenNotPaused() external view; + #[derive(Debug)] function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); #[derive(Debug)] function tokenByIndex(uint256 index) external view returns (uint256 tokenId); + function supportsInterface(bytes4 interface_id) external view returns (bool supportsInterface); + error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); error ERC721InsufficientApproval(address operator, uint256 tokenId); error ERC721InvalidApprover(address approver); diff --git a/examples/erc721/tests/erc721.rs b/examples/erc721/tests/erc721.rs index b8bf68fd..f00504a9 100644 --- a/examples/erc721/tests/erc721.rs +++ b/examples/erc721/tests/erc721.rs @@ -2097,3 +2097,45 @@ async fn token_by_index_after_burn_and_some_mints( Ok(()) } + +// ============================================================================ +// Integration Tests: ERC-165 Support Interface +// ============================================================================ + +#[e2e::test] +async fn support_interface(alice: Account) -> eyre::Result<()> { + let contract_addr = alice.as_deployer().deploy().await?.address()?; + let contract = Erc721::new(contract_addr, &alice.wallet); + let invalid_interface_id: u32 = 0x_ffffffff; + let Erc721::supportsInterfaceReturn { + supportsInterface: supports_interface, + } = contract.supportsInterface(invalid_interface_id.into()).call().await?; + + assert_eq!(supports_interface, false); + + let erc721_interface_id: u32 = 0x80ac58cd; + let Erc721::supportsInterfaceReturn { + supportsInterface: supports_interface, + } = contract.supportsInterface(erc721_interface_id.into()).call().await?; + + assert_eq!(supports_interface, true); + + let erc165_interface_id: u32 = 0x01ffc9a7; + let Erc721::supportsInterfaceReturn { + supportsInterface: supports_interface, + } = contract.supportsInterface(erc165_interface_id.into()).call().await?; + + assert_eq!(supports_interface, true); + + let erc721_enumerable_interface_id: u32 = 0x780e9d63; + let Erc721::supportsInterfaceReturn { + supportsInterface: supports_interface, + } = contract + .supportsInterface(erc721_enumerable_interface_id.into()) + .call() + .await?; + + assert_eq!(supports_interface, true); + + Ok(()) +} diff --git a/lib/crypto/Cargo.toml b/lib/crypto/Cargo.toml index 81a44fd8..777aeaca 100644 --- a/lib/crypto/Cargo.toml +++ b/lib/crypto/Cargo.toml @@ -1,9 +1,9 @@ [package] name = "openzeppelin-crypto" -categories = ["cryptography", "algorithms", "no-std", "wasm"] -description = "Cryptography Utilities" +description = "Cryptographic Utilities" edition.workspace = true -keywords.workspace = true +categories = ["cryptography", "algorithms", "no-std", "wasm"] +keywords = ["crypto", "web3", "blockchain", "merkle"] license.workspace = true repository.workspace = true version.workspace = true diff --git a/lib/e2e-proc/Cargo.toml b/lib/e2e-proc/Cargo.toml index c89b39f3..aaa76ad1 100644 --- a/lib/e2e-proc/Cargo.toml +++ b/lib/e2e-proc/Cargo.toml @@ -2,10 +2,11 @@ name = "e2e-proc" description = "End-to-end Testing Procedural Macros" version = "0.1.0" +categories = ["development-tools::testing", "cryptography::cryptocurrencies"] +keywords = ["arbitrum", "ethereum", "stylus", "integration-testing", "tests"] authors.workspace = true edition.workspace = true license.workspace = true -keywords.workspace = true repository.workspace = true [dependencies] diff --git a/lib/e2e/Cargo.toml b/lib/e2e/Cargo.toml index 0c48aa14..84a9c6df 100644 --- a/lib/e2e/Cargo.toml +++ b/lib/e2e/Cargo.toml @@ -2,10 +2,11 @@ name = "e2e" description = "End-to-end Testing for Stylus" version = "0.1.0" +categories = ["development-tools::testing", "cryptography::cryptocurrencies"] +keywords = ["arbitrum", "ethereum", "stylus", "integration-testing", "tests"] authors.workspace = true edition.workspace = true license.workspace = true -keywords.workspace = true repository.workspace = true [dependencies] diff --git a/lib/e2e/src/account.rs b/lib/e2e/src/account.rs index 5e0e9559..83d4cd26 100644 --- a/lib/e2e/src/account.rs +++ b/lib/e2e/src/account.rs @@ -13,6 +13,8 @@ use crate::{ system::{fund_account, Wallet, RPC_URL_ENV_VAR_NAME}, }; +const DEFAULT_FUNDING_ETH: u32 = 100; + /// Type that corresponds to a test account. #[derive(Clone, Debug)] pub struct Account { @@ -23,7 +25,7 @@ pub struct Account { } impl Account { - /// Create a new account. + /// Create a new account with a default funding of [`DEFAULT_FUNDING_ETH`]. /// /// # Errors /// @@ -103,7 +105,7 @@ impl AccountFactory { let signer = PrivateKeySigner::random(); let addr = signer.address(); - fund_account(addr, "100")?; + fund_account(addr, DEFAULT_FUNDING_ETH)?; let rpc_url = std::env::var(RPC_URL_ENV_VAR_NAME) .expect("failed to load RPC_URL var from env") diff --git a/lib/e2e/src/system.rs b/lib/e2e/src/system.rs index aef9ac3e..5d90cd8b 100644 --- a/lib/e2e/src/system.rs +++ b/lib/e2e/src/system.rs @@ -61,7 +61,7 @@ pub fn provider() -> Provider { } /// Send `amount` eth to `address` in the nitro-tesnode. -pub fn fund_account(address: Address, amount: &str) -> eyre::Result<()> { +pub fn fund_account(address: Address, amount: u32) -> eyre::Result<()> { let node_script = get_node_path()?.join("test-node.bash"); if !node_script.exists() { bail!("Test nitro node wasn't setup properly. Try to setup it first with `./scripts/nitro-testnode.sh -i -d`") @@ -73,7 +73,7 @@ pub fn fund_account(address: Address, amount: &str) -> eyre::Result<()> { .arg("--to") .arg(format!("address_{address}")) .arg("--ethamount") - .arg(amount) + .arg(amount.to_string()) .output()?; if !output.status.success() { diff --git a/lib/motsu-proc/Cargo.toml b/lib/motsu-proc/Cargo.toml index 7b172b60..4d009022 100644 --- a/lib/motsu-proc/Cargo.toml +++ b/lib/motsu-proc/Cargo.toml @@ -2,7 +2,8 @@ name = "motsu-proc" description = "Mostu's Procedural Macros" edition.workspace = true -keywords.workspace = true +categories = ["development-tools::testing", "cryptography::cryptocurrencies"] +keywords = ["arbitrum", "ethereum", "stylus", "unit-tests", "tests"] license.workspace = true repository.workspace = true version = "0.1.0" diff --git a/lib/motsu/Cargo.toml b/lib/motsu/Cargo.toml index 57f1f19a..5f3e5958 100644 --- a/lib/motsu/Cargo.toml +++ b/lib/motsu/Cargo.toml @@ -2,7 +2,8 @@ name = "motsu" description = "Unit Testing for Stylus" edition.workspace = true -keywords.workspace = true +categories = ["development-tools::testing", "cryptography::cryptocurrencies"] +keywords = ["arbitrum", "ethereum", "stylus", "unit-tests", "tests"] license.workspace = true repository.workspace = true version = "0.1.0" diff --git a/scripts/bench.sh b/scripts/bench.sh index 8878daec..1801d6c3 100755 --- a/scripts/bench.sh +++ b/scripts/bench.sh @@ -5,9 +5,16 @@ MYDIR=$(realpath "$(dirname "$0")") cd "$MYDIR" cd .. -NIGHTLY_TOOLCHAIN=${NIGHTLY_TOOLCHAIN:-nightly} +NIGHTLY_TOOLCHAIN=${NIGHTLY_TOOLCHAIN:-nightly-2024-01-01} cargo +"$NIGHTLY_TOOLCHAIN" build --release --target wasm32-unknown-unknown -Z build-std=std,panic_abort -Z build-std-features=panic_immediate_abort export RPC_URL=http://localhost:8547 -cargo run --release -p benches + +# No need to compile benchmarks with `--release` +# since this only runs the benchmarking code and the contracts have already been compiled with `--release` +cargo run -p benches + +echo "NOTE: To measure non cached contract's gas usage correctly, + benchmarks should run on a clean instance of the nitro test node." +echo echo "Finished running benches!" diff --git a/scripts/nitro-testnode.sh b/scripts/nitro-testnode.sh index 815323c2..4e807379 100755 --- a/scripts/nitro-testnode.sh +++ b/scripts/nitro-testnode.sh @@ -18,7 +18,14 @@ do shift ;; -q|--quit) - docker container stop $(docker container ls -q --filter name=nitro-testnode) + NITRO_CONTAINERS=$(docker container ls -q --filter name=nitro-testnode) + + if [ -z "$NITRO_CONTAINERS" ]; then + echo "No nitro-testnode containers running" + else + docker container stop $NITRO_CONTAINERS || exit + fi + exit 0 ;; *) @@ -43,8 +50,8 @@ then git clone --recurse-submodules https://github.com/OffchainLabs/nitro-testnode.git cd ./nitro-testnode || exit - # `release` branch. - git checkout 8cb6b84e31909157d431e7e4af9fb83799443e00 || exit + git pull origin release --recurse-submodules + git checkout d4244cd5c2cb56ca3d11c23478ef9642f8ebf472 || exit ./test-node.bash --no-run --init || exit fi