9

I want to use web3 to call evm_snapshot (only available on testrpc). This is not in web3's list of methods, but I don't want to have to make an actual http call.

3 Answers 3

11

In addition to sendAsync, you can extend web3 like so:

    web3._extend({
        property: 'evm',
        methods: [new web3._extend.Method({
            name: 'snapshot',
            call: 'evm_snapshot',
            params: 0,
            outputFormatter: toIntVal
        })]
    });

    web3._extend({
        property: 'evm',
        methods: [new web3._extend.Method({
            name: 'revert',
            call: 'evm_revert',
            params: 1,
            inputFormatter: [toIntVal]
        })]
    });

That way you can use the command just like any other method, so it's far more readable.

Also, if you don't want to deal with implementing these methods yourself, you can use my extended web3

3
  • Are these documented anywhere?
    – Daniel Que
    Commented Jul 27, 2018 at 20:21
  • 1
    For web3 >1.0.0 web3js.readthedocs.io/en/1.0/web3.html#extend. I don't know if there's docs for web3 <1.0.0, which is what this answer is based on Commented Jul 27, 2018 at 21:46
  • Thanks for the fast reply! Yeah I couldn't find it in 0.20.x. Also can't find sendAsync docs.
    – Daniel Que
    Commented Jul 27, 2018 at 21:52
8

Looks like I can use web3.currentProvider.sendAsync().

web3.currentProvider.sendAsync({
  method: "eth_getBalance",
  params: ['0x407d73d8a49eeb85d32cf465507dd71d507100c1', 'latest'],
  jsonrpc: "2.0",
  id: new Date().getTime()
} function (error, result) {...})
1
  • +1 for dynamic id generation for avoiding collisions.
    – Daniel
    Commented Jul 22, 2018 at 12:14
0

Improving a bit Jehan's answer:

  window.ethereum.sendAsync({
  method: "eth_getBalance",
  params: ['0x407d73d8a49eeb85d32cf465507dd71d507100c1', 'latest'],
  jsonrpc: "2.0",
  id: new Date().getTime()
} , function (error, result){
           console.log(result);
       });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.