Use NetIdType

idea by @Theo
This commit is contained in:
Tornado Contrib 2024-04-29 00:34:16 +00:00
parent 5eb3a310c5
commit 0d8c3cc7a4
Signed by: tornadocontrib
GPG Key ID: 60B4DF1A076C64B1
10 changed files with 93 additions and 76 deletions

@ -28,7 +28,6 @@ import {
ZeroAddress, ZeroAddress,
MaxUint256, MaxUint256,
Transaction, Transaction,
BigNumberish,
getAddress, getAddress,
} from 'ethers'; } from 'ethers';
import type MerkleTree from '@tornado/fixed-merkle-tree'; import type MerkleTree from '@tornado/fixed-merkle-tree';
@ -73,6 +72,8 @@ import {
Invoice, Invoice,
fetchData, fetchData,
fetchDataOptions, fetchDataOptions,
NetId,
NetIdType,
getInstanceByAddress, getInstanceByAddress,
getSubdomains, getSubdomains,
getConfig, getConfig,
@ -87,7 +88,7 @@ import {
const DEFAULT_GAS_LIMIT = Number(process.env.DEFAULT_GAS_LIMIT) || 600_000; const DEFAULT_GAS_LIMIT = Number(process.env.DEFAULT_GAS_LIMIT) || 600_000;
const RELAYER_NETWORK = Number(process.env.RELAYER_NETWORK) || 1; const RELAYER_NETWORK = Number(process.env.RELAYER_NETWORK) || NetId.MAINNET;
// Where cached events, trees, circuits, and key is saved // Where cached events, trees, circuits, and key is saved
const STATIC_DIR = process.env.CACHE_DIR || path.join(__dirname, '../static'); const STATIC_DIR = process.env.CACHE_DIR || path.join(__dirname, '../static');
@ -231,7 +232,7 @@ export function getProgramGraphAPI(options: commonProgramOptions, config: Config
} }
export function getProgramProvider( export function getProgramProvider(
netId: BigNumberish, netId: NetIdType,
rpcUrl: string = '', rpcUrl: string = '',
config: Config, config: Config,
providerOptions?: getProviderOptions, providerOptions?: getProviderOptions,
@ -270,7 +271,7 @@ export async function getProgramRelayer({
}: { }: {
options: commonProgramOptions; options: commonProgramOptions;
fetchDataOptions?: fetchDataOptions; fetchDataOptions?: fetchDataOptions;
netId: number | string; netId: NetIdType;
}): Promise<{ }): Promise<{
validRelayers?: RelayerInfo[] | Relayer[]; validRelayers?: RelayerInfo[] | Relayer[];
invalidRelayers?: RelayerError[]; invalidRelayers?: RelayerError[];
@ -458,7 +459,7 @@ export function tornadoProgram() {
.argument('<netId>', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber) .argument('<netId>', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber)
.argument('<currency>', 'Currency to deposit on Tornado Cash') .argument('<currency>', 'Currency to deposit on Tornado Cash')
.argument('<amount>', 'Amount to deposit on Tornado Cash') .argument('<amount>', 'Amount to deposit on Tornado Cash')
.action(async (netId: string | number, currency: string, amount: string) => { .action(async (netId: NetIdType, currency: string, amount: string) => {
currency = currency.toLowerCase(); currency = currency.toLowerCase();
const config = getConfig(netId); const config = getConfig(netId);
@ -518,7 +519,7 @@ export function tornadoProgram() {
.argument('<netId>', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber) .argument('<netId>', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber)
.argument('<currency>', 'Currency to deposit on Tornado Cash') .argument('<currency>', 'Currency to deposit on Tornado Cash')
.argument('<amount>', 'Amount to deposit on Tornado Cash') .argument('<amount>', 'Amount to deposit on Tornado Cash')
.action(async (netId: string | number, currency: string, amount: string, cmdOptions: commonProgramOptions) => { .action(async (netId: NetIdType, currency: string, amount: string, cmdOptions: commonProgramOptions) => {
const { options, fetchDataOptions } = await getProgramOptions(cmdOptions); const { options, fetchDataOptions } = await getProgramOptions(cmdOptions);
currency = currency.toLowerCase(); currency = currency.toLowerCase();
const { rpc, accountKey } = options; const { rpc, accountKey } = options;
@ -1267,11 +1268,7 @@ export function tornadoProgram() {
.argument('[netId]', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber) .argument('[netId]', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber)
.argument('[currency]', 'Currency to sync events') .argument('[currency]', 'Currency to sync events')
.action( .action(
async ( async (netIdOpts: NetIdType | undefined, currencyOpts: string | undefined, cmdOptions: commonProgramOptions) => {
netIdOpts: number | string | undefined,
currencyOpts: string | undefined,
cmdOptions: commonProgramOptions,
) => {
const { options, fetchDataOptions } = await getProgramOptions(cmdOptions); const { options, fetchDataOptions } = await getProgramOptions(cmdOptions);
const { rpc } = options; const { rpc } = options;
@ -1439,7 +1436,7 @@ export function tornadoProgram() {
.command('relayers') .command('relayers')
.description('List all registered relayers from the tornado cash registry.\n\n') .description('List all registered relayers from the tornado cash registry.\n\n')
.argument('<netId>', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber) .argument('<netId>', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber)
.action(async (netIdOpts: number | string, cmdOptions: commonProgramOptions) => { .action(async (netIdOpts: NetIdType, cmdOptions: commonProgramOptions) => {
const { options, fetchDataOptions } = await getProgramOptions(cmdOptions); const { options, fetchDataOptions } = await getProgramOptions(cmdOptions);
const allRelayers = await getProgramRelayer({ const allRelayers = await getProgramRelayer({
@ -1507,7 +1504,7 @@ export function tornadoProgram() {
'Requires a valid signable wallet (mnemonic or a private key) to work (Since they would encrypt or encrypted)', 'Requires a valid signable wallet (mnemonic or a private key) to work (Since they would encrypt or encrypted)',
) )
.argument('<netId>', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber) .argument('<netId>', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber)
.action(async (netId: string | number, cmdOptions: commonProgramOptions) => { .action(async (netId: NetIdType, cmdOptions: commonProgramOptions) => {
const { options, fetchDataOptions } = await getProgramOptions(cmdOptions); const { options, fetchDataOptions } = await getProgramOptions(cmdOptions);
const { rpc } = options; const { rpc } = options;
@ -1624,7 +1621,7 @@ export function tornadoProgram() {
'Account key generated from UI or the createAccount to store encrypted notes on-chain', 'Account key generated from UI or the createAccount to store encrypted notes on-chain',
parseRecoveryKey, parseRecoveryKey,
) )
.action(async (netId: string | number, accountKey: string | undefined, cmdOptions: commonProgramOptions) => { .action(async (netId: NetIdType, accountKey: string | undefined, cmdOptions: commonProgramOptions) => {
const { options, fetchDataOptions } = await getProgramOptions(cmdOptions); const { options, fetchDataOptions } = await getProgramOptions(cmdOptions);
const { rpc } = options; const { rpc } = options;
if (!accountKey) { if (!accountKey) {
@ -1701,7 +1698,7 @@ export function tornadoProgram() {
.argument('[token]', 'ERC20 Token Contract to check Token Balance', parseAddress) .argument('[token]', 'ERC20 Token Contract to check Token Balance', parseAddress)
.action( .action(
async ( async (
netId: string | number, netId: NetIdType,
to: string, to: string,
amountArgs: number | undefined, amountArgs: number | undefined,
tokenArgs: string | undefined, tokenArgs: string | undefined,
@ -1838,7 +1835,7 @@ export function tornadoProgram() {
.argument('[token]', 'ERC20 Token Contract to check Token Balance', parseAddress) .argument('[token]', 'ERC20 Token Contract to check Token Balance', parseAddress)
.action( .action(
async ( async (
netId: string | number, netId: NetIdType,
addressArgs: string | undefined, addressArgs: string | undefined,
tokenArgs: string | undefined, tokenArgs: string | undefined,
cmdOptions: commonProgramOptions, cmdOptions: commonProgramOptions,

@ -1,10 +1,11 @@
import { bnToBytes, bytesToBN, leBuff2Int, leInt2Buff, rBigInt, toFixedHex } from './utils'; import { bnToBytes, bytesToBN, leBuff2Int, leInt2Buff, rBigInt, toFixedHex } from './utils';
import { buffPedersenHash } from './pedersen'; import { buffPedersenHash } from './pedersen';
import type { NetIdType } from './networkConfig';
export type DepositType = { export type DepositType = {
currency: string; currency: string;
amount: string; amount: string;
netId: string | number; netId: NetIdType;
}; };
export type createDepositParams = { export type createDepositParams = {
@ -61,7 +62,7 @@ export async function createDeposit({ nullifier, secret }: createDepositParams):
export interface DepositConstructor { export interface DepositConstructor {
currency: string; currency: string;
amount: string; amount: string;
netId: number; netId: NetIdType;
nullifier: bigint; nullifier: bigint;
secret: bigint; secret: bigint;
note: string; note: string;
@ -74,7 +75,7 @@ export interface DepositConstructor {
export class Deposit { export class Deposit {
currency: string; currency: string;
amount: string; amount: string;
netId: number; netId: NetIdType;
nullifier: bigint; nullifier: bigint;
secret: bigint; secret: bigint;
@ -148,7 +149,7 @@ export class Deposit {
const newDeposit = new Deposit({ const newDeposit = new Deposit({
currency: currency.toLowerCase(), currency: currency.toLowerCase(),
amount: amount, amount: amount,
netId: Number(netId), netId,
note: `tornado-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.noteHex}`, note: `tornado-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.noteHex}`,
noteHex: depositObject.noteHex, noteHex: depositObject.noteHex,
invoice: `tornadoInvoice-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.commitmentHex}`, invoice: `tornadoInvoice-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.commitmentHex}`,
@ -182,14 +183,14 @@ export class Deposit {
const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${depositObject.commitmentHex}`; const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${depositObject.commitmentHex}`;
const newDeposit = new Deposit({ const newDeposit = new Deposit({
currency: currency, currency,
amount: amount, amount,
netId: netId, netId,
note: noteString, note: noteString,
noteHex: depositObject.noteHex, noteHex: depositObject.noteHex,
invoice: invoice, invoice,
nullifier: nullifier, nullifier,
secret: secret, secret,
commitmentHex: depositObject.commitmentHex, commitmentHex: depositObject.commitmentHex,
nullifierHex: depositObject.nullifierHex, nullifierHex: depositObject.nullifierHex,
}); });
@ -205,7 +206,7 @@ export type parsedInvoiceExec = DepositType & {
export class Invoice { export class Invoice {
currency: string; currency: string;
amount: string; amount: string;
netId: number; netId: NetIdType;
commitment: string; commitment: string;
invoice: string; invoice: string;

@ -3,6 +3,7 @@ import { Echoer } from '@tornado/contracts';
import { Wallet, computeAddress, getAddress } from 'ethers'; import { Wallet, computeAddress, getAddress } from 'ethers';
import { crypto, base64ToBytes, bytesToBase64, bytesToHex, hexToBytes, toFixedHex, concatBytes } from './utils'; import { crypto, base64ToBytes, bytesToBase64, bytesToHex, hexToBytes, toFixedHex, concatBytes } from './utils';
import { EchoEvents, EncryptedNotesEvents } from './events'; import { EchoEvents, EncryptedNotesEvents } from './events';
import type { NetIdType } from './networkConfig';
export interface NoteToEncrypt { export interface NoteToEncrypt {
address: string; address: string;
@ -43,7 +44,7 @@ export function unpackEncryptedMessage(encryptedMessage: string) {
} }
export interface NoteAccountConstructor { export interface NoteAccountConstructor {
netId: string | number; netId: NetIdType;
blockNumber?: number; blockNumber?: number;
// hex // hex
recoveryKey?: string; recoveryKey?: string;
@ -51,7 +52,7 @@ export interface NoteAccountConstructor {
} }
export class NoteAccount { export class NoteAccount {
netId: number; netId: NetIdType;
blockNumber?: number; blockNumber?: number;
// Dedicated 32 bytes private key only used for note encryption, backed up to an Echoer and local for future derivation // Dedicated 32 bytes private key only used for note encryption, backed up to an Echoer and local for future derivation
// Note that unlike the private key it shouldn't have the 0x prefix // Note that unlike the private key it shouldn't have the 0x prefix

@ -16,6 +16,7 @@ import {
BatchBlockOnProgress, BatchBlockOnProgress,
} from '../batch'; } from '../batch';
import { fetchDataOptions } from '../providers'; import { fetchDataOptions } from '../providers';
import type { NetIdType } from '../networkConfig';
import type { import type {
BaseEvents, BaseEvents,
MinimalEvents, MinimalEvents,
@ -36,7 +37,7 @@ export const DEPOSIT = 'deposit';
export const WITHDRAWAL = 'withdrawal'; export const WITHDRAWAL = 'withdrawal';
export type BaseEventsServiceConstructor = { export type BaseEventsServiceConstructor = {
netId: number | string; netId: NetIdType;
provider: Provider; provider: Provider;
graphApi?: string; graphApi?: string;
subgraphName?: string; subgraphName?: string;
@ -66,7 +67,7 @@ export type BaseGraphParams = {
}; };
export class BaseEventsService<EventType extends MinimalEvents> { export class BaseEventsService<EventType extends MinimalEvents> {
netId: number | string; netId: NetIdType;
provider: Provider; provider: Provider;
graphApi?: string; graphApi?: string;
subgraphName?: string; subgraphName?: string;
@ -324,7 +325,7 @@ export class BaseEventsService<EventType extends MinimalEvents> {
} }
export type BaseDepositsServiceConstructor = { export type BaseDepositsServiceConstructor = {
netId: number | string; netId: NetIdType;
provider: Provider; provider: Provider;
graphApi?: string; graphApi?: string;
subgraphName?: string; subgraphName?: string;
@ -464,7 +465,7 @@ export class BaseDepositsService extends BaseEventsService<DepositsEvents | With
} }
export type BaseEchoServiceConstructor = { export type BaseEchoServiceConstructor = {
netId: number | string; netId: NetIdType;
provider: Provider; provider: Provider;
graphApi?: string; graphApi?: string;
subgraphName?: string; subgraphName?: string;
@ -534,7 +535,7 @@ export class BaseEchoService extends BaseEventsService<EchoEvents> {
} }
export type BaseEncryptedNotesServiceConstructor = { export type BaseEncryptedNotesServiceConstructor = {
netId: number | string; netId: NetIdType;
provider: Provider; provider: Provider;
graphApi?: string; graphApi?: string;
subgraphName?: string; subgraphName?: string;
@ -591,7 +592,7 @@ export class BaseEncryptedNotesService extends BaseEventsService<EncryptedNotesE
} }
export type BaseGovernanceServiceConstructor = { export type BaseGovernanceServiceConstructor = {
netId: number | string; netId: NetIdType;
provider: Provider; provider: Provider;
graphApi?: string; graphApi?: string;
subgraphName?: string; subgraphName?: string;
@ -733,7 +734,7 @@ export class BaseGovernanceService extends BaseEventsService<AllGovernanceEvents
} }
export type BaseRegistryServiceConstructor = { export type BaseRegistryServiceConstructor = {
netId: number | string; netId: NetIdType;
provider: Provider; provider: Provider;
graphApi?: string; graphApi?: string;
subgraphName?: string; subgraphName?: string;

@ -5,6 +5,7 @@ import { isNode, toFixedHex } from './utils';
import { mimc } from './mimc'; import { mimc } from './mimc';
import type { DepositType } from './deposits'; import type { DepositType } from './deposits';
import type { DepositsEvents } from './events'; import type { DepositsEvents } from './events';
import type { NetIdType } from './networkConfig';
export type MerkleTreeConstructor = DepositType & { export type MerkleTreeConstructor = DepositType & {
Tornado: Tornado; Tornado: Tornado;
@ -17,7 +18,7 @@ export type MerkleTreeConstructor = DepositType & {
export class MerkleTreeService { export class MerkleTreeService {
currency: string; currency: string;
amount: string; amount: string;
netId: number; netId: NetIdType;
Tornado: Tornado; Tornado: Tornado;
commitmentHex?: string; commitmentHex?: string;
instanceName: string; instanceName: string;

@ -1,3 +1,19 @@
/**
* Type of default supported networks
*/
export enum NetId {
MAINNET = 1,
BSC = 56,
POLYGON = 137,
OPTIMISM = 10,
ARBITRUM = 42161,
GNOSIS = 100,
AVALANCHE = 43114,
SEPOLIA = 11155111,
}
export type NetIdType = NetId | number;
export interface RpcUrl { export interface RpcUrl {
name: string; name: string;
url: string; url: string;
@ -85,7 +101,7 @@ export type Config = {
}; };
export type networkConfig = { export type networkConfig = {
[key in string]: Config; [key in NetIdType]: Config;
}; };
const theGraph = { const theGraph = {
@ -98,7 +114,7 @@ const tornado = {
}; };
export const defaultConfig: networkConfig = { export const defaultConfig: networkConfig = {
netId1: { [NetId.MAINNET]: {
rpcCallRetryAttempt: 15, rpcCallRetryAttempt: 15,
gasPrices: { gasPrices: {
instant: 80, instant: 80,
@ -246,7 +262,7 @@ export const defaultConfig: networkConfig = {
MINING_BLOCK_TIME: 15, MINING_BLOCK_TIME: 15,
}, },
}, },
netId56: { [NetId.BSC]: {
rpcCallRetryAttempt: 15, rpcCallRetryAttempt: 15,
gasPrices: { gasPrices: {
instant: 5, instant: 5,
@ -311,7 +327,7 @@ export const defaultConfig: networkConfig = {
ENCRYPTED_NOTES_BLOCK: 8159269, ENCRYPTED_NOTES_BLOCK: 8159269,
}, },
}, },
netId137: { [NetId.POLYGON]: {
rpcCallRetryAttempt: 15, rpcCallRetryAttempt: 15,
gasPrices: { gasPrices: {
instant: 100, instant: 100,
@ -369,7 +385,7 @@ export const defaultConfig: networkConfig = {
ENCRYPTED_NOTES_BLOCK: 16257996, ENCRYPTED_NOTES_BLOCK: 16257996,
}, },
}, },
netId10: { [NetId.OPTIMISM]: {
rpcCallRetryAttempt: 15, rpcCallRetryAttempt: 15,
gasPrices: { gasPrices: {
instant: 0.001, instant: 0.001,
@ -435,7 +451,7 @@ export const defaultConfig: networkConfig = {
ENCRYPTED_NOTES_BLOCK: 2243694, ENCRYPTED_NOTES_BLOCK: 2243694,
}, },
}, },
netId42161: { [NetId.ARBITRUM]: {
rpcCallRetryAttempt: 15, rpcCallRetryAttempt: 15,
gasPrices: { gasPrices: {
instant: 4, instant: 4,
@ -500,7 +516,7 @@ export const defaultConfig: networkConfig = {
ENCRYPTED_NOTES_BLOCK: 3430605, ENCRYPTED_NOTES_BLOCK: 3430605,
}, },
}, },
netId100: { [NetId.GNOSIS]: {
rpcCallRetryAttempt: 15, rpcCallRetryAttempt: 15,
gasPrices: { gasPrices: {
instant: 6, instant: 6,
@ -565,7 +581,7 @@ export const defaultConfig: networkConfig = {
ENCRYPTED_NOTES_BLOCK: 17754564, ENCRYPTED_NOTES_BLOCK: 17754564,
}, },
}, },
netId43114: { [NetId.AVALANCHE]: {
rpcCallRetryAttempt: 15, rpcCallRetryAttempt: 15,
gasPrices: { gasPrices: {
instant: 225, instant: 225,
@ -620,7 +636,7 @@ export const defaultConfig: networkConfig = {
ENCRYPTED_NOTES_BLOCK: 4429813, ENCRYPTED_NOTES_BLOCK: 4429813,
}, },
}, },
netId11155111: { [NetId.SEPOLIA]: {
rpcCallRetryAttempt: 15, rpcCallRetryAttempt: 15,
gasPrices: { gasPrices: {
instant: 2, instant: 2,
@ -698,7 +714,7 @@ export const defaultConfig: networkConfig = {
}, },
}; };
export const enabledChains = ['1', '10', '56', '100', '137', '42161', '43114', '11155111']; export const enabledChains = Object.values(NetId) as NetIdType[];
/** /**
* Custom config object to extend default config * Custom config object to extend default config
@ -711,12 +727,12 @@ export let customConfig: networkConfig = {};
/** /**
* Add or override existing network config object * Add or override existing network config object
* *
* Could be also called on the UI hook so that the UI could allow people to use privacy pools that it hasn't deployed * Could be also called on the UI hook so that the UI could allow people to use custom privacy pools
*/ */
export function addNetwork(newConfig: networkConfig) { export function addNetwork(newConfig: networkConfig) {
enabledChains.push( enabledChains.push(
...Object.keys(newConfig) ...Object.keys(newConfig)
.map((netId) => netId.replace('netId', '')) .map((netId) => Number(netId))
.filter((netId) => !enabledChains.includes(netId)), .filter((netId) => !enabledChains.includes(netId)),
); );
@ -734,25 +750,25 @@ export function getNetworkConfig(): networkConfig {
}; };
return enabledChains.reduce((acc, curr) => { return enabledChains.reduce((acc, curr) => {
acc[`netId${curr}`] = allConfig[`netId${curr}`]; acc[curr] = allConfig[curr];
return acc; return acc;
}, {} as networkConfig); }, {} as networkConfig);
} }
export function getConfig(netId: string | number) { export function getConfig(netId: NetIdType) {
const allConfig = getNetworkConfig(); const allConfig = getNetworkConfig();
const chainConfig = allConfig[`netId${netId}`]; const chainConfig = allConfig[netId];
if (!chainConfig) { if (!chainConfig) {
const errMsg = `No config found for ${netId}!`; const errMsg = `No config found for network ${netId}!`;
throw new Error(errMsg); throw new Error(errMsg);
} }
return chainConfig; return chainConfig;
} }
export function getInstanceByAddress({ netId, address }: { netId: number | string; address: string }) { export function getInstanceByAddress({ netId, address }: { netId: NetIdType; address: string }) {
const { tokens } = getConfig(netId); const { tokens } = getConfig(netId);
for (const [currency, { instanceAddress }] of Object.entries(tokens)) { for (const [currency, { instanceAddress }] of Object.entries(tokens)) {
@ -770,5 +786,5 @@ export function getInstanceByAddress({ netId, address }: { netId: number | strin
export function getSubdomains() { export function getSubdomains() {
const allConfig = getNetworkConfig(); const allConfig = getNetworkConfig();
return enabledChains.map((chain) => allConfig[`netId${chain}`].ensSubdomainKey); return enabledChains.map((chain) => allConfig[chain].ensSubdomainKey);
} }

@ -22,7 +22,6 @@ import {
Network, Network,
parseUnits, parseUnits,
FetchUrlFeeDataNetworkPlugin, FetchUrlFeeDataNetworkPlugin,
BigNumberish,
FeeData, FeeData,
EnsPlugin, EnsPlugin,
GasCostPlugin, GasCostPlugin,
@ -30,7 +29,7 @@ import {
import type { RequestInfo, RequestInit, Response, HeadersInit } from 'node-fetch'; import type { RequestInfo, RequestInit, Response, HeadersInit } from 'node-fetch';
import { GasPriceOracle, GasPriceOracle__factory, Multicall, Multicall__factory } from '../typechain'; import { GasPriceOracle, GasPriceOracle__factory, Multicall, Multicall__factory } from '../typechain';
import { isNode, sleep } from './utils'; import { isNode, sleep } from './utils';
import type { Config } from './networkConfig'; import type { Config, NetIdType } from './networkConfig';
import { multicall } from './multicall'; import { multicall } from './multicall';
declare global { declare global {
@ -366,7 +365,7 @@ export async function getProvider(rpcUrl: string, fetchOptions?: getProviderOpti
} }
export function getProviderWithNetId( export function getProviderWithNetId(
netId: BigNumberish, netId: NetIdType,
rpcUrl: string, rpcUrl: string,
config: Config, config: Config,
fetchOptions?: getProviderOptions, fetchOptions?: getProviderOptions,
@ -604,7 +603,7 @@ export type handleWalletFunc = (...args: any[]) => void;
/* eslint-enable @typescript-eslint/no-explicit-any */ /* eslint-enable @typescript-eslint/no-explicit-any */
export type TornadoBrowserProviderOptions = TornadoWalletOptions & { export type TornadoBrowserProviderOptions = TornadoWalletOptions & {
webChainId?: BigNumberish; webChainId?: NetIdType;
connectWallet?: connectWalletFunc; connectWallet?: connectWalletFunc;
handleNetworkChanges?: handleWalletFunc; handleNetworkChanges?: handleWalletFunc;
handleAccountChanges?: handleWalletFunc; handleAccountChanges?: handleWalletFunc;

@ -2,7 +2,7 @@ import { getAddress, namehash, parseEther } from 'ethers';
import type { Aggregator } from '@tornado/contracts'; import type { Aggregator } from '@tornado/contracts';
import type { RelayerStructOutput } from '@tornado/contracts/dist/contracts/Governance/Aggregator/Aggregator'; import type { RelayerStructOutput } from '@tornado/contracts/dist/contracts/Governance/Aggregator/Aggregator';
import { sleep } from './utils'; import { sleep } from './utils';
import type { Config } from './networkConfig'; import { NetId, NetIdType, Config } from './networkConfig';
import { fetchData, fetchDataOptions } from './providers'; import { fetchData, fetchDataOptions } from './providers';
import { ajv, jobsSchema, getStatusSchema } from './schemas'; import { ajv, jobsSchema, getStatusSchema } from './schemas';
import type { snarkProofs } from './websnark'; import type { snarkProofs } from './websnark';
@ -15,7 +15,7 @@ export interface RelayerParams {
} }
export interface Relayer { export interface Relayer {
netId: number; netId: NetIdType;
url: string; url: string;
hostname: string; hostname: string;
rewardAccount: string; rewardAccount: string;
@ -57,7 +57,7 @@ export interface RelayerStatus {
fast: number; fast: number;
additionalProperties?: number; additionalProperties?: number;
}; };
netId: number; netId: NetIdType;
ethPrices?: { ethPrices?: {
[key in string]: string; [key in string]: string;
}; };
@ -107,14 +107,14 @@ export function parseSemanticVersion(version: string) {
return groups as unknown as semanticVersion; return groups as unknown as semanticVersion;
} }
export function isRelayerUpdated(relayerVersion: string, netId: number | string) { export function isRelayerUpdated(relayerVersion: string, netId: NetIdType) {
const { major, patch, prerelease } = parseSemanticVersion(relayerVersion); const { major, patch, prerelease } = parseSemanticVersion(relayerVersion);
// Save backwards compatibility with V4 relayers for Ethereum Mainnet // Save backwards compatibility with V4 relayers for Ethereum Mainnet
const requiredMajor = netId === 1 ? '4' : '5'; const requiredMajor = netId === NetId.MAINNET ? '4' : '5';
const isUpdatedMajor = major === requiredMajor; const isUpdatedMajor = major === requiredMajor;
if (prerelease) return false; if (prerelease) return false;
return isUpdatedMajor && (Number(patch) >= 5 || Number(netId) !== 1); // Patch checking - also backwards compatibility for Mainnet return isUpdatedMajor && (Number(patch) >= 5 || netId !== NetId.MAINNET); // Patch checking - also backwards compatibility for Mainnet
} }
export function calculateScore({ stakeBalance, tornadoServiceFee }: RelayerInfo, minFee = 0.33, maxFee = 0.53) { export function calculateScore({ stakeBalance, tornadoServiceFee }: RelayerInfo, minFee = 0.33, maxFee = 0.53) {
@ -159,10 +159,10 @@ export function getSupportedInstances(instanceList: RelayerInstanceList) {
return rawList.map((l) => getAddress(l)); return rawList.map((l) => getAddress(l));
} }
export function pickWeightedRandomRelayer(relayers: RelayerInfo[], netId: string | number) { export function pickWeightedRandomRelayer(relayers: RelayerInfo[], netId: NetIdType) {
let minFee: number, maxFee: number; let minFee: number, maxFee: number;
if (Number(netId) !== 1) { if (netId !== NetId.MAINNET) {
minFee = 0.01; minFee = 0.01;
maxFee = 0.3; maxFee = 0.3;
} }
@ -179,7 +179,7 @@ export function pickWeightedRandomRelayer(relayers: RelayerInfo[], netId: string
} }
export interface RelayerClientConstructor { export interface RelayerClientConstructor {
netId: number | string; netId: NetIdType;
config: Config; config: Config;
Aggregator: Aggregator; Aggregator: Aggregator;
fetchDataOptions?: fetchDataOptions; fetchDataOptions?: fetchDataOptions;
@ -190,14 +190,14 @@ export type RelayerClientWithdraw = snarkProofs & {
}; };
export class RelayerClient { export class RelayerClient {
netId: number; netId: NetIdType;
config: Config; config: Config;
Aggregator: Aggregator; Aggregator: Aggregator;
selectedRelayer?: Relayer; selectedRelayer?: Relayer;
fetchDataOptions?: fetchDataOptions; fetchDataOptions?: fetchDataOptions;
constructor({ netId, config, Aggregator, fetchDataOptions }: RelayerClientConstructor) { constructor({ netId, config, Aggregator, fetchDataOptions }: RelayerClientConstructor) {
this.netId = Number(netId); this.netId = netId;
this.config = config; this.config = config;
this.Aggregator = Aggregator; this.Aggregator = Aggregator;
this.fetchDataOptions = fetchDataOptions; this.fetchDataOptions = fetchDataOptions;
@ -240,7 +240,7 @@ export class RelayerClient {
throw new Error('This relayer serves a different network'); throw new Error('This relayer serves a different network');
} }
if (relayerAddress && this.netId === 1 && status.rewardAccount !== relayerAddress) { if (relayerAddress && this.netId === NetId.MAINNET && status.rewardAccount !== relayerAddress) {
throw new Error('The Relayer reward address must match registered address'); throw new Error('The Relayer reward address must match registered address');
} }

@ -1,4 +1,4 @@
import type { Config } from '../networkConfig'; import { Config, NetId, NetIdType } from '../networkConfig';
export type statusInstanceType = { export type statusInstanceType = {
type: string; type: string;
@ -110,7 +110,7 @@ const statusSchema: statusSchema = {
required: ['rewardAccount', 'instances', 'netId', 'tornadoServiceFee', 'version', 'health'], required: ['rewardAccount', 'instances', 'netId', 'tornadoServiceFee', 'version', 'health'],
}; };
export function getStatusSchema(netId: number | string, config: Config) { export function getStatusSchema(netId: NetIdType, config: Config) {
const { tokens, optionalTokens = [], nativeCurrency } = config; const { tokens, optionalTokens = [], nativeCurrency } = config;
// deep copy schema // deep copy schema
@ -162,7 +162,7 @@ export function getStatusSchema(netId: number | string, config: Config) {
schema.properties.instances = instances; schema.properties.instances = instances;
if (Number(netId) === 1) { if (netId === NetId.MAINNET) {
const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency);
const ethPrices: statusEthPricesType = { const ethPrices: statusEthPricesType = {

@ -7,9 +7,10 @@ import { MerkleTree } from '@tornado/fixed-merkle-tree';
import BloomFilter from 'bloomfilter.js'; import BloomFilter from 'bloomfilter.js';
import { saveUserFile } from './data'; import { saveUserFile } from './data';
import { DepositsEvents } from './events'; import { DepositsEvents } from './events';
import type { NetIdType } from './networkConfig';
export interface TreeCacheConstructor { export interface TreeCacheConstructor {
netId: number | string; netId: NetIdType;
amount: string; amount: string;
currency: string; currency: string;
userDirectory: string; userDirectory: string;
@ -28,7 +29,7 @@ export interface treeMetadata {
} }
export class TreeCache { export class TreeCache {
netId: number | string; netId: NetIdType;
amount: string; amount: string;
currency: string; currency: string;
userDirectory: string; userDirectory: string;