Skip to content

Commit

Permalink
PR feedback
Browse files Browse the repository at this point in the history
  • Loading branch information
MBerguer committed Apr 22, 2024
1 parent ca4ce4f commit 62fca2d
Showing 1 changed file with 29 additions and 18 deletions.
47 changes: 29 additions & 18 deletions examples/transactions/examples/transfer_sign.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
use alloy::network::{eip2718::Encodable2718, TransactionBuilder};
use alloy::primitives::utils::parse_units;
use alloy::providers::Provider;
//! Example of how to create and sign a transfer with EthereumSigner.
use alloy::{
network::EthereumSigner, node_bindings::Anvil, primitives::U256, providers::ProviderBuilder,
rpc::types::eth::TransactionRequest, signers::wallet::LocalWallet,
network::{eip2718::Encodable2718, EthereumSigner, TransactionBuilder},
node_bindings::Anvil,
primitives::U256,
providers::{Provider, ProviderBuilder},
rpc::types::eth::TransactionRequest,
signers::wallet::LocalWallet,
};
use eyre::Result;

Expand All @@ -13,30 +16,38 @@ async fn main() -> Result<()> {

// Set up signer from the first default Anvil account (Alice).
let signer: LocalWallet = anvil.keys()[0].clone().into();
let destination: LocalWallet = anvil.keys()[1].clone().into();

// Create two users, Alice and Bob.
let alice = anvil.addresses()[0];
let bob = anvil.addresses()[1];

let rpc_url = anvil.endpoint().parse()?;
let provider = ProviderBuilder::new().on_http(rpc_url)?;

let tx = TransactionRequest {
from: Some(signer.address()),
to: Some(destination.address()),
nonce: Some(provider.get_transaction_count(signer.address(), 0.into()).await?),
chain_id: Some(provider.get_chain_id().await?),
value: Some(U256::from(42)),
gas: Some(21000),
max_priority_fee_per_gas: Some(parse_units("0.1", "gwei").unwrap().get_absolute().to()),
max_fee_per_gas: Some(parse_units("30", "gwei").unwrap().get_absolute().to()),
..Default::default()
};

// Build a transaction to send 100 wei from Alice to Bob.
let tx = TransactionRequest::default()
.with_from(alice)
.with_to(bob.into())
.with_nonce(0)
.with_chain_id(provider.get_chain_id().await?)
.with_value(U256::from(100))
.with_gas_limit(21_000)
.with_max_priority_fee_per_gas(1_000_000_000)
.with_max_fee_per_gas(20_000_000_000);

// Build the transaction using the EthereumSigner with the provided signer.
let to_send = tx.build(&EthereumSigner::from(signer)).await?;

// Encode the transaction using EIP-2718 encoding.
let out = to_send.encoded_2718();

// Send the raw transaction and retrieve the transaction receipt.
let receipt = provider.send_raw_transaction(&out).await?.get_receipt().await?;

println!("Send transaction receipt: {receipt:?}");

assert_eq!(receipt.from, alice);
assert_eq!(receipt.to, Some(bob));

Ok(())
}

0 comments on commit 62fca2d

Please sign in to comment.