当前位置:   article > 正文

web3js 进行转账

node.js服务端使用web3.js调用合约实现两个地址间转账

 1、准备阶段

部署以太坊geth

安装nodejs

npm install web3

npm install 

npm install ethereumjs-tx

其中, web3是1.0.0.beta-36版本

 

2、在部署有geth的机器上,执行node命令, 就入控制台模式,然后逐行执行下面程序: 

  1. const Web3 = require('web3')
  2. const EthereumTx = require('ethereumjs-tx')
  3. const web3 = new Web3( new Web3.providers.HttpProvider('http://47.254.215.233:8145') ) // 服务器RPC地址
  4. web3.eth.defaultAccount = 'af7574a21729d22e119df7456bf913194d73c209' // 发送方地址
  5. let details = {
  6. "to": '0x5cf83df52a32165a7f392168ac009b168c9e8915', // 接收方地址
  7. "value": 4052500000, // 转账多少wei
  8. "gas": 51000, // GAS
  9. "gasPrice": 2 * 1000000000, // GAS PRICE 需要一个比较合理的价格, 不然可能会报错(replacement transaction underpriced)
  10. "gasLimit": '0x420710',
  11. "nonce": 40, // 序号ID, 重要, 需要一个账号的交易序号,可以通过web3.eth.getTransactionCount(web3.eth.defaultAccount)获得
  12. "chainId": 11243575,
  13. "data":'0x40aabbccdd000011223344'
  14. } // 网络ID, 这是区别于具体在哪个网络上
  15. var tx = new EthereumTx(details)
  16. tx.sign( Buffer.from('FC1A5C66932BD7C93E05661A58FD534967739CE517D8695EBBE89135CEE78DA4', 'hex') )
  17. var serializedTx = tx.serialize();
  18. web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex')).on('receipt', console.log);

  

  

输出输出:

Promise {
<pending>,
_events: { receipt: EE { fn: [Function: bound ], context: [Circular], once: false } },
emit: [Function: emit],
on: [Function: on],
once: [Function: once],
off: [Function: removeListener],
listeners: [Function: listeners],
addListener: [Function: on],
removeListener: [Function: removeListener],
removeAllListeners: [Function: removeAllListeners] }

 

最终成功,输出(这里等待了很长时间):

{ blockHash: '0x7a0f412ba0b09dfcfacb826712f4b8e5089e8d1c6d35385d2e29d5dc4400ab37',
blockNumber: 155425,
contractAddress: null,
cumulativeGasUsed: 63000,
from: '0xaf7574a21729d22e119df7456bf913194d73c209',
gasUsed: 21000,
logs: [],
logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
status: true,
to: '0x5cf83df52a32165a7f392168ac009b168c9e8915',
transactionHash: '0x6030b35f4d948a83370d0a759be98820eb72d94623e9d9063fabaab4a9543aed',
transactionIndex: 2 }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/445156
推荐阅读
相关标签
  

闽ICP备14008679号