こんにちは、学生ブロックチェーンエンジニアのアカネヤ(@ToshioAkaneya)です。
今回はNode.jsバックエンドでトランザクションを送る方法を解説します。
Node.jsでweb3を使いスマートコントラクトにトランザクションを送る方法
適当なディレクトリを作成し、ターミナルで以下のコマンドを入力して下さい。
1 2 3 |
$ npm init -f $ npm install web3 $ npm install ethereumjs-tx |
そして、main.jsというファイルを作成し、次のように入力して下さい。
なお、今回はERC20トークンのコントラクトを想定してコントラクトに対してtransferを呼び出しています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
const fs = require('fs'); const Web3 = require('web3'); const EthereumTx = require('ethereumjs-tx') const abi = [] // あなたのコントラクトのABI const contractAddress = "コントラクトのアドレス"; const privateKey = Buffer.from('秘密鍵', 'hex') const provider = new Web3.providers.HttpProvider('https://ropsten.infura.io/v3/APIキー'); const web3 = new Web3(provider); const contract = new web3.eth.Contract(abi, contractAddress); const myAddress = 'あなたのアドレス'; const toAddress = '送り先のアドレス'; web3.eth.getTransactionCount(myAddress).then((nonce) => { console.log("Nonce: " + nonce); const amount = web3.utils.toHex(1e16); const rawTransaction = {"from":myAddress, "gasPrice":web3js.utils.toHex(20* 1e9),"gasLimit":web3js.utils.toHex(210000),"to":contractAddress,"value":"0x0","data":contract.methods.transfer(toAddress, amount).encodeABI(),"nonce":web3js.utils.toHex(count)} console.log(rawTransaction); const transaction = new EthereumTx(rawTransaction); transaction.sign(privateKey); web3.eth.sendSignedTransaction('0x' + transaction.serialize().toString('hex')) .on('transactionHash', console.log); contract.methods.balanceOf(myAddress).call() .then(function (balance) { console.log({ balance }) }); }); |
ABI、Infuraキー、秘密鍵、アドレス3つを適切に記入すれば完成です。
ターミナルで
1 |
$ node main.js |
を実行すればNode.jsでトランザクションを送る事ができます。お疲れ様でした。
注意点としては、Nodeのバージョンが8.x系でないと不具合が起こる事があります。
nodebrewを使ってv8.12.0を使うことをおすすめします。