web3.eth.sendSignedTransaction(signedTransactionData [, callback])

1. 发送签名后的交易数据

web3.eth.sendSignedTransaction(signedTransactionData [, callback])

2. 参数 signedTransactionData-String:以HEX格式签名的交易数据

交易数据对象可以包含如下字段:

  • from- String|Number:发送帐户的地址。如果未指定,则使用web3.eth.defaultAccount属性。或web3.eth.accounts.wallet中本地钱包的地址。
  • to- String:(可选)消息的目标地址,若未定义则为合同发送消息。
  • value- Number|String|BN|BigNumber:(可选)为wei中的交易转移的数量,如果是合约发送消息,则是捐赠给合约地址。
  • gas - Number:(可选,默认:待定)用于交易的gas(未使用的gas会退还)。
  • gasPrice- Number|String|BN|BigNumber:(可选)此交易的gas价格,以wei为单位,默认为web3.eth.gasPrice。
  • data- String:(可选)包含合同上函数调用数据的ABI字节字符串。
  • nonce- Number:(可选)随机数的整数。
  • callback-Function:(可选)可选回调,将错误对象作为第一个参数返回,结果作为第二个参数返回。

3. 返回参数 PromiEvent:promise组合的事件,将在交易完成时调用

  • "transactionHash"返回String:在发送事务并且事务哈希可用之后立即触发。
  • "receipt"返回Object:在交易确认时触发。
  • "confirmation"返回Number,Object:每次确认都会被调用,直到第12次确认。接收确认编号作为第一个参数,将数据作为第二个参数。
  • "error"返回Error:如果在发送过程中发生错误,则会触发。

4. 示例demo

var Tx = require('ethereumjs-tx');
var privateKey = new Buffer('e331b6d69882b4cb4ea581d88e0b604039a3de5967688d3dcffdd2270c0fd109', 'hex')

var rawTx = {
  nonce: '0x00',
  gasPrice: '0x09184e72a000',
  gasLimit: '0x2710',
  to: '0x0000000000000000000000000000000000000000',
  value: '0x00',
  data: '0x7f7465737432000000000000000000000000000000000000000000000000000000600057'
}

var tx = new Tx(rawTx);
tx.sign(privateKey);

var serializedTx = tx.serialize();

// console.log(serializedTx.toString('hex'));
// 0xf889808609184e72a00082271094000000000000000000000000000000000000000080a47f74657374320000000000000000000000000000000000000000000000000000006000571ca08a8bbf888cfa37bbf0bb965423625641fc956967b81d12e23709cead01446075a01ce999b56a8a88504be365442ea61239198e23d1fce7d00fcfc5cd3b44b7215f

web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);

> { blockHash: '0xc7e2d6db8a5a5dba40f553b61699e3eedededd90d0651acf59da62d4b94d2247',
  blockNumber: 8858763,
  contractAddress: null,
  cumulativeGasUsed: 218855,
  gasUsed: 21004,
  logs: [],
  logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
  root: null,
  status: true,
  transactionHash: '0xc983ac8c59b7cc74fe23637e6fa8e08b7649b6508d09768cc09abd6d800d9ddf',
  transactionIndex: 2 }

5. 注意事项

  • to字段是转账接收方的地址。
  • nonce字段传入的就是发送方的交易次数的值。
  • value字段传入的是以wei为单位的值,而一般显示的以太币的单位是ether,因此需要调用web3.utils.toWei()方法将单位进行转换。
  • 若是转以太币,则必填字段是to、nonce、gas、value。建议将其它字段都添加上。
let { fromaddress, toaddress, number, privatekey } = ctx.request.body

let nonce = await web3.eth.getTransactionCount(fromaddress)
let gasPrice = await web3.eth.getGasPrice()
let balance = await web3.utils.toWei(number)

var Tx = require('ethereumjs-tx');
var privateKey = new Buffer(privatekey.slice(2), 'hex')

var rawTx = {
    from:fromaddress,
    nonce: nonce,
    gasPrice: gasPrice,
    to: toaddress,
    value: balance,
    data: '0x00'//转Token代币会用到的一个字段
}
//需要将交易的数据进行预估gas计算,然后将gas值设置到数据参数中
let gas = await web3.eth.estimateGas(rawTx)
rawTx.gas = gas
let { success, fail } = require("../utils/myUtils")
let web3 = require("../utils/myUtils").getweb3()

module.exports = {
    ...... 

    sendTransaction: async (ctx) => {
        let { fromaddress, toaddress, number, privatekey } = ctx.request.body
        console.log(JSON.stringify(ctx.request.body))

        let nonce = await web3.eth.getTransactionCount(fromaddress)
        let gasPrice = await web3.eth.getGasPrice()
        let balance = await web3.utils.toWei(number)

        var Tx = require('ethereumjs-tx');
        var privateKey = new Buffer(privatekey.slice(2), 'hex')

        var rawTx = {
            from:fromaddress,
            nonce: nonce,
            gasPrice: gasPrice,
            to: toaddress,
            value: balance,
            data: '0x00'//转Token代币会用到的一个字段
        }
        //需要将交易的数据进行预估gas计算,然后将gas值设置到数据参数中
        let gas = await web3.eth.estimateGas(rawTx)
        rawTx.gas = gas

        var tx = new Tx(rawTx);
        tx.sign(privateKey);

        var serializedTx = tx.serialize();
        let responseData;
        await web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), function(err, data) {
            console.log(err)
            console.log(data)

            if (err) {
                responseData = fail(err)
            }
        })
        .then(function(data) {
            console.log(data)
            if (data) {
                responseData = success({
                    "transactionHash":data.transactionHash
                })
            } else {
                responseData = fail("交易失败")
            }
        })

        ctx.body = responseData
    },
}

你可能感兴趣的:(以太坊)