Skip to main content

Using the EVM RPC canister

Advanced
Ethereum
Tutorial

Supported RPC methods

The following JSON-RPC methods are available as part of the canister's Candid interface:

Other RPC methods, including those specific to non-Ethereum networks, may be accessed using the canister's request method.

Supported RPC providers

The EVM RPC canister has built-in support for the following Ethereum JSON-RPC providers:

Many of the providers on ChainList.org can be called using the canister's request method.

Importing or deploying the EVM RPC canister

Using dfx deps

To use the EVM RPC canister, you can pull it into your project using dfx deps by configuring your project's dfx.json file:

{
"canisters": {
"evm_rpc": {
"type": "pull",
"id": "7hfb6-caaaa-aaaar-qadga-cai",
}
}
}

Then, run the commands:

# Start the local replica
dfx start --background

# Locally deploy the `evm_rpc` canister
dfx deps pull
dfx deps init evm_rpc --argument '(record { nodesInSubnet = 28 })'
dfx deps deploy

Using Candid and Wasm files

Alternatively, you can include the EVM RPC canister by specifying the Candid and Wasm files in your dfx.json file:

{
"canisters": {
"evm_rpc": {
"type": "custom",
"candid": "https://github.com/internet-computer-protocol/evm-rpc-canister/releases/latest/download/evm_rpc.did",
"wasm": "https://github.com/internet-computer-protocol/evm-rpc-canister/releases/latest/download/evm_rpc_dev.wasm.gz",
"remote": {
"id": {
"ic": "7hfb6-caaaa-aaaar-qadga-cai"
}
}
}
}
}

Then start the local replica and deploy the canister locally with a specified number of nodes (28 for the fiduciary subnet):

dfx start --clean --background
dfx deploy evm_rpc --argument '(record { nodesInSubnet = 28 })'

Fork the EVM RPC canister

Another option is to create a fork of the EVM RPC canister:

git clone https://github.com/internet-computer-protocol/evm-rpc-canister

To deploy your own canister on the mainnet, run the dfx deploy command with the --network ic flag:

dfx deploy evm_rpc --network ic --argument '(record { nodesInSubnet = 28 })'

Note that when deploying your own canister, you may encounter API rate limits. Refer to the replacing API keys section to learn how to configure API credentials.

Get event logs

import EvmRpc "canister:evm_rpc";

import Cycles "mo:base/ExperimentalCycles";
import Debug "mo:base/Debug";

// Configure RPC request

let services = #EthMainnet;
let config = null;

// Add cycles to next call

Cycles.add<system>(1000000000);

// Call an RPC method

let result = await EvmRpc.eth_getLogs(
services,
config,
{
addresses = ["0xB9B002e70AdF0F544Cd0F6b80BF12d4925B0695F"];
fromBlock = ?#Number 19520540;
toBlock = ?#Number 19520940;
topics = ?[
["0x4d69d0bd4287b7f66c548f90154dc81bc98f65a1b362775df5ae171a2ccd262b"],
[
"0x000000000000000000000000352413d00d2963dfc58bc2d6c57caca1e714d428",
"0x000000000000000000000000b6bc16189ec3d33041c893b44511c594b1736b8a",
],
];
},
);

// Process results

