7个版本

0.2.1 2024年8月2日
0.2.0 2024年7月16日
0.1.4 2024年7月8日
0.1.3 2024年6月25日
0.0.0-保留2024年1月29日

#634 in 魔法豆

Download history 1/week @ 2024-05-20 5/week @ 2024-06-03 4/week @ 2024-06-10 2085/week @ 2024-06-17 3092/week @ 2024-06-24 3141/week @ 2024-07-01 3676/week @ 2024-07-08 5475/week @ 2024-07-15 6766/week @ 2024-07-22 7262/week @ 2024-07-29 10207/week @ 2024-08-05 11256/week @ 2024-08-12

35,930 每月下载量
17 个crate中使用 (5 直接)

MIT/Apache

1.5MB
14K SLoC

alloy-contract

与链上合约交互。

主要类型是 CallBuilder,它是一个用于构造调用链上合约的构建器。它提供了一种对链上调用进行编码和解码数据的方法,并将这些调用发送到链上。请参阅其文档以获取更多详细信息。

用法

结合 sol! 宏的 #[sol(rpc)] 属性,CallBuilder 可以用于与链上合约交互。该属性为合约中的每个返回 CallBuilder 的函数生成一个方法。请参阅其文档以获取更多详细信息。

# async fn test() -> Result<(), Box<dyn std::error::Error>> {
use alloy_contract::SolCallBuilder;
use alloy_network::Ethereum;
use alloy_primitives::{Address, U256};
use alloy_provider::ProviderBuilder;
use alloy_sol_types::sol;

sol! {
    #[sol(rpc)] // <-- Important! Generates the necessary `MyContract` struct and function methods.
    #[sol(bytecode = "0x1234")] // <-- Generates the `BYTECODE` static and the `deploy` method.
    contract MyContract {
        constructor(address) {} // The `deploy` method will also include any constructor arguments.

        #[derive(Debug)]
        function doStuff(uint a, bool b) public payable returns(address c, bytes32 d);
    }
}

// Build a provider.
let provider = ProviderBuilder::new().with_recommended_fillers().on_builtin("https://127.0.0.1:8545").await?;

// If `#[sol(bytecode = "0x...")]` is provided, the contract can be deployed with `MyContract::deploy`,
// and a new instance will be created.
let constructor_arg = Address::ZERO;
let contract = MyContract::deploy(&provider, constructor_arg).await?;

// Otherwise, or if already deployed, a new contract instance can be created with `MyContract::new`.
let address = Address::ZERO;
let contract = MyContract::new(address, &provider);

// Build a call to the `doStuff` function and configure it.
let a = U256::from(123);
let b = true;
let call_builder = contract.doStuff(a, b).value(U256::from(50e18 as u64));

// Send the call. Note that this is not broadcasted as a transaction.
let call_return = call_builder.call().await?;
println!("{call_return:?}"); // doStuffReturn { c: 0x..., d: 0x... }

// Use `send` to broadcast the call as a transaction.
let _pending_tx = call_builder.send().await?;
# Ok(())
# }

依赖项

~26–35MB
~699K SLoC