- ローカルで秘密鍵を管理していてる場合、次のような 2 ステップで Ethereum のトランザクションを実行可能です。
- Ethereum のトランザクションの作成から署名まではローカルで行います。
- 署名済みトランザクションは JSON RPC API 等を通じて Ethereum ネットワークに投げます。
ライブラリのインストール
- ethereumjs-txを使用します。
- npm でのインストール
$ npm install ethereumjs-tx
- npm でのインポート
const EthereumTx = require('ethereumjs-tx');
Ethereum のトランザクションを作成
- 0.01 ETH を
0x2890228D4478e2c3B0eBf5a38479E3396C1d6074
に送る例です。
const txParams = { nonce: '0x00', gasPrice: '0x4a817c800', // 20000000000 gasLimit: '0x5208', // 21000 to: '0x2890228D4478e2c3B0eBf5a38479E3396C1d6074', value: '0x2386f26fc10000', // 0.01 data: null, chainId: 3 // mainnet: 1, ropsten: 3 } const tx = new EthereumTx(txParams);
トランザクションに署名
- トランザクションの署名には秘密鍵が必要です。
const privateKey = Buffer.from('61ce8b95ca5fd6f55cd97ac60817777bdf64f1670e903758ce53efc32c3dffeb', 'hex'); tx.sign(privateKey);
トランザクションのバイト列を取得
- シリアライズして16進数のバイト列形式にします。
const serializedTx = tx.serialize(); const signedTx = '0x' + serializedTx.toString('hex');
トランザクションをブロードキャスト
- トランザクションのブロードキャストには、Web3 を使用すると簡単です。
- npm での Web3 のインストール
$ npm install web3
- npm でのインポート
const Web3 = require('Web3');
var web3 = new Web3('wss://ropsten.infura.io/ws'); // Ropsten // var web3 = new Web3('wss://mainnet.infura.io/ws'); // Mainnet web3.eth.sendSignedTransaction(signedTx) .on('transactionHash', function(hash){ console.log(hash); })
実際に作成した署名済みトランザクションのバイト列
0xf86b808504a817c800825208942890228d4478e2c3b0ebf5a38479e3396c1d6074872386f26fc100008029a0520e5053c1b573d747f823a0b23d52e5a619298f46cd781d677d0e5e78fbc750a075be461137c2c2a5594beff76ecb11a215384c574a7e5b620dba5cc63b0a0f13
実際に送信したトランザクション
http://ropsten.etherscan.io/tx/0xf4727b35f10cbe2256b38adcc594f25854a7f16c8461e280079e7003a18d446d