diff --git a/src/program.ts b/src/program.ts index 4d7207d..de4b3b6 100644 --- a/src/program.ts +++ b/src/program.ts @@ -28,7 +28,6 @@ import { ZeroAddress, MaxUint256, Transaction, - BigNumberish, getAddress, } from 'ethers'; import type MerkleTree from '@tornado/fixed-merkle-tree'; @@ -73,6 +72,8 @@ import { Invoice, fetchData, fetchDataOptions, + NetId, + NetIdType, getInstanceByAddress, getSubdomains, getConfig, @@ -87,7 +88,7 @@ import { 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 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( - netId: BigNumberish, + netId: NetIdType, rpcUrl: string = '', config: Config, providerOptions?: getProviderOptions, @@ -270,7 +271,7 @@ export async function getProgramRelayer({ }: { options: commonProgramOptions; fetchDataOptions?: fetchDataOptions; - netId: number | string; + netId: NetIdType; }): Promise<{ validRelayers?: RelayerInfo[] | Relayer[]; invalidRelayers?: RelayerError[]; @@ -458,7 +459,7 @@ export function tornadoProgram() { .argument('', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber) .argument('', 'Currency to deposit on Tornado Cash') .argument('', '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(); const config = getConfig(netId); @@ -518,7 +519,7 @@ export function tornadoProgram() { .argument('', 'Network Chain ID to connect with (see https://chainlist.org for examples)', parseNumber) .argument('', 'Currency to deposit on Tornado Cash') .argument('', '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); currency = currency.toLowerCase(); 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('[currency]', 'Currency to sync events') .action( - async ( - netIdOpts: number | string | undefined, - currencyOpts: string | undefined, - cmdOptions: commonProgramOptions, - ) => { + async (netIdOpts: NetIdType | undefined, currencyOpts: string | undefined, cmdOptions: commonProgramOptions) => { const { options, fetchDataOptions } = await getProgramOptions(cmdOptions); const { rpc } = options; @@ -1439,7 +1436,7 @@ export function tornadoProgram() { .command('relayers') .description('List all registered relayers from the tornado cash registry.\n\n') .argument('', '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 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)', ) .argument('', '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 { rpc } = options; @@ -1624,7 +1621,7 @@ export function tornadoProgram() { 'Account key generated from UI or the createAccount to store encrypted notes on-chain', 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 { rpc } = options; if (!accountKey) { @@ -1701,7 +1698,7 @@ export function tornadoProgram() { .argument('[token]', 'ERC20 Token Contract to check Token Balance', parseAddress) .action( async ( - netId: string | number, + netId: NetIdType, to: string, amountArgs: number | undefined, tokenArgs: string | undefined, @@ -1838,7 +1835,7 @@ export function tornadoProgram() { .argument('[token]', 'ERC20 Token Contract to check Token Balance', parseAddress) .action( async ( - netId: string | number, + netId: NetIdType, addressArgs: string | undefined, tokenArgs: string | undefined, cmdOptions: commonProgramOptions, diff --git a/src/services/deposits.ts b/src/services/deposits.ts index 1edf379..2e7d8e1 100644 --- a/src/services/deposits.ts +++ b/src/services/deposits.ts @@ -1,10 +1,11 @@ import { bnToBytes, bytesToBN, leBuff2Int, leInt2Buff, rBigInt, toFixedHex } from './utils'; import { buffPedersenHash } from './pedersen'; +import type { NetIdType } from './networkConfig'; export type DepositType = { currency: string; amount: string; - netId: string | number; + netId: NetIdType; }; export type createDepositParams = { @@ -61,7 +62,7 @@ export async function createDeposit({ nullifier, secret }: createDepositParams): export interface DepositConstructor { currency: string; amount: string; - netId: number; + netId: NetIdType; nullifier: bigint; secret: bigint; note: string; @@ -74,7 +75,7 @@ export interface DepositConstructor { export class Deposit { currency: string; amount: string; - netId: number; + netId: NetIdType; nullifier: bigint; secret: bigint; @@ -148,7 +149,7 @@ export class Deposit { const newDeposit = new Deposit({ currency: currency.toLowerCase(), amount: amount, - netId: Number(netId), + netId, note: `tornado-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.noteHex}`, noteHex: depositObject.noteHex, invoice: `tornadoInvoice-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.commitmentHex}`, @@ -182,14 +183,14 @@ export class Deposit { const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${depositObject.commitmentHex}`; const newDeposit = new Deposit({ - currency: currency, - amount: amount, - netId: netId, + currency, + amount, + netId, note: noteString, noteHex: depositObject.noteHex, - invoice: invoice, - nullifier: nullifier, - secret: secret, + invoice, + nullifier, + secret, commitmentHex: depositObject.commitmentHex, nullifierHex: depositObject.nullifierHex, }); @@ -205,7 +206,7 @@ export type parsedInvoiceExec = DepositType & { export class Invoice { currency: string; amount: string; - netId: number; + netId: NetIdType; commitment: string; invoice: string; diff --git a/src/services/encryptedNotes.ts b/src/services/encryptedNotes.ts index f71a4d6..1064491 100644 --- a/src/services/encryptedNotes.ts +++ b/src/services/encryptedNotes.ts @@ -3,6 +3,7 @@ import { Echoer } from '@tornado/contracts'; import { Wallet, computeAddress, getAddress } from 'ethers'; import { crypto, base64ToBytes, bytesToBase64, bytesToHex, hexToBytes, toFixedHex, concatBytes } from './utils'; import { EchoEvents, EncryptedNotesEvents } from './events'; +import type { NetIdType } from './networkConfig'; export interface NoteToEncrypt { address: string; @@ -43,7 +44,7 @@ export function unpackEncryptedMessage(encryptedMessage: string) { } export interface NoteAccountConstructor { - netId: string | number; + netId: NetIdType; blockNumber?: number; // hex recoveryKey?: string; @@ -51,7 +52,7 @@ export interface NoteAccountConstructor { } export class NoteAccount { - netId: number; + netId: NetIdType; blockNumber?: number; // 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 diff --git a/src/services/events/base.ts b/src/services/events/base.ts index da89faf..8b79d62 100644 --- a/src/services/events/base.ts +++ b/src/services/events/base.ts @@ -16,6 +16,7 @@ import { BatchBlockOnProgress, } from '../batch'; import { fetchDataOptions } from '../providers'; +import type { NetIdType } from '../networkConfig'; import type { BaseEvents, MinimalEvents, @@ -36,7 +37,7 @@ export const DEPOSIT = 'deposit'; export const WITHDRAWAL = 'withdrawal'; export type BaseEventsServiceConstructor = { - netId: number | string; + netId: NetIdType; provider: Provider; graphApi?: string; subgraphName?: string; @@ -66,7 +67,7 @@ export type BaseGraphParams = { }; export class BaseEventsService { - netId: number | string; + netId: NetIdType; provider: Provider; graphApi?: string; subgraphName?: string; @@ -324,7 +325,7 @@ export class BaseEventsService { } export type BaseDepositsServiceConstructor = { - netId: number | string; + netId: NetIdType; provider: Provider; graphApi?: string; subgraphName?: string; @@ -464,7 +465,7 @@ export class BaseDepositsService extends BaseEventsService { } export type BaseEncryptedNotesServiceConstructor = { - netId: number | string; + netId: NetIdType; provider: Provider; graphApi?: string; subgraphName?: string; @@ -591,7 +592,7 @@ export class BaseEncryptedNotesService extends BaseEventsService netId.replace('netId', '')) + .map((netId) => Number(netId)) .filter((netId) => !enabledChains.includes(netId)), ); @@ -734,25 +750,25 @@ export function getNetworkConfig(): networkConfig { }; return enabledChains.reduce((acc, curr) => { - acc[`netId${curr}`] = allConfig[`netId${curr}`]; + acc[curr] = allConfig[curr]; return acc; }, {} as networkConfig); } -export function getConfig(netId: string | number) { +export function getConfig(netId: NetIdType) { const allConfig = getNetworkConfig(); - const chainConfig = allConfig[`netId${netId}`]; + const chainConfig = allConfig[netId]; if (!chainConfig) { - const errMsg = `No config found for ${netId}!`; + const errMsg = `No config found for network ${netId}!`; throw new Error(errMsg); } 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); for (const [currency, { instanceAddress }] of Object.entries(tokens)) { @@ -770,5 +786,5 @@ export function getInstanceByAddress({ netId, address }: { netId: number | strin export function getSubdomains() { const allConfig = getNetworkConfig(); - return enabledChains.map((chain) => allConfig[`netId${chain}`].ensSubdomainKey); + return enabledChains.map((chain) => allConfig[chain].ensSubdomainKey); } diff --git a/src/services/providers.ts b/src/services/providers.ts index 1bd1d00..4f6e0a5 100644 --- a/src/services/providers.ts +++ b/src/services/providers.ts @@ -22,7 +22,6 @@ import { Network, parseUnits, FetchUrlFeeDataNetworkPlugin, - BigNumberish, FeeData, EnsPlugin, GasCostPlugin, @@ -30,7 +29,7 @@ import { import type { RequestInfo, RequestInit, Response, HeadersInit } from 'node-fetch'; import { GasPriceOracle, GasPriceOracle__factory, Multicall, Multicall__factory } from '../typechain'; import { isNode, sleep } from './utils'; -import type { Config } from './networkConfig'; +import type { Config, NetIdType } from './networkConfig'; import { multicall } from './multicall'; declare global { @@ -366,7 +365,7 @@ export async function getProvider(rpcUrl: string, fetchOptions?: getProviderOpti } export function getProviderWithNetId( - netId: BigNumberish, + netId: NetIdType, rpcUrl: string, config: Config, fetchOptions?: getProviderOptions, @@ -604,7 +603,7 @@ export type handleWalletFunc = (...args: any[]) => void; /* eslint-enable @typescript-eslint/no-explicit-any */ export type TornadoBrowserProviderOptions = TornadoWalletOptions & { - webChainId?: BigNumberish; + webChainId?: NetIdType; connectWallet?: connectWalletFunc; handleNetworkChanges?: handleWalletFunc; handleAccountChanges?: handleWalletFunc; diff --git a/src/services/relayerClient.ts b/src/services/relayerClient.ts index 546cf67..5326891 100644 --- a/src/services/relayerClient.ts +++ b/src/services/relayerClient.ts @@ -2,7 +2,7 @@ import { getAddress, namehash, parseEther } from 'ethers'; import type { Aggregator } from '@tornado/contracts'; import type { RelayerStructOutput } from '@tornado/contracts/dist/contracts/Governance/Aggregator/Aggregator'; import { sleep } from './utils'; -import type { Config } from './networkConfig'; +import { NetId, NetIdType, Config } from './networkConfig'; import { fetchData, fetchDataOptions } from './providers'; import { ajv, jobsSchema, getStatusSchema } from './schemas'; import type { snarkProofs } from './websnark'; @@ -15,7 +15,7 @@ export interface RelayerParams { } export interface Relayer { - netId: number; + netId: NetIdType; url: string; hostname: string; rewardAccount: string; @@ -57,7 +57,7 @@ export interface RelayerStatus { fast: number; additionalProperties?: number; }; - netId: number; + netId: NetIdType; ethPrices?: { [key in string]: string; }; @@ -107,14 +107,14 @@ export function parseSemanticVersion(version: string) { 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); // 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; 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) { @@ -159,10 +159,10 @@ export function getSupportedInstances(instanceList: RelayerInstanceList) { 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; - if (Number(netId) !== 1) { + if (netId !== NetId.MAINNET) { minFee = 0.01; maxFee = 0.3; } @@ -179,7 +179,7 @@ export function pickWeightedRandomRelayer(relayers: RelayerInfo[], netId: string } export interface RelayerClientConstructor { - netId: number | string; + netId: NetIdType; config: Config; Aggregator: Aggregator; fetchDataOptions?: fetchDataOptions; @@ -190,14 +190,14 @@ export type RelayerClientWithdraw = snarkProofs & { }; export class RelayerClient { - netId: number; + netId: NetIdType; config: Config; Aggregator: Aggregator; selectedRelayer?: Relayer; fetchDataOptions?: fetchDataOptions; constructor({ netId, config, Aggregator, fetchDataOptions }: RelayerClientConstructor) { - this.netId = Number(netId); + this.netId = netId; this.config = config; this.Aggregator = Aggregator; this.fetchDataOptions = fetchDataOptions; @@ -240,7 +240,7 @@ export class RelayerClient { 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'); } diff --git a/src/services/schemas/status.ts b/src/services/schemas/status.ts index ea0ef49..4a0a516 100644 --- a/src/services/schemas/status.ts +++ b/src/services/schemas/status.ts @@ -1,4 +1,4 @@ -import type { Config } from '../networkConfig'; +import { Config, NetId, NetIdType } from '../networkConfig'; export type statusInstanceType = { type: string; @@ -110,7 +110,7 @@ const statusSchema: statusSchema = { 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; // deep copy schema @@ -162,7 +162,7 @@ export function getStatusSchema(netId: number | string, config: Config) { schema.properties.instances = instances; - if (Number(netId) === 1) { + if (netId === NetId.MAINNET) { const _tokens = Object.keys(tokens).filter((t) => t !== nativeCurrency); const ethPrices: statusEthPricesType = { diff --git a/src/services/treeCache.ts b/src/services/treeCache.ts index 735172e..bff46c2 100644 --- a/src/services/treeCache.ts +++ b/src/services/treeCache.ts @@ -7,9 +7,10 @@ import { MerkleTree } from '@tornado/fixed-merkle-tree'; import BloomFilter from 'bloomfilter.js'; import { saveUserFile } from './data'; import { DepositsEvents } from './events'; +import type { NetIdType } from './networkConfig'; export interface TreeCacheConstructor { - netId: number | string; + netId: NetIdType; amount: string; currency: string; userDirectory: string; @@ -28,7 +29,7 @@ export interface treeMetadata { } export class TreeCache { - netId: number | string; + netId: NetIdType; amount: string; currency: string; userDirectory: string;