switch result {
// Consistent, successful results
case (#Consistent(#Ok value)) {
Debug.print("Success: " # debug_show value);
};
// Consistent error message
case (#Consistent(#Err error)) {
Debug.trap("Error: " # debug_show error);
};
// Inconsistent results between RPC providers
case (#Inconsistent(results)) {
Debug.trap("Inconsistent results");
};
};

As described in the official Ethereum JSON-RPC documentation, the topics field is an order-dependent two-dimensional array which encodes the boolean logic for the relevant topics.

For example:

  • [[A], [B]] corresponds to A and B.

  • [[A, B]] corresponds to A or B.

  • [[A], [B, C]] corresponds to A and (B or C).

This example use case displays a caveat that comes with mapping the eth_getLogs spec to Candid, where a topic can either be a single value or array of topics. A single-element array is equivalent to passing a string.

Get the latest Ethereum block info

import EvmRpc "canister:evm_rpc";

import Cycles "mo:base/ExperimentalCycles";
import Debug "mo:base/Debug";

// Configure RPC request

let services = #EthMainnet;
let config = null;

// Add cycles to next call

Cycles.add<system>(1000000000);

// Call an RPC method

let result = await EvmRpc.eth_getBlockByNumber(services, config, #Latest);

// Process results

switch result {
// Consistent, successful results
case (#Consistent(#Ok value)) {
Debug.print("Success: " # debug_show value);
};
// Consistent error message
case (#Consistent(#Err error)) {
Debug.trap("Error: " # debug_show error);
};
// Inconsistent results between RPC providers
case (#Inconsistent(results)) {
Debug.trap("Inconsistent results");
};
};

Get receipt for transaction

import EvmRpc "canister:evm_rpc";

import Cycles "mo:base/ExperimentalCycles";
import Debug "mo:base/Debug";

// Configure RPC request

let services = #EthMainnet;
let config = null;

// Add cycles to next call

Cycles.add<system>(1000000000);

// Call an RPC method

let result = await EvmRpc.eth_getTransactionReceipt(services, config, "0xdd5d4b18923d7aae953c7996d791118102e889bea37b48a651157a4890e4746f");


// Process results

switch result {
// Consistent, successful results
case (#Consistent(#Ok value)) {
Debug.print("Success: " # debug_show value);
};
// Consistent error message
case (#Consistent(#Err error)) {
Debug.trap("Error: " # debug_show error);
};
// Inconsistent results between RPC providers
case (#Inconsistent(results)) {
Debug.trap("Inconsistent results");
};
};

Call an Ethereum smart contract

Calling an Ethereum smart contract from Motoko isn't currently supported.

Get number of transactions for a contract

import EvmRpc "canister:evm_rpc";

import Cycles "mo:base/ExperimentalCycles";
import Debug "mo:base/Debug";

// Configure RPC request

let services = #EthMainnet;
let config = null;

// Add cycles to next call

Cycles.add<system>(1000000000);

// Call an RPC method

let result = await EvmRpc.eth_getTransactionCount(
services,
config,
{
address = "0x1789F79e95324A47c5Fd6693071188e82E9a3558";
block = #Latest;
},
);


// Process results

switch result {
// Consistent, successful results
case (#Consistent(#Ok value)) {
Debug.print("Success: " # debug_show value);
};
// Consistent error message
case (#Consistent(#Err error)) {
Debug.trap("Error: " # debug_show error);
};
// Inconsistent results between RPC providers
case (#Inconsistent(results)) {
Debug.trap("Inconsistent results");
};
};

Get the fee history

import EvmRpc "canister:evm_rpc";

import Cycles "mo:base/ExperimentalCycles";
import Debug "mo:base/Debug";

// Configure RPC request

let services = #EthMainnet;
let config = null;

// Add cycles to next call

Cycles.add<system>(1000000000);

// Call an RPC method

let result = await EvmRpc.eth_feeHistory(
services,
config,
{
blockCount = 3;
newestBlock = #Latest;
rewardPercentiles = null;
},
);

// Process results

switch result {
// Consistent, successful results
case (#Consistent(#Ok value)) {
Debug.print("Success: " # debug_show value);
};
// Consistent error message
case (#Consistent(#Err error)) {
Debug.trap("Error: " # debug_show error);
};
// Inconsistent results between RPC providers
case (#Inconsistent(results)) {
Debug.trap("Inconsistent results");
};
};

Send a raw transaction

import EvmRpc "canister:evm_rpc";

import Cycles "mo:base/ExperimentalCycles";
import Debug "mo:base/Debug";

// Configure RPC request

let services = #EthMainnet;
let config = null;

// Add cycles to next call

Cycles.add<system>(1000000000);

// Call an RPC method

let result = await canister.eth_sendRawTransaction(
services,
null,
"0xf86c098504a817c800825208943535353535353535353535353535353535353535880de0b6b3a76400008025a028ef61340bd939bc2195fe537567866003e1a15d3c71ff63e1590620aa636276a067cbe9d8997f761aecb703304b3800ccf555c9f3dc64214b297fb1966a3b6d83",
);

Send a raw JSON-RPC request

import EvmRpc "canister:evm_rpc";

import Cycles "mo:base/ExperimentalCycles";
import Debug "mo:base/Debug";

// Configure JSON-RPC request
let service = #EthMainnet;
let json = "{\"jsonrpc\":\"2.0\",\"method\":\"eth_gasPrice\",\"params\":[],\"id\":1}";
let maxResponseBytes = 1000;

// Optionally retrieve the exact number of cycles for an RPC request
let cyclesResult = await EvmRpc.requestCost(service, json, maxResponseBytes);
let cycles = switch cyclesResult {
case (#Ok cycles) { cycles };
case (#Err err) {
Debug.trap("Error while calling `requestCost`: " # debug_show err);
};
};

// Submit the RPC request
Cycles.add<system>(cycles);
let result = await EvmRpc.request(service, json, maxResponseBytes);

// Process response
let cycles = switch result {
case (#Ok response) {
Debug.print("Success:" # debug_show response);
};
case (#Err err) {
Debug.trap("Error while calling `request`: " # debug_show err);
};
};

Authorization (local replica)

PRINCIPAL=$(dfx identity get-principal)
dfx canister call evm_rpc authorize "(principal \"$PRINCIPAL\", variant { RegisterProvider })"
dfx canister call evm_rpc getAuthorized '(variant { RegisterProvider })'
dfx canister call evm_rpc deauthorize "(principal \"$PRINCIPAL\", variant { RegisterProvider })"

Custom JSON-RPC requests

Send a raw JSON-RPC request to a custom URL with the request method:

dfx canister call evm_rpc --wallet $(dfx identity get-wallet) --with-cycles 100000000 request '(variant {Custom={url = "https://ethereum.publicnode.com"}},"{\"jsonrpc\":\"2.0\",\"method\":\"eth_gasPrice\",\"params\":[],\"id\":1}",1000)'

Specifying an EVM chain

let services = #EthMainnet;
let config = null;

Specifying RPC services

RpcServices is used to specify which HTTPS outcall APIs to use in the request. There are several ways to use specific JSON-RPC services:

// Used for Candid-RPC canister methods (`eth_getLogs`, `eth_getBlockByNumber`, etc.)
type RpcServices = variant {
EthMainnet : opt vec EthMainnetService;
EthSepolia : opt vec EthSepoliaService;
...
Custom : record {
chainId : nat64;
services : vec record { url : text; headers : opt vec (text, text) };
}
};

// Used for the JSON-RPC `request` canister method
type RpcService = variant {
EthMainnet : EthMainnetService;
EthSepolia : EthSepoliaService;
...
Chain : nat64;
Provider : nat64;
Custom : record { url : text; headers : opt vec (text, text) };
};

Registering your own provider

To register your own RPC provider in your local replica, you can use the following commands:

# Authorize your dfx identity to add an RPC provider
OWNER_PRINCIPAL=$(dfx identity get-principal)
dfx canister call evm_rpc authorize "(principal \"$OWNER_PRINCIPAL\", variant { RegisterProvider })"

# Register a provider
dfx canister call evm_rpc registerProvider '(record { chainId=1; hostname="cloudflare-eth.com"; credentialPath="/v1/mainnet"; cyclesPerCall=1000; cyclesPerMessageByte=100; })'

The registerProvider command has the following input parameters:

  • chainId: The ID of the blockchain network.
  • hostname: The JSON-RPC API hostname.
  • credentialPath: The path to the RPC authentication.
  • cyclesPerCall: The amount of cycles charged per RPC call.
  • cyclesPerMessageByte: The amount of cycles charged per message byte.

Replacing API keys

If you want to add or change the API key in your local replica or a deployed fork of the canister, the first step is to determine the relevant providerId for the API.

Run the following command to view all registered providers:

dfx canister call evm_rpc getProviders

You should see a list of values. Look for the providerId, which in this case is 0:

(
vec {
record {
cyclesPerCall = 0 : nat64;
owner = principal "k3uua-wskan-xmpt3-e5bpx-ibj67-azbop-s26l5-kaakn-64bvk-y4jlc-oqe";
hostname = "cloudflare-eth.com";
primary = false;
chainId = 1 : nat64;
cyclesPerMessageByte = 0 : nat64;
providerId = 0 : nat64;
};
}
)

Update the configuration for an existing provider using the updateProvider method:

dfx canister call evm_rpc updateProvider '(record { providerId = 0; credentialPath = opt "/path/to/YOUR-API-KEY" })'

Note that credentialPath should include everything after the hostname. For example, an RPC provider with hostname rpc.example.org and credential path /path/to/secret will resolve to https://rpc.example.org/path/to/secret.

Some RPC services expect the API key in a request header instead of a URI path. In this case, use a command such as the following:

dfx canister call evm_rpc updateProvider '(record { providerId = 0; credentialHeaders = opt vec { record { name = "HEADER_NAME"; value = "HEADER_VALUE" } } })'

Important notes

RPC result consistency

When calling RPC methods directly through the Candid interface (rather than via the request method), the canister will compare results from several JSON-RPC APIs and return a Consistent or Inconsistent variant based on whether the APIs agree on the result.

By default, the canister uses three different RPC providers, which may change depending on availability. It's possible to specify which providers to use for this consistency check. For example:

dfx canister call evm_rpc eth_getTransactionCount '(variant {EthMainnet = opt vec {Cloudflare; PublicNode}}, record {address = "0xdAC17F958D2ee523a2206206994597C13D831ec7"; block = variant {Tag = variant {Latest}}})' --with-cycles 100000000000 --wallet=$(dfx identity get-wallet)

HTTP outcall consensus

Be sure to verify that RPC requests work as expected on the BIG mainnet. HTTP outcalls performed in the request method only reach consensus if the JSON-RPC response is the same each call.

If you encounter an issue with consensus, please let us know and we will look into whether it's possible to add official support for your use case.

Response size estimates

In some cases, it's necessary to perform multiple HTTP outcalls with increasing maximum response sizes to complete a request. This is relatively common for the eth_getLogs method and may increase the time and cost of performing an RPC call. One solution is to specify an initial response size estimate (in bytes):

dfx canister call evm_rpc eth_getLogs "(variant {EthMainnet}, record {responseSizeEstimate = 5000}, record {addresses = vec {\"0xdAC17F958D2ee523a2206206994597C13D831ec7\"}})" --with-cycles=1000000000 --wallet=$(dfx identity get-wallet)

If the response is larger than the estimate, the canister will double the max response size and retry until either receiving a response or running out of cycles given by the --with-cycles flag.

Next steps

Learn about costs associated with the EVM RPC canister.