6
1

More than 5 years have passed since last update.

【Ethereum】署名付きトランザクションの送信【web3.js】

Last updated at Posted at 2018-12-18

Ethereumベースのウォレットの署名付きトランザクションを開発していて、ググってもちょうどいい事例が見つからず試行錯誤して動くようになったので、これからやる人が私と同じ苦しみを味わわずに済むようにここに記しておく。

前提

  • Mac
  • Node.js インストール済み
  • Web3.js インストール済み
  • Ganache インストール済み

上記のインストール事例はネットの海に広がっているので割愛

Ganache上にウォレットを作成してローカルストレージに保存

web3読み込み

import Web3 from 'web3'

Ganacheに接続

Ganacheを起動してね

const web3 = new Web3('http://localhost:7545')

ウォレットを1つ作成

引数はアカウントに対するウォレットの数

const wallet = web3.eth.accounts.wallet.create(1)

ローカルストレージにウォレットを保存

keynameとpasswordは適当

const keyname = 'wallet'
const password = 'walletwallet'
wallet.save(password, keyname)

ローカルストレージからウォレットを読み込んで署名付きトランザクションを送信

ローカルストレージからウォレットを読み込む

保存したときと同じkeynameとpasswordを使う

const keyname = 'wallet'
const password = 'walletwallet'
const wallet = web3.eth.accounts.wallet.load(password, keyname)

署名付きトランザクションを作成

to: 送信先アドレス(Ganacheにデフォルトで作成されてるものでも良い)
value: 1etherをweiに変換
gas: 適当

const signedTx = wallet.signTransaction({
  to: '0x827E07A9652a2CfD7fDa2aa6d1a2fB08bD0cE919',
  value: web3.utils.toWei('1', "ether"),
  gas: 2000000
})

トランザクションを送信

web3.eth.sendSignedTransaction(signedTx.rawTransaction)

まとめ

web3.jsすごい!

それではみなさん良いクリスマスと良いお年を!

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1