Web3-Js:以太坊用ethereumjs-tx庫發送簽名交易

以太坊發送簽名交易

ethereumjs-tx推薦版本1.3.7
直接上代碼:

const Web3 = require('web3');
const Tx = require('ethereumjs-tx');
const web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:8546") ) ;     
var _from = "簽名以太坊賬戶";
var privateKey1 = Buffer.from('對應私鑰','hex');//process.env.PRIVATE_KEY_1
web3.eth.getTransactionCount(_from,(err,txcount)=>{
     var txObject ={
        nonce: web3.utils.toHex(txcount),
        gasPrice: web3.utils.toHex(web3.utils.toWei('10','gwei')),
        gasLimit: web3.utils.toHex(21000),
        to: '對方賬戶',
        value:web3.utils.toHex(web3.utils.toWei('1','ether')),
}
var tx = new Tx(txObject);
tx.sign(privateKey1);
var serializedTx = tx.serialize();

web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
    if (!err){
        console.log(hash);
    }else{
        console.log(err);
    }
});

上面是單純的轉賬交易,下面是把調用合約函數打包成交易發送出去
無論哪一個 ethereumjs-tx版本是重點!!!不然會報錯

const Web3 = require('web3');
const EthereumTx = require('ethereumjs-tx');//因爲ethereum-tx2.0版本實例化需要帶未知參數,目前私有鏈好像行不通,所以npm install [email protected]
const web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:8546") ) ;   

//智能合約地址
const registryAddress = "0xb77065c8adf97e94ca2924c602ac7c3fd92ecdaa"
//智能合約對應Abi文件
var contractAbi = [{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"initialSupply","type":"uint256"},{"name":"tokenName","type":"string"},{"name":"tokenSymbol","type":"string"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","type":"event"}];

//私鑰轉換爲Buffer
const privateKey =  Buffer.from('你的私鑰',"hex")//推薦使用cmd set命令然後env.process導出來
//私鑰轉換爲賬號                
const account = web3.eth.accounts.privateKeyToAccount("0x"+"你的私鑰");
//私鑰對應的賬號地地址
const address = account.address
console.log("address: ",address)

//獲取合約實例
var myContract = new web3.eth.Contract(contractAbi,registryAddress)

//獲取nonce,使用本地私鑰發送交易
web3.eth.getTransactionCount(address).then(
    nonce => {
        console.log("nonce: ",nonce)
        const txParams = {
            nonce: nonce,
            gasLimit: '0x271000',
            to: registryAddress,
            data: myContract.methods.transfer('0x198b2feE780F944F4b9D80e87C59AAe5ee8460bd',1000).encodeABI(), //ERC20轉賬
           
          }
          const tx = new EthereumTx(txParams)
        tx.sign(privateKey)
        const serializedTx = tx.serialize()
        web3.eth.sendSignedTransaction('0x' + serializedTx.toString('hex'))
.on('receipt', console.log);
          
    },
    e => console.log(e)
)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章