decentralized-identity / veramo

A JavaScript Framework for Verifiable Data
https://veramo.io
Apache License 2.0
445 stars 133 forks source link

[proposal] Document using a static JsonRpcProvider to avoid burning through call credits with RPC endpoint (e.g. Infura) #1420

Closed pauldesmondparker closed 2 months ago

pauldesmondparker commented 2 months ago

TLDR; Skip to solution at bottom.

Is your feature request related to a problem? Please describe. We have had issues with high volumes of eth_chainid calls with Infura for a while. This was caused by the default JsonRpcProvider assuming that the chainid can change at any time, making repetitive calls to eth_chainid necessary. However, this is not necessary with a RPC endpoint like Infura and acts to burn through the daily call allocation.

Describe the solution you'd like A public and accessible solution to this issue.

Describe alternatives you've considered A PR to the class EthrDIDProvider to make this mandatory, but that would not be appropriate given the different contexts that Veramo can be used in. Even a switch is unnecessary given the solution below.

Solution An explicit option on the JsonRpcProvider is required => { staticNetwork: Network.from(CHAIN_ID)} where CHAIN_ID is either the numerical chain id or the hexadecimal string. And Network is ethers.Network.

import { JsonRpcProvider, Network } from 'ethers';

const SEPOLIA_TESTNET_NAMESPACE = 'sepolia';
const SEPOLIA_TESTNET_PROVIDER = `did:ethr:${SEPOLIA_TESTNET_NAMESPACE}`;
const SEPOLIA_TESTNET_CHAINID = 11155111;
const SEPOLIA_TESTNET_RPC_URL = `https://sepolia.infura.io/v3/${process.env.INFURA_API_KEY}`;

new DIDManager({
  store: new DIDStore(dbConnection),
  defaultProvider: 'did:ethr:sepolia',
  providers: {
    'did:ethr:sepolia': new EthrDIDProvider({
      defaultKms: 'local',
      networks: [
        {
          name: SEPOLIA_TESTNET_NAMESPACE,
          provider: new JsonRpcProvider(
            SEPOLIA_TESTNET_RPC_URL,
            SEPOLIA_TESTNET_CHAINID,
            { staticNetwork: Network.from(SEPOLIA_TESTNET_CHAINID) },  // <<<--- The important part.
          ),
          rpcUrl: SEPOLIA_TESTNET_RPC_URL,
          registry: '0x03d5003bf0e79c5f5223588f347eba39afbc3818',
          chainId: SEPOLIA_TESTNET_CHAINID,
        },
      ],
    }),
  },
});

With the legacy and deprecated (single) network input method:

'did:ethr:sepolia': new EthrDIDProvider({
  defaultKms: 'local',
  network: SEPOLIA_TESTNET_NAMESPACE,
  rpcUrl: SEPOLIA_TESTNET_RPC_URL,
  web3Provider: new JsonRpcProvider(
    SEPOLIA_TESTNET_RPC_URL,
    SEPOLIA_TESTNET_CHAINID,
    { staticNetwork: Network.from(SEPOLIA_TESTNET_CHAINID) },  // <<<--- The important part.
  ),
  registry: '0x03d5003bf0e79c5f5223588f347eba39afbc3818',
}),