LoginSignup
1
3

More than 5 years have passed since last update.

[Ethereum]テストネット上でEthereumをやりとりする

Last updated at Posted at 2018-12-02

Ganacheを用いてテストネットにつなぐ

おなじみのやつ

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

アカウント間でEthereumをやりとりする

テストアカウントを使う

const account1 = 'xxxxxxxxxxxxxxxxxxx'
const account2 = 'xxxxxxxxxxxxxxxxxxx'

アカウント1の残高を見てみる

web3.eth.getBalance(account1, (err, result) => { 
    console.log(result) 
})
> 100000000000000000000

アカウント1からアカウント2に送金する

web3.eth.sendTransaction({
    from: account1,
    to: account2,
    value: web3.utils.toWei('1', 'ether')
})

それぞれの残高を見てみる

web3.eth.getBalance(account1, (err, result) => { 
    console.log(result) 
})
> 98999958000000000000

web3.eth.getBalance(account2, (err, result) => { 
    console.log(result) 
})
> 101000000000000000000

Infuraを用いてテストネットにつなぐ

今回はRopstenでやってみます

Infuraでやりとりするには、ethereumjs-tx というやつが必要らしい。

ご参考
https://noumenon-th.net/programming/2018/06/17/ethereumjs-tx/

app.js
var Tx = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/v3/xxxxxxxxxx')

アカウントを設定する

アドレスと秘密鍵は自分のやつをどうぞ

app.js
const account1 = 'xxxxxxxxxxxxxxxxxxx'
const privateKey1 = Buffer.from('your private key', 'hex')
const account2 = 'xxxxxxxxxxxxxxxxxxx'
const privateKey2 = Buffer.from('your private key', 'hex')

テスト用にEthereumがない人はここでクレクレしてこよう。1日1ETHもらえます。

残高を見てみる

web3.eth.getBalance(account1, (err, balance) => { 
    console.log('account 1 balance:', web3.utils.fromWei(balance, 'ether')) 
})

web3.eth.getBalance(account2, (err, balance) => { 
    console.log('account 2 balance:', web3.utils.fromWei(balance, 'ether')) 
})

> account 1 balance: 1.998581233
> account 2 balance: 0

送金する

ガスの料金とかはいい感じに変えてください

app.js
web3.eth.getTransactionCount(account1, (err, txCount) => {
    // Build the transaction
    const txObject = {
        nonce: web3.utils.toHex(txCount),
        to: account2,
        value: web3.utils.toHex(web3.utils.toWei('1', 'ether')),
        gasLimit: web3.utils.toHex(21000),
        gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei'))
    }

    // Sign the transaction
    const tx = new Tx(txObject)
    tx.sign(privateKey1)

    const serializedTransaction = tx.serialize()
    const row = '0x' + serializedTransaction.toString('hex')

    // Broadcast the transaction
    web3.eth.sendSignedTransaction(row, (err, txHash) => {
        console.log('txHash', txHash)
    })
})

> txHash 0xe33b5408cf03c499f3ebd14a9b7990b06586a67857ea86433a3a0d25b6c4bd76

トランザクションを確認

ばっちり1ETH動きました

1
3
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
1
3