Post

Ganache-Core Notes #1: Adding a custom rpc method

Ganache implements all the rpc methods in lib/subproviders/geth_api_double.js. To add a custom rpc method, one can add a function under GethApiDouble like below:

1
2
3
4
5
6
GethApiDouble.prototype.helloWorld = function(testInput, callback) {
  console.log("Hello World");
  console.log(testInput);

  callback(null, null);
};

The ganache-core will pass in all the arguments along with a end function that would serve as the callback here. callback must be called after all relevant execution are done, otherwise the ganache-core would freeze.

With this implemented into the ganache-core, you could try to invoke it through rpc. I used WebSocket package in nodeJS to do this:

1
2
3
4
5
const ws = new WebSocket('ws://localhost:8545');
// ...
// ...
ws.send('{"jsonrpc":"2.0","id":1,"method":"helloWorld","params":["let us see if it succeeded"]}');

Output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
Gas Price
==================
20000000000

Gas Limit
==================
6721975

Call Gas Limit
==================
9007199254740991

Forked Chain
==================
Location:    undefined
Block:       7869160
Network ID:  3
Time:        Fri May 08 2020 16:46:43 GMT-0400 (Eastern Daylight Time)

Listening on 127.0.0.1:8545
helloWorld
Hello World
let us see if it succeeded

This post is licensed under CC BY 4.0 by the author.