shengbuchao

shengbuchao

web3 js coder

nodejs transfer ETH

We are going to learn how to transfer ETH transactions using nodejs.

Install Dependencies#

For the basic ETH transfer, you only need to run the following command:

yarn add web3 ethereumjs-tx --dev

To keep everyone in sync, I will provide the version numbers here.

"devDependencies": {
  "web3": "^1.6.0",
  "ethereumjs-tx": "^2.1.2"
}

Initialize web3#

Just like before, apply for a test Ethereum URL from Infura. It's similar to using web3 on the previous page, so I won't go into detail here. Let's look at the code directly.

const Web3 = require('web3')
// const EthereumTx = require('ethereumjs-tx').Transaction

const rpcUrl = "https://goerli.infura.io/v3/your-infura-address"

const web3Provider = new Web3.providers.HttpProvider(rpcUrl)

const web3 = new Web3(web3Provider)

Transfer ETH#

const EthereumTx = require('ethereumjs-tx').Transaction

let currentAddress = '0x3EcAa09DD6B8828607bba4B1d7055Ea1143f8B94'	// The current ETH address being used

const start = async () => {
  // You can try querying the balance
  const balance = await web3.eth.getBalance(currentAddress)
  console.log({balance})
  
  const toAddress = '0xe208D2fB37df02061B78848B83F02b4AD33540e1'
  const privateKey = Buffer.from('your-wallet-private-key', 'hex')
  // Transfer amount in Wei, web3.utils.toWei can convert 1 Ether to Wei
  const amount = web3.utils.toHex(web3.utils.toWei('1', 'ether'))
  const count = await web3.eth.getTransactionCount(currentAddress)
  
  const txParams = {
    from: currentAddress,
    to: toAddress,
    gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')), // 10 Gwei
    gasLimit: web3.utils.toHex(21000),
    value: amount,
    nonce: web3.utils.toHex(count)
  }
  
  const tx = new EthereumTx(txParams, {
    chain: 'goerli'	// ethereumjs-tx requires the chain to be specified, otherwise it will throw an invalid sender error
  })
  
  tx.sign(privateKey)	// Sign the transaction
  
  // Send the signed transaction
  web3.eth.sendSignedTransaction('0x' + tx.serialize().toString('hex'))
        .on('transactionHash', console.log)
        .catch(err => console.log({err}))
}
start()

For the above ethereumjs-tx signing solution, it uses ethereumjs-common and has the following defaults:

  • mainnet
  • ropsten
  • rinkeby
  • kovan
  • goerli (final configuration since v1.1.0)
    You can directly sign transactions for these chains. For other chains, you need to require ethereumjs-common yourself.
const  Common = require('ethereumjs-common').default
const blockchain = Common.forCustomChain(
    'mainnet', {
        name: 'Fantom Opera',
        networkId: 250,
        chainId: 250
    },
    'petersburg'
)

const tx = new EthereumTx(txParams, {
    common: blockchain
})

tx.sign(privateKey)

After execution, if successful, the transactionHash event listener will return a hash. Check if the transaction was successful on the blockchain.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.