Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: multicall3 support #542

Draft
wants to merge 1 commit into
base: master
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"lint:tests:fix": "eslint -c .eslintrc.js --fix 'packages/**/tests/**/*.{ts,tsx}'",
"format": "prettier --write \"packages/**/src/**/*.ts\" \"packages/**/tests/**/*.ts\"",
"audit:fix": "pnpm audit --fix",
"typecheck": "tsc --noEmit",
"typecheck": "tsc --noEmit --skipLibCheck",
"dev": "preconstruct dev",
"postinstall": "preconstruct dev",
"coverage": "rimraf ./coverage && rimraf ./.nyc_output && nyc pnpm test",
Expand Down
1 change: 1 addition & 0 deletions packages/multicall/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"ethers": "^5.7.2",
"ganache": "^7.5.0",
"json-rpc-engine": "^6.1.0",
"vitest": "^1.6.0",
"web3": "^1.8.1",
"web3-provider-engine": "^16.0.4"
},
Expand Down
4 changes: 3 additions & 1 deletion packages/multicall/src/constants.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
export enum JsonRpcMethod {
ethCall = 'eth_call',
ethGetBalance = 'eth_getBalance',
ethGetCode = 'eth_getCode'
ethGetCode = 'eth_getCode', // not used in multicall3
ethGetChainId = 'eth_chainId',
ethBlockNumber = 'eth_blockNumber',
}
74 changes: 37 additions & 37 deletions packages/multicall/src/multicall.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { BigNumber, ethers } from 'ethers'
import { walletContracts } from '@0xsequence/abi'
import { JsonRpcMethod } from './constants'
import { BlockTag, eqBlockTag, parseBlockTag, partition, safeSolve } from './utils'
import { promisify, getRandomInt } from '@0xsequence/utils'
import { JsonRpcVersion, JsonRpcRequest, JsonRpcResponseCallback, JsonRpcHandlerFunc } from '@0xsequence/network'
import { multicall3Abi } from './multicall3Abi'

