批量操作以太坊錢包


描述
有N個通過一個mnemonic生成的wallet(BIP 39 https://github.com/bitcoin/bips/blob/master/bip-0039.mediawiki),需要把他們的余額都發送到一個wallet

 

思路
通過web3連接到一個安裝好了ethereum node (Parity or Geth) 

https://www.parity.io/
https://geth.ethereum.org/

使用ethereumjs-wallet來管理錢包
使用ethereumjs-tx來簽名tx
最后使用web3發送到Ethereum network中

本地的js庫有

const hdkey = require('ethereumjs-wallet/hdkey')
const utils = require("ethereumjs-util")
const etheTx = require('ethereumjs-tx')
const bip39 = require('bip39')

 

思路詳細描述
通過mnemonic生成seed,生成總wallet,然后生成很多wallet,每個wallet都有priv key,pub key,address

再生成tx

const txParams = {
nonce: '0x'+ nonce.toString(16),
gasPrice: '0x'+ gasPrice.toString(16),
gasLimit: '0x'+ gasLimit.toString(16),
to: toAddress,
value: '0x'+ transfer.toString(16),
chainId: '0x01'
}

特別要注意tx的參數,

nonce是一個錢包地址發送tx的次數,從0開始,即第一次發送是0.第二次發送是1
這個nonce可以從let nonce = web3.eth.getTransactionCount(fromAddr)拿到
拿到之后不要+1了,因為它已經是符合當前交易的nonce了。nonce很重要,因為那些miner節點不會接受nonce值不正確的tx的,比如你這個地址應該是第二次發送,你的nonce值應該是1,當你的nonce值設置了2,那么你的tx永遠不會被miner節點接受,除非你的地址的nonce為1的tx被接受了之后,nonce為2的tx才會被處理。
gasprice,就是gas的單價你願意放多少,平均值可以用etherscan或者ether gas station參考
gaslimit,是你會放多少gas。所以理論上你要抵押的手續費就是gasprice * gaslimit,一些miner會收完這些錢,一些miner會收一部分,返回一部分。具體不展開了。
value就是轉多少錢
data是給ethererum的smart contract編程用的
chainid是1表示mainnet
所有的參數最好用16進制編碼后,轉為string類型,這樣就不會有bignumber問題了

下一步是簽名,用錢包的priv key去簽名tx,證明是我發送的
簽名好了之后再序列化就是個raw tx了,可以發送到ether網絡了

tx.sign(fromWallet.getPrivateKey())
const serializedTx = tx.serialize()
console.log(`${count}: ${fromAddr} has balance ${balance.toNumber()} Wei`)
console.log(`${count}: Raw Tx: 0x${serializedTx.toString('hex')}`)

使用很多ether的門戶網站,比如myetherwallet就可以發送到他們的node上了,我們自己有自己的node,於是用web3的方法發送

web3.eth.sendRawTransaction('0x'+serializedTx.toString('hex') , (err, hash)=>{
if(!err)
{ 
console.log(`Tx hash is: ${hash}, from ${fromAddr} sent ${transfer} Wei to ${toAddress} with gas fee: ${gasPrice} Wei and gas limit: ${gasLimit}`)
}
else{
console.log(`${err}`)
}
})

 

注意事項
因為是N個地址,需要一個一個的發送,所以也是需要控制間隔時間的,在同步環境下使用nodejs的timer來控制

 

 

源碼

tw7613781/eth_transfer 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM