Skip to content

LIT-Protocol/pkp-multicall-example

Repository files navigation

PKP Multicall Example

This project demonstrates how to efficiently fetch all PKPs (Programmable Key Pairs) owned by an Ethereum address using Multicall3 to minimize RPC calls.

What it does

The example script fetches all PKP NFTs owned by a given Ethereum address on the Lit Protocol testnet (Chronicle Yellowstone) and retrieves their metadata including:

  • Token IDs
  • Public keys
  • Derived Ethereum addresses

How it works

The script uses only 3 RPC calls to fetch all PKP data, regardless of how many PKPs are owned:

  1. First call: balanceOf() to get the count of PKPs owned
  2. Second call: Multicall3 to batch all tokenOfOwnerByIndex() calls to get all token IDs
  3. Third call: Multicall3 to batch all getPubkey() calls to get the public key for each PKP

This is a significant optimization compared to making individual RPC calls for each PKP, which would require 2N+1 calls (1 for balance, N for token IDs, N for public keys).

Setup

  1. Install dependencies:
npm install
  1. Copy the example environment file and configure it:
cp .env.example .env
  1. Ensure your .env file contains:
  • YELLOWSTONE_RPC_URL: RPC endpoint for Chronicle Yellowstone testnet
  • PKP_NFT_CONTRACT_ADDRESS: Address of the PKP NFT contract
  • MULTICALL3_ADDRESS: Address of the Multicall3 contract
  • EXAMPLE_WALLET_WITH_PKPS: An Ethereum address that owns PKPs

Usage

Run the example:

npm run example

Code Structure

  • getPKPsWithMulticall.ts: Main example script that demonstrates the multicall approach
  • abis/PKPNFTDiamond.json: ABI for the PKP NFT contract
  • abis/Multicall3.json: ABI for the Multicall3 contract

Key Functions Used

PKP NFT Contract

  • balanceOf(address): Get the number of PKPs owned by an address
  • tokenOfOwnerByIndex(address, index): Get the token ID at a specific index for an owner
  • getPubkey(tokenId): Get the public key for a specific PKP

Multicall3

  • aggregate3(calls): Execute multiple contract calls in a single RPC request

Alternative Approach

The PKP NFT contract also provides getPkpInfoFromTokenIds(tokenIds[]) which could fetch all metadata in a single call. However, this function may have issues with large arrays on some networks. The example uses individual getPubkey() calls batched through Multicall3 for better reliability.

Benefits

  • Efficiency: Only 3 RPC calls regardless of PKP count
  • Cost-effective: Reduces RPC usage and associated costs
  • Fast: Parallel execution of all data fetching
  • Reliable: Handles any number of PKPs owned by an address

Requirements

  • Node.js 14+
  • TypeScript
  • Ethers.js v5

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published