export type MulticallOptions = {
// number of calls to enqueue before calling.
Expand Down Expand Up @@ -31,17 +31,22 @@ type QueueEntry = {
const DefaultMulticallOptions = {
batchSize: 50,
timeWindow: 50,
// SequenceUtils: v2
contract: '0xdbbFa3cB3B087B64F4ef5E3D20Dda2488AA244e6',
// https://www.multicall3.com/
contract: '0xcA11bde05977b3631167028862bE2a173976CA11',
verbose: false
}

export class Multicall {
public static DefaultOptions = { ...DefaultMulticallOptions }

readonly batchableJsonRpcMethods = [JsonRpcMethod.ethCall, JsonRpcMethod.ethGetCode, JsonRpcMethod.ethGetBalance]
readonly batchableJsonRpcMethods = [
JsonRpcMethod.ethCall,
JsonRpcMethod.ethGetChainId,
JsonRpcMethod.ethGetBalance,
JsonRpcMethod.ethBlockNumber
]

readonly multicallInterface = new ethers.utils.Interface(walletContracts.sequenceUtils.abi)
readonly multicallInterface = new ethers.utils.Interface(multicall3Abi)

public options: MulticallOptions

Expand Down Expand Up @@ -129,7 +134,6 @@ export class Multicall {
return false
}
case JsonRpcMethod.ethGetBalance:
case JsonRpcMethod.ethGetCode:
// Mixed blockTags
const itemBlockTag = parseBlockTag(item.request.params![1])
if (blockTag === undefined) blockTag = itemBlockTag
Expand Down Expand Up @@ -157,34 +161,31 @@ export class Multicall {
let callParams = items.map(v => {
try {
switch (v.request.method) {
case JsonRpcMethod.ethCall:
case JsonRpcMethod.ethGetChainId:
return {
delegateCall: false,
revertOnError: false,
target: v.request.params![0].to,
data: v.request.params![0].data,
gasLimit: v.request.params![0].gas ? v.request.params![0].gas : 0,
value: 0
allowFailure: true,
target: this.options.contract,
data: this.multicallInterface.encodeFunctionData(this.multicallInterface.getFunction('getChainId'), [])
}
case JsonRpcMethod.ethGetCode:
case JsonRpcMethod.ethBlockNumber:
return {
delegateCall: false,
revertOnError: false,
allowFailure: true,
target: this.options.contract,
gasLimit: 0,
value: 0,
data: this.multicallInterface.encodeFunctionData(this.multicallInterface.getFunction('callCode'), [
v.request.params![0]
])
callData: this.multicallInterface.encodeFunctionData(this.multicallInterface.getFunction('getBlockNumber'), [])
}
case JsonRpcMethod.ethCall:
return {
allowFailure: true,
target: v.request.params![0].to,
callData: v.request.params![0].data,
value: 0
}
case JsonRpcMethod.ethGetBalance:
return {
delegateCall: false,
revertOnError: false,
allowFailure: true,
target: this.options.contract,
gasLimit: 0,
value: 0,
data: this.multicallInterface.encodeFunctionData(this.multicallInterface.getFunction('callBalanceOf'), [
callData: this.multicallInterface.encodeFunctionData(this.multicallInterface.getFunction('getEthBalance'), [
v.request.params![0]
])
}
Expand Down Expand Up @@ -212,8 +213,11 @@ export class Multicall {
// Encode multicall
let encodedCall: string
try {
if (this.options.verbose) console.log('Encoding multicall')
encodedCall = this.multicallInterface.encodeFunctionData(this.multicallInterface.getFunction('multiCall'), [callParams])
if (this.options.verbose) {
console.log('Encoding multicall')
console.log('callParams', callParams)
}
encodedCall = this.multicallInterface.encodeFunctionData(this.multicallInterface.getFunction('aggregate3'), [callParams])
} catch (err) {
if (this.options.verbose) console.warn('Error encoding multicall, forwarding one by one', err)
this.forward(items)
Expand Down Expand Up @@ -261,7 +265,8 @@ export class Multicall {
let decoded: ethers.utils.Result
try {
// @ts-ignore
decoded = this.multicallInterface.decodeFunctionResult(this.multicallInterface.getFunction('multiCall'), res.result)
decoded = this.multicallInterface.decodeFunctionResult(this.multicallInterface.getFunction('aggregate3'), res.result)
if (this.options.verbose) console.log('decoded', decoded)
} catch (err) {
if (this.options.verbose) console.warn('Error decoding multicall result, forwarding one by one', err)
this.forward(items)
Expand All @@ -277,25 +282,20 @@ export class Multicall {
this.forward(item)
} else {
switch (item.request.method) {
case JsonRpcMethod.ethBlockNumber:
case JsonRpcMethod.ethGetChainId:
case JsonRpcMethod.ethCall:
item.callback(undefined, {
jsonrpc: item.request.jsonrpc!,
id: item.request.id!,
result: decoded[1][index]
})
break
case JsonRpcMethod.ethGetCode:
item.callback(undefined, {
jsonrpc: item.request.jsonrpc!,
id: item.request.id!,
result: ethers.utils.defaultAbiCoder.decode(['bytes'], decoded[1][index])[0]
result: decoded.returnData[index].returnData
})
break
case JsonRpcMethod.ethGetBalance:
item.callback(undefined, {
jsonrpc: item.request.jsonrpc!,
id: item.request.id!,
result: ethers.utils.defaultAbiCoder.decode(['uint256'], decoded[1][index])[0]
result: ethers.utils.defaultAbiCoder.decode(['uint256'], decoded.returnData[index].returnData)[0]
})
break
}
Expand Down
33 changes: 33 additions & 0 deletions packages/multicall/src/multicall3.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Contract, providers } from 'ethers';
import { test, expect } from 'vitest';
import { MulticallProvider } from './providers';

test('multicall3', { retry: 0 }, async () => {
const transport = new providers.JsonRpcProvider('https://eth.llamarpc.com');

const provider = new MulticallProvider(transport, {
contract: '0xcA11bde05977b3631167028862bE2a173976CA11',
verbose: false
});

const erc20Abi = [
"function balanceOf(address owner) view returns (uint256)"
];

const usdc = new Contract('0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', erc20Abi, provider);


const results = await Promise.allSettled([
provider.getBlockNumber(),
provider.getBalance("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48"),
usdc.getBalance('0x1000000000000000000100000000000000000000'),
usdc.getBalance('0x2000000000000000000000000000000000000001'),
usdc.getBalance('0x3000000000000000000000000000000000000003'),
usdc.getBalance('0x4000000000000000000000000000000000000004'),
])

for (const result of results) {
expect(result.status).to.equal('fulfilled');
}

})
1 change: 1 addition & 0 deletions packages/multicall/src/multicall3Abi.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const multicall3Abi = [{"inputs":[{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct Multicall3.Call[]","name":"calls","type":"tuple[]"}],"name":"aggregate","outputs":[{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"bytes[]","name":"returnData","type":"bytes[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bool","name":"allowFailure","type":"bool"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct Multicall3.Call3[]","name":"calls","type":"tuple[]"}],"name":"aggregate3","outputs":[{"components":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"bytes","name":"returnData","type":"bytes"}],"internalType":"struct Multicall3.Result[]","name":"returnData","type":"tuple[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bool","name":"allowFailure","type":"bool"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct Multicall3.Call3Value[]","name":"calls","type":"tuple[]"}],"name":"aggregate3Value","outputs":[{"components":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"bytes","name":"returnData","type":"bytes"}],"internalType":"struct Multicall3.Result[]","name":"returnData","type":"tuple[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct Multicall3.Call[]","name":"calls","type":"tuple[]"}],"name":"blockAndAggregate","outputs":[{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"bytes32","name":"blockHash","type":"bytes32"},{"components":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"bytes","name":"returnData","type":"bytes"}],"internalType":"struct Multicall3.Result[]","name":"returnData","type":"tuple[]"}],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"getBasefee","outputs":[{"internalType":"uint256","name":"basefee","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"blockNumber","type":"uint256"}],"name":"getBlockHash","outputs":[{"internalType":"bytes32","name":"blockHash","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getBlockNumber","outputs":[{"internalType":"uint256","name":"blockNumber","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getChainId","outputs":[{"internalType":"uint256","name":"chainid","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentBlockCoinbase","outputs":[{"internalType":"address","name":"coinbase","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentBlockDifficulty","outputs":[{"internalType":"uint256","name":"difficulty","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentBlockGasLimit","outputs":[{"internalType":"uint256","name":"gaslimit","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getCurrentBlockTimestamp","outputs":[{"internalType":"uint256","name":"timestamp","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"getEthBalance","outputs":[{"internalType":"uint256","name":"balance","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getLastBlockHash","outputs":[{"internalType":"bytes32","name":"blockHash","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"requireSuccess","type":"bool"},{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct Multicall3.Call[]","name":"calls","type":"tuple[]"}],"name":"tryAggregate","outputs":[{"components":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"bytes","name":"returnData","type":"bytes"}],"internalType":"struct Multicall3.Result[]","name":"returnData","type":"tuple[]"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"bool","name":"requireSuccess","type":"bool"},{"components":[{"internalType":"address","name":"target","type":"address"},{"internalType":"bytes","name":"callData","type":"bytes"}],"internalType":"struct Multicall3.Call[]","name":"calls","type":"tuple[]"}],"name":"tryBlockAndAggregate","outputs":[{"internalType":"uint256","name":"blockNumber","type":"uint256"},{"internalType":"bytes32","name":"blockHash","type":"bytes32"},{"components":[{"internalType":"bool","name":"success","type":"bool"},{"internalType":"bytes","name":"returnData","type":"bytes"}],"internalType":"struct Multicall3.Result[]","name":"returnData","type":"tuple[]"}],"stateMutability":"payable","type":"function"}] as const
14 changes: 4 additions & 10 deletions packages/multicall/src/providers/provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { JsonRpcVersion, JsonRpcRequest, JsonRpcResponseCallback } from '@0xsequ

export const ProxyMethods = [
'getNetwork',
'getBlockNumber',
'getCode',
'getGasPrice',
'getTransactionCount',
'getStorageAt',
Expand Down Expand Up @@ -63,10 +63,6 @@ export class MulticallProvider extends ethers.providers.BaseProvider {
this.callback(req, callback, await this.provider.call(req.params![0], req.params![1]))
break

case JsonRpcMethod.ethGetCode:
this.callback(req, callback, await this.provider.getCode(req.params![0], req.params![1]))
break

case JsonRpcMethod.ethGetBalance:
this.callback(req, callback, await this.provider.getBalance(req.params![0], req.params![1]))
break
Expand All @@ -92,11 +88,9 @@ export class MulticallProvider extends ethers.providers.BaseProvider {
return this.rpcCall(JsonRpcMethod.ethCall, transaction, blockTag)
}

async getCode(
addressOrName: string | Promise<string>,
blockTag?: string | number | Promise<ethers.providers.BlockTag>
): Promise<string> {
return this.rpcCall(JsonRpcMethod.ethGetCode, addressOrName, blockTag)
async getBlockNumber(): Promise<number> {
const value = await this.rpcCall(JsonRpcMethod.ethBlockNumber);
return Number(value);
}

async getBalance(
Expand Down
Loading