以太币转账 #web3 #区块链

210 阅读1分钟

以太币转账 #web3 #区块链

node js

web3

npm install web3 -S

ethereumjs-tx

npm install ethereumjs-tx -S

const Web3 = require('web3')
const Tx = require('ethereumjs-tx')
// 账号
const currentAccount = (loc) => {
  return loc;
}

export const EthTransfer = () => {
	// 以太币转账
	// 先获取当前账号交易的nonce
	web3.eth.getTransactionCount(currentAccount("xxxxxxxxxxx"), web3.eth.defaultBlock.pending).then(function(nonce){
		// 获取交易数据
		const txData = {
		  // nonce每次++,以免覆盖之前pending中的交易
		  nonce: web3.utils.toHex(nonce++),
		  // 设置gasLimit和gasPrice
		  gasLimit: web3.utils.toHex(99000),
		  gasPrice: web3.utils.toHex(10e9),
		  // 要转账的哪个账号
		  to: 'xxxxxxxxxxx',
		  // 从哪个账号转
		  from: currentAccount("xxxxxxxxxx"),
		  // 0.001 以太币
		  value: web3.utils.toHex(web3.utils.toWei('0.001',  'ether')),
		  data: ''
		}
		
		const tx = new Tx(txData)
		// 引入私钥,并转换为16进制
		const privateKey = new Buffer('xxxxxxx', 'hex')
		// 用私钥签署交易
		tx.sign(privateKey)
		// 序列化
		const serializedTx = tx.serialize().toString('hex')
		web3.eth.sendSignedTransaction(serializedTx.toString('hex'), function(err, hash) {
			  if (!err) {
			    alert(hash)
			  } else {
			    alert(err)
			  }
		})
	})
}