tomusdrw / rust-web3

Ethereum JSON-RPC multi-transport client. Rust implementation of web3 library. ENS address: rust-web3.eth
MIT License
1.45k stars 471 forks source link

How to send a transaction signed with privatekey #422

Open Lanjiejie opened 3 years ago

Lanjiejie commented 3 years ago

I want to send a transaction signed with privatekey. And I try to do like this :

let web3 = web3::Web3::new(web3::transports::Http::new("http://localhost:8545")?);
let seckey: secp256k1::key::SecretKey= "4d6f9e640ef9c982f1612e23966c4be3bc7b7105fb77239ca4718a881737ed42".parse().unwrap();
let tx=TransactionParameters{
        to: Some("54aa76ac8c18fc4d268fff1551e6579972a3e192".parse().unwrap()),
        gas: 2_000_000.into(),
        chain_id: Some(10),
        data: Bytes::from(hex!("7ed0c3b2000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000025678000000000000000000000000000000000000000000000000000000000000")),
        ..Default::default()
    };   
let signed = futures::executor::block_on(web3.accounts().sign_transaction(tx, &seckey));

It gives back a SignedTransaction struct, but I don't know how to send it. Could anybody help me? Please give me an example

tomusdrw commented 3 years ago

This should be RLP encoded and passed to Eth::send_raw_transaction. Happy to accept a PR with example showing how to use it or some API change.

ppoliani commented 3 years ago

@Lanjiejie you should simply use the RLP encoded tx to make this work. I think you should be able to do that like this:

let signed = futures::executor::block_on(web3.accounts().sign_transaction(tx, &seckey));
web3.eth().send_raw_transaction(signed.raw_transaction).await
fosres commented 2 years ago

This post helped me make use of the Rust-web3. Thank you to everyone who initiated this discussion.

It is important that we learn how to spend with:

(1) Our own keys. Not your keys. Not your Ethereum.

(2) Our own node. Not your node. Not your rules.

This post quickly captures the essence--though not everything--on how to get both done. Thanks!

ZachEsenbock commented 9 months ago

If you are trying to do this in a Windows environment, be sure to include the "signing" feature. Spent way too long on this haha.

web3 = { version = "0.19.0", default-features = false, features = ["http", "http-tls", "signing"] }