• 批量操作以太坊钱包


    描述
    有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 

  • 相关阅读:
    JVM内存结构
    JVM中的类加载
    数据库索引详解
    Spring IOC 总结
    Java多线程(一)—— 常见问题整理
    Java集合框架 面试问题整理
    Java8 Lambda表达式
    vue开发技巧
    mysql(MariaDB)问题处理
    字符串非空判断的效率问题
  • 原文地址:https://www.cnblogs.com/wtang/p/8911056.html
Copyright © 2020-2023  润新知