Skip to main content
Version: Firesquid

Query the contract state

In order to make on-chain calls, one must set up a websocket JSON-RPC endpoint using setDataSource(). We recommend using a private endpoint from e.g. Infura or Node Real, and set it via an environment variable:

//... 
.setDataSource({
chain: process.env.ETHEREUM_MAINNET_WSS,
archive: 'https://eth.archive.subsquid.io',
})
//...

For local runs, simply update the local .env file and when the squid deployed to Aquarium define at as a secret on your Aquairum account.

Contract class

The EVM contract state is accessed using the Contract class generated by evm-typegen(1). It takes the handler context and the contract address as constructor arguments. The state is always accessed at the context block height unless explicitly defined in the constructor.

For example, assume that we index an ERC721 contract. Then we first run evm-typegen against the ERC721.json ABI file with

npx squid-evm-typegen --abi=src/abi/ERC721.json --output=src/abi/erc721.ts

The generated src/abi/erc721.ts will contain the following section:

src/abi/erc721.ts
export class Contract  {
constructor(ctx: BlockContext, address: string)
constructor(ctx: ChainContext, block: Block, address: string) {
//...
}
private async call(name: string, args: any[]) : Promise<ReadonlyArray<any>> {
//...
}
async balanceOf(owner: string): Promise<ethers.BigNumber> {
return this.call("balanceOf", [owner])
}
}

Now we want to query our contract from the processor handler. To create a Contract pass the context and the current block in the handler. Then the contract state at the given block height is queried in a straightforward way:

// ...
const CONTRACT_ADDRESS= "0xb654611f84a8dc429ba3cb4fda9fad236c505a1a"

processor.run(new TypeormDatabase(), async ctx => {
for (const block of ctx.blocks) {
for (const item of block.items) {
if (item.name === "evmLog") {
const contract = new erc721.Contract(ctx, block, CONTRACT_ADDRESS);
// query the contract state at the current block
const uri = await contract.tokenURI(1137)
}
}
}
})

For more information on EVM Typegen, see this dedicated page.