Web3.js geth JavaScript実装[Ethereum]


前提

この記事を読み進める前にこちらの記事を読むことをおすすめします。
json-rpc使って、gethを動かしてみた

gethでプライベートネットワーク構築

$ geth --rpc --networkid 15 --nodiscover --datadir "ethereum-rpc" \
 --rpc --rpcaddr "localhost" --rpcport "8545" --rpccorsdomain "*"  \
--rpcapi "eth,net,web3,personal,accounts" console
//このようになったと思います。
<略>
INFO [10-03|11:26:03.816] HTTP endpoint opened  url=http://localhost:8545       cors=* vhosts=localhost
Welcome to the Geth JavaScript console!

instance: Geth/v1.8.14-stable/darwin-amd64/go1.10.3
 modules: admin:1.0 debug:1.0 eth:1.0 ethash:1.0 miner:1.0 net:1.0 personal:1.0 rpc:1.0 txpool:1.0 web3:1.0

立ち上げたままにしておいてください。

アカウント設定・マイニング

geth consoleでの処理

// アカウントの新規作成
> personal.newAccount("hoge")
"0x419973e5e3062e02560d4924174d0172fdf74ab7"
// coinbaseの設定
> miner.setEtherbase(eth.accounts[0])
true
// マイニング
> miner.start()

web3.js (Ethereum JavaScript API)

HTTPやIPCを使ってローカルまたはリモートのイーサリアムノードとやりとり出来るJavaScriptライブラリのことです。

$ npm install web3

まずは、web3を使ってBalanceを取得してみようと思います。

json-rpc.js
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
// addressには、上記で作成したアカウントを入れてください
const address = "0xb710b51683e1a83b66bc2a8934f0cc9ad3d8780a"

web3.eth.getBalance(address).then( balance => {
    console.log(balance)
 });

上のコードがかけたら実行していきます。

$ node json-rpc.js
2400000000000000000000

このようになれば大丈夫です。

Postmanで動作確認

ここからは、Google Chromeの拡張機能であるPostmanを使ってリクエストを送ったらjsonでレスポンスを返すようにしていきます。
上記のコードをこのように書き換えてください。

json-rpc.js
//gethを動かすのに必要
const Web3 = require('web3');
const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
// ここは自分のアカウント
const address = "0xb710b51683e1a83b66bc2a8934f0cc9ad3d8780a"

const express = require('express');
const app = express();
const bodyParser = require('body-parser');

// POSTでdataを受け取るための記述
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

// 3000portを指定
var port = process.env.PORT || 3000;

// expressでAPIサーバを使うための準備
var router = express.Router();

router.use(function(req, res, next) {
    console.log('Something is happening.');
    next();
});

// 正しく実行出来るか左記にアクセスしてテストする (GET http://localhost:3000/api)
router.get('/', function(req, res) {
    res.json({ message: 'Successfully Posted a test message.' });
});

//geth ルート作成
router.route('/geth')
    .post(async function(req, res) {
        try{
            const balance = await eval(req.body.code);
            // res.send({ balance: balance });
            res.send({ balance });

        } catch (e){
            res.send(e);
        }
    })


// ルーティング登録
app.use('/api', router);

//サーバ起動
app.listen(port);
console.log('listen on port ' + port);

そしたら、

$ node json-rpc.js

でサーバを立ち上げてください。

Postmanを立ち上げて、POSTを選び、http://localhost:3000/api/gethを入れたら、
Bodyに、keyにcode,valueにweb3.eth.getBalance("0xb710b51683e1a83b66bc2a8934f0cc9ad3d8780a")
Balance(ここは自分のアカウントを入れてください。)

上記のようになったらSendを押してください。そしたら画像のようにjsonで返ってきます。