Reverse engineering the Web3 API

I've been working on the Web3 API for quite a while now.

The JSON RPC protocol is documented here and the Web3 API is documented here, however, there were limitations I found in the APIs, so last week, I decided to look at porting the Web3js API to Delphi, and removing the limitations at the same time.

Before this, I was writing Javascript, and either executing them in the browser, using Node.js to execute them locally, or using Truffle to test these scripts.

As Node.js does not have a proxy, I wrote my own proxy (instead of using Fiddler, as it wasn't able to intercept the traffic due to some unknown reason) which supported both Web3 and WebSockets, and routed the Web3 Javascripts to point at it, as seen below.

For each call, I wrote a Node.js script, that you see below:

Using the Web provider directly

const Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://rinkeby.infura.io/'));
console.log("blockNumber");
console.log(web3.eth.blockNumber);

Using the local Ethereum provider directly

const Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545/'));
console.log("blockNumber");
console.log(web3.eth.blockNumber);

Using the Web3 proxy

const Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:81/'));
console.log("blockNumber");
console.log(web3.eth.blockNumber);

Getting the accounts:

const Web3 = require('web3');
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:81/'));

console.log("getAccounts");
console.log(web3.eth.accounts);

One of the most challenging parts of this is the ConstructJsonObject method, which takes a name and a variable number of parameters, and wraps them into a JSON object, which would then be passed to the Web3 provider, as the Web3 API provided functionality to call any contract methods.

This was eventually implemented using Delphi's variant open array parameters, so now working on Web3 blockchain projects for me are more enjoyable!

Published Sat, 3 Mar 2018 @ 9:45 PM by chuacw
Related articles: ,