Compare commits
1 Commits
8041bd7f78
...
f411159f15
| Author | SHA1 | Date | |
|---|---|---|---|
|
f411159f15
|
104
.eslintrc.js
104
.eslintrc.js
@@ -1,66 +1,44 @@
|
||||
module.exports = {
|
||||
"env": {
|
||||
"es2021": true,
|
||||
"node": true
|
||||
},
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"plugin:import/recommended",
|
||||
"plugin:import/typescript",
|
||||
"prettier",
|
||||
"plugin:prettier/recommended",
|
||||
],
|
||||
"overrides": [
|
||||
{
|
||||
"env": {
|
||||
"node": true
|
||||
},
|
||||
"files": [
|
||||
".eslintrc.{js,cjs}"
|
||||
],
|
||||
"parserOptions": {
|
||||
"sourceType": "script"
|
||||
}
|
||||
}
|
||||
],
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": "latest",
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": [
|
||||
"@typescript-eslint",
|
||||
"prettier"
|
||||
],
|
||||
"rules": {
|
||||
"prettier/prettier": [
|
||||
"error",
|
||||
{
|
||||
singleQuote: true,
|
||||
printWidth: 120
|
||||
}
|
||||
env: {
|
||||
es2021: true,
|
||||
node: true,
|
||||
},
|
||||
extends: [
|
||||
'prettier',
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:import/recommended',
|
||||
'plugin:import/typescript',
|
||||
'plugin:prettier/recommended',
|
||||
],
|
||||
"import/order": ["error"],
|
||||
/**
|
||||
"indent": [
|
||||
"error",
|
||||
2
|
||||
overrides: [
|
||||
{
|
||||
env: {
|
||||
node: true,
|
||||
},
|
||||
files: ['.eslintrc.{js,cjs}'],
|
||||
parserOptions: {
|
||||
sourceType: 'script',
|
||||
},
|
||||
},
|
||||
],
|
||||
**/
|
||||
"linebreak-style": [
|
||||
"error",
|
||||
"unix"
|
||||
],
|
||||
"quotes": [
|
||||
"error",
|
||||
"single"
|
||||
],
|
||||
"semi": [
|
||||
"error",
|
||||
"always"
|
||||
],
|
||||
"@typescript-eslint/no-unused-vars": ["warn"],
|
||||
"@typescript-eslint/no-unused-expressions": ["off"]
|
||||
}
|
||||
}
|
||||
parser: '@typescript-eslint/parser',
|
||||
parserOptions: {
|
||||
ecmaVersion: 'latest',
|
||||
sourceType: 'module',
|
||||
},
|
||||
plugins: ['@typescript-eslint', 'prettier'],
|
||||
rules: {
|
||||
'prettier/prettier': [
|
||||
'error',
|
||||
{
|
||||
tabWidth: 4,
|
||||
printWidth: 120,
|
||||
singleQuote: true,
|
||||
},
|
||||
],
|
||||
'import/order': ['error'],
|
||||
'@typescript-eslint/no-unused-vars': ['warn'],
|
||||
'@typescript-eslint/no-unused-expressions': ['off'],
|
||||
},
|
||||
};
|
||||
|
||||
22
.nycrc
22
.nycrc
@@ -1,13 +1,13 @@
|
||||
{
|
||||
"all": true,
|
||||
"extension": [".ts"],
|
||||
"report-dir": "coverage",
|
||||
"reporter": [
|
||||
"html",
|
||||
"lcov",
|
||||
"text",
|
||||
"text-summary"
|
||||
],
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/typechain/**/*"]
|
||||
"all": true,
|
||||
"extension": [".ts"],
|
||||
"report-dir": "coverage",
|
||||
"reporter": [
|
||||
"html",
|
||||
"lcov",
|
||||
"text",
|
||||
"text-summary"
|
||||
],
|
||||
"include": ["src/**/*.ts"],
|
||||
"exclude": ["src/typechain/**/*"]
|
||||
}
|
||||
7
dist/encryptedNotes.d.ts
vendored
7
dist/encryptedNotes.d.ts
vendored
@@ -1,7 +1,6 @@
|
||||
import { EthEncryptedData } from '@metamask/eth-sig-util';
|
||||
import { Signer, Wallet } from 'ethers';
|
||||
import { EchoEvents, EncryptedNotesEvents } from './events';
|
||||
import type { NetIdType } from './networkConfig';
|
||||
export interface NoteToEncrypt {
|
||||
address: string;
|
||||
noteHex: string;
|
||||
@@ -16,17 +15,15 @@ export declare function unpackEncryptedMessage(encryptedMessage: string): EthEnc
|
||||
messageBuff: string;
|
||||
};
|
||||
export interface NoteAccountConstructor {
|
||||
netId: NetIdType;
|
||||
blockNumber?: number;
|
||||
recoveryKey?: string;
|
||||
}
|
||||
export declare class NoteAccount {
|
||||
netId: NetIdType;
|
||||
blockNumber?: number;
|
||||
recoveryKey: string;
|
||||
recoveryAddress: string;
|
||||
recoveryPublicKey: string;
|
||||
constructor({ netId, blockNumber, recoveryKey }: NoteAccountConstructor);
|
||||
constructor({ blockNumber, recoveryKey }: NoteAccountConstructor);
|
||||
/**
|
||||
* Intends to mock eth_getEncryptionPublicKey behavior from MetaMask
|
||||
* In order to make the recoveryKey retrival from Echoer possible from the bare private key
|
||||
@@ -39,7 +36,7 @@ export declare class NoteAccount {
|
||||
/**
|
||||
* Decrypt Echoer backuped note encryption account with private keys
|
||||
*/
|
||||
decryptSignerNoteAccounts(signer: Signer | Wallet, events: EchoEvents[]): Promise<NoteAccount[]>;
|
||||
static decryptSignerNoteAccounts(signer: Signer | Wallet, events: EchoEvents[]): Promise<NoteAccount[]>;
|
||||
decryptNotes(events: EncryptedNotesEvents[]): DecryptedNotes[];
|
||||
encryptNote({ address, noteHex }: NoteToEncrypt): string;
|
||||
}
|
||||
|
||||
2
dist/events/base.d.ts
vendored
2
dist/events/base.d.ts
vendored
@@ -120,7 +120,7 @@ export declare class BaseTornadoService extends BaseEventsService<DepositsEvents
|
||||
validateEvents<S>({ events, hasNewEvents, }: BaseEvents<DepositsEvents | WithdrawalsEvents> & {
|
||||
hasNewEvents?: boolean;
|
||||
}): Promise<S>;
|
||||
getLatestEvents({ fromBlock }: {
|
||||
getLatestEvents({ fromBlock, }: {
|
||||
fromBlock: number;
|
||||
}): Promise<BaseEvents<DepositsEvents | WithdrawalsEvents>>;
|
||||
}
|
||||
|
||||
306
dist/index.js
vendored
306
dist/index.js
vendored
@@ -15,20 +15,20 @@ var websnarkUtils = require('@tornado/websnark/src/utils');
|
||||
var websnarkGroth = require('@tornado/websnark/src/groth16');
|
||||
|
||||
function _interopNamespaceDefault(e) {
|
||||
var n = Object.create(null);
|
||||
if (e) {
|
||||
Object.keys(e).forEach(function (k) {
|
||||
if (k !== 'default') {
|
||||
var d = Object.getOwnPropertyDescriptor(e, k);
|
||||
Object.defineProperty(n, k, d.get ? d : {
|
||||
enumerable: true,
|
||||
get: function () { return e[k]; }
|
||||
var n = Object.create(null);
|
||||
if (e) {
|
||||
Object.keys(e).forEach(function (k) {
|
||||
if (k !== 'default') {
|
||||
var d = Object.getOwnPropertyDescriptor(e, k);
|
||||
Object.defineProperty(n, k, d.get ? d : {
|
||||
enumerable: true,
|
||||
get: function () { return e[k]; }
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
n.default = e;
|
||||
return Object.freeze(n);
|
||||
}
|
||||
n.default = e;
|
||||
return Object.freeze(n);
|
||||
}
|
||||
|
||||
var websnarkUtils__namespace = /*#__PURE__*/_interopNamespaceDefault(websnarkUtils);
|
||||
@@ -778,7 +778,12 @@ async function getAllRegisters({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getRegisters({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -867,7 +872,14 @@ async function getAllDeposits({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getDeposits({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -962,7 +974,14 @@ async function getAllWithdrawals({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getWithdrawals({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -1085,7 +1104,12 @@ async function getAllGraphEchoEvents({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getGraphEchoEvents({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -1172,7 +1196,12 @@ async function getAllEncryptedNotes({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getEncryptedNotes({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -1257,14 +1286,29 @@ async function getAllGovernanceEvents({
|
||||
_meta: {
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getGovernanceEvents({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length;
|
||||
if (eventsLength === 0) {
|
||||
break;
|
||||
}
|
||||
const formattedProposals = proposals.map(
|
||||
({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => {
|
||||
({
|
||||
blockNumber,
|
||||
logIndex,
|
||||
transactionHash,
|
||||
proposalId,
|
||||
proposer,
|
||||
target,
|
||||
startTime,
|
||||
endTime,
|
||||
description
|
||||
}) => {
|
||||
return {
|
||||
blockNumber: Number(blockNumber),
|
||||
logIndex: Number(logIndex),
|
||||
@@ -1367,33 +1411,33 @@ async function getAllGovernanceEvents({
|
||||
}
|
||||
|
||||
var graph = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null,
|
||||
GET_DEPOSITS: GET_DEPOSITS,
|
||||
GET_ECHO_EVENTS: GET_ECHO_EVENTS,
|
||||
GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES,
|
||||
GET_GOVERNANCE_APY: GET_GOVERNANCE_APY,
|
||||
GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS,
|
||||
GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS,
|
||||
GET_REGISTERED: GET_REGISTERED,
|
||||
GET_STATISTIC: GET_STATISTIC,
|
||||
GET_WITHDRAWALS: GET_WITHDRAWALS,
|
||||
_META: _META,
|
||||
getAllDeposits: getAllDeposits,
|
||||
getAllEncryptedNotes: getAllEncryptedNotes,
|
||||
getAllGovernanceEvents: getAllGovernanceEvents,
|
||||
getAllGraphEchoEvents: getAllGraphEchoEvents,
|
||||
getAllRegisters: getAllRegisters,
|
||||
getAllWithdrawals: getAllWithdrawals,
|
||||
getDeposits: getDeposits,
|
||||
getEncryptedNotes: getEncryptedNotes,
|
||||
getGovernanceEvents: getGovernanceEvents,
|
||||
getGraphEchoEvents: getGraphEchoEvents,
|
||||
getMeta: getMeta,
|
||||
getNoteAccounts: getNoteAccounts,
|
||||
getRegisters: getRegisters,
|
||||
getStatistic: getStatistic,
|
||||
getWithdrawals: getWithdrawals,
|
||||
queryGraph: queryGraph
|
||||
__proto__: null,
|
||||
GET_DEPOSITS: GET_DEPOSITS,
|
||||
GET_ECHO_EVENTS: GET_ECHO_EVENTS,
|
||||
GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES,
|
||||
GET_GOVERNANCE_APY: GET_GOVERNANCE_APY,
|
||||
GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS,
|
||||
GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS,
|
||||
GET_REGISTERED: GET_REGISTERED,
|
||||
GET_STATISTIC: GET_STATISTIC,
|
||||
GET_WITHDRAWALS: GET_WITHDRAWALS,
|
||||
_META: _META,
|
||||
getAllDeposits: getAllDeposits,
|
||||
getAllEncryptedNotes: getAllEncryptedNotes,
|
||||
getAllGovernanceEvents: getAllGovernanceEvents,
|
||||
getAllGraphEchoEvents: getAllGraphEchoEvents,
|
||||
getAllRegisters: getAllRegisters,
|
||||
getAllWithdrawals: getAllWithdrawals,
|
||||
getDeposits: getDeposits,
|
||||
getEncryptedNotes: getEncryptedNotes,
|
||||
getGovernanceEvents: getGovernanceEvents,
|
||||
getGraphEchoEvents: getGraphEchoEvents,
|
||||
getMeta: getMeta,
|
||||
getNoteAccounts: getNoteAccounts,
|
||||
getRegisters: getRegisters,
|
||||
getStatistic: getStatistic,
|
||||
getWithdrawals: getWithdrawals,
|
||||
queryGraph: queryGraph
|
||||
});
|
||||
|
||||
class BatchBlockService {
|
||||
@@ -1526,7 +1570,11 @@ class BatchTransactionService {
|
||||
results.push(...chunksResult);
|
||||
txCount += chunks.length;
|
||||
if (typeof this.onProgress === "function") {
|
||||
this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length });
|
||||
this.onProgress({
|
||||
percentage: txCount / txs.length,
|
||||
currentIndex: txCount,
|
||||
totalIndex: txs.length
|
||||
});
|
||||
}
|
||||
}
|
||||
return results;
|
||||
@@ -2265,8 +2313,14 @@ const addressSchemaType = {
|
||||
isAddress: true
|
||||
};
|
||||
const bnSchemaType = { type: "string", BN: true };
|
||||
const proofSchemaType = { type: "string", pattern: "^0x[a-fA-F0-9]{512}$" };
|
||||
const bytes32SchemaType = { type: "string", pattern: "^0x[a-fA-F0-9]{64}$" };
|
||||
const proofSchemaType = {
|
||||
type: "string",
|
||||
pattern: "^0x[a-fA-F0-9]{512}$"
|
||||
};
|
||||
const bytes32SchemaType = {
|
||||
type: "string",
|
||||
pattern: "^0x[a-fA-F0-9]{64}$"
|
||||
};
|
||||
const bytes32BNSchemaType = { ...bytes32SchemaType, BN: true };
|
||||
|
||||
const baseEventsSchemaProperty = {
|
||||
@@ -2319,7 +2373,16 @@ const governanceEventsSchema = {
|
||||
from: addressSchemaType,
|
||||
input: { type: "string" }
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, "event", "proposalId", "voter", "support", "votes", "from", "input"],
|
||||
required: [
|
||||
...baseEventsSchemaRequired,
|
||||
"event",
|
||||
"proposalId",
|
||||
"voter",
|
||||
"support",
|
||||
"votes",
|
||||
"from",
|
||||
"input"
|
||||
],
|
||||
additionalProperties: false
|
||||
},
|
||||
{
|
||||
@@ -2488,10 +2551,13 @@ function getStatusSchema(netId, config, tovarish) {
|
||||
properties: {
|
||||
instanceAddress: {
|
||||
type: "object",
|
||||
properties: amounts.reduce((acc2, cur) => {
|
||||
acc2[cur] = addressSchemaType;
|
||||
return acc2;
|
||||
}, {}),
|
||||
properties: amounts.reduce(
|
||||
(acc2, cur) => {
|
||||
acc2[cur] = addressSchemaType;
|
||||
return acc2;
|
||||
},
|
||||
{}
|
||||
),
|
||||
required: amounts.filter((amount) => !optionalInstances.includes(amount))
|
||||
},
|
||||
decimals: { enum: [decimals] }
|
||||
@@ -2664,7 +2730,10 @@ class RelayerClient {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await this.askRelayerStatus({ hostname, relayerAddress });
|
||||
const status = await this.askRelayerStatus({
|
||||
hostname,
|
||||
relayerAddress
|
||||
});
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
@@ -2690,16 +2759,18 @@ class RelayerClient {
|
||||
}
|
||||
async getValidRelayers(relayers) {
|
||||
const invalidRelayers = [];
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter(
|
||||
(r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
);
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers
|
||||
@@ -2918,7 +2989,11 @@ class BaseEventsService {
|
||||
}
|
||||
this.updateEventProgress({ percentage: 0, type: this.getType() });
|
||||
const events = await this.formatEvents(
|
||||
await this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() })
|
||||
await this.batchEventsService.getBatchEvents({
|
||||
fromBlock,
|
||||
toBlock,
|
||||
type: this.getType()
|
||||
})
|
||||
);
|
||||
return {
|
||||
events,
|
||||
@@ -2945,7 +3020,9 @@ class BaseEventsService {
|
||||
}
|
||||
const graphEvents = await this.getEventsFromGraph({ fromBlock });
|
||||
const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock;
|
||||
const rpcEvents = await this.getEventsFromRpc({ fromBlock: lastSyncBlock });
|
||||
const rpcEvents = await this.getEventsFromRpc({
|
||||
fromBlock: lastSyncBlock
|
||||
});
|
||||
return {
|
||||
events: [...graphEvents.events, ...rpcEvents.events],
|
||||
lastBlock: rpcEvents.lastBlock
|
||||
@@ -3111,7 +3188,9 @@ class BaseTornadoService extends BaseEventsService {
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
async getLatestEvents({ fromBlock }) {
|
||||
async getLatestEvents({
|
||||
fromBlock
|
||||
}) {
|
||||
if (this.tovarishClient?.selectedRelayer) {
|
||||
const { events, lastSyncBlock: lastBlock } = await this.tovarishClient.getEvents({
|
||||
type: this.getTovarishType(),
|
||||
@@ -3257,7 +3336,11 @@ function parseComment(Governance, calldata) {
|
||||
try {
|
||||
const methodLength = 4;
|
||||
const result = abiCoder.decode(["address[]", "uint256", "bool"], ethers.dataSlice(calldata, methodLength));
|
||||
const data = Governance.interface.encodeFunctionData("castDelegatedVote", result);
|
||||
const data = Governance.interface.encodeFunctionData(
|
||||
// @ts-expect-error encodeFunctionData is broken lol
|
||||
"castDelegatedVote",
|
||||
result
|
||||
);
|
||||
const length = ethers.dataLength(data);
|
||||
const str = abiCoder.decode(["string"], ethers.dataSlice(calldata, length))[0];
|
||||
const [contact, message] = JSON.parse(str);
|
||||
@@ -3746,7 +3829,9 @@ async function loadDBEvents({
|
||||
lastBlock: 0
|
||||
};
|
||||
}
|
||||
const events = (await idb.getAll({ storeName: instanceName })).map((e) => {
|
||||
const events = (await idb.getAll({
|
||||
storeName: instanceName
|
||||
})).map((e) => {
|
||||
delete e.eid;
|
||||
return e;
|
||||
});
|
||||
@@ -9204,16 +9289,16 @@ class ReverseRecords__factory {
|
||||
}
|
||||
|
||||
var index = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null,
|
||||
ENSNameWrapper__factory: ENSNameWrapper__factory,
|
||||
ENSRegistry__factory: ENSRegistry__factory,
|
||||
ENSResolver__factory: ENSResolver__factory,
|
||||
ENS__factory: ENS__factory,
|
||||
ERC20__factory: ERC20__factory,
|
||||
Multicall__factory: Multicall__factory,
|
||||
OffchainOracle__factory: OffchainOracle__factory,
|
||||
OvmGasPriceOracle__factory: OvmGasPriceOracle__factory,
|
||||
ReverseRecords__factory: ReverseRecords__factory
|
||||
__proto__: null,
|
||||
ENSNameWrapper__factory: ENSNameWrapper__factory,
|
||||
ENSRegistry__factory: ENSRegistry__factory,
|
||||
ENSResolver__factory: ENSResolver__factory,
|
||||
ENS__factory: ENS__factory,
|
||||
ERC20__factory: ERC20__factory,
|
||||
Multicall__factory: Multicall__factory,
|
||||
OffchainOracle__factory: OffchainOracle__factory,
|
||||
OvmGasPriceOracle__factory: OvmGasPriceOracle__factory,
|
||||
ReverseRecords__factory: ReverseRecords__factory
|
||||
});
|
||||
|
||||
class Pedersen {
|
||||
@@ -9373,7 +9458,10 @@ class Deposit {
|
||||
const bytes = bnToBytes(parsedNoteHex);
|
||||
const nullifier = BigInt(leBuff2Int(bytes.slice(0, 31)).toString());
|
||||
const secret = BigInt(leBuff2Int(bytes.slice(31, 62)).toString());
|
||||
const { noteHex, commitmentHex, nullifierHex } = await createDeposit({ nullifier, secret });
|
||||
const { noteHex, commitmentHex, nullifierHex } = await createDeposit({
|
||||
nullifier,
|
||||
secret
|
||||
});
|
||||
const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${commitmentHex}`;
|
||||
const newDeposit = new Deposit({
|
||||
currency,
|
||||
@@ -9444,7 +9532,6 @@ function unpackEncryptedMessage(encryptedMessage) {
|
||||
};
|
||||
}
|
||||
class NoteAccount {
|
||||
netId;
|
||||
blockNumber;
|
||||
// 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
|
||||
@@ -9453,11 +9540,10 @@ class NoteAccount {
|
||||
recoveryAddress;
|
||||
// Note encryption public key derived from recoveryKey
|
||||
recoveryPublicKey;
|
||||
constructor({ netId, blockNumber, recoveryKey }) {
|
||||
constructor({ blockNumber, recoveryKey }) {
|
||||
if (!recoveryKey) {
|
||||
recoveryKey = rHex(32).slice(2);
|
||||
}
|
||||
this.netId = Math.floor(Number(netId));
|
||||
this.blockNumber = blockNumber;
|
||||
this.recoveryKey = recoveryKey;
|
||||
this.recoveryAddress = ethers.computeAddress("0x" + recoveryKey);
|
||||
@@ -9500,7 +9586,7 @@ class NoteAccount {
|
||||
/**
|
||||
* Decrypt Echoer backuped note encryption account with private keys
|
||||
*/
|
||||
async decryptSignerNoteAccounts(signer, events) {
|
||||
static async decryptSignerNoteAccounts(signer, events) {
|
||||
const signerAddress = signer.address;
|
||||
const decryptedEvents = [];
|
||||
for (const event of events) {
|
||||
@@ -9534,7 +9620,6 @@ class NoteAccount {
|
||||
}
|
||||
decryptedEvents.push(
|
||||
new NoteAccount({
|
||||
netId: this.netId,
|
||||
blockNumber: event.blockNumber,
|
||||
recoveryKey
|
||||
})
|
||||
@@ -10570,7 +10655,9 @@ class TokenPriceOracle {
|
||||
const price = await this.oracle.getRateToEth(tokenAddress, true);
|
||||
return price * BigInt(10 ** decimals) / BigInt(10 ** 18);
|
||||
} catch (err) {
|
||||
console.log(`Failed to fetch oracle price for ${tokenAddress}, will use fallback price ${this.fallbackPrice}`);
|
||||
console.log(
|
||||
`Failed to fetch oracle price for ${tokenAddress}, will use fallback price ${this.fallbackPrice}`
|
||||
);
|
||||
console.log(err);
|
||||
return this.fallbackPrice;
|
||||
}
|
||||
@@ -10670,7 +10757,11 @@ class TovarishClient extends RelayerClient {
|
||||
url,
|
||||
relayerAddress
|
||||
}) {
|
||||
const status = await super.askRelayerStatus({ hostname, url, relayerAddress });
|
||||
const status = await super.askRelayerStatus({
|
||||
hostname,
|
||||
url,
|
||||
relayerAddress
|
||||
});
|
||||
if (!status.version.includes("tovarish")) {
|
||||
throw new Error("Not a tovarish relayer!");
|
||||
}
|
||||
@@ -10706,7 +10797,14 @@ class TovarishClient extends RelayerClient {
|
||||
for (const rawStatus of statusArray) {
|
||||
const netId = rawStatus.netId;
|
||||
const config = getConfig(netId);
|
||||
const statusValidator = ajv.compile(getStatusSchema(rawStatus.netId, config, this.tovarish));
|
||||
const statusValidator = ajv.compile(
|
||||
getStatusSchema(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
rawStatus.netId,
|
||||
config,
|
||||
this.tovarish
|
||||
)
|
||||
);
|
||||
if (!statusValidator) {
|
||||
continue;
|
||||
}
|
||||
@@ -10737,7 +10835,10 @@ class TovarishClient extends RelayerClient {
|
||||
}
|
||||
const hostname = `${tovarishHost}/${this.netId}`;
|
||||
try {
|
||||
const status = await this.askRelayerStatus({ hostname, relayerAddress });
|
||||
const status = await this.askRelayerStatus({
|
||||
hostname,
|
||||
relayerAddress
|
||||
});
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
@@ -10769,16 +10870,18 @@ class TovarishClient extends RelayerClient {
|
||||
}
|
||||
async getValidRelayers(relayers) {
|
||||
const invalidRelayers = [];
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter(
|
||||
(r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
);
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers
|
||||
@@ -10791,7 +10894,10 @@ class TovarishClient extends RelayerClient {
|
||||
relayers.filter((r) => r.tovarishHost && r.tovarishNetworks?.length).map(async (relayer) => {
|
||||
const { ensName, relayerAddress, tovarishHost } = relayer;
|
||||
try {
|
||||
const statusArray = await this.askAllStatus({ hostname: tovarishHost, relayerAddress });
|
||||
const statusArray = await this.askAllStatus({
|
||||
hostname: tovarishHost,
|
||||
relayerAddress
|
||||
});
|
||||
for (const status of statusArray) {
|
||||
validRelayers.push({
|
||||
netId: status.netId,
|
||||
|
||||
280
dist/index.mjs
vendored
280
dist/index.mjs
vendored
@@ -757,7 +757,12 @@ async function getAllRegisters({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getRegisters({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -846,7 +851,14 @@ async function getAllDeposits({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getDeposits({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -941,7 +953,14 @@ async function getAllWithdrawals({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getWithdrawals({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -1064,7 +1083,12 @@ async function getAllGraphEchoEvents({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getGraphEchoEvents({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -1151,7 +1175,12 @@ async function getAllEncryptedNotes({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getEncryptedNotes({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -1236,14 +1265,29 @@ async function getAllGovernanceEvents({
|
||||
_meta: {
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getGovernanceEvents({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length;
|
||||
if (eventsLength === 0) {
|
||||
break;
|
||||
}
|
||||
const formattedProposals = proposals.map(
|
||||
({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => {
|
||||
({
|
||||
blockNumber,
|
||||
logIndex,
|
||||
transactionHash,
|
||||
proposalId,
|
||||
proposer,
|
||||
target,
|
||||
startTime,
|
||||
endTime,
|
||||
description
|
||||
}) => {
|
||||
return {
|
||||
blockNumber: Number(blockNumber),
|
||||
logIndex: Number(logIndex),
|
||||
@@ -1346,33 +1390,33 @@ async function getAllGovernanceEvents({
|
||||
}
|
||||
|
||||
var graph = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null,
|
||||
GET_DEPOSITS: GET_DEPOSITS,
|
||||
GET_ECHO_EVENTS: GET_ECHO_EVENTS,
|
||||
GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES,
|
||||
GET_GOVERNANCE_APY: GET_GOVERNANCE_APY,
|
||||
GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS,
|
||||
GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS,
|
||||
GET_REGISTERED: GET_REGISTERED,
|
||||
GET_STATISTIC: GET_STATISTIC,
|
||||
GET_WITHDRAWALS: GET_WITHDRAWALS,
|
||||
_META: _META,
|
||||
getAllDeposits: getAllDeposits,
|
||||
getAllEncryptedNotes: getAllEncryptedNotes,
|
||||
getAllGovernanceEvents: getAllGovernanceEvents,
|
||||
getAllGraphEchoEvents: getAllGraphEchoEvents,
|
||||
getAllRegisters: getAllRegisters,
|
||||
getAllWithdrawals: getAllWithdrawals,
|
||||
getDeposits: getDeposits,
|
||||
getEncryptedNotes: getEncryptedNotes,
|
||||
getGovernanceEvents: getGovernanceEvents,
|
||||
getGraphEchoEvents: getGraphEchoEvents,
|
||||
getMeta: getMeta,
|
||||
getNoteAccounts: getNoteAccounts,
|
||||
getRegisters: getRegisters,
|
||||
getStatistic: getStatistic,
|
||||
getWithdrawals: getWithdrawals,
|
||||
queryGraph: queryGraph
|
||||
__proto__: null,
|
||||
GET_DEPOSITS: GET_DEPOSITS,
|
||||
GET_ECHO_EVENTS: GET_ECHO_EVENTS,
|
||||
GET_ENCRYPTED_NOTES: GET_ENCRYPTED_NOTES,
|
||||
GET_GOVERNANCE_APY: GET_GOVERNANCE_APY,
|
||||
GET_GOVERNANCE_EVENTS: GET_GOVERNANCE_EVENTS,
|
||||
GET_NOTE_ACCOUNTS: GET_NOTE_ACCOUNTS,
|
||||
GET_REGISTERED: GET_REGISTERED,
|
||||
GET_STATISTIC: GET_STATISTIC,
|
||||
GET_WITHDRAWALS: GET_WITHDRAWALS,
|
||||
_META: _META,
|
||||
getAllDeposits: getAllDeposits,
|
||||
getAllEncryptedNotes: getAllEncryptedNotes,
|
||||
getAllGovernanceEvents: getAllGovernanceEvents,
|
||||
getAllGraphEchoEvents: getAllGraphEchoEvents,
|
||||
getAllRegisters: getAllRegisters,
|
||||
getAllWithdrawals: getAllWithdrawals,
|
||||
getDeposits: getDeposits,
|
||||
getEncryptedNotes: getEncryptedNotes,
|
||||
getGovernanceEvents: getGovernanceEvents,
|
||||
getGraphEchoEvents: getGraphEchoEvents,
|
||||
getMeta: getMeta,
|
||||
getNoteAccounts: getNoteAccounts,
|
||||
getRegisters: getRegisters,
|
||||
getStatistic: getStatistic,
|
||||
getWithdrawals: getWithdrawals,
|
||||
queryGraph: queryGraph
|
||||
});
|
||||
|
||||
class BatchBlockService {
|
||||
@@ -1505,7 +1549,11 @@ class BatchTransactionService {
|
||||
results.push(...chunksResult);
|
||||
txCount += chunks.length;
|
||||
if (typeof this.onProgress === "function") {
|
||||
this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length });
|
||||
this.onProgress({
|
||||
percentage: txCount / txs.length,
|
||||
currentIndex: txCount,
|
||||
totalIndex: txs.length
|
||||
});
|
||||
}
|
||||
}
|
||||
return results;
|
||||
@@ -2244,8 +2292,14 @@ const addressSchemaType = {
|
||||
isAddress: true
|
||||
};
|
||||
const bnSchemaType = { type: "string", BN: true };
|
||||
const proofSchemaType = { type: "string", pattern: "^0x[a-fA-F0-9]{512}$" };
|
||||
const bytes32SchemaType = { type: "string", pattern: "^0x[a-fA-F0-9]{64}$" };
|
||||
const proofSchemaType = {
|
||||
type: "string",
|
||||
pattern: "^0x[a-fA-F0-9]{512}$"
|
||||
};
|
||||
const bytes32SchemaType = {
|
||||
type: "string",
|
||||
pattern: "^0x[a-fA-F0-9]{64}$"
|
||||
};
|
||||
const bytes32BNSchemaType = { ...bytes32SchemaType, BN: true };
|
||||
|
||||
const baseEventsSchemaProperty = {
|
||||
@@ -2298,7 +2352,16 @@ const governanceEventsSchema = {
|
||||
from: addressSchemaType,
|
||||
input: { type: "string" }
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, "event", "proposalId", "voter", "support", "votes", "from", "input"],
|
||||
required: [
|
||||
...baseEventsSchemaRequired,
|
||||
"event",
|
||||
"proposalId",
|
||||
"voter",
|
||||
"support",
|
||||
"votes",
|
||||
"from",
|
||||
"input"
|
||||
],
|
||||
additionalProperties: false
|
||||
},
|
||||
{
|
||||
@@ -2467,10 +2530,13 @@ function getStatusSchema(netId, config, tovarish) {
|
||||
properties: {
|
||||
instanceAddress: {
|
||||
type: "object",
|
||||
properties: amounts.reduce((acc2, cur) => {
|
||||
acc2[cur] = addressSchemaType;
|
||||
return acc2;
|
||||
}, {}),
|
||||
properties: amounts.reduce(
|
||||
(acc2, cur) => {
|
||||
acc2[cur] = addressSchemaType;
|
||||
return acc2;
|
||||
},
|
||||
{}
|
||||
),
|
||||
required: amounts.filter((amount) => !optionalInstances.includes(amount))
|
||||
},
|
||||
decimals: { enum: [decimals] }
|
||||
@@ -2643,7 +2709,10 @@ class RelayerClient {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await this.askRelayerStatus({ hostname, relayerAddress });
|
||||
const status = await this.askRelayerStatus({
|
||||
hostname,
|
||||
relayerAddress
|
||||
});
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
@@ -2669,16 +2738,18 @@ class RelayerClient {
|
||||
}
|
||||
async getValidRelayers(relayers) {
|
||||
const invalidRelayers = [];
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter(
|
||||
(r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
);
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers
|
||||
@@ -2897,7 +2968,11 @@ class BaseEventsService {
|
||||
}
|
||||
this.updateEventProgress({ percentage: 0, type: this.getType() });
|
||||
const events = await this.formatEvents(
|
||||
await this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() })
|
||||
await this.batchEventsService.getBatchEvents({
|
||||
fromBlock,
|
||||
toBlock,
|
||||
type: this.getType()
|
||||
})
|
||||
);
|
||||
return {
|
||||
events,
|
||||
@@ -2924,7 +2999,9 @@ class BaseEventsService {
|
||||
}
|
||||
const graphEvents = await this.getEventsFromGraph({ fromBlock });
|
||||
const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock;
|
||||
const rpcEvents = await this.getEventsFromRpc({ fromBlock: lastSyncBlock });
|
||||
const rpcEvents = await this.getEventsFromRpc({
|
||||
fromBlock: lastSyncBlock
|
||||
});
|
||||
return {
|
||||
events: [...graphEvents.events, ...rpcEvents.events],
|
||||
lastBlock: rpcEvents.lastBlock
|
||||
@@ -3090,7 +3167,9 @@ class BaseTornadoService extends BaseEventsService {
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
async getLatestEvents({ fromBlock }) {
|
||||
async getLatestEvents({
|
||||
fromBlock
|
||||
}) {
|
||||
if (this.tovarishClient?.selectedRelayer) {
|
||||
const { events, lastSyncBlock: lastBlock } = await this.tovarishClient.getEvents({
|
||||
type: this.getTovarishType(),
|
||||
@@ -3236,7 +3315,11 @@ function parseComment(Governance, calldata) {
|
||||
try {
|
||||
const methodLength = 4;
|
||||
const result = abiCoder.decode(["address[]", "uint256", "bool"], dataSlice(calldata, methodLength));
|
||||
const data = Governance.interface.encodeFunctionData("castDelegatedVote", result);
|
||||
const data = Governance.interface.encodeFunctionData(
|
||||
// @ts-expect-error encodeFunctionData is broken lol
|
||||
"castDelegatedVote",
|
||||
result
|
||||
);
|
||||
const length = dataLength(data);
|
||||
const str = abiCoder.decode(["string"], dataSlice(calldata, length))[0];
|
||||
const [contact, message] = JSON.parse(str);
|
||||
@@ -3725,7 +3808,9 @@ async function loadDBEvents({
|
||||
lastBlock: 0
|
||||
};
|
||||
}
|
||||
const events = (await idb.getAll({ storeName: instanceName })).map((e) => {
|
||||
const events = (await idb.getAll({
|
||||
storeName: instanceName
|
||||
})).map((e) => {
|
||||
delete e.eid;
|
||||
return e;
|
||||
});
|
||||
@@ -9183,16 +9268,16 @@ class ReverseRecords__factory {
|
||||
}
|
||||
|
||||
var index = /*#__PURE__*/Object.freeze({
|
||||
__proto__: null,
|
||||
ENSNameWrapper__factory: ENSNameWrapper__factory,
|
||||
ENSRegistry__factory: ENSRegistry__factory,
|
||||
ENSResolver__factory: ENSResolver__factory,
|
||||
ENS__factory: ENS__factory,
|
||||
ERC20__factory: ERC20__factory,
|
||||
Multicall__factory: Multicall__factory,
|
||||
OffchainOracle__factory: OffchainOracle__factory,
|
||||
OvmGasPriceOracle__factory: OvmGasPriceOracle__factory,
|
||||
ReverseRecords__factory: ReverseRecords__factory
|
||||
__proto__: null,
|
||||
ENSNameWrapper__factory: ENSNameWrapper__factory,
|
||||
ENSRegistry__factory: ENSRegistry__factory,
|
||||
ENSResolver__factory: ENSResolver__factory,
|
||||
ENS__factory: ENS__factory,
|
||||
ERC20__factory: ERC20__factory,
|
||||
Multicall__factory: Multicall__factory,
|
||||
OffchainOracle__factory: OffchainOracle__factory,
|
||||
OvmGasPriceOracle__factory: OvmGasPriceOracle__factory,
|
||||
ReverseRecords__factory: ReverseRecords__factory
|
||||
});
|
||||
|
||||
class Pedersen {
|
||||
@@ -9352,7 +9437,10 @@ class Deposit {
|
||||
const bytes = bnToBytes(parsedNoteHex);
|
||||
const nullifier = BigInt(leBuff2Int(bytes.slice(0, 31)).toString());
|
||||
const secret = BigInt(leBuff2Int(bytes.slice(31, 62)).toString());
|
||||
const { noteHex, commitmentHex, nullifierHex } = await createDeposit({ nullifier, secret });
|
||||
const { noteHex, commitmentHex, nullifierHex } = await createDeposit({
|
||||
nullifier,
|
||||
secret
|
||||
});
|
||||
const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${commitmentHex}`;
|
||||
const newDeposit = new Deposit({
|
||||
currency,
|
||||
@@ -9423,7 +9511,6 @@ function unpackEncryptedMessage(encryptedMessage) {
|
||||
};
|
||||
}
|
||||
class NoteAccount {
|
||||
netId;
|
||||
blockNumber;
|
||||
// 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
|
||||
@@ -9432,11 +9519,10 @@ class NoteAccount {
|
||||
recoveryAddress;
|
||||
// Note encryption public key derived from recoveryKey
|
||||
recoveryPublicKey;
|
||||
constructor({ netId, blockNumber, recoveryKey }) {
|
||||
constructor({ blockNumber, recoveryKey }) {
|
||||
if (!recoveryKey) {
|
||||
recoveryKey = rHex(32).slice(2);
|
||||
}
|
||||
this.netId = Math.floor(Number(netId));
|
||||
this.blockNumber = blockNumber;
|
||||
this.recoveryKey = recoveryKey;
|
||||
this.recoveryAddress = computeAddress("0x" + recoveryKey);
|
||||
@@ -9479,7 +9565,7 @@ class NoteAccount {
|
||||
/**
|
||||
* Decrypt Echoer backuped note encryption account with private keys
|
||||
*/
|
||||
async decryptSignerNoteAccounts(signer, events) {
|
||||
static async decryptSignerNoteAccounts(signer, events) {
|
||||
const signerAddress = signer.address;
|
||||
const decryptedEvents = [];
|
||||
for (const event of events) {
|
||||
@@ -9513,7 +9599,6 @@ class NoteAccount {
|
||||
}
|
||||
decryptedEvents.push(
|
||||
new NoteAccount({
|
||||
netId: this.netId,
|
||||
blockNumber: event.blockNumber,
|
||||
recoveryKey
|
||||
})
|
||||
@@ -10549,7 +10634,9 @@ class TokenPriceOracle {
|
||||
const price = await this.oracle.getRateToEth(tokenAddress, true);
|
||||
return price * BigInt(10 ** decimals) / BigInt(10 ** 18);
|
||||
} catch (err) {
|
||||
console.log(`Failed to fetch oracle price for ${tokenAddress}, will use fallback price ${this.fallbackPrice}`);
|
||||
console.log(
|
||||
`Failed to fetch oracle price for ${tokenAddress}, will use fallback price ${this.fallbackPrice}`
|
||||
);
|
||||
console.log(err);
|
||||
return this.fallbackPrice;
|
||||
}
|
||||
@@ -10649,7 +10736,11 @@ class TovarishClient extends RelayerClient {
|
||||
url,
|
||||
relayerAddress
|
||||
}) {
|
||||
const status = await super.askRelayerStatus({ hostname, url, relayerAddress });
|
||||
const status = await super.askRelayerStatus({
|
||||
hostname,
|
||||
url,
|
||||
relayerAddress
|
||||
});
|
||||
if (!status.version.includes("tovarish")) {
|
||||
throw new Error("Not a tovarish relayer!");
|
||||
}
|
||||
@@ -10685,7 +10776,14 @@ class TovarishClient extends RelayerClient {
|
||||
for (const rawStatus of statusArray) {
|
||||
const netId = rawStatus.netId;
|
||||
const config = getConfig(netId);
|
||||
const statusValidator = ajv.compile(getStatusSchema(rawStatus.netId, config, this.tovarish));
|
||||
const statusValidator = ajv.compile(
|
||||
getStatusSchema(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
rawStatus.netId,
|
||||
config,
|
||||
this.tovarish
|
||||
)
|
||||
);
|
||||
if (!statusValidator) {
|
||||
continue;
|
||||
}
|
||||
@@ -10716,7 +10814,10 @@ class TovarishClient extends RelayerClient {
|
||||
}
|
||||
const hostname = `${tovarishHost}/${this.netId}`;
|
||||
try {
|
||||
const status = await this.askRelayerStatus({ hostname, relayerAddress });
|
||||
const status = await this.askRelayerStatus({
|
||||
hostname,
|
||||
relayerAddress
|
||||
});
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
@@ -10748,16 +10849,18 @@ class TovarishClient extends RelayerClient {
|
||||
}
|
||||
async getValidRelayers(relayers) {
|
||||
const invalidRelayers = [];
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter(
|
||||
(r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
);
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers
|
||||
@@ -10770,7 +10873,10 @@ class TovarishClient extends RelayerClient {
|
||||
relayers.filter((r) => r.tovarishHost && r.tovarishNetworks?.length).map(async (relayer) => {
|
||||
const { ensName, relayerAddress, tovarishHost } = relayer;
|
||||
try {
|
||||
const statusArray = await this.askAllStatus({ hostname: tovarishHost, relayerAddress });
|
||||
const statusArray = await this.askAllStatus({
|
||||
hostname: tovarishHost,
|
||||
relayerAddress
|
||||
});
|
||||
for (const status of statusArray) {
|
||||
validRelayers.push({
|
||||
netId: status.netId,
|
||||
|
||||
206
dist/tornado.umd.js
vendored
206
dist/tornado.umd.js
vendored
@@ -58681,7 +58681,11 @@ class BatchTransactionService {
|
||||
results.push(...chunksResult);
|
||||
txCount += chunks.length;
|
||||
if (typeof this.onProgress === "function") {
|
||||
this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length });
|
||||
this.onProgress({
|
||||
percentage: txCount / txs.length,
|
||||
currentIndex: txCount,
|
||||
totalIndex: txs.length
|
||||
});
|
||||
}
|
||||
}
|
||||
return results;
|
||||
@@ -58920,7 +58924,10 @@ class Deposit {
|
||||
const bytes = (0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .bnToBytes */ .jm)(parsedNoteHex);
|
||||
const nullifier = BigInt((0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .leBuff2Int */ .ae)(bytes.slice(0, 31)).toString());
|
||||
const secret = BigInt((0,_utils__WEBPACK_IMPORTED_MODULE_0__/* .leBuff2Int */ .ae)(bytes.slice(31, 62)).toString());
|
||||
const { noteHex, commitmentHex, nullifierHex } = await createDeposit({ nullifier, secret });
|
||||
const { noteHex, commitmentHex, nullifierHex } = await createDeposit({
|
||||
nullifier,
|
||||
secret
|
||||
});
|
||||
const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${commitmentHex}`;
|
||||
const newDeposit = new Deposit({
|
||||
currency,
|
||||
@@ -59012,7 +59019,6 @@ function unpackEncryptedMessage(encryptedMessage) {
|
||||
};
|
||||
}
|
||||
class NoteAccount {
|
||||
netId;
|
||||
blockNumber;
|
||||
// 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
|
||||
@@ -59021,11 +59027,10 @@ class NoteAccount {
|
||||
recoveryAddress;
|
||||
// Note encryption public key derived from recoveryKey
|
||||
recoveryPublicKey;
|
||||
constructor({ netId, blockNumber, recoveryKey }) {
|
||||
constructor({ blockNumber, recoveryKey }) {
|
||||
if (!recoveryKey) {
|
||||
recoveryKey = (0,_utils__WEBPACK_IMPORTED_MODULE_1__/* .rHex */ .G9)(32).slice(2);
|
||||
}
|
||||
this.netId = Math.floor(Number(netId));
|
||||
this.blockNumber = blockNumber;
|
||||
this.recoveryKey = recoveryKey;
|
||||
this.recoveryAddress = (0,ethers__WEBPACK_IMPORTED_MODULE_2__/* .computeAddress */ .K)("0x" + recoveryKey);
|
||||
@@ -59068,7 +59073,7 @@ class NoteAccount {
|
||||
/**
|
||||
* Decrypt Echoer backuped note encryption account with private keys
|
||||
*/
|
||||
async decryptSignerNoteAccounts(signer, events) {
|
||||
static async decryptSignerNoteAccounts(signer, events) {
|
||||
const signerAddress = signer.address;
|
||||
const decryptedEvents = [];
|
||||
for (const event of events) {
|
||||
@@ -59102,7 +59107,6 @@ class NoteAccount {
|
||||
}
|
||||
decryptedEvents.push(
|
||||
new NoteAccount({
|
||||
netId: this.netId,
|
||||
blockNumber: event.blockNumber,
|
||||
recoveryKey
|
||||
})
|
||||
@@ -59435,7 +59439,11 @@ class BaseEventsService {
|
||||
}
|
||||
this.updateEventProgress({ percentage: 0, type: this.getType() });
|
||||
const events = await this.formatEvents(
|
||||
await this.batchEventsService.getBatchEvents({ fromBlock, toBlock, type: this.getType() })
|
||||
await this.batchEventsService.getBatchEvents({
|
||||
fromBlock,
|
||||
toBlock,
|
||||
type: this.getType()
|
||||
})
|
||||
);
|
||||
return {
|
||||
events,
|
||||
@@ -59462,7 +59470,9 @@ class BaseEventsService {
|
||||
}
|
||||
const graphEvents = await this.getEventsFromGraph({ fromBlock });
|
||||
const lastSyncBlock = graphEvents.lastBlock && graphEvents.lastBlock >= fromBlock ? graphEvents.lastBlock : fromBlock;
|
||||
const rpcEvents = await this.getEventsFromRpc({ fromBlock: lastSyncBlock });
|
||||
const rpcEvents = await this.getEventsFromRpc({
|
||||
fromBlock: lastSyncBlock
|
||||
});
|
||||
return {
|
||||
events: [...graphEvents.events, ...rpcEvents.events],
|
||||
lastBlock: rpcEvents.lastBlock
|
||||
@@ -59628,7 +59638,9 @@ class BaseTornadoService extends BaseEventsService {
|
||||
}
|
||||
return void 0;
|
||||
}
|
||||
async getLatestEvents({ fromBlock }) {
|
||||
async getLatestEvents({
|
||||
fromBlock
|
||||
}) {
|
||||
if (this.tovarishClient?.selectedRelayer) {
|
||||
const { events, lastSyncBlock: lastBlock } = await this.tovarishClient.getEvents({
|
||||
type: this.getTovarishType(),
|
||||
@@ -59774,7 +59786,11 @@ function parseComment(Governance, calldata) {
|
||||
try {
|
||||
const methodLength = 4;
|
||||
const result = abiCoder.decode(["address[]", "uint256", "bool"], (0,ethers__WEBPACK_IMPORTED_MODULE_7__/* .dataSlice */ .ZG)(calldata, methodLength));
|
||||
const data = Governance.interface.encodeFunctionData("castDelegatedVote", result);
|
||||
const data = Governance.interface.encodeFunctionData(
|
||||
// @ts-expect-error encodeFunctionData is broken lol
|
||||
"castDelegatedVote",
|
||||
result
|
||||
);
|
||||
const length = (0,ethers__WEBPACK_IMPORTED_MODULE_7__/* .dataLength */ .pO)(data);
|
||||
const str = abiCoder.decode(["string"], (0,ethers__WEBPACK_IMPORTED_MODULE_7__/* .dataSlice */ .ZG)(calldata, length))[0];
|
||||
const [contact, message] = JSON.parse(str);
|
||||
@@ -60236,7 +60252,9 @@ async function loadDBEvents({
|
||||
lastBlock: 0
|
||||
};
|
||||
}
|
||||
const events = (await idb.getAll({ storeName: instanceName })).map((e) => {
|
||||
const events = (await idb.getAll({
|
||||
storeName: instanceName
|
||||
})).map((e) => {
|
||||
delete e.eid;
|
||||
return e;
|
||||
});
|
||||
@@ -61051,7 +61069,12 @@ async function getAllRegisters({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getRegisters({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getRegisters({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -61140,7 +61163,14 @@ async function getAllDeposits({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getDeposits({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getDeposits({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -61235,7 +61265,14 @@ async function getAllWithdrawals({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getWithdrawals({ graphApi, subgraphName, currency, amount, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getWithdrawals({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -61358,7 +61395,12 @@ async function getAllGraphEchoEvents({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getGraphEchoEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getGraphEchoEvents({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -61445,7 +61487,12 @@ async function getAllEncryptedNotes({
|
||||
// eslint-disable-next-line prefer-const
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getEncryptedNotes({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getEncryptedNotes({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
if (isEmptyArray(result2)) {
|
||||
break;
|
||||
@@ -61530,14 +61577,29 @@ async function getAllGovernanceEvents({
|
||||
_meta: {
|
||||
block: { number: currentBlock }
|
||||
}
|
||||
} = await getGovernanceEvents({ graphApi, subgraphName, fromBlock, fetchDataOptions: fetchDataOptions2 });
|
||||
} = await getGovernanceEvents({
|
||||
graphApi,
|
||||
subgraphName,
|
||||
fromBlock,
|
||||
fetchDataOptions: fetchDataOptions2
|
||||
});
|
||||
lastSyncBlock = currentBlock;
|
||||
const eventsLength = proposals.length + votes.length + delegates.length + undelegates.length;
|
||||
if (eventsLength === 0) {
|
||||
break;
|
||||
}
|
||||
const formattedProposals = proposals.map(
|
||||
({ blockNumber, logIndex, transactionHash, proposalId, proposer, target, startTime, endTime, description }) => {
|
||||
({
|
||||
blockNumber,
|
||||
logIndex,
|
||||
transactionHash,
|
||||
proposalId,
|
||||
proposer,
|
||||
target,
|
||||
startTime,
|
||||
endTime,
|
||||
description
|
||||
}) => {
|
||||
return {
|
||||
blockNumber: Number(blockNumber),
|
||||
logIndex: Number(logIndex),
|
||||
@@ -63661,7 +63723,9 @@ class TokenPriceOracle {
|
||||
const price = await this.oracle.getRateToEth(tokenAddress, true);
|
||||
return price * BigInt(10 ** decimals) / BigInt(10 ** 18);
|
||||
} catch (err) {
|
||||
console.log(`Failed to fetch oracle price for ${tokenAddress}, will use fallback price ${this.fallbackPrice}`);
|
||||
console.log(
|
||||
`Failed to fetch oracle price for ${tokenAddress}, will use fallback price ${this.fallbackPrice}`
|
||||
);
|
||||
console.log(err);
|
||||
return this.fallbackPrice;
|
||||
}
|
||||
@@ -71151,7 +71215,10 @@ class RelayerClient {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const status = await this.askRelayerStatus({ hostname, relayerAddress });
|
||||
const status = await this.askRelayerStatus({
|
||||
hostname,
|
||||
relayerAddress
|
||||
});
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
@@ -71177,16 +71244,18 @@ class RelayerClient {
|
||||
}
|
||||
async getValidRelayers(relayers) {
|
||||
const invalidRelayers = [];
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter(
|
||||
(r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
);
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers
|
||||
@@ -71343,8 +71412,14 @@ const addressSchemaType = {
|
||||
isAddress: true
|
||||
};
|
||||
const bnSchemaType = { type: "string", BN: true };
|
||||
const proofSchemaType = { type: "string", pattern: "^0x[a-fA-F0-9]{512}$" };
|
||||
const bytes32SchemaType = { type: "string", pattern: "^0x[a-fA-F0-9]{64}$" };
|
||||
const proofSchemaType = {
|
||||
type: "string",
|
||||
pattern: "^0x[a-fA-F0-9]{512}$"
|
||||
};
|
||||
const bytes32SchemaType = {
|
||||
type: "string",
|
||||
pattern: "^0x[a-fA-F0-9]{64}$"
|
||||
};
|
||||
const bytes32BNSchemaType = { ...bytes32SchemaType, BN: true };
|
||||
|
||||
;// ./src/schemas/events.ts
|
||||
@@ -71402,7 +71477,16 @@ const governanceEventsSchema = {
|
||||
from: addressSchemaType,
|
||||
input: { type: "string" }
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, "event", "proposalId", "voter", "support", "votes", "from", "input"],
|
||||
required: [
|
||||
...baseEventsSchemaRequired,
|
||||
"event",
|
||||
"proposalId",
|
||||
"voter",
|
||||
"support",
|
||||
"votes",
|
||||
"from",
|
||||
"input"
|
||||
],
|
||||
additionalProperties: false
|
||||
},
|
||||
{
|
||||
@@ -71577,10 +71661,13 @@ function getStatusSchema(netId, config, tovarish) {
|
||||
properties: {
|
||||
instanceAddress: {
|
||||
type: "object",
|
||||
properties: amounts.reduce((acc2, cur) => {
|
||||
acc2[cur] = addressSchemaType;
|
||||
return acc2;
|
||||
}, {}),
|
||||
properties: amounts.reduce(
|
||||
(acc2, cur) => {
|
||||
acc2[cur] = addressSchemaType;
|
||||
return acc2;
|
||||
},
|
||||
{}
|
||||
),
|
||||
required: amounts.filter((amount) => !optionalInstances.includes(amount))
|
||||
},
|
||||
decimals: { enum: [decimals] }
|
||||
@@ -71781,7 +71868,11 @@ class TovarishClient extends _relayerClient__WEBPACK_IMPORTED_MODULE_0__/* .Rela
|
||||
url,
|
||||
relayerAddress
|
||||
}) {
|
||||
const status = await super.askRelayerStatus({ hostname, url, relayerAddress });
|
||||
const status = await super.askRelayerStatus({
|
||||
hostname,
|
||||
url,
|
||||
relayerAddress
|
||||
});
|
||||
if (!status.version.includes("tovarish")) {
|
||||
throw new Error("Not a tovarish relayer!");
|
||||
}
|
||||
@@ -71817,7 +71908,14 @@ class TovarishClient extends _relayerClient__WEBPACK_IMPORTED_MODULE_0__/* .Rela
|
||||
for (const rawStatus of statusArray) {
|
||||
const netId = rawStatus.netId;
|
||||
const config = (0,_networkConfig__WEBPACK_IMPORTED_MODULE_3__/* .getConfig */ .zj)(netId);
|
||||
const statusValidator = _schemas__WEBPACK_IMPORTED_MODULE_2__/* .ajv */ .SS.compile((0,_schemas__WEBPACK_IMPORTED_MODULE_2__/* .getStatusSchema */ .c_)(rawStatus.netId, config, this.tovarish));
|
||||
const statusValidator = _schemas__WEBPACK_IMPORTED_MODULE_2__/* .ajv */ .SS.compile(
|
||||
(0,_schemas__WEBPACK_IMPORTED_MODULE_2__/* .getStatusSchema */ .c_)(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
rawStatus.netId,
|
||||
config,
|
||||
this.tovarish
|
||||
)
|
||||
);
|
||||
if (!statusValidator) {
|
||||
continue;
|
||||
}
|
||||
@@ -71848,7 +71946,10 @@ class TovarishClient extends _relayerClient__WEBPACK_IMPORTED_MODULE_0__/* .Rela
|
||||
}
|
||||
const hostname = `${tovarishHost}/${this.netId}`;
|
||||
try {
|
||||
const status = await this.askRelayerStatus({ hostname, relayerAddress });
|
||||
const status = await this.askRelayerStatus({
|
||||
hostname,
|
||||
relayerAddress
|
||||
});
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
@@ -71880,16 +71981,18 @@ class TovarishClient extends _relayerClient__WEBPACK_IMPORTED_MODULE_0__/* .Rela
|
||||
}
|
||||
async getValidRelayers(relayers) {
|
||||
const invalidRelayers = [];
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter(
|
||||
(r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (r.hasError) {
|
||||
invalidRelayers.push(r);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
);
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers
|
||||
@@ -71902,7 +72005,10 @@ class TovarishClient extends _relayerClient__WEBPACK_IMPORTED_MODULE_0__/* .Rela
|
||||
relayers.filter((r) => r.tovarishHost && r.tovarishNetworks?.length).map(async (relayer) => {
|
||||
const { ensName, relayerAddress, tovarishHost } = relayer;
|
||||
try {
|
||||
const statusArray = await this.askAllStatus({ hostname: tovarishHost, relayerAddress });
|
||||
const statusArray = await this.askAllStatus({
|
||||
hostname: tovarishHost,
|
||||
relayerAddress
|
||||
});
|
||||
for (const status of statusArray) {
|
||||
validRelayers.push({
|
||||
netId: status.netId,
|
||||
|
||||
2
dist/tornado.umd.min.js
vendored
2
dist/tornado.umd.min.js
vendored
File diff suppressed because one or more lines are too long
@@ -3,7 +3,7 @@ import '@nomicfoundation/hardhat-toolbox';
|
||||
import '@nomicfoundation/hardhat-ethers';
|
||||
|
||||
const config: HardhatUserConfig = {
|
||||
solidity: '0.8.28',
|
||||
solidity: '0.8.28',
|
||||
};
|
||||
|
||||
export default config;
|
||||
182
package.json
182
package.json
@@ -1,93 +1,93 @@
|
||||
{
|
||||
"name": "@tornado/core",
|
||||
"version": "1.0.19",
|
||||
"description": "An SDK for building applications on top of Privacy Pools",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"unpkg": "./dist/tornado.umd.min.js",
|
||||
"jsdelivr": "./dist/tornado.umd.min.js",
|
||||
"scripts": {
|
||||
"typechain": "typechain --target ethers-v6 --out-dir src/typechain src/abi/*.json",
|
||||
"types": "tsc --declaration --emitDeclarationOnly -p tsconfig.build.json",
|
||||
"lint": "eslint src/**/*.ts test/**/*.ts --ext .ts --ignore-pattern src/typechain",
|
||||
"build:node": "rollup -c",
|
||||
"build:web": "webpack",
|
||||
"build": "yarn types && yarn build:node && yarn build:web",
|
||||
"test": "nyc mocha --require ts-node/register --require source-map-support/register --recursive 'test/**/*.ts' --timeout '300000'"
|
||||
},
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
".eslintrc.js",
|
||||
".gitattributes",
|
||||
".gitignore",
|
||||
".npmrc",
|
||||
"logo.png",
|
||||
"logo2.png",
|
||||
"rollup.config.mjs",
|
||||
"tsconfig.json",
|
||||
"yarn.lock"
|
||||
],
|
||||
"dependencies": {
|
||||
"@metamask/eth-sig-util": "^8.0.0",
|
||||
"@tornado/contracts": "git+https://git.tornado.ws/tornadocontrib/tornado-contracts.git#1b1d707878c16a3dc60d295299d4f0e7ce6ba831",
|
||||
"@tornado/fixed-merkle-tree": "^0.7.3",
|
||||
"@tornado/snarkjs": "^0.1.20",
|
||||
"@tornado/websnark": "^0.0.4",
|
||||
"ajv": "^8.17.1",
|
||||
"bn.js": "^5.2.1",
|
||||
"circomlibjs": "0.1.7",
|
||||
"cross-fetch": "^4.0.0",
|
||||
"ethers": "^6.13.4",
|
||||
"ffjavascript": "0.2.48",
|
||||
"fflate": "^0.8.2",
|
||||
"idb": "^8.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nomicfoundation/hardhat-chai-matchers": "^2.0.7",
|
||||
"@nomicfoundation/hardhat-ethers": "^3.0.8",
|
||||
"@nomicfoundation/hardhat-ignition": "^0.15.5",
|
||||
"@nomicfoundation/hardhat-ignition-ethers": "^0.15.5",
|
||||
"@nomicfoundation/hardhat-network-helpers": "^1.0.11",
|
||||
"@nomicfoundation/hardhat-toolbox": "^5.0.0",
|
||||
"@nomicfoundation/hardhat-verify": "^2.0.10",
|
||||
"@nomicfoundation/ignition-core": "^0.15.5",
|
||||
"@rollup/plugin-commonjs": "^28.0.1",
|
||||
"@rollup/plugin-json": "^6.1.0",
|
||||
"@rollup/plugin-node-resolve": "^15.3.0",
|
||||
"@typechain/ethers-v6": "^0.5.1",
|
||||
"@typechain/hardhat": "^9.1.0",
|
||||
"@types/bn.js": "^5.1.6",
|
||||
"@types/chai": "^4.2.0",
|
||||
"@types/circomlibjs": "^0.1.6",
|
||||
"@types/mocha": "^10.0.9",
|
||||
"@types/node": "^22.8.0",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
"@typescript-eslint/eslint-plugin": "^8.11.0",
|
||||
"@typescript-eslint/parser": "^8.11.0",
|
||||
"esbuild-loader": "^4.2.2",
|
||||
"eslint": "8.57.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-import-resolver-typescript": "^3.6.3",
|
||||
"eslint-plugin-import": "^2.31.0",
|
||||
"eslint-plugin-prettier": "^5.2.1",
|
||||
"hardhat": "^2.22.10",
|
||||
"hardhat-gas-reporter": "^2.2.1",
|
||||
"mocha": "^10.7.3",
|
||||
"node-polyfill-webpack-plugin": "^4.0.0",
|
||||
"nyc": "^17.1.0",
|
||||
"prettier": "^3.3.3",
|
||||
"rollup": "^4.24.0",
|
||||
"rollup-plugin-esbuild": "^6.1.1",
|
||||
"solidity-coverage": "^0.8.13",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsc": "^2.0.4",
|
||||
"typechain": "^8.3.2",
|
||||
"typescript": "^5.6.3",
|
||||
"webpack": "^5.95.0",
|
||||
"webpack-cli": "^5.1.4"
|
||||
}
|
||||
"name": "@tornado/core",
|
||||
"version": "1.0.19",
|
||||
"description": "An SDK for building applications on top of Privacy Pools",
|
||||
"main": "./dist/index.js",
|
||||
"module": "./dist/index.mjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"unpkg": "./dist/tornado.umd.min.js",
|
||||
"jsdelivr": "./dist/tornado.umd.min.js",
|
||||
"scripts": {
|
||||
"typechain": "typechain --target ethers-v6 --out-dir src/typechain src/abi/*.json",
|
||||
"types": "tsc --declaration --emitDeclarationOnly -p tsconfig.build.json",
|
||||
"lint": "eslint src/**/*.ts test/**/*.ts --ext .ts --ignore-pattern src/typechain",
|
||||
"build:node": "rollup -c",
|
||||
"build:web": "webpack",
|
||||
"build": "yarn types && yarn build:node && yarn build:web",
|
||||
"test": "nyc mocha --require ts-node/register --require source-map-support/register --recursive 'test/**/*.ts' --timeout '300000'"
|
||||
},
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"files": [
|
||||
"dist",
|
||||
"src",
|
||||
".eslintrc.js",
|
||||
".gitattributes",
|
||||
".gitignore",
|
||||
".npmrc",
|
||||
"logo.png",
|
||||
"logo2.png",
|
||||
"rollup.config.mjs",
|
||||
"tsconfig.json",
|
||||
"yarn.lock"
|
||||
],
|
||||
"dependencies": {
|
||||
"@metamask/eth-sig-util": "^8.0.0",
|
||||
"@tornado/contracts": "git+https://git.tornado.ws/tornadocontrib/tornado-contracts.git#1b1d707878c16a3dc60d295299d4f0e7ce6ba831",
|
||||
"@tornado/fixed-merkle-tree": "^0.7.3",
|
||||
"@tornado/snarkjs": "^0.1.20",
|
||||
"@tornado/websnark": "^0.0.4",
|
||||
"ajv": "^8.17.1",
|
||||
"bn.js": "^5.2.1",
|
||||
"circomlibjs": "0.1.7",
|
||||
"cross-fetch": "^4.0.0",
|
||||
"ethers": "^6.13.4",
|
||||
"ffjavascript": "0.2.48",
|
||||
"fflate": "^0.8.2",
|
||||
"idb": "^8.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@nomicfoundation/hardhat-chai-matchers": "^2.0.7",
|
||||
"@nomicfoundation/hardhat-ethers": "^3.0.8",
|
||||
"@nomicfoundation/hardhat-ignition": "^0.15.5",
|
||||
"@nomicfoundation/hardhat-ignition-ethers": "^0.15.5",
|
||||
"@nomicfoundation/hardhat-network-helpers": "^1.0.11",
|
||||
"@nomicfoundation/hardhat-toolbox": "^5.0.0",
|
||||
"@nomicfoundation/hardhat-verify": "^2.0.10",
|
||||
"@nomicfoundation/ignition-core": "^0.15.5",
|
||||
"@rollup/plugin-commonjs": "^28.0.1",
|
||||
"@rollup/plugin-json": "^6.1.0",
|
||||
"@rollup/plugin-node-resolve": "^15.3.0",
|
||||
"@typechain/ethers-v6": "^0.5.1",
|
||||
"@typechain/hardhat": "^9.1.0",
|
||||
"@types/bn.js": "^5.1.6",
|
||||
"@types/chai": "^4.2.0",
|
||||
"@types/circomlibjs": "^0.1.6",
|
||||
"@types/mocha": "^10.0.9",
|
||||
"@types/node": "^22.8.0",
|
||||
"@types/node-fetch": "^2.6.11",
|
||||
"@typescript-eslint/eslint-plugin": "^8.11.0",
|
||||
"@typescript-eslint/parser": "^8.11.0",
|
||||
"esbuild-loader": "^4.2.2",
|
||||
"eslint": "8.57.0",
|
||||
"eslint-config-prettier": "^9.1.0",
|
||||
"eslint-import-resolver-typescript": "^3.6.3",
|
||||
"eslint-plugin-import": "^2.31.0",
|
||||
"eslint-plugin-prettier": "^5.2.1",
|
||||
"hardhat": "^2.22.10",
|
||||
"hardhat-gas-reporter": "^2.2.1",
|
||||
"mocha": "^10.7.3",
|
||||
"node-polyfill-webpack-plugin": "^4.0.0",
|
||||
"nyc": "^17.1.0",
|
||||
"prettier": "^3.3.3",
|
||||
"rollup": "^4.24.0",
|
||||
"rollup-plugin-esbuild": "^6.1.1",
|
||||
"solidity-coverage": "^0.8.13",
|
||||
"ts-node": "^10.9.2",
|
||||
"tsc": "^2.0.4",
|
||||
"typechain": "^8.3.2",
|
||||
"typescript": "^5.6.3",
|
||||
"webpack": "^5.95.0",
|
||||
"webpack-cli": "^5.1.4"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,81 +7,81 @@ import { readFileSync } from 'fs';
|
||||
const pkgJson = JSON.parse(readFileSync("./package.json"));
|
||||
|
||||
const external = Object.keys(pkgJson.dependencies).concat(
|
||||
Object.keys(pkgJson.optionalDependencies || {}),
|
||||
[
|
||||
'http-proxy-agent',
|
||||
'https-proxy-agent',
|
||||
'socks-proxy-agent',
|
||||
'@tornado/websnark/src/utils',
|
||||
'@tornado/websnark/src/groth16',
|
||||
]
|
||||
Object.keys(pkgJson.optionalDependencies || {}),
|
||||
[
|
||||
'http-proxy-agent',
|
||||
'https-proxy-agent',
|
||||
'socks-proxy-agent',
|
||||
'@tornado/websnark/src/utils',
|
||||
'@tornado/websnark/src/groth16',
|
||||
]
|
||||
);
|
||||
|
||||
const config = [
|
||||
{
|
||||
input: 'src/index.ts',
|
||||
output: [
|
||||
{
|
||||
file: pkgJson.main,
|
||||
format: "cjs",
|
||||
esModule: false,
|
||||
},
|
||||
],
|
||||
external,
|
||||
plugins: [
|
||||
esbuild({
|
||||
include: /\.[jt]sx?$/,
|
||||
minify: false,
|
||||
sourceMap: true,
|
||||
target: 'es2022',
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve(),
|
||||
json()
|
||||
],
|
||||
},
|
||||
{
|
||||
input: 'src/index.ts',
|
||||
output: [
|
||||
{
|
||||
file: pkgJson.module,
|
||||
format: "esm",
|
||||
},
|
||||
],
|
||||
external,
|
||||
plugins: [
|
||||
esbuild({
|
||||
include: /\.[jt]sx?$/,
|
||||
minify: false,
|
||||
sourceMap: true,
|
||||
target: 'es2022',
|
||||
}),
|
||||
nodeResolve(),
|
||||
json()
|
||||
],
|
||||
},
|
||||
{
|
||||
input: 'src/merkleTreeWorker.ts',
|
||||
output: [
|
||||
{
|
||||
file: 'dist/merkleTreeWorker.js',
|
||||
format: "cjs",
|
||||
esModule: false,
|
||||
},
|
||||
],
|
||||
treeshake: 'smallest',
|
||||
plugins: [
|
||||
esbuild({
|
||||
include: /\.[jt]sx?$/,
|
||||
minify: false,
|
||||
sourceMap: true,
|
||||
target: 'es2022',
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve(),
|
||||
json()
|
||||
],
|
||||
}
|
||||
{
|
||||
input: 'src/index.ts',
|
||||
output: [
|
||||
{
|
||||
file: pkgJson.main,
|
||||
format: "cjs",
|
||||
esModule: false,
|
||||
},
|
||||
],
|
||||
external,
|
||||
plugins: [
|
||||
esbuild({
|
||||
include: /\.[jt]sx?$/,
|
||||
minify: false,
|
||||
sourceMap: true,
|
||||
target: 'es2022',
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve(),
|
||||
json()
|
||||
],
|
||||
},
|
||||
{
|
||||
input: 'src/index.ts',
|
||||
output: [
|
||||
{
|
||||
file: pkgJson.module,
|
||||
format: "esm",
|
||||
},
|
||||
],
|
||||
external,
|
||||
plugins: [
|
||||
esbuild({
|
||||
include: /\.[jt]sx?$/,
|
||||
minify: false,
|
||||
sourceMap: true,
|
||||
target: 'es2022',
|
||||
}),
|
||||
nodeResolve(),
|
||||
json()
|
||||
],
|
||||
},
|
||||
{
|
||||
input: 'src/merkleTreeWorker.ts',
|
||||
output: [
|
||||
{
|
||||
file: 'dist/merkleTreeWorker.js',
|
||||
format: "cjs",
|
||||
esModule: false,
|
||||
},
|
||||
],
|
||||
treeshake: 'smallest',
|
||||
plugins: [
|
||||
esbuild({
|
||||
include: /\.[jt]sx?$/,
|
||||
minify: false,
|
||||
sourceMap: true,
|
||||
target: 'es2022',
|
||||
}),
|
||||
commonjs(),
|
||||
nodeResolve(),
|
||||
json()
|
||||
],
|
||||
}
|
||||
]
|
||||
|
||||
export default config;
|
||||
556
src/batch.ts
556
src/batch.ts
@@ -2,338 +2,342 @@ import type { Provider, BlockTag, Block, TransactionResponse, BaseContract, Cont
|
||||
import { chunk, sleep } from './utils';
|
||||
|
||||
export interface BatchBlockServiceConstructor {
|
||||
provider: Provider;
|
||||
onProgress?: BatchBlockOnProgress;
|
||||
concurrencySize?: number;
|
||||
batchSize?: number;
|
||||
shouldRetry?: boolean;
|
||||
retryMax?: number;
|
||||
retryOn?: number;
|
||||
provider: Provider;
|
||||
onProgress?: BatchBlockOnProgress;
|
||||
concurrencySize?: number;
|
||||
batchSize?: number;
|
||||
shouldRetry?: boolean;
|
||||
retryMax?: number;
|
||||
retryOn?: number;
|
||||
}
|
||||
|
||||
export type BatchBlockOnProgress = ({
|
||||
percentage,
|
||||
currentIndex,
|
||||
totalIndex,
|
||||
percentage,
|
||||
currentIndex,
|
||||
totalIndex,
|
||||
}: {
|
||||
percentage: number;
|
||||
currentIndex?: number;
|
||||
totalIndex?: number;
|
||||
percentage: number;
|
||||
currentIndex?: number;
|
||||
totalIndex?: number;
|
||||
}) => void;
|
||||
|
||||
/**
|
||||
* Fetch blocks from web3 provider on batches
|
||||
*/
|
||||
export class BatchBlockService {
|
||||
provider: Provider;
|
||||
onProgress?: BatchBlockOnProgress;
|
||||
concurrencySize: number;
|
||||
batchSize: number;
|
||||
shouldRetry: boolean;
|
||||
retryMax: number;
|
||||
retryOn: number;
|
||||
constructor({
|
||||
provider,
|
||||
onProgress,
|
||||
concurrencySize = 10,
|
||||
batchSize = 10,
|
||||
shouldRetry = true,
|
||||
retryMax = 5,
|
||||
retryOn = 500,
|
||||
}: BatchBlockServiceConstructor) {
|
||||
this.provider = provider;
|
||||
this.onProgress = onProgress;
|
||||
this.concurrencySize = concurrencySize;
|
||||
this.batchSize = batchSize;
|
||||
this.shouldRetry = shouldRetry;
|
||||
this.retryMax = retryMax;
|
||||
this.retryOn = retryOn;
|
||||
}
|
||||
|
||||
async getBlock(blockTag: BlockTag): Promise<Block> {
|
||||
const blockObject = await this.provider.getBlock(blockTag);
|
||||
|
||||
// if the provider returns null (which they have corrupted block data for one of their nodes) throw and retry
|
||||
if (!blockObject) {
|
||||
const errMsg = `No block for ${blockTag}`;
|
||||
throw new Error(errMsg);
|
||||
provider: Provider;
|
||||
onProgress?: BatchBlockOnProgress;
|
||||
concurrencySize: number;
|
||||
batchSize: number;
|
||||
shouldRetry: boolean;
|
||||
retryMax: number;
|
||||
retryOn: number;
|
||||
constructor({
|
||||
provider,
|
||||
onProgress,
|
||||
concurrencySize = 10,
|
||||
batchSize = 10,
|
||||
shouldRetry = true,
|
||||
retryMax = 5,
|
||||
retryOn = 500,
|
||||
}: BatchBlockServiceConstructor) {
|
||||
this.provider = provider;
|
||||
this.onProgress = onProgress;
|
||||
this.concurrencySize = concurrencySize;
|
||||
this.batchSize = batchSize;
|
||||
this.shouldRetry = shouldRetry;
|
||||
this.retryMax = retryMax;
|
||||
this.retryOn = retryOn;
|
||||
}
|
||||
|
||||
return blockObject;
|
||||
}
|
||||
async getBlock(blockTag: BlockTag): Promise<Block> {
|
||||
const blockObject = await this.provider.getBlock(blockTag);
|
||||
|
||||
createBatchRequest(batchArray: BlockTag[][]): Promise<Block[]>[] {
|
||||
return batchArray.map(async (blocks: BlockTag[], index: number) => {
|
||||
// send batch requests on milliseconds to avoid including them on a single batch request
|
||||
await sleep(20 * index);
|
||||
|
||||
return (async () => {
|
||||
let retries = 0;
|
||||
let err;
|
||||
|
||||
// eslint-disable-next-line no-unmodified-loop-condition
|
||||
while ((!this.shouldRetry && retries === 0) || (this.shouldRetry && retries < this.retryMax)) {
|
||||
try {
|
||||
return await Promise.all(blocks.map((b) => this.getBlock(b)));
|
||||
} catch (e) {
|
||||
retries++;
|
||||
err = e;
|
||||
|
||||
// retry on 0.5 seconds
|
||||
await sleep(this.retryOn);
|
||||
}
|
||||
// if the provider returns null (which they have corrupted block data for one of their nodes) throw and retry
|
||||
if (!blockObject) {
|
||||
const errMsg = `No block for ${blockTag}`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
throw err;
|
||||
})();
|
||||
});
|
||||
}
|
||||
|
||||
async getBatchBlocks(blocks: BlockTag[]): Promise<Block[]> {
|
||||
let blockCount = 0;
|
||||
const results: Block[] = [];
|
||||
|
||||
for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) {
|
||||
const chunksResult = (await Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat();
|
||||
|
||||
results.push(...chunksResult);
|
||||
|
||||
blockCount += chunks.length;
|
||||
|
||||
if (typeof this.onProgress === 'function') {
|
||||
this.onProgress({
|
||||
percentage: blockCount / blocks.length,
|
||||
currentIndex: blockCount,
|
||||
totalIndex: blocks.length,
|
||||
});
|
||||
}
|
||||
return blockObject;
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
createBatchRequest(batchArray: BlockTag[][]): Promise<Block[]>[] {
|
||||
return batchArray.map(async (blocks: BlockTag[], index: number) => {
|
||||
// send batch requests on milliseconds to avoid including them on a single batch request
|
||||
await sleep(20 * index);
|
||||
|
||||
return (async () => {
|
||||
let retries = 0;
|
||||
let err;
|
||||
|
||||
// eslint-disable-next-line no-unmodified-loop-condition
|
||||
while ((!this.shouldRetry && retries === 0) || (this.shouldRetry && retries < this.retryMax)) {
|
||||
try {
|
||||
return await Promise.all(blocks.map((b) => this.getBlock(b)));
|
||||
} catch (e) {
|
||||
retries++;
|
||||
err = e;
|
||||
|
||||
// retry on 0.5 seconds
|
||||
await sleep(this.retryOn);
|
||||
}
|
||||
}
|
||||
|
||||
throw err;
|
||||
})();
|
||||
});
|
||||
}
|
||||
|
||||
async getBatchBlocks(blocks: BlockTag[]): Promise<Block[]> {
|
||||
let blockCount = 0;
|
||||
const results: Block[] = [];
|
||||
|
||||
for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) {
|
||||
const chunksResult = (await Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat();
|
||||
|
||||
results.push(...chunksResult);
|
||||
|
||||
blockCount += chunks.length;
|
||||
|
||||
if (typeof this.onProgress === 'function') {
|
||||
this.onProgress({
|
||||
percentage: blockCount / blocks.length,
|
||||
currentIndex: blockCount,
|
||||
totalIndex: blocks.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch transactions from web3 provider on batches
|
||||
*/
|
||||
export class BatchTransactionService {
|
||||
provider: Provider;
|
||||
onProgress?: BatchBlockOnProgress;
|
||||
concurrencySize: number;
|
||||
batchSize: number;
|
||||
shouldRetry: boolean;
|
||||
retryMax: number;
|
||||
retryOn: number;
|
||||
constructor({
|
||||
provider,
|
||||
onProgress,
|
||||
concurrencySize = 10,
|
||||
batchSize = 10,
|
||||
shouldRetry = true,
|
||||
retryMax = 5,
|
||||
retryOn = 500,
|
||||
}: BatchBlockServiceConstructor) {
|
||||
this.provider = provider;
|
||||
this.onProgress = onProgress;
|
||||
this.concurrencySize = concurrencySize;
|
||||
this.batchSize = batchSize;
|
||||
this.shouldRetry = shouldRetry;
|
||||
this.retryMax = retryMax;
|
||||
this.retryOn = retryOn;
|
||||
}
|
||||
|
||||
async getTransaction(txHash: string): Promise<TransactionResponse> {
|
||||
const txObject = await this.provider.getTransaction(txHash);
|
||||
|
||||
if (!txObject) {
|
||||
const errMsg = `No transaction for ${txHash}`;
|
||||
throw new Error(errMsg);
|
||||
provider: Provider;
|
||||
onProgress?: BatchBlockOnProgress;
|
||||
concurrencySize: number;
|
||||
batchSize: number;
|
||||
shouldRetry: boolean;
|
||||
retryMax: number;
|
||||
retryOn: number;
|
||||
constructor({
|
||||
provider,
|
||||
onProgress,
|
||||
concurrencySize = 10,
|
||||
batchSize = 10,
|
||||
shouldRetry = true,
|
||||
retryMax = 5,
|
||||
retryOn = 500,
|
||||
}: BatchBlockServiceConstructor) {
|
||||
this.provider = provider;
|
||||
this.onProgress = onProgress;
|
||||
this.concurrencySize = concurrencySize;
|
||||
this.batchSize = batchSize;
|
||||
this.shouldRetry = shouldRetry;
|
||||
this.retryMax = retryMax;
|
||||
this.retryOn = retryOn;
|
||||
}
|
||||
|
||||
return txObject;
|
||||
}
|
||||
async getTransaction(txHash: string): Promise<TransactionResponse> {
|
||||
const txObject = await this.provider.getTransaction(txHash);
|
||||
|
||||
createBatchRequest(batchArray: string[][]): Promise<TransactionResponse[]>[] {
|
||||
return batchArray.map(async (txs: string[], index: number) => {
|
||||
await sleep(20 * index);
|
||||
|
||||
return (async () => {
|
||||
let retries = 0;
|
||||
let err;
|
||||
|
||||
// eslint-disable-next-line no-unmodified-loop-condition
|
||||
while ((!this.shouldRetry && retries === 0) || (this.shouldRetry && retries < this.retryMax)) {
|
||||
try {
|
||||
return await Promise.all(txs.map((tx) => this.getTransaction(tx)));
|
||||
} catch (e) {
|
||||
retries++;
|
||||
err = e;
|
||||
|
||||
// retry on 0.5 seconds
|
||||
await sleep(this.retryOn);
|
||||
}
|
||||
if (!txObject) {
|
||||
const errMsg = `No transaction for ${txHash}`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
throw err;
|
||||
})();
|
||||
});
|
||||
}
|
||||
|
||||
async getBatchTransactions(txs: string[]): Promise<TransactionResponse[]> {
|
||||
let txCount = 0;
|
||||
const results = [];
|
||||
|
||||
for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) {
|
||||
const chunksResult = (await Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat();
|
||||
|
||||
results.push(...chunksResult);
|
||||
|
||||
txCount += chunks.length;
|
||||
|
||||
if (typeof this.onProgress === 'function') {
|
||||
this.onProgress({ percentage: txCount / txs.length, currentIndex: txCount, totalIndex: txs.length });
|
||||
}
|
||||
return txObject;
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
createBatchRequest(batchArray: string[][]): Promise<TransactionResponse[]>[] {
|
||||
return batchArray.map(async (txs: string[], index: number) => {
|
||||
await sleep(20 * index);
|
||||
|
||||
return (async () => {
|
||||
let retries = 0;
|
||||
let err;
|
||||
|
||||
// eslint-disable-next-line no-unmodified-loop-condition
|
||||
while ((!this.shouldRetry && retries === 0) || (this.shouldRetry && retries < this.retryMax)) {
|
||||
try {
|
||||
return await Promise.all(txs.map((tx) => this.getTransaction(tx)));
|
||||
} catch (e) {
|
||||
retries++;
|
||||
err = e;
|
||||
|
||||
// retry on 0.5 seconds
|
||||
await sleep(this.retryOn);
|
||||
}
|
||||
}
|
||||
|
||||
throw err;
|
||||
})();
|
||||
});
|
||||
}
|
||||
|
||||
async getBatchTransactions(txs: string[]): Promise<TransactionResponse[]> {
|
||||
let txCount = 0;
|
||||
const results = [];
|
||||
|
||||
for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) {
|
||||
const chunksResult = (await Promise.all(this.createBatchRequest(chunk(chunks, this.batchSize)))).flat();
|
||||
|
||||
results.push(...chunksResult);
|
||||
|
||||
txCount += chunks.length;
|
||||
|
||||
if (typeof this.onProgress === 'function') {
|
||||
this.onProgress({
|
||||
percentage: txCount / txs.length,
|
||||
currentIndex: txCount,
|
||||
totalIndex: txs.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
export interface BatchEventServiceConstructor {
|
||||
provider: Provider;
|
||||
contract: BaseContract;
|
||||
onProgress?: BatchEventOnProgress;
|
||||
concurrencySize?: number;
|
||||
blocksPerRequest?: number;
|
||||
shouldRetry?: boolean;
|
||||
retryMax?: number;
|
||||
retryOn?: number;
|
||||
provider: Provider;
|
||||
contract: BaseContract;
|
||||
onProgress?: BatchEventOnProgress;
|
||||
concurrencySize?: number;
|
||||
blocksPerRequest?: number;
|
||||
shouldRetry?: boolean;
|
||||
retryMax?: number;
|
||||
retryOn?: number;
|
||||
}
|
||||
|
||||
export type BatchEventOnProgress = ({
|
||||
percentage,
|
||||
type,
|
||||
fromBlock,
|
||||
toBlock,
|
||||
count,
|
||||
percentage,
|
||||
type,
|
||||
fromBlock,
|
||||
toBlock,
|
||||
count,
|
||||
}: {
|
||||
percentage: number;
|
||||
type?: ContractEventName;
|
||||
fromBlock?: number;
|
||||
toBlock?: number;
|
||||
count?: number;
|
||||
percentage: number;
|
||||
type?: ContractEventName;
|
||||
fromBlock?: number;
|
||||
toBlock?: number;
|
||||
count?: number;
|
||||
}) => void;
|
||||
|
||||
// To enable iteration only numbers are accepted for fromBlock input
|
||||
export interface EventInput {
|
||||
fromBlock: number;
|
||||
toBlock: number;
|
||||
type: ContractEventName;
|
||||
fromBlock: number;
|
||||
toBlock: number;
|
||||
type: ContractEventName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch events from web3 provider on bulk
|
||||
*/
|
||||
export class BatchEventsService {
|
||||
provider: Provider;
|
||||
contract: BaseContract;
|
||||
onProgress?: BatchEventOnProgress;
|
||||
concurrencySize: number;
|
||||
blocksPerRequest: number;
|
||||
shouldRetry: boolean;
|
||||
retryMax: number;
|
||||
retryOn: number;
|
||||
constructor({
|
||||
provider,
|
||||
contract,
|
||||
onProgress,
|
||||
concurrencySize = 10,
|
||||
blocksPerRequest = 2000,
|
||||
shouldRetry = true,
|
||||
retryMax = 5,
|
||||
retryOn = 500,
|
||||
}: BatchEventServiceConstructor) {
|
||||
this.provider = provider;
|
||||
this.contract = contract;
|
||||
this.onProgress = onProgress;
|
||||
this.concurrencySize = concurrencySize;
|
||||
this.blocksPerRequest = blocksPerRequest;
|
||||
this.shouldRetry = shouldRetry;
|
||||
this.retryMax = retryMax;
|
||||
this.retryOn = retryOn;
|
||||
}
|
||||
provider: Provider;
|
||||
contract: BaseContract;
|
||||
onProgress?: BatchEventOnProgress;
|
||||
concurrencySize: number;
|
||||
blocksPerRequest: number;
|
||||
shouldRetry: boolean;
|
||||
retryMax: number;
|
||||
retryOn: number;
|
||||
constructor({
|
||||
provider,
|
||||
contract,
|
||||
onProgress,
|
||||
concurrencySize = 10,
|
||||
blocksPerRequest = 2000,
|
||||
shouldRetry = true,
|
||||
retryMax = 5,
|
||||
retryOn = 500,
|
||||
}: BatchEventServiceConstructor) {
|
||||
this.provider = provider;
|
||||
this.contract = contract;
|
||||
this.onProgress = onProgress;
|
||||
this.concurrencySize = concurrencySize;
|
||||
this.blocksPerRequest = blocksPerRequest;
|
||||
this.shouldRetry = shouldRetry;
|
||||
this.retryMax = retryMax;
|
||||
this.retryOn = retryOn;
|
||||
}
|
||||
|
||||
async getPastEvents({ fromBlock, toBlock, type }: EventInput): Promise<EventLog[]> {
|
||||
let err;
|
||||
let retries = 0;
|
||||
async getPastEvents({ fromBlock, toBlock, type }: EventInput): Promise<EventLog[]> {
|
||||
let err;
|
||||
let retries = 0;
|
||||
|
||||
// eslint-disable-next-line no-unmodified-loop-condition
|
||||
while ((!this.shouldRetry && retries === 0) || (this.shouldRetry && retries < this.retryMax)) {
|
||||
try {
|
||||
return (await this.contract.queryFilter(type, fromBlock, toBlock)) as EventLog[];
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
err = e;
|
||||
retries++;
|
||||
// eslint-disable-next-line no-unmodified-loop-condition
|
||||
while ((!this.shouldRetry && retries === 0) || (this.shouldRetry && retries < this.retryMax)) {
|
||||
try {
|
||||
return (await this.contract.queryFilter(type, fromBlock, toBlock)) as EventLog[];
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (e: any) {
|
||||
err = e;
|
||||
retries++;
|
||||
|
||||
// If provider.getBlockNumber returned last block that isn't accepted (happened on Avalanche/Gnosis),
|
||||
// get events to last accepted block
|
||||
if (e.message.includes('after last accepted block')) {
|
||||
const acceptedBlock = parseInt(e.message.split('after last accepted block ')[1]);
|
||||
toBlock = acceptedBlock;
|
||||
// If provider.getBlockNumber returned last block that isn't accepted (happened on Avalanche/Gnosis),
|
||||
// get events to last accepted block
|
||||
if (e.message.includes('after last accepted block')) {
|
||||
const acceptedBlock = parseInt(e.message.split('after last accepted block ')[1]);
|
||||
toBlock = acceptedBlock;
|
||||
}
|
||||
|
||||
// retry on 0.5 seconds
|
||||
await sleep(this.retryOn);
|
||||
}
|
||||
}
|
||||
|
||||
// retry on 0.5 seconds
|
||||
await sleep(this.retryOn);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
createBatchRequest(batchArray: EventInput[]): Promise<EventLog[]>[] {
|
||||
return batchArray.map(async (event: EventInput, index: number) => {
|
||||
await sleep(20 * index);
|
||||
|
||||
createBatchRequest(batchArray: EventInput[]): Promise<EventLog[]>[] {
|
||||
return batchArray.map(async (event: EventInput, index: number) => {
|
||||
await sleep(20 * index);
|
||||
|
||||
return this.getPastEvents(event);
|
||||
});
|
||||
}
|
||||
|
||||
async getBatchEvents({ fromBlock, toBlock, type = '*' }: EventInput): Promise<EventLog[]> {
|
||||
if (!toBlock) {
|
||||
toBlock = await this.provider.getBlockNumber();
|
||||
}
|
||||
|
||||
const eventsToSync = [];
|
||||
|
||||
for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) {
|
||||
const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1;
|
||||
|
||||
eventsToSync.push({ fromBlock: i, toBlock: j, type });
|
||||
}
|
||||
|
||||
const events = [];
|
||||
const eventChunk = chunk(eventsToSync, this.concurrencySize);
|
||||
|
||||
let chunkCount = 0;
|
||||
|
||||
for (const chunk of eventChunk) {
|
||||
chunkCount++;
|
||||
|
||||
const fetchedEvents = (await Promise.all(this.createBatchRequest(chunk))).flat();
|
||||
events.push(...fetchedEvents);
|
||||
|
||||
if (typeof this.onProgress === 'function') {
|
||||
this.onProgress({
|
||||
percentage: chunkCount / eventChunk.length,
|
||||
type,
|
||||
fromBlock: chunk[0].fromBlock,
|
||||
toBlock: chunk[chunk.length - 1].toBlock,
|
||||
count: fetchedEvents.length,
|
||||
return this.getPastEvents(event);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
async getBatchEvents({ fromBlock, toBlock, type = '*' }: EventInput): Promise<EventLog[]> {
|
||||
if (!toBlock) {
|
||||
toBlock = await this.provider.getBlockNumber();
|
||||
}
|
||||
|
||||
const eventsToSync = [];
|
||||
|
||||
for (let i = fromBlock; i < toBlock; i += this.blocksPerRequest) {
|
||||
const j = i + this.blocksPerRequest - 1 > toBlock ? toBlock : i + this.blocksPerRequest - 1;
|
||||
|
||||
eventsToSync.push({ fromBlock: i, toBlock: j, type });
|
||||
}
|
||||
|
||||
const events = [];
|
||||
const eventChunk = chunk(eventsToSync, this.concurrencySize);
|
||||
|
||||
let chunkCount = 0;
|
||||
|
||||
for (const chunk of eventChunk) {
|
||||
chunkCount++;
|
||||
|
||||
const fetchedEvents = (await Promise.all(this.createBatchRequest(chunk))).flat();
|
||||
events.push(...fetchedEvents);
|
||||
|
||||
if (typeof this.onProgress === 'function') {
|
||||
this.onProgress({
|
||||
percentage: chunkCount / eventChunk.length,
|
||||
type,
|
||||
fromBlock: chunk[0].fromBlock,
|
||||
toBlock: chunk[chunk.length - 1].toBlock,
|
||||
count: fetchedEvents.length,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
export * from '@tornado/contracts';
|
||||
export {
|
||||
Multicall,
|
||||
Multicall__factory,
|
||||
OffchainOracle,
|
||||
OffchainOracle__factory,
|
||||
OvmGasPriceOracle,
|
||||
OvmGasPriceOracle__factory,
|
||||
ReverseRecords,
|
||||
ReverseRecords__factory,
|
||||
ENSNameWrapper,
|
||||
ENSNameWrapper__factory,
|
||||
ENSRegistry,
|
||||
ENSRegistry__factory,
|
||||
ENSResolver,
|
||||
ENSResolver__factory,
|
||||
Multicall,
|
||||
Multicall__factory,
|
||||
OffchainOracle,
|
||||
OffchainOracle__factory,
|
||||
OvmGasPriceOracle,
|
||||
OvmGasPriceOracle__factory,
|
||||
ReverseRecords,
|
||||
ReverseRecords__factory,
|
||||
ENSNameWrapper,
|
||||
ENSNameWrapper__factory,
|
||||
ENSRegistry,
|
||||
ENSRegistry__factory,
|
||||
ENSResolver,
|
||||
ENSResolver__factory,
|
||||
} from './typechain';
|
||||
|
||||
413
src/deposits.ts
413
src/deposits.ts
@@ -3,267 +3,270 @@ import { buffPedersenHash } from './pedersen';
|
||||
import type { NetIdType } from './networkConfig';
|
||||
|
||||
export interface DepositType {
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
}
|
||||
|
||||
export interface createDepositParams {
|
||||
nullifier: bigint;
|
||||
secret: bigint;
|
||||
nullifier: bigint;
|
||||
secret: bigint;
|
||||
}
|
||||
|
||||
export interface createDepositObject {
|
||||
preimage: Uint8Array;
|
||||
noteHex: string;
|
||||
commitment: bigint;
|
||||
commitmentHex: string;
|
||||
nullifierHash: bigint;
|
||||
nullifierHex: string;
|
||||
preimage: Uint8Array;
|
||||
noteHex: string;
|
||||
commitment: bigint;
|
||||
commitmentHex: string;
|
||||
nullifierHash: bigint;
|
||||
nullifierHex: string;
|
||||
}
|
||||
|
||||
export interface createNoteParams extends DepositType {
|
||||
nullifier?: bigint;
|
||||
secret?: bigint;
|
||||
nullifier?: bigint;
|
||||
secret?: bigint;
|
||||
}
|
||||
|
||||
export interface parsedNoteExec extends DepositType {
|
||||
note: string;
|
||||
noteHex: string;
|
||||
note: string;
|
||||
noteHex: string;
|
||||
}
|
||||
|
||||
export interface parsedInvoiceExec extends DepositType {
|
||||
invoice: string;
|
||||
commitmentHex: string;
|
||||
invoice: string;
|
||||
commitmentHex: string;
|
||||
}
|
||||
|
||||
export function parseNote(noteString: string): parsedNoteExec | undefined {
|
||||
const noteRegex = /tornado-(?<currency>\w+)-(?<amount>[\d.]+)-(?<netId>\d+)-0x(?<noteHex>[0-9a-fA-F]{124})/g;
|
||||
const match = noteRegex.exec(noteString);
|
||||
if (!match) {
|
||||
return;
|
||||
}
|
||||
const noteRegex = /tornado-(?<currency>\w+)-(?<amount>[\d.]+)-(?<netId>\d+)-0x(?<noteHex>[0-9a-fA-F]{124})/g;
|
||||
const match = noteRegex.exec(noteString);
|
||||
if (!match) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { currency, amount, netId, noteHex } = match.groups as unknown as parsedNoteExec;
|
||||
const { currency, amount, netId, noteHex } = match.groups as unknown as parsedNoteExec;
|
||||
|
||||
return {
|
||||
currency: currency.toLowerCase(),
|
||||
amount,
|
||||
netId: Number(netId),
|
||||
noteHex: '0x' + noteHex,
|
||||
note: noteString,
|
||||
};
|
||||
return {
|
||||
currency: currency.toLowerCase(),
|
||||
amount,
|
||||
netId: Number(netId),
|
||||
noteHex: '0x' + noteHex,
|
||||
note: noteString,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseInvoice(invoiceString: string): parsedInvoiceExec | undefined {
|
||||
const invoiceRegex =
|
||||
/tornadoInvoice-(?<currency>\w+)-(?<amount>[\d.]+)-(?<netId>\d+)-0x(?<commitmentHex>[0-9a-fA-F]{64})/g;
|
||||
const match = invoiceRegex.exec(invoiceString);
|
||||
if (!match) {
|
||||
return;
|
||||
}
|
||||
const invoiceRegex =
|
||||
/tornadoInvoice-(?<currency>\w+)-(?<amount>[\d.]+)-(?<netId>\d+)-0x(?<commitmentHex>[0-9a-fA-F]{64})/g;
|
||||
const match = invoiceRegex.exec(invoiceString);
|
||||
if (!match) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { currency, amount, netId, commitmentHex } = match.groups as unknown as parsedInvoiceExec;
|
||||
const { currency, amount, netId, commitmentHex } = match.groups as unknown as parsedInvoiceExec;
|
||||
|
||||
return {
|
||||
currency: currency.toLowerCase(),
|
||||
amount,
|
||||
netId: Number(netId),
|
||||
commitmentHex: '0x' + commitmentHex,
|
||||
invoice: invoiceString,
|
||||
};
|
||||
return {
|
||||
currency: currency.toLowerCase(),
|
||||
amount,
|
||||
netId: Number(netId),
|
||||
commitmentHex: '0x' + commitmentHex,
|
||||
invoice: invoiceString,
|
||||
};
|
||||
}
|
||||
|
||||
export async function createDeposit({ nullifier, secret }: createDepositParams): Promise<createDepositObject> {
|
||||
const preimage = new Uint8Array([...leInt2Buff(nullifier), ...leInt2Buff(secret)]);
|
||||
const noteHex = toFixedHex(bytesToBN(preimage), 62);
|
||||
const commitment = BigInt(await buffPedersenHash(preimage));
|
||||
const commitmentHex = toFixedHex(commitment);
|
||||
const nullifierHash = BigInt(await buffPedersenHash(leInt2Buff(nullifier)));
|
||||
const nullifierHex = toFixedHex(nullifierHash);
|
||||
const preimage = new Uint8Array([...leInt2Buff(nullifier), ...leInt2Buff(secret)]);
|
||||
const noteHex = toFixedHex(bytesToBN(preimage), 62);
|
||||
const commitment = BigInt(await buffPedersenHash(preimage));
|
||||
const commitmentHex = toFixedHex(commitment);
|
||||
const nullifierHash = BigInt(await buffPedersenHash(leInt2Buff(nullifier)));
|
||||
const nullifierHex = toFixedHex(nullifierHash);
|
||||
|
||||
return {
|
||||
preimage,
|
||||
noteHex,
|
||||
commitment,
|
||||
commitmentHex,
|
||||
nullifierHash,
|
||||
nullifierHex,
|
||||
};
|
||||
return {
|
||||
preimage,
|
||||
noteHex,
|
||||
commitment,
|
||||
commitmentHex,
|
||||
nullifierHash,
|
||||
nullifierHex,
|
||||
};
|
||||
}
|
||||
|
||||
export interface DepositConstructor {
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
nullifier: bigint;
|
||||
secret: bigint;
|
||||
note: string;
|
||||
noteHex: string;
|
||||
invoice: string;
|
||||
commitmentHex: string;
|
||||
nullifierHex: string;
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
nullifier: bigint;
|
||||
secret: bigint;
|
||||
note: string;
|
||||
noteHex: string;
|
||||
invoice: string;
|
||||
commitmentHex: string;
|
||||
nullifierHex: string;
|
||||
}
|
||||
|
||||
export class Deposit {
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
|
||||
nullifier: bigint;
|
||||
secret: bigint;
|
||||
nullifier: bigint;
|
||||
secret: bigint;
|
||||
|
||||
note: string;
|
||||
noteHex: string;
|
||||
invoice: string;
|
||||
note: string;
|
||||
noteHex: string;
|
||||
invoice: string;
|
||||
|
||||
commitmentHex: string;
|
||||
nullifierHex: string;
|
||||
commitmentHex: string;
|
||||
nullifierHex: string;
|
||||
|
||||
constructor({
|
||||
currency,
|
||||
amount,
|
||||
netId,
|
||||
nullifier,
|
||||
secret,
|
||||
note,
|
||||
noteHex,
|
||||
invoice,
|
||||
commitmentHex,
|
||||
nullifierHex,
|
||||
}: DepositConstructor) {
|
||||
this.currency = currency;
|
||||
this.amount = amount;
|
||||
this.netId = netId;
|
||||
constructor({
|
||||
currency,
|
||||
amount,
|
||||
netId,
|
||||
nullifier,
|
||||
secret,
|
||||
note,
|
||||
noteHex,
|
||||
invoice,
|
||||
commitmentHex,
|
||||
nullifierHex,
|
||||
}: DepositConstructor) {
|
||||
this.currency = currency;
|
||||
this.amount = amount;
|
||||
this.netId = netId;
|
||||
|
||||
this.nullifier = nullifier;
|
||||
this.secret = secret;
|
||||
this.nullifier = nullifier;
|
||||
this.secret = secret;
|
||||
|
||||
this.note = note;
|
||||
this.noteHex = noteHex;
|
||||
this.invoice = invoice;
|
||||
this.note = note;
|
||||
this.noteHex = noteHex;
|
||||
this.invoice = invoice;
|
||||
|
||||
this.commitmentHex = commitmentHex;
|
||||
this.nullifierHex = nullifierHex;
|
||||
}
|
||||
|
||||
toString() {
|
||||
return JSON.stringify(
|
||||
{
|
||||
currency: this.currency,
|
||||
amount: this.amount,
|
||||
netId: this.netId,
|
||||
nullifier: this.nullifier,
|
||||
secret: this.secret,
|
||||
note: this.note,
|
||||
noteHex: this.noteHex,
|
||||
invoice: this.invoice,
|
||||
commitmentHex: this.commitmentHex,
|
||||
nullifierHex: this.nullifierHex,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
static async createNote({ currency, amount, netId, nullifier, secret }: createNoteParams): Promise<Deposit> {
|
||||
if (!nullifier) {
|
||||
nullifier = rBigInt(31);
|
||||
}
|
||||
if (!secret) {
|
||||
secret = rBigInt(31);
|
||||
this.commitmentHex = commitmentHex;
|
||||
this.nullifierHex = nullifierHex;
|
||||
}
|
||||
|
||||
const depositObject = await createDeposit({
|
||||
nullifier,
|
||||
secret,
|
||||
});
|
||||
|
||||
const newDeposit = new Deposit({
|
||||
currency: currency.toLowerCase(),
|
||||
amount: amount,
|
||||
netId,
|
||||
note: `tornado-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.noteHex}`,
|
||||
noteHex: depositObject.noteHex,
|
||||
invoice: `tornadoInvoice-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.commitmentHex}`,
|
||||
nullifier: nullifier,
|
||||
secret: secret,
|
||||
commitmentHex: depositObject.commitmentHex,
|
||||
nullifierHex: depositObject.nullifierHex,
|
||||
});
|
||||
|
||||
return newDeposit;
|
||||
}
|
||||
|
||||
static async parseNote(noteString: string): Promise<Deposit> {
|
||||
const parsedNote = parseNote(noteString);
|
||||
|
||||
if (!parsedNote) {
|
||||
throw new Error('The note has invalid format');
|
||||
toString() {
|
||||
return JSON.stringify(
|
||||
{
|
||||
currency: this.currency,
|
||||
amount: this.amount,
|
||||
netId: this.netId,
|
||||
nullifier: this.nullifier,
|
||||
secret: this.secret,
|
||||
note: this.note,
|
||||
noteHex: this.noteHex,
|
||||
invoice: this.invoice,
|
||||
commitmentHex: this.commitmentHex,
|
||||
nullifierHex: this.nullifierHex,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
const { currency, amount, netId, note, noteHex: parsedNoteHex } = parsedNote;
|
||||
static async createNote({ currency, amount, netId, nullifier, secret }: createNoteParams): Promise<Deposit> {
|
||||
if (!nullifier) {
|
||||
nullifier = rBigInt(31);
|
||||
}
|
||||
if (!secret) {
|
||||
secret = rBigInt(31);
|
||||
}
|
||||
|
||||
const bytes = bnToBytes(parsedNoteHex);
|
||||
const nullifier = BigInt(leBuff2Int(bytes.slice(0, 31)).toString());
|
||||
const secret = BigInt(leBuff2Int(bytes.slice(31, 62)).toString());
|
||||
const depositObject = await createDeposit({
|
||||
nullifier,
|
||||
secret,
|
||||
});
|
||||
|
||||
const { noteHex, commitmentHex, nullifierHex } = await createDeposit({ nullifier, secret });
|
||||
const newDeposit = new Deposit({
|
||||
currency: currency.toLowerCase(),
|
||||
amount: amount,
|
||||
netId,
|
||||
note: `tornado-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.noteHex}`,
|
||||
noteHex: depositObject.noteHex,
|
||||
invoice: `tornadoInvoice-${currency.toLowerCase()}-${amount}-${netId}-${depositObject.commitmentHex}`,
|
||||
nullifier: nullifier,
|
||||
secret: secret,
|
||||
commitmentHex: depositObject.commitmentHex,
|
||||
nullifierHex: depositObject.nullifierHex,
|
||||
});
|
||||
|
||||
const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${commitmentHex}`;
|
||||
return newDeposit;
|
||||
}
|
||||
|
||||
const newDeposit = new Deposit({
|
||||
currency,
|
||||
amount,
|
||||
netId,
|
||||
note,
|
||||
noteHex,
|
||||
invoice,
|
||||
nullifier,
|
||||
secret,
|
||||
commitmentHex,
|
||||
nullifierHex,
|
||||
});
|
||||
static async parseNote(noteString: string): Promise<Deposit> {
|
||||
const parsedNote = parseNote(noteString);
|
||||
|
||||
return newDeposit;
|
||||
}
|
||||
if (!parsedNote) {
|
||||
throw new Error('The note has invalid format');
|
||||
}
|
||||
|
||||
const { currency, amount, netId, note, noteHex: parsedNoteHex } = parsedNote;
|
||||
|
||||
const bytes = bnToBytes(parsedNoteHex);
|
||||
const nullifier = BigInt(leBuff2Int(bytes.slice(0, 31)).toString());
|
||||
const secret = BigInt(leBuff2Int(bytes.slice(31, 62)).toString());
|
||||
|
||||
const { noteHex, commitmentHex, nullifierHex } = await createDeposit({
|
||||
nullifier,
|
||||
secret,
|
||||
});
|
||||
|
||||
const invoice = `tornadoInvoice-${currency}-${amount}-${netId}-${commitmentHex}`;
|
||||
|
||||
const newDeposit = new Deposit({
|
||||
currency,
|
||||
amount,
|
||||
netId,
|
||||
note,
|
||||
noteHex,
|
||||
invoice,
|
||||
nullifier,
|
||||
secret,
|
||||
commitmentHex,
|
||||
nullifierHex,
|
||||
});
|
||||
|
||||
return newDeposit;
|
||||
}
|
||||
}
|
||||
|
||||
export class Invoice {
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
commitmentHex: string;
|
||||
invoice: string;
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
commitmentHex: string;
|
||||
invoice: string;
|
||||
|
||||
constructor(invoiceString: string) {
|
||||
const parsedInvoice = parseInvoice(invoiceString);
|
||||
constructor(invoiceString: string) {
|
||||
const parsedInvoice = parseInvoice(invoiceString);
|
||||
|
||||
if (!parsedInvoice) {
|
||||
throw new Error('The invoice has invalid format');
|
||||
if (!parsedInvoice) {
|
||||
throw new Error('The invoice has invalid format');
|
||||
}
|
||||
|
||||
const { currency, amount, netId, invoice, commitmentHex } = parsedInvoice;
|
||||
|
||||
this.currency = currency;
|
||||
this.amount = amount;
|
||||
this.netId = netId;
|
||||
|
||||
this.commitmentHex = commitmentHex;
|
||||
this.invoice = invoice;
|
||||
}
|
||||
|
||||
const { currency, amount, netId, invoice, commitmentHex } = parsedInvoice;
|
||||
|
||||
this.currency = currency;
|
||||
this.amount = amount;
|
||||
this.netId = netId;
|
||||
|
||||
this.commitmentHex = commitmentHex;
|
||||
this.invoice = invoice;
|
||||
}
|
||||
|
||||
toString() {
|
||||
return JSON.stringify(
|
||||
{
|
||||
currency: this.currency,
|
||||
amount: this.amount,
|
||||
netId: this.netId,
|
||||
commitmentHex: this.commitmentHex,
|
||||
invoice: this.invoice,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
}
|
||||
toString() {
|
||||
return JSON.stringify(
|
||||
{
|
||||
currency: this.currency,
|
||||
amount: this.amount,
|
||||
netId: this.netId,
|
||||
commitmentHex: this.commitmentHex,
|
||||
invoice: this.invoice,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,212 +2,208 @@ import { getEncryptionPublicKey, encrypt, decrypt, EthEncryptedData } from '@met
|
||||
import { JsonRpcApiProvider, Signer, Wallet, computeAddress, getAddress } from 'ethers';
|
||||
import { base64ToBytes, bytesToBase64, bytesToHex, hexToBytes, toFixedHex, concatBytes, rHex } from './utils';
|
||||
import { EchoEvents, EncryptedNotesEvents } from './events';
|
||||
import type { NetIdType } from './networkConfig';
|
||||
|
||||
export interface NoteToEncrypt {
|
||||
address: string;
|
||||
noteHex: string;
|
||||
address: string;
|
||||
noteHex: string;
|
||||
}
|
||||
|
||||
export interface DecryptedNotes {
|
||||
blockNumber: number;
|
||||
address: string;
|
||||
noteHex: string;
|
||||
blockNumber: number;
|
||||
address: string;
|
||||
noteHex: string;
|
||||
}
|
||||
|
||||
export function packEncryptedMessage({ nonce, ephemPublicKey, ciphertext }: EthEncryptedData) {
|
||||
const nonceBuf = toFixedHex(bytesToHex(base64ToBytes(nonce)), 24);
|
||||
const ephemPublicKeyBuf = toFixedHex(bytesToHex(base64ToBytes(ephemPublicKey)), 32);
|
||||
const ciphertextBuf = bytesToHex(base64ToBytes(ciphertext));
|
||||
const nonceBuf = toFixedHex(bytesToHex(base64ToBytes(nonce)), 24);
|
||||
const ephemPublicKeyBuf = toFixedHex(bytesToHex(base64ToBytes(ephemPublicKey)), 32);
|
||||
const ciphertextBuf = bytesToHex(base64ToBytes(ciphertext));
|
||||
|
||||
const messageBuff = concatBytes(hexToBytes(nonceBuf), hexToBytes(ephemPublicKeyBuf), hexToBytes(ciphertextBuf));
|
||||
const messageBuff = concatBytes(hexToBytes(nonceBuf), hexToBytes(ephemPublicKeyBuf), hexToBytes(ciphertextBuf));
|
||||
|
||||
return bytesToHex(messageBuff);
|
||||
return bytesToHex(messageBuff);
|
||||
}
|
||||
|
||||
export function unpackEncryptedMessage(encryptedMessage: string) {
|
||||
const messageBuff = hexToBytes(encryptedMessage);
|
||||
const nonceBuf = bytesToBase64(messageBuff.slice(0, 24));
|
||||
const ephemPublicKeyBuf = bytesToBase64(messageBuff.slice(24, 56));
|
||||
const ciphertextBuf = bytesToBase64(messageBuff.slice(56));
|
||||
const messageBuff = hexToBytes(encryptedMessage);
|
||||
const nonceBuf = bytesToBase64(messageBuff.slice(0, 24));
|
||||
const ephemPublicKeyBuf = bytesToBase64(messageBuff.slice(24, 56));
|
||||
const ciphertextBuf = bytesToBase64(messageBuff.slice(56));
|
||||
|
||||
return {
|
||||
messageBuff: bytesToHex(messageBuff),
|
||||
version: 'x25519-xsalsa20-poly1305',
|
||||
nonce: nonceBuf,
|
||||
ephemPublicKey: ephemPublicKeyBuf,
|
||||
ciphertext: ciphertextBuf,
|
||||
} as EthEncryptedData & {
|
||||
messageBuff: string;
|
||||
};
|
||||
return {
|
||||
messageBuff: bytesToHex(messageBuff),
|
||||
version: 'x25519-xsalsa20-poly1305',
|
||||
nonce: nonceBuf,
|
||||
ephemPublicKey: ephemPublicKeyBuf,
|
||||
ciphertext: ciphertextBuf,
|
||||
} as EthEncryptedData & {
|
||||
messageBuff: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface NoteAccountConstructor {
|
||||
netId: NetIdType;
|
||||
blockNumber?: number;
|
||||
// hex
|
||||
recoveryKey?: string;
|
||||
blockNumber?: number;
|
||||
// hex
|
||||
recoveryKey?: string;
|
||||
}
|
||||
|
||||
export class NoteAccount {
|
||||
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
|
||||
recoveryKey: string;
|
||||
// Address derived from recoveryKey, only used for frontend UI
|
||||
recoveryAddress: string;
|
||||
// Note encryption public key derived from recoveryKey
|
||||
recoveryPublicKey: string;
|
||||
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
|
||||
recoveryKey: string;
|
||||
// Address derived from recoveryKey, only used for frontend UI
|
||||
recoveryAddress: string;
|
||||
// Note encryption public key derived from recoveryKey
|
||||
recoveryPublicKey: string;
|
||||
|
||||
constructor({ netId, blockNumber, recoveryKey }: NoteAccountConstructor) {
|
||||
if (!recoveryKey) {
|
||||
recoveryKey = rHex(32).slice(2);
|
||||
}
|
||||
|
||||
this.netId = Math.floor(Number(netId));
|
||||
this.blockNumber = blockNumber;
|
||||
this.recoveryKey = recoveryKey;
|
||||
this.recoveryAddress = computeAddress('0x' + recoveryKey);
|
||||
this.recoveryPublicKey = getEncryptionPublicKey(recoveryKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Intends to mock eth_getEncryptionPublicKey behavior from MetaMask
|
||||
* In order to make the recoveryKey retrival from Echoer possible from the bare private key
|
||||
*/
|
||||
static async getSignerPublicKey(signer: Signer | Wallet) {
|
||||
if ((signer as Wallet).privateKey) {
|
||||
const wallet = signer as Wallet;
|
||||
const privateKey = wallet.privateKey.slice(0, 2) === '0x' ? wallet.privateKey.slice(2) : wallet.privateKey;
|
||||
|
||||
// Should return base64 encoded public key
|
||||
return getEncryptionPublicKey(privateKey);
|
||||
}
|
||||
|
||||
const provider = signer.provider as JsonRpcApiProvider;
|
||||
|
||||
return (await provider.send('eth_getEncryptionPublicKey', [
|
||||
(signer as Signer & { address: string }).address,
|
||||
])) as string;
|
||||
}
|
||||
|
||||
// This function intends to provide an encrypted value of recoveryKey for an on-chain Echoer backup purpose
|
||||
// Thus, the pubKey should be derived by a Wallet instance or from Web3 wallets
|
||||
// pubKey: base64 encoded 32 bytes key from https://docs.metamask.io/wallet/reference/eth_getencryptionpublickey/
|
||||
getEncryptedAccount(walletPublicKey: string) {
|
||||
const encryptedData = encrypt({
|
||||
publicKey: walletPublicKey,
|
||||
data: this.recoveryKey,
|
||||
version: 'x25519-xsalsa20-poly1305',
|
||||
});
|
||||
|
||||
const data = packEncryptedMessage(encryptedData);
|
||||
|
||||
return {
|
||||
// Use this later to save hexPrivateKey generated with
|
||||
// Buffer.from(JSON.stringify(encryptedData)).toString('hex')
|
||||
// As we don't use buffer with this library we should leave UI to do the rest
|
||||
encryptedData,
|
||||
// Data that could be used as an echo(data) params
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt Echoer backuped note encryption account with private keys
|
||||
*/
|
||||
async decryptSignerNoteAccounts(signer: Signer | Wallet, events: EchoEvents[]): Promise<NoteAccount[]> {
|
||||
const signerAddress = (signer as (Signer & { address: string }) | Wallet).address;
|
||||
|
||||
const decryptedEvents = [];
|
||||
|
||||
for (const event of events) {
|
||||
if (event.address !== signerAddress) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const unpackedMessage = unpackEncryptedMessage(event.encryptedAccount);
|
||||
|
||||
let recoveryKey;
|
||||
|
||||
if ((signer as Wallet).privateKey) {
|
||||
const wallet = signer as Wallet;
|
||||
const privateKey = wallet.privateKey.slice(0, 2) === '0x' ? wallet.privateKey.slice(2) : wallet.privateKey;
|
||||
|
||||
recoveryKey = decrypt({
|
||||
encryptedData: unpackedMessage,
|
||||
privateKey,
|
||||
});
|
||||
} else {
|
||||
const { version, nonce, ephemPublicKey, ciphertext } = unpackedMessage;
|
||||
|
||||
const unpackedBuffer = bytesToHex(
|
||||
new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
version,
|
||||
nonce,
|
||||
ephemPublicKey,
|
||||
ciphertext,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const provider = signer.provider as JsonRpcApiProvider;
|
||||
|
||||
recoveryKey = await provider.send('eth_decrypt', [unpackedBuffer, signerAddress]);
|
||||
constructor({ blockNumber, recoveryKey }: NoteAccountConstructor) {
|
||||
if (!recoveryKey) {
|
||||
recoveryKey = rHex(32).slice(2);
|
||||
}
|
||||
|
||||
decryptedEvents.push(
|
||||
new NoteAccount({
|
||||
netId: this.netId,
|
||||
blockNumber: event.blockNumber,
|
||||
recoveryKey,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// decryption may fail for invalid accounts
|
||||
continue;
|
||||
}
|
||||
this.blockNumber = blockNumber;
|
||||
this.recoveryKey = recoveryKey;
|
||||
this.recoveryAddress = computeAddress('0x' + recoveryKey);
|
||||
this.recoveryPublicKey = getEncryptionPublicKey(recoveryKey);
|
||||
}
|
||||
|
||||
return decryptedEvents;
|
||||
}
|
||||
/**
|
||||
* Intends to mock eth_getEncryptionPublicKey behavior from MetaMask
|
||||
* In order to make the recoveryKey retrival from Echoer possible from the bare private key
|
||||
*/
|
||||
static async getSignerPublicKey(signer: Signer | Wallet) {
|
||||
if ((signer as Wallet).privateKey) {
|
||||
const wallet = signer as Wallet;
|
||||
const privateKey = wallet.privateKey.slice(0, 2) === '0x' ? wallet.privateKey.slice(2) : wallet.privateKey;
|
||||
|
||||
decryptNotes(events: EncryptedNotesEvents[]): DecryptedNotes[] {
|
||||
const decryptedEvents = [];
|
||||
// Should return base64 encoded public key
|
||||
return getEncryptionPublicKey(privateKey);
|
||||
}
|
||||
|
||||
for (const event of events) {
|
||||
try {
|
||||
const unpackedMessage = unpackEncryptedMessage(event.encryptedNote);
|
||||
const provider = signer.provider as JsonRpcApiProvider;
|
||||
|
||||
const [address, noteHex] = decrypt({
|
||||
encryptedData: unpackedMessage,
|
||||
privateKey: this.recoveryKey,
|
||||
}).split('-');
|
||||
return (await provider.send('eth_getEncryptionPublicKey', [
|
||||
(signer as Signer & { address: string }).address,
|
||||
])) as string;
|
||||
}
|
||||
|
||||
decryptedEvents.push({
|
||||
blockNumber: event.blockNumber,
|
||||
address: getAddress(address),
|
||||
noteHex,
|
||||
// This function intends to provide an encrypted value of recoveryKey for an on-chain Echoer backup purpose
|
||||
// Thus, the pubKey should be derived by a Wallet instance or from Web3 wallets
|
||||
// pubKey: base64 encoded 32 bytes key from https://docs.metamask.io/wallet/reference/eth_getencryptionpublickey/
|
||||
getEncryptedAccount(walletPublicKey: string) {
|
||||
const encryptedData = encrypt({
|
||||
publicKey: walletPublicKey,
|
||||
data: this.recoveryKey,
|
||||
version: 'x25519-xsalsa20-poly1305',
|
||||
});
|
||||
} catch {
|
||||
// decryption may fail for foreign notes
|
||||
continue;
|
||||
}
|
||||
|
||||
const data = packEncryptedMessage(encryptedData);
|
||||
|
||||
return {
|
||||
// Use this later to save hexPrivateKey generated with
|
||||
// Buffer.from(JSON.stringify(encryptedData)).toString('hex')
|
||||
// As we don't use buffer with this library we should leave UI to do the rest
|
||||
encryptedData,
|
||||
// Data that could be used as an echo(data) params
|
||||
data,
|
||||
};
|
||||
}
|
||||
|
||||
return decryptedEvents;
|
||||
}
|
||||
/**
|
||||
* Decrypt Echoer backuped note encryption account with private keys
|
||||
*/
|
||||
static async decryptSignerNoteAccounts(signer: Signer | Wallet, events: EchoEvents[]): Promise<NoteAccount[]> {
|
||||
const signerAddress = (signer as (Signer & { address: string }) | Wallet).address;
|
||||
|
||||
encryptNote({ address, noteHex }: NoteToEncrypt) {
|
||||
const encryptedData = encrypt({
|
||||
publicKey: this.recoveryPublicKey,
|
||||
data: `${address}-${noteHex}`,
|
||||
version: 'x25519-xsalsa20-poly1305',
|
||||
});
|
||||
const decryptedEvents = [];
|
||||
|
||||
return packEncryptedMessage(encryptedData);
|
||||
}
|
||||
for (const event of events) {
|
||||
if (event.address !== signerAddress) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const unpackedMessage = unpackEncryptedMessage(event.encryptedAccount);
|
||||
|
||||
let recoveryKey;
|
||||
|
||||
if ((signer as Wallet).privateKey) {
|
||||
const wallet = signer as Wallet;
|
||||
const privateKey =
|
||||
wallet.privateKey.slice(0, 2) === '0x' ? wallet.privateKey.slice(2) : wallet.privateKey;
|
||||
|
||||
recoveryKey = decrypt({
|
||||
encryptedData: unpackedMessage,
|
||||
privateKey,
|
||||
});
|
||||
} else {
|
||||
const { version, nonce, ephemPublicKey, ciphertext } = unpackedMessage;
|
||||
|
||||
const unpackedBuffer = bytesToHex(
|
||||
new TextEncoder().encode(
|
||||
JSON.stringify({
|
||||
version,
|
||||
nonce,
|
||||
ephemPublicKey,
|
||||
ciphertext,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const provider = signer.provider as JsonRpcApiProvider;
|
||||
|
||||
recoveryKey = await provider.send('eth_decrypt', [unpackedBuffer, signerAddress]);
|
||||
}
|
||||
|
||||
decryptedEvents.push(
|
||||
new NoteAccount({
|
||||
blockNumber: event.blockNumber,
|
||||
recoveryKey,
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// decryption may fail for invalid accounts
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return decryptedEvents;
|
||||
}
|
||||
|
||||
decryptNotes(events: EncryptedNotesEvents[]): DecryptedNotes[] {
|
||||
const decryptedEvents = [];
|
||||
|
||||
for (const event of events) {
|
||||
try {
|
||||
const unpackedMessage = unpackEncryptedMessage(event.encryptedNote);
|
||||
|
||||
const [address, noteHex] = decrypt({
|
||||
encryptedData: unpackedMessage,
|
||||
privateKey: this.recoveryKey,
|
||||
}).split('-');
|
||||
|
||||
decryptedEvents.push({
|
||||
blockNumber: event.blockNumber,
|
||||
address: getAddress(address),
|
||||
noteHex,
|
||||
});
|
||||
} catch {
|
||||
// decryption may fail for foreign notes
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return decryptedEvents;
|
||||
}
|
||||
|
||||
encryptNote({ address, noteHex }: NoteToEncrypt) {
|
||||
const encryptedData = encrypt({
|
||||
publicKey: this.recoveryPublicKey,
|
||||
data: `${address}-${noteHex}`,
|
||||
version: 'x25519-xsalsa20-poly1305',
|
||||
});
|
||||
|
||||
return packEncryptedMessage(encryptedData);
|
||||
}
|
||||
}
|
||||
|
||||
206
src/ens.ts
206
src/ens.ts
@@ -1,145 +1,145 @@
|
||||
import { namehash, EnsResolver, AbstractProvider, keccak256, Signer } from 'ethers';
|
||||
|
||||
import {
|
||||
ENSNameWrapper,
|
||||
ENSNameWrapper__factory,
|
||||
ENSRegistry,
|
||||
ENSRegistry__factory,
|
||||
ENSResolver,
|
||||
ENSResolver__factory,
|
||||
ENSNameWrapper,
|
||||
ENSNameWrapper__factory,
|
||||
ENSRegistry,
|
||||
ENSRegistry__factory,
|
||||
ENSResolver,
|
||||
ENSResolver__factory,
|
||||
} from './typechain';
|
||||
import { bytesToHex, isHex } from './utils';
|
||||
import { NetId, NetIdType } from './networkConfig';
|
||||
|
||||
export function encodedLabelToLabelhash(label: string): string | null {
|
||||
if (label.length !== 66) return null;
|
||||
if (label.indexOf('[') !== 0) return null;
|
||||
if (label.indexOf(']') !== 65) return null;
|
||||
const hash = `0x${label.slice(1, 65)}`;
|
||||
if (!isHex(hash)) return null;
|
||||
return hash;
|
||||
if (label.length !== 66) return null;
|
||||
if (label.indexOf('[') !== 0) return null;
|
||||
if (label.indexOf(']') !== 65) return null;
|
||||
const hash = `0x${label.slice(1, 65)}`;
|
||||
if (!isHex(hash)) return null;
|
||||
return hash;
|
||||
}
|
||||
|
||||
export function labelhash(label: string) {
|
||||
if (!label) {
|
||||
return bytesToHex(new Uint8Array(32).fill(0));
|
||||
}
|
||||
return encodedLabelToLabelhash(label) || keccak256(new TextEncoder().encode(label));
|
||||
if (!label) {
|
||||
return bytesToHex(new Uint8Array(32).fill(0));
|
||||
}
|
||||
return encodedLabelToLabelhash(label) || keccak256(new TextEncoder().encode(label));
|
||||
}
|
||||
|
||||
export function makeLabelNodeAndParent(name: string) {
|
||||
const labels = name.split('.');
|
||||
const label = labels.shift() as string;
|
||||
const parentNode = namehash(labels.join('.'));
|
||||
const labels = name.split('.');
|
||||
const label = labels.shift() as string;
|
||||
const parentNode = namehash(labels.join('.'));
|
||||
|
||||
return {
|
||||
label,
|
||||
labelhash: labelhash(label),
|
||||
parentNode,
|
||||
};
|
||||
return {
|
||||
label,
|
||||
labelhash: labelhash(label),
|
||||
parentNode,
|
||||
};
|
||||
}
|
||||
|
||||
// https://github.com/ensdomains/ensjs/blob/main/packages/ensjs/src/contracts/consts.ts
|
||||
export const EnsContracts: {
|
||||
[key: NetIdType]: {
|
||||
ensRegistry: string;
|
||||
ensPublicResolver: string;
|
||||
ensNameWrapper: string;
|
||||
};
|
||||
[key: NetIdType]: {
|
||||
ensRegistry: string;
|
||||
ensPublicResolver: string;
|
||||
ensNameWrapper: string;
|
||||
};
|
||||
} = {
|
||||
[NetId.MAINNET]: {
|
||||
ensRegistry: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
|
||||
ensPublicResolver: '0x231b0Ee14048e9dCcD1d247744d114a4EB5E8E63',
|
||||
ensNameWrapper: '0xD4416b13d2b3a9aBae7AcD5D6C2BbDBE25686401',
|
||||
},
|
||||
[NetId.SEPOLIA]: {
|
||||
ensRegistry: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
|
||||
ensPublicResolver: '0x8FADE66B79cC9f707aB26799354482EB93a5B7dD',
|
||||
ensNameWrapper: '0x0635513f179D50A207757E05759CbD106d7dFcE8',
|
||||
},
|
||||
[NetId.MAINNET]: {
|
||||
ensRegistry: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
|
||||
ensPublicResolver: '0x231b0Ee14048e9dCcD1d247744d114a4EB5E8E63',
|
||||
ensNameWrapper: '0xD4416b13d2b3a9aBae7AcD5D6C2BbDBE25686401',
|
||||
},
|
||||
[NetId.SEPOLIA]: {
|
||||
ensRegistry: '0x00000000000C2E074eC69A0dFb2997BA6C7d2e1e',
|
||||
ensPublicResolver: '0x8FADE66B79cC9f707aB26799354482EB93a5B7dD',
|
||||
ensNameWrapper: '0x0635513f179D50A207757E05759CbD106d7dFcE8',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* ENSUtils to manage on-chain registered relayers
|
||||
*/
|
||||
export class ENSUtils {
|
||||
ENSRegistry?: ENSRegistry;
|
||||
ENSResolver?: ENSResolver;
|
||||
ENSNameWrapper?: ENSNameWrapper;
|
||||
provider: AbstractProvider;
|
||||
ENSRegistry?: ENSRegistry;
|
||||
ENSResolver?: ENSResolver;
|
||||
ENSNameWrapper?: ENSNameWrapper;
|
||||
provider: AbstractProvider;
|
||||
|
||||
constructor(provider: AbstractProvider) {
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
async getContracts() {
|
||||
const { chainId } = await this.provider.getNetwork();
|
||||
|
||||
const { ensRegistry, ensPublicResolver, ensNameWrapper } = EnsContracts[Number(chainId)];
|
||||
|
||||
this.ENSRegistry = ENSRegistry__factory.connect(ensRegistry, this.provider);
|
||||
this.ENSResolver = ENSResolver__factory.connect(ensPublicResolver, this.provider);
|
||||
this.ENSNameWrapper = ENSNameWrapper__factory.connect(ensNameWrapper, this.provider);
|
||||
}
|
||||
|
||||
async getOwner(name: string) {
|
||||
if (!this.ENSRegistry) {
|
||||
await this.getContracts();
|
||||
constructor(provider: AbstractProvider) {
|
||||
this.provider = provider;
|
||||
}
|
||||
|
||||
return (this.ENSRegistry as ENSRegistry).owner(namehash(name));
|
||||
}
|
||||
async getContracts() {
|
||||
const { chainId } = await this.provider.getNetwork();
|
||||
|
||||
// nameWrapper connected with wallet signer
|
||||
async unwrap(signer: Signer, name: string) {
|
||||
if (!this.ENSNameWrapper) {
|
||||
await this.getContracts();
|
||||
const { ensRegistry, ensPublicResolver, ensNameWrapper } = EnsContracts[Number(chainId)];
|
||||
|
||||
this.ENSRegistry = ENSRegistry__factory.connect(ensRegistry, this.provider);
|
||||
this.ENSResolver = ENSResolver__factory.connect(ensPublicResolver, this.provider);
|
||||
this.ENSNameWrapper = ENSNameWrapper__factory.connect(ensNameWrapper, this.provider);
|
||||
}
|
||||
|
||||
const owner = (signer as unknown as { address: string }).address;
|
||||
async getOwner(name: string) {
|
||||
if (!this.ENSRegistry) {
|
||||
await this.getContracts();
|
||||
}
|
||||
|
||||
const nameWrapper = (this.ENSNameWrapper as ENSNameWrapper).connect(signer);
|
||||
|
||||
const { labelhash } = makeLabelNodeAndParent(name);
|
||||
|
||||
return nameWrapper.unwrapETH2LD(labelhash, owner, owner);
|
||||
}
|
||||
|
||||
// https://github.com/ensdomains/ensjs/blob/main/packages/ensjs/src/functions/wallet/createSubname.ts
|
||||
async setSubnodeRecord(signer: Signer, name: string) {
|
||||
if (!this.ENSResolver) {
|
||||
await this.getContracts();
|
||||
return (this.ENSRegistry as ENSRegistry).owner(namehash(name));
|
||||
}
|
||||
|
||||
const resolver = this.ENSResolver as ENSResolver;
|
||||
const registry = (this.ENSRegistry as ENSRegistry).connect(signer);
|
||||
// nameWrapper connected with wallet signer
|
||||
async unwrap(signer: Signer, name: string) {
|
||||
if (!this.ENSNameWrapper) {
|
||||
await this.getContracts();
|
||||
}
|
||||
|
||||
const owner = (signer as unknown as { address: string }).address;
|
||||
const owner = (signer as unknown as { address: string }).address;
|
||||
|
||||
const { labelhash, parentNode } = makeLabelNodeAndParent(name);
|
||||
const nameWrapper = (this.ENSNameWrapper as ENSNameWrapper).connect(signer);
|
||||
|
||||
return registry.setSubnodeRecord(parentNode, labelhash, owner, resolver.target, BigInt(0));
|
||||
}
|
||||
const { labelhash } = makeLabelNodeAndParent(name);
|
||||
|
||||
// https://github.com/ensdomains/ensjs/blob/main/packages/ensjs/src/functions/wallet/setTextRecord.ts
|
||||
async setText(signer: Signer, name: string, key: string, value: string) {
|
||||
const resolver = ENSResolver__factory.connect((await this.getResolver(name))?.address as string, signer);
|
||||
|
||||
return resolver.setText(namehash(name), key, value);
|
||||
}
|
||||
|
||||
getResolver(name: string) {
|
||||
return EnsResolver.fromName(this.provider, name);
|
||||
}
|
||||
|
||||
async getText(name: string, key: string) {
|
||||
const resolver = await this.getResolver(name);
|
||||
|
||||
// Retuns null if the name doesn't exist
|
||||
if (!resolver) {
|
||||
return resolver;
|
||||
return nameWrapper.unwrapETH2LD(labelhash, owner, owner);
|
||||
}
|
||||
|
||||
return (await resolver.getText(key)) || '';
|
||||
}
|
||||
// https://github.com/ensdomains/ensjs/blob/main/packages/ensjs/src/functions/wallet/createSubname.ts
|
||||
async setSubnodeRecord(signer: Signer, name: string) {
|
||||
if (!this.ENSResolver) {
|
||||
await this.getContracts();
|
||||
}
|
||||
|
||||
const resolver = this.ENSResolver as ENSResolver;
|
||||
const registry = (this.ENSRegistry as ENSRegistry).connect(signer);
|
||||
|
||||
const owner = (signer as unknown as { address: string }).address;
|
||||
|
||||
const { labelhash, parentNode } = makeLabelNodeAndParent(name);
|
||||
|
||||
return registry.setSubnodeRecord(parentNode, labelhash, owner, resolver.target, BigInt(0));
|
||||
}
|
||||
|
||||
// https://github.com/ensdomains/ensjs/blob/main/packages/ensjs/src/functions/wallet/setTextRecord.ts
|
||||
async setText(signer: Signer, name: string, key: string, value: string) {
|
||||
const resolver = ENSResolver__factory.connect((await this.getResolver(name))?.address as string, signer);
|
||||
|
||||
return resolver.setText(namehash(name), key, value);
|
||||
}
|
||||
|
||||
getResolver(name: string) {
|
||||
return EnsResolver.fromName(this.provider, name);
|
||||
}
|
||||
|
||||
async getText(name: string, key: string) {
|
||||
const resolver = await this.getResolver(name);
|
||||
|
||||
// Retuns null if the name doesn't exist
|
||||
if (!resolver) {
|
||||
return resolver;
|
||||
}
|
||||
|
||||
return (await resolver.getText(key)) || '';
|
||||
}
|
||||
}
|
||||
|
||||
2105
src/events/base.ts
2105
src/events/base.ts
File diff suppressed because it is too large
Load Diff
559
src/events/db.ts
559
src/events/db.ts
@@ -2,365 +2,372 @@ import { downloadZip } from '../zip';
|
||||
import { IndexedDB } from '../idb';
|
||||
|
||||
import {
|
||||
BaseTornadoService,
|
||||
BaseTornadoServiceConstructor,
|
||||
BaseEchoService,
|
||||
BaseEchoServiceConstructor,
|
||||
BaseEncryptedNotesService,
|
||||
BaseEncryptedNotesServiceConstructor,
|
||||
BaseGovernanceService,
|
||||
BaseGovernanceServiceConstructor,
|
||||
BaseRegistryService,
|
||||
BaseRegistryServiceConstructor,
|
||||
BaseTornadoService,
|
||||
BaseTornadoServiceConstructor,
|
||||
BaseEchoService,
|
||||
BaseEchoServiceConstructor,
|
||||
BaseEncryptedNotesService,
|
||||
BaseEncryptedNotesServiceConstructor,
|
||||
BaseGovernanceService,
|
||||
BaseGovernanceServiceConstructor,
|
||||
BaseRegistryService,
|
||||
BaseRegistryServiceConstructor,
|
||||
} from './base';
|
||||
|
||||
import {
|
||||
BaseEvents,
|
||||
MinimalEvents,
|
||||
DepositsEvents,
|
||||
WithdrawalsEvents,
|
||||
CachedEvents,
|
||||
EchoEvents,
|
||||
EncryptedNotesEvents,
|
||||
AllGovernanceEvents,
|
||||
RegistersEvents,
|
||||
BaseEvents,
|
||||
MinimalEvents,
|
||||
DepositsEvents,
|
||||
WithdrawalsEvents,
|
||||
CachedEvents,
|
||||
EchoEvents,
|
||||
EncryptedNotesEvents,
|
||||
AllGovernanceEvents,
|
||||
RegistersEvents,
|
||||
} from './types';
|
||||
|
||||
export async function saveDBEvents<T extends MinimalEvents>({
|
||||
idb,
|
||||
instanceName,
|
||||
events,
|
||||
lastBlock,
|
||||
idb,
|
||||
instanceName,
|
||||
events,
|
||||
lastBlock,
|
||||
}: {
|
||||
idb: IndexedDB;
|
||||
instanceName: string;
|
||||
events: T[];
|
||||
lastBlock: number;
|
||||
idb: IndexedDB;
|
||||
instanceName: string;
|
||||
events: T[];
|
||||
lastBlock: number;
|
||||
}) {
|
||||
try {
|
||||
const formattedEvents = events.map((e) => {
|
||||
return {
|
||||
eid: `${e.transactionHash}_${e.logIndex}`,
|
||||
...e,
|
||||
};
|
||||
});
|
||||
try {
|
||||
const formattedEvents = events.map((e) => {
|
||||
return {
|
||||
eid: `${e.transactionHash}_${e.logIndex}`,
|
||||
...e,
|
||||
};
|
||||
});
|
||||
|
||||
await idb.createMultipleTransactions({
|
||||
data: formattedEvents,
|
||||
storeName: instanceName,
|
||||
});
|
||||
await idb.createMultipleTransactions({
|
||||
data: formattedEvents,
|
||||
storeName: instanceName,
|
||||
});
|
||||
|
||||
await idb.putItem({
|
||||
data: {
|
||||
blockNumber: lastBlock,
|
||||
name: instanceName,
|
||||
},
|
||||
storeName: 'lastEvents',
|
||||
});
|
||||
} catch (err) {
|
||||
console.log('Method saveDBEvents has error');
|
||||
console.log(err);
|
||||
}
|
||||
await idb.putItem({
|
||||
data: {
|
||||
blockNumber: lastBlock,
|
||||
name: instanceName,
|
||||
},
|
||||
storeName: 'lastEvents',
|
||||
});
|
||||
} catch (err) {
|
||||
console.log('Method saveDBEvents has error');
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadDBEvents<T extends MinimalEvents>({
|
||||
idb,
|
||||
instanceName,
|
||||
idb,
|
||||
instanceName,
|
||||
}: {
|
||||
idb: IndexedDB;
|
||||
instanceName: string;
|
||||
idb: IndexedDB;
|
||||
instanceName: string;
|
||||
}): Promise<BaseEvents<T>> {
|
||||
try {
|
||||
const lastBlockStore = await idb.getItem<{ blockNumber: number; name: string }>({
|
||||
storeName: 'lastEvents',
|
||||
key: instanceName,
|
||||
});
|
||||
try {
|
||||
const lastBlockStore = await idb.getItem<{
|
||||
blockNumber: number;
|
||||
name: string;
|
||||
}>({
|
||||
storeName: 'lastEvents',
|
||||
key: instanceName,
|
||||
});
|
||||
|
||||
if (!lastBlockStore?.blockNumber) {
|
||||
return {
|
||||
events: [],
|
||||
lastBlock: 0,
|
||||
};
|
||||
if (!lastBlockStore?.blockNumber) {
|
||||
return {
|
||||
events: [],
|
||||
lastBlock: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const events = (
|
||||
await idb.getAll<(T & { eid?: string })[]>({
|
||||
storeName: instanceName,
|
||||
})
|
||||
).map((e) => {
|
||||
delete e.eid;
|
||||
return e;
|
||||
});
|
||||
|
||||
return {
|
||||
events,
|
||||
lastBlock: lastBlockStore.blockNumber,
|
||||
};
|
||||
} catch (err) {
|
||||
console.log('Method loadDBEvents has error');
|
||||
console.log(err);
|
||||
|
||||
return {
|
||||
events: [],
|
||||
lastBlock: 0,
|
||||
};
|
||||
}
|
||||
|
||||
const events = (await idb.getAll<(T & { eid?: string })[]>({ storeName: instanceName })).map((e) => {
|
||||
delete e.eid;
|
||||
return e;
|
||||
});
|
||||
|
||||
return {
|
||||
events,
|
||||
lastBlock: lastBlockStore.blockNumber,
|
||||
};
|
||||
} catch (err) {
|
||||
console.log('Method loadDBEvents has error');
|
||||
console.log(err);
|
||||
|
||||
return {
|
||||
events: [],
|
||||
lastBlock: 0,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function loadRemoteEvents<T extends MinimalEvents>({
|
||||
staticUrl,
|
||||
instanceName,
|
||||
deployedBlock,
|
||||
zipDigest,
|
||||
staticUrl,
|
||||
instanceName,
|
||||
deployedBlock,
|
||||
zipDigest,
|
||||
}: {
|
||||
staticUrl: string;
|
||||
instanceName: string;
|
||||
deployedBlock: number;
|
||||
zipDigest?: string;
|
||||
staticUrl: string;
|
||||
instanceName: string;
|
||||
deployedBlock: number;
|
||||
zipDigest?: string;
|
||||
}): Promise<CachedEvents<T>> {
|
||||
try {
|
||||
const zipName = `${instanceName}.json`.toLowerCase();
|
||||
try {
|
||||
const zipName = `${instanceName}.json`.toLowerCase();
|
||||
|
||||
const events = await downloadZip<T[]>({
|
||||
staticUrl,
|
||||
zipName,
|
||||
zipDigest,
|
||||
});
|
||||
const events = await downloadZip<T[]>({
|
||||
staticUrl,
|
||||
zipName,
|
||||
zipDigest,
|
||||
});
|
||||
|
||||
if (!Array.isArray(events)) {
|
||||
const errStr = `Invalid events from ${staticUrl}/${zipName}`;
|
||||
throw new Error(errStr);
|
||||
if (!Array.isArray(events)) {
|
||||
const errStr = `Invalid events from ${staticUrl}/${zipName}`;
|
||||
throw new Error(errStr);
|
||||
}
|
||||
|
||||
return {
|
||||
events,
|
||||
lastBlock: events[events.length - 1]?.blockNumber || deployedBlock,
|
||||
fromCache: true,
|
||||
};
|
||||
} catch (err) {
|
||||
console.log('Method loadRemoteEvents has error');
|
||||
console.log(err);
|
||||
|
||||
return {
|
||||
events: [],
|
||||
lastBlock: deployedBlock,
|
||||
fromCache: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
events,
|
||||
lastBlock: events[events.length - 1]?.blockNumber || deployedBlock,
|
||||
fromCache: true,
|
||||
};
|
||||
} catch (err) {
|
||||
console.log('Method loadRemoteEvents has error');
|
||||
console.log(err);
|
||||
|
||||
return {
|
||||
events: [],
|
||||
lastBlock: deployedBlock,
|
||||
fromCache: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export interface DBTornadoServiceConstructor extends BaseTornadoServiceConstructor {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
}
|
||||
|
||||
export class DBTornadoService extends BaseTornadoService {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
|
||||
zipDigest?: string;
|
||||
zipDigest?: string;
|
||||
|
||||
constructor(params: DBTornadoServiceConstructor) {
|
||||
super(params);
|
||||
constructor(params: DBTornadoServiceConstructor) {
|
||||
super(params);
|
||||
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<DepositsEvents | WithdrawalsEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<DepositsEvents | WithdrawalsEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<DepositsEvents | WithdrawalsEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<DepositsEvents | WithdrawalsEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<DepositsEvents | WithdrawalsEvents>) {
|
||||
await saveDBEvents<DepositsEvents | WithdrawalsEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<DepositsEvents | WithdrawalsEvents>) {
|
||||
await saveDBEvents<DepositsEvents | WithdrawalsEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface DBEchoServiceConstructor extends BaseEchoServiceConstructor {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
}
|
||||
|
||||
export class DBEchoService extends BaseEchoService {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
|
||||
zipDigest?: string;
|
||||
zipDigest?: string;
|
||||
|
||||
constructor(params: DBEchoServiceConstructor) {
|
||||
super(params);
|
||||
constructor(params: DBEchoServiceConstructor) {
|
||||
super(params);
|
||||
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<EchoEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<EchoEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<EchoEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<EchoEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<EchoEvents>) {
|
||||
await saveDBEvents<EchoEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<EchoEvents>) {
|
||||
await saveDBEvents<EchoEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface DBEncryptedNotesServiceConstructor extends BaseEncryptedNotesServiceConstructor {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
}
|
||||
|
||||
export class DBEncryptedNotesService extends BaseEncryptedNotesService {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
|
||||
zipDigest?: string;
|
||||
zipDigest?: string;
|
||||
|
||||
constructor(params: DBEncryptedNotesServiceConstructor) {
|
||||
super(params);
|
||||
constructor(params: DBEncryptedNotesServiceConstructor) {
|
||||
super(params);
|
||||
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<EncryptedNotesEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<EncryptedNotesEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<EncryptedNotesEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<EncryptedNotesEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<EncryptedNotesEvents>) {
|
||||
await saveDBEvents<EncryptedNotesEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<EncryptedNotesEvents>) {
|
||||
await saveDBEvents<EncryptedNotesEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface DBGovernanceServiceConstructor extends BaseGovernanceServiceConstructor {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
}
|
||||
|
||||
export class DBGovernanceService extends BaseGovernanceService {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
|
||||
zipDigest?: string;
|
||||
zipDigest?: string;
|
||||
|
||||
constructor(params: DBGovernanceServiceConstructor) {
|
||||
super(params);
|
||||
constructor(params: DBGovernanceServiceConstructor) {
|
||||
super(params);
|
||||
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<AllGovernanceEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<AllGovernanceEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<AllGovernanceEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<AllGovernanceEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<AllGovernanceEvents>) {
|
||||
await saveDBEvents<AllGovernanceEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<AllGovernanceEvents>) {
|
||||
await saveDBEvents<AllGovernanceEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export interface DBRegistryServiceConstructor extends BaseRegistryServiceConstructor {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
}
|
||||
|
||||
export class DBRegistryService extends BaseRegistryService {
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
staticUrl: string;
|
||||
idb: IndexedDB;
|
||||
|
||||
zipDigest?: string;
|
||||
zipDigest?: string;
|
||||
|
||||
constructor(params: DBRegistryServiceConstructor) {
|
||||
super(params);
|
||||
constructor(params: DBRegistryServiceConstructor) {
|
||||
super(params);
|
||||
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
this.staticUrl = params.staticUrl;
|
||||
this.idb = params.idb;
|
||||
}
|
||||
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<RegistersEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
async getEventsFromDB() {
|
||||
return await loadDBEvents<RegistersEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
});
|
||||
}
|
||||
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<RegistersEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
async getEventsFromCache() {
|
||||
return await loadRemoteEvents<RegistersEvents>({
|
||||
staticUrl: this.staticUrl,
|
||||
instanceName: this.getInstanceName(),
|
||||
deployedBlock: this.deployedBlock,
|
||||
zipDigest: this.zipDigest,
|
||||
});
|
||||
}
|
||||
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<RegistersEvents>) {
|
||||
await saveDBEvents<RegistersEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
async saveEvents({ events, lastBlock }: BaseEvents<RegistersEvents>) {
|
||||
await saveDBEvents<RegistersEvents>({
|
||||
idb: this.idb,
|
||||
instanceName: this.getInstanceName(),
|
||||
events,
|
||||
lastBlock,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,84 +1,84 @@
|
||||
import { RelayerParams } from '../relayerClient';
|
||||
|
||||
export interface BaseEvents<T> {
|
||||
events: T[];
|
||||
lastBlock: number;
|
||||
events: T[];
|
||||
lastBlock: number;
|
||||
}
|
||||
|
||||
export interface CachedEvents<T> extends BaseEvents<T> {
|
||||
fromCache: boolean;
|
||||
fromCache: boolean;
|
||||
}
|
||||
|
||||
export interface BaseGraphEvents<T> {
|
||||
events: T[];
|
||||
lastSyncBlock: number;
|
||||
events: T[];
|
||||
lastSyncBlock: number;
|
||||
}
|
||||
|
||||
export interface MinimalEvents {
|
||||
blockNumber: number;
|
||||
logIndex: number;
|
||||
transactionHash: string;
|
||||
blockNumber: number;
|
||||
logIndex: number;
|
||||
transactionHash: string;
|
||||
}
|
||||
|
||||
export interface GovernanceEvents extends MinimalEvents {
|
||||
event: string;
|
||||
event: string;
|
||||
}
|
||||
|
||||
export interface GovernanceProposalCreatedEvents extends GovernanceEvents {
|
||||
id: number;
|
||||
proposer: string;
|
||||
target: string;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
description: string;
|
||||
id: number;
|
||||
proposer: string;
|
||||
target: string;
|
||||
startTime: number;
|
||||
endTime: number;
|
||||
description: string;
|
||||
}
|
||||
|
||||
export interface GovernanceVotedEvents extends GovernanceEvents {
|
||||
proposalId: number;
|
||||
voter: string;
|
||||
support: boolean;
|
||||
votes: string;
|
||||
from: string;
|
||||
input: string;
|
||||
proposalId: number;
|
||||
voter: string;
|
||||
support: boolean;
|
||||
votes: string;
|
||||
from: string;
|
||||
input: string;
|
||||
}
|
||||
|
||||
export interface GovernanceDelegatedEvents extends GovernanceEvents {
|
||||
account: string;
|
||||
delegateTo: string;
|
||||
account: string;
|
||||
delegateTo: string;
|
||||
}
|
||||
|
||||
export interface GovernanceUndelegatedEvents extends GovernanceEvents {
|
||||
account: string;
|
||||
delegateFrom: string;
|
||||
account: string;
|
||||
delegateFrom: string;
|
||||
}
|
||||
|
||||
export type AllGovernanceEvents =
|
||||
| GovernanceProposalCreatedEvents
|
||||
| GovernanceVotedEvents
|
||||
| GovernanceDelegatedEvents
|
||||
| GovernanceUndelegatedEvents;
|
||||
| GovernanceProposalCreatedEvents
|
||||
| GovernanceVotedEvents
|
||||
| GovernanceDelegatedEvents
|
||||
| GovernanceUndelegatedEvents;
|
||||
|
||||
export type RegistersEvents = MinimalEvents & RelayerParams;
|
||||
|
||||
export interface DepositsEvents extends MinimalEvents {
|
||||
commitment: string;
|
||||
leafIndex: number;
|
||||
timestamp: number;
|
||||
from: string;
|
||||
commitment: string;
|
||||
leafIndex: number;
|
||||
timestamp: number;
|
||||
from: string;
|
||||
}
|
||||
|
||||
export interface WithdrawalsEvents extends MinimalEvents {
|
||||
nullifierHash: string;
|
||||
to: string;
|
||||
fee: string;
|
||||
timestamp: number;
|
||||
nullifierHash: string;
|
||||
to: string;
|
||||
fee: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
export interface EchoEvents extends MinimalEvents {
|
||||
address: string;
|
||||
encryptedAccount: string;
|
||||
address: string;
|
||||
encryptedAccount: string;
|
||||
}
|
||||
|
||||
export interface EncryptedNotesEvents extends MinimalEvents {
|
||||
encryptedNote: string;
|
||||
encryptedNote: string;
|
||||
}
|
||||
|
||||
236
src/fees.ts
236
src/fees.ts
@@ -7,7 +7,7 @@ const DUMMY_ADDRESS = '0x1111111111111111111111111111111111111111';
|
||||
const DUMMY_NONCE = 1024;
|
||||
|
||||
const DUMMY_WITHDRAW_DATA =
|
||||
'0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111';
|
||||
'0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111';
|
||||
|
||||
/**
|
||||
* Example:
|
||||
@@ -15,141 +15,141 @@ const DUMMY_WITHDRAW_DATA =
|
||||
* amountInWei (0.1 ETH) * tokenDecimals (18) * tokenPriceInWei (0.0008) = 125 TOKEN
|
||||
*/
|
||||
export function convertETHToTokenAmount(
|
||||
amountInWei: BigNumberish,
|
||||
tokenPriceInWei: BigNumberish,
|
||||
tokenDecimals: number = 18,
|
||||
amountInWei: BigNumberish,
|
||||
tokenPriceInWei: BigNumberish,
|
||||
tokenDecimals: number = 18,
|
||||
): bigint {
|
||||
const tokenDecimalsMultiplier = BigInt(10 ** Number(tokenDecimals));
|
||||
return (BigInt(amountInWei) * tokenDecimalsMultiplier) / BigInt(tokenPriceInWei);
|
||||
const tokenDecimalsMultiplier = BigInt(10 ** Number(tokenDecimals));
|
||||
return (BigInt(amountInWei) * tokenDecimalsMultiplier) / BigInt(tokenPriceInWei);
|
||||
}
|
||||
|
||||
export interface RelayerFeeParams {
|
||||
gasPrice: BigNumberish;
|
||||
gasLimit?: BigNumberish;
|
||||
l1Fee?: BigNumberish;
|
||||
denomination: BigNumberish;
|
||||
ethRefund: BigNumberish;
|
||||
tokenPriceInWei: BigNumberish;
|
||||
tokenDecimals: number;
|
||||
relayerFeePercent?: number;
|
||||
isEth?: boolean;
|
||||
premiumPercent?: number;
|
||||
gasPrice: BigNumberish;
|
||||
gasLimit?: BigNumberish;
|
||||
l1Fee?: BigNumberish;
|
||||
denomination: BigNumberish;
|
||||
ethRefund: BigNumberish;
|
||||
tokenPriceInWei: BigNumberish;
|
||||
tokenDecimals: number;
|
||||
relayerFeePercent?: number;
|
||||
isEth?: boolean;
|
||||
premiumPercent?: number;
|
||||
}
|
||||
|
||||
export class TornadoFeeOracle {
|
||||
provider: JsonRpcApiProvider;
|
||||
ovmGasPriceOracle?: OvmGasPriceOracle;
|
||||
provider: JsonRpcApiProvider;
|
||||
ovmGasPriceOracle?: OvmGasPriceOracle;
|
||||
|
||||
constructor(provider: JsonRpcApiProvider, ovmGasPriceOracle?: OvmGasPriceOracle) {
|
||||
this.provider = provider;
|
||||
constructor(provider: JsonRpcApiProvider, ovmGasPriceOracle?: OvmGasPriceOracle) {
|
||||
this.provider = provider;
|
||||
|
||||
if (ovmGasPriceOracle) {
|
||||
this.ovmGasPriceOracle = ovmGasPriceOracle;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates Gas Price
|
||||
* We apply 50% premium of EIP-1559 network fees instead of 100% from ethers.js
|
||||
* (This should cover up to 4 full blocks which is equivalent of minute)
|
||||
* (A single block can bump 12.5% of fees, see the methodology https://hackmd.io/@tvanepps/1559-wallets)
|
||||
* (Still it is recommended to use 100% premium for sending transactions to prevent stucking it)
|
||||
*/
|
||||
async gasPrice() {
|
||||
const [block, getGasPrice, getPriorityFee] = await Promise.all([
|
||||
this.provider.getBlock('latest'),
|
||||
(async () => {
|
||||
try {
|
||||
return BigInt(await this.provider.send('eth_gasPrice', []));
|
||||
} catch {
|
||||
return parseUnits('1', 'gwei');
|
||||
if (ovmGasPriceOracle) {
|
||||
this.ovmGasPriceOracle = ovmGasPriceOracle;
|
||||
}
|
||||
})(),
|
||||
(async () => {
|
||||
try {
|
||||
return BigInt(await this.provider.send('eth_maxPriorityFeePerGas', []));
|
||||
} catch {
|
||||
return BigInt(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates Gas Price
|
||||
* We apply 50% premium of EIP-1559 network fees instead of 100% from ethers.js
|
||||
* (This should cover up to 4 full blocks which is equivalent of minute)
|
||||
* (A single block can bump 12.5% of fees, see the methodology https://hackmd.io/@tvanepps/1559-wallets)
|
||||
* (Still it is recommended to use 100% premium for sending transactions to prevent stucking it)
|
||||
*/
|
||||
async gasPrice() {
|
||||
const [block, getGasPrice, getPriorityFee] = await Promise.all([
|
||||
this.provider.getBlock('latest'),
|
||||
(async () => {
|
||||
try {
|
||||
return BigInt(await this.provider.send('eth_gasPrice', []));
|
||||
} catch {
|
||||
return parseUnits('1', 'gwei');
|
||||
}
|
||||
})(),
|
||||
(async () => {
|
||||
try {
|
||||
return BigInt(await this.provider.send('eth_maxPriorityFeePerGas', []));
|
||||
} catch {
|
||||
return BigInt(0);
|
||||
}
|
||||
})(),
|
||||
]);
|
||||
|
||||
return block?.baseFeePerGas ? (block.baseFeePerGas * BigInt(15)) / BigInt(10) + getPriorityFee : getGasPrice;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate L1 fee for op-stack chains
|
||||
*
|
||||
* This is required since relayers would pay the full transaction fees for users
|
||||
*/
|
||||
fetchL1OptimismFee(tx?: TransactionLike): Promise<bigint> {
|
||||
if (!this.ovmGasPriceOracle) {
|
||||
return new Promise((resolve) => resolve(BigInt(0)));
|
||||
}
|
||||
})(),
|
||||
]);
|
||||
|
||||
return block?.baseFeePerGas ? (block.baseFeePerGas * BigInt(15)) / BigInt(10) + getPriorityFee : getGasPrice;
|
||||
}
|
||||
if (!tx) {
|
||||
// this tx is only used to simulate bytes size of the encoded tx so has nothing to with the accuracy
|
||||
// inspired by the old style classic-ui calculation
|
||||
tx = {
|
||||
type: 0,
|
||||
gasLimit: 1_000_000,
|
||||
nonce: DUMMY_NONCE,
|
||||
data: DUMMY_WITHDRAW_DATA,
|
||||
gasPrice: parseUnits('1', 'gwei'),
|
||||
to: DUMMY_ADDRESS,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate L1 fee for op-stack chains
|
||||
*
|
||||
* This is required since relayers would pay the full transaction fees for users
|
||||
*/
|
||||
fetchL1OptimismFee(tx?: TransactionLike): Promise<bigint> {
|
||||
if (!this.ovmGasPriceOracle) {
|
||||
return new Promise((resolve) => resolve(BigInt(0)));
|
||||
return this.ovmGasPriceOracle.getL1Fee.staticCall(Transaction.from(tx).unsignedSerialized);
|
||||
}
|
||||
|
||||
if (!tx) {
|
||||
// this tx is only used to simulate bytes size of the encoded tx so has nothing to with the accuracy
|
||||
// inspired by the old style classic-ui calculation
|
||||
tx = {
|
||||
type: 0,
|
||||
gasLimit: 1_000_000,
|
||||
nonce: DUMMY_NONCE,
|
||||
data: DUMMY_WITHDRAW_DATA,
|
||||
gasPrice: parseUnits('1', 'gwei'),
|
||||
to: DUMMY_ADDRESS,
|
||||
};
|
||||
/**
|
||||
* We don't need to distinguish default refunds by tokens since most users interact with other defi protocols after withdrawal
|
||||
* So we default with 1M gas which is enough for two or three swaps
|
||||
* Using 30 gwei for default but it is recommended to supply cached gasPrice value from the UI
|
||||
*/
|
||||
defaultEthRefund(gasPrice?: BigNumberish, gasLimit?: BigNumberish): bigint {
|
||||
return (gasPrice ? BigInt(gasPrice) : parseUnits('30', 'gwei')) * BigInt(gasLimit || 1_000_000);
|
||||
}
|
||||
|
||||
return this.ovmGasPriceOracle.getL1Fee.staticCall(Transaction.from(tx).unsignedSerialized);
|
||||
}
|
||||
|
||||
/**
|
||||
* We don't need to distinguish default refunds by tokens since most users interact with other defi protocols after withdrawal
|
||||
* So we default with 1M gas which is enough for two or three swaps
|
||||
* Using 30 gwei for default but it is recommended to supply cached gasPrice value from the UI
|
||||
*/
|
||||
defaultEthRefund(gasPrice?: BigNumberish, gasLimit?: BigNumberish): bigint {
|
||||
return (gasPrice ? BigInt(gasPrice) : parseUnits('30', 'gwei')) * BigInt(gasLimit || 1_000_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates token amount for required ethRefund purchases required to calculate fees
|
||||
*/
|
||||
calculateTokenAmount(ethRefund: BigNumberish, tokenPriceInEth: BigNumberish, tokenDecimals?: number): bigint {
|
||||
return convertETHToTokenAmount(ethRefund, tokenPriceInEth, tokenDecimals);
|
||||
}
|
||||
|
||||
/**
|
||||
* Warning: For tokens you need to check if the fees are above denomination
|
||||
* (Usually happens for small denomination pool or if the gas price is high)
|
||||
*/
|
||||
calculateRelayerFee({
|
||||
gasPrice,
|
||||
gasLimit = 600_000,
|
||||
l1Fee = 0,
|
||||
denomination,
|
||||
ethRefund = BigInt(0),
|
||||
tokenPriceInWei,
|
||||
tokenDecimals = 18,
|
||||
relayerFeePercent = 0.33,
|
||||
isEth = true,
|
||||
premiumPercent = 20,
|
||||
}: RelayerFeeParams): bigint {
|
||||
const gasCosts = BigInt(gasPrice) * BigInt(gasLimit) + BigInt(l1Fee);
|
||||
|
||||
const relayerFee = (BigInt(denomination) * BigInt(Math.floor(10000 * relayerFeePercent))) / BigInt(10000 * 100);
|
||||
|
||||
if (isEth) {
|
||||
// Add 20% premium
|
||||
return ((gasCosts + relayerFee) * BigInt(premiumPercent ? 100 + premiumPercent : 100)) / BigInt(100);
|
||||
/**
|
||||
* Calculates token amount for required ethRefund purchases required to calculate fees
|
||||
*/
|
||||
calculateTokenAmount(ethRefund: BigNumberish, tokenPriceInEth: BigNumberish, tokenDecimals?: number): bigint {
|
||||
return convertETHToTokenAmount(ethRefund, tokenPriceInEth, tokenDecimals);
|
||||
}
|
||||
|
||||
const feeInEth = gasCosts + BigInt(ethRefund);
|
||||
/**
|
||||
* Warning: For tokens you need to check if the fees are above denomination
|
||||
* (Usually happens for small denomination pool or if the gas price is high)
|
||||
*/
|
||||
calculateRelayerFee({
|
||||
gasPrice,
|
||||
gasLimit = 600_000,
|
||||
l1Fee = 0,
|
||||
denomination,
|
||||
ethRefund = BigInt(0),
|
||||
tokenPriceInWei,
|
||||
tokenDecimals = 18,
|
||||
relayerFeePercent = 0.33,
|
||||
isEth = true,
|
||||
premiumPercent = 20,
|
||||
}: RelayerFeeParams): bigint {
|
||||
const gasCosts = BigInt(gasPrice) * BigInt(gasLimit) + BigInt(l1Fee);
|
||||
|
||||
return (
|
||||
((convertETHToTokenAmount(feeInEth, tokenPriceInWei, tokenDecimals) + relayerFee) *
|
||||
BigInt(premiumPercent ? 100 + premiumPercent : 100)) /
|
||||
BigInt(100)
|
||||
);
|
||||
}
|
||||
const relayerFee = (BigInt(denomination) * BigInt(Math.floor(10000 * relayerFeePercent))) / BigInt(10000 * 100);
|
||||
|
||||
if (isEth) {
|
||||
// Add 20% premium
|
||||
return ((gasCosts + relayerFee) * BigInt(premiumPercent ? 100 + premiumPercent : 100)) / BigInt(100);
|
||||
}
|
||||
|
||||
const feeInEth = gasCosts + BigInt(ethRefund);
|
||||
|
||||
return (
|
||||
((convertETHToTokenAmount(feeInEth, tokenPriceInWei, tokenDecimals) + relayerFee) *
|
||||
BigInt(premiumPercent ? 100 + premiumPercent : 100)) /
|
||||
BigInt(100)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,52 +3,52 @@ import { NetId, NetIdType } from './networkConfig';
|
||||
|
||||
// https://dev.gas.zip/gas/chain-support/inbound
|
||||
export const gasZipInbounds: { [key in NetIdType]: string } = {
|
||||
[NetId.MAINNET]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.BSC]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.POLYGON]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.OPTIMISM]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.ARBITRUM]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.GNOSIS]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.AVALANCHE]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.MAINNET]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.BSC]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.POLYGON]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.OPTIMISM]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.ARBITRUM]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.GNOSIS]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
[NetId.AVALANCHE]: '0x391E7C679d29bD940d63be94AD22A25d25b5A604',
|
||||
};
|
||||
|
||||
// https://dev.gas.zip/gas/chain-support/outbound
|
||||
export const gasZipID: { [key in NetIdType]: number } = {
|
||||
[NetId.MAINNET]: 255,
|
||||
[NetId.BSC]: 14,
|
||||
[NetId.POLYGON]: 17,
|
||||
[NetId.OPTIMISM]: 55,
|
||||
[NetId.ARBITRUM]: 57,
|
||||
[NetId.GNOSIS]: 16,
|
||||
[NetId.AVALANCHE]: 15,
|
||||
[NetId.SEPOLIA]: 102,
|
||||
[NetId.MAINNET]: 255,
|
||||
[NetId.BSC]: 14,
|
||||
[NetId.POLYGON]: 17,
|
||||
[NetId.OPTIMISM]: 55,
|
||||
[NetId.ARBITRUM]: 57,
|
||||
[NetId.GNOSIS]: 16,
|
||||
[NetId.AVALANCHE]: 15,
|
||||
[NetId.SEPOLIA]: 102,
|
||||
};
|
||||
|
||||
// https://dev.gas.zip/gas/code-examples/eoaDeposit
|
||||
export function gasZipInput(to: string, shorts: number[]): string | null {
|
||||
let data = '0x';
|
||||
if (isAddress(to)) {
|
||||
if (to.length === 42) {
|
||||
data += '02';
|
||||
data += to.slice(2);
|
||||
let data = '0x';
|
||||
if (isAddress(to)) {
|
||||
if (to.length === 42) {
|
||||
data += '02';
|
||||
data += to.slice(2);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
data += '01'; // to == sender
|
||||
}
|
||||
} else {
|
||||
data += '01'; // to == sender
|
||||
}
|
||||
|
||||
for (const i in shorts) {
|
||||
data += Number(shorts[i]).toString(16).padStart(4, '0');
|
||||
}
|
||||
for (const i in shorts) {
|
||||
data += Number(shorts[i]).toString(16).padStart(4, '0');
|
||||
}
|
||||
|
||||
return data;
|
||||
return data;
|
||||
}
|
||||
|
||||
export function gasZipMinMax(ethUsd: number) {
|
||||
return {
|
||||
min: 1 / ethUsd,
|
||||
max: 50 / ethUsd,
|
||||
ethUsd,
|
||||
};
|
||||
return {
|
||||
min: 1 / ethUsd,
|
||||
max: 50 / ethUsd,
|
||||
ethUsd,
|
||||
};
|
||||
}
|
||||
|
||||
1864
src/graphql/index.ts
1864
src/graphql/index.ts
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
832
src/idb.ts
832
src/idb.ts
@@ -5,447 +5,447 @@ import { getConfig, NetIdType } from './networkConfig';
|
||||
export const INDEX_DB_ERROR = 'A mutation operation was attempted on a database that did not allow mutations.';
|
||||
|
||||
export interface IDBIndex {
|
||||
name: string;
|
||||
unique?: boolean;
|
||||
name: string;
|
||||
unique?: boolean;
|
||||
}
|
||||
|
||||
export interface IDBStores {
|
||||
name: string;
|
||||
keyPath?: string;
|
||||
indexes?: IDBIndex[];
|
||||
name: string;
|
||||
keyPath?: string;
|
||||
indexes?: IDBIndex[];
|
||||
}
|
||||
|
||||
export interface IDBConstructor {
|
||||
dbName: string;
|
||||
stores?: IDBStores[];
|
||||
dbName: string;
|
||||
stores?: IDBStores[];
|
||||
}
|
||||
|
||||
export class IndexedDB {
|
||||
dbExists: boolean;
|
||||
isBlocked: boolean;
|
||||
// todo: TestDBSchema on any
|
||||
options: OpenDBCallbacks<any>;
|
||||
dbName: string;
|
||||
dbVersion: number;
|
||||
db?: IDBPDatabase<any>;
|
||||
dbExists: boolean;
|
||||
isBlocked: boolean;
|
||||
// todo: TestDBSchema on any
|
||||
options: OpenDBCallbacks<any>;
|
||||
dbName: string;
|
||||
dbVersion: number;
|
||||
db?: IDBPDatabase<any>;
|
||||
|
||||
constructor({ dbName, stores }: IDBConstructor) {
|
||||
this.dbExists = false;
|
||||
this.isBlocked = false;
|
||||
constructor({ dbName, stores }: IDBConstructor) {
|
||||
this.dbExists = false;
|
||||
this.isBlocked = false;
|
||||
|
||||
this.options = {
|
||||
upgrade(db) {
|
||||
Object.values(db.objectStoreNames).forEach((value) => {
|
||||
db.deleteObjectStore(value);
|
||||
});
|
||||
this.options = {
|
||||
upgrade(db) {
|
||||
Object.values(db.objectStoreNames).forEach((value) => {
|
||||
db.deleteObjectStore(value);
|
||||
});
|
||||
|
||||
[{ name: 'keyval' }, ...(stores || [])].forEach(({ name, keyPath, indexes }) => {
|
||||
const store = db.createObjectStore(name, {
|
||||
keyPath,
|
||||
autoIncrement: true,
|
||||
});
|
||||
[{ name: 'keyval' }, ...(stores || [])].forEach(({ name, keyPath, indexes }) => {
|
||||
const store = db.createObjectStore(name, {
|
||||
keyPath,
|
||||
autoIncrement: true,
|
||||
});
|
||||
|
||||
if (Array.isArray(indexes)) {
|
||||
indexes.forEach(({ name, unique = false }) => {
|
||||
store.createIndex(name, name, { unique });
|
||||
if (Array.isArray(indexes)) {
|
||||
indexes.forEach(({ name, unique = false }) => {
|
||||
store.createIndex(name, name, { unique });
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
this.dbName = dbName;
|
||||
this.dbVersion = 35;
|
||||
}
|
||||
|
||||
async initDB() {
|
||||
try {
|
||||
if (this.dbExists || this.isBlocked) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.db = await openDB(this.dbName, this.dbVersion, this.options);
|
||||
this.db.addEventListener('onupgradeneeded', async () => {
|
||||
await this._removeExist();
|
||||
});
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
this.dbName = dbName;
|
||||
this.dbVersion = 35;
|
||||
}
|
||||
this.dbExists = true;
|
||||
} catch (err: any) {
|
||||
// needed for private mode firefox browser
|
||||
if (err.message.includes(INDEX_DB_ERROR)) {
|
||||
console.log('This browser does not support IndexedDB!');
|
||||
this.isBlocked = true;
|
||||
return;
|
||||
}
|
||||
|
||||
async initDB() {
|
||||
try {
|
||||
if (this.dbExists || this.isBlocked) {
|
||||
return;
|
||||
}
|
||||
if (err.message.includes('less than the existing version')) {
|
||||
console.log(`Upgrading DB ${this.dbName} to ${this.dbVersion}`);
|
||||
await this._removeExist();
|
||||
return;
|
||||
}
|
||||
|
||||
this.db = await openDB(this.dbName, this.dbVersion, this.options);
|
||||
this.db.addEventListener('onupgradeneeded', async () => {
|
||||
await this._removeExist();
|
||||
});
|
||||
|
||||
this.dbExists = true;
|
||||
} catch (err: any) {
|
||||
// needed for private mode firefox browser
|
||||
if (err.message.includes(INDEX_DB_ERROR)) {
|
||||
console.log('This browser does not support IndexedDB!');
|
||||
this.isBlocked = true;
|
||||
return;
|
||||
}
|
||||
|
||||
if (err.message.includes('less than the existing version')) {
|
||||
console.log(`Upgrading DB ${this.dbName} to ${this.dbVersion}`);
|
||||
await this._removeExist();
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(`Method initDB has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async _removeExist() {
|
||||
await deleteDB(this.dbName);
|
||||
this.dbExists = false;
|
||||
|
||||
await this.initDB();
|
||||
}
|
||||
|
||||
async getFromIndex<T>({
|
||||
storeName,
|
||||
indexName,
|
||||
key,
|
||||
}: {
|
||||
storeName: string;
|
||||
indexName: string;
|
||||
key?: string;
|
||||
}): Promise<T | undefined> {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
return (await this.db.getFromIndex(storeName, indexName, key)) as T;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method getFromIndex has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllFromIndex<T>({
|
||||
storeName,
|
||||
indexName,
|
||||
key,
|
||||
count,
|
||||
}: {
|
||||
storeName: string;
|
||||
indexName: string;
|
||||
key?: string;
|
||||
count?: number;
|
||||
}): Promise<T> {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return [] as T;
|
||||
}
|
||||
|
||||
try {
|
||||
return (await this.db.getAllFromIndex(storeName, indexName, key, count)) as T;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method getAllFromIndex has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getItem<T>({ storeName, key }: { storeName: string; key: string }): Promise<T | undefined> {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const store = this.db.transaction(storeName).objectStore(storeName);
|
||||
|
||||
return (await store.get(key)) as T;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method getItem has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async addItem({ storeName, data, key = '' }: { storeName: string; data: any; key: string }) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, 'readwrite');
|
||||
const isExist = await tx.objectStore(storeName).get(key);
|
||||
|
||||
if (!isExist) {
|
||||
await tx.objectStore(storeName).add(data);
|
||||
}
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method addItem has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async putItem({ storeName, data, key }: { storeName: string; data: any; key?: string }) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, 'readwrite');
|
||||
|
||||
await tx.objectStore(storeName).put(data, key);
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method putItem has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteItem({ storeName, key }: { storeName: string; key: string }) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, 'readwrite');
|
||||
|
||||
await tx.objectStore(storeName).delete(key);
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method deleteItem has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getAll<T>({ storeName }: { storeName: string }): Promise<T> {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return [] as T;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, 'readonly');
|
||||
|
||||
return (await tx.objectStore(storeName).getAll()) as T;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method getAll has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple key-value store inspired by idb-keyval package
|
||||
*/
|
||||
getValue<T>(key: string) {
|
||||
return this.getItem<T>({ storeName: 'keyval', key });
|
||||
}
|
||||
|
||||
setValue(key: string, data: any) {
|
||||
return this.putItem({ storeName: 'keyval', key, data });
|
||||
}
|
||||
|
||||
delValue(key: string) {
|
||||
return this.deleteItem({ storeName: 'keyval', key });
|
||||
}
|
||||
|
||||
async clearStore({ storeName, mode = 'readwrite' }: { storeName: string; mode: IDBTransactionMode }) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, mode);
|
||||
|
||||
await (tx.objectStore(storeName).clear as () => Promise<void>)();
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method clearStore has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async createTransactions({
|
||||
storeName,
|
||||
data,
|
||||
mode = 'readwrite',
|
||||
}: {
|
||||
storeName: string;
|
||||
data: any;
|
||||
mode: IDBTransactionMode;
|
||||
}) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, mode);
|
||||
|
||||
await (tx.objectStore(storeName).add as (value: any, key?: any) => Promise<any>)(data);
|
||||
await tx.done;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method createTransactions has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async createMultipleTransactions({
|
||||
storeName,
|
||||
data,
|
||||
index,
|
||||
mode = 'readwrite',
|
||||
}: {
|
||||
storeName: string;
|
||||
data: any[];
|
||||
index?: any;
|
||||
mode?: IDBTransactionMode;
|
||||
}) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, mode);
|
||||
|
||||
for (const item of data) {
|
||||
if (item) {
|
||||
await (tx.store.put as (value: any, key?: any) => Promise<any>)({ ...item, ...index });
|
||||
console.error(`Method initDB has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async _removeExist() {
|
||||
await deleteDB(this.dbName);
|
||||
this.dbExists = false;
|
||||
|
||||
await this.initDB();
|
||||
}
|
||||
|
||||
async getFromIndex<T>({
|
||||
storeName,
|
||||
indexName,
|
||||
key,
|
||||
}: {
|
||||
storeName: string;
|
||||
indexName: string;
|
||||
key?: string;
|
||||
}): Promise<T | undefined> {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
return (await this.db.getFromIndex(storeName, indexName, key)) as T;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method getFromIndex has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getAllFromIndex<T>({
|
||||
storeName,
|
||||
indexName,
|
||||
key,
|
||||
count,
|
||||
}: {
|
||||
storeName: string;
|
||||
indexName: string;
|
||||
key?: string;
|
||||
count?: number;
|
||||
}): Promise<T> {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return [] as T;
|
||||
}
|
||||
|
||||
try {
|
||||
return (await this.db.getAllFromIndex(storeName, indexName, key, count)) as T;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method getAllFromIndex has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getItem<T>({ storeName, key }: { storeName: string; key: string }): Promise<T | undefined> {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const store = this.db.transaction(storeName).objectStore(storeName);
|
||||
|
||||
return (await store.get(key)) as T;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method getItem has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async addItem({ storeName, data, key = '' }: { storeName: string; data: any; key: string }) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, 'readwrite');
|
||||
const isExist = await tx.objectStore(storeName).get(key);
|
||||
|
||||
if (!isExist) {
|
||||
await tx.objectStore(storeName).add(data);
|
||||
}
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method addItem has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async putItem({ storeName, data, key }: { storeName: string; data: any; key?: string }) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, 'readwrite');
|
||||
|
||||
await tx.objectStore(storeName).put(data, key);
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method putItem has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteItem({ storeName, key }: { storeName: string; key: string }) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, 'readwrite');
|
||||
|
||||
await tx.objectStore(storeName).delete(key);
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method deleteItem has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async getAll<T>({ storeName }: { storeName: string }): Promise<T> {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return [] as T;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, 'readonly');
|
||||
|
||||
return (await tx.objectStore(storeName).getAll()) as T;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method getAll has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple key-value store inspired by idb-keyval package
|
||||
*/
|
||||
getValue<T>(key: string) {
|
||||
return this.getItem<T>({ storeName: 'keyval', key });
|
||||
}
|
||||
|
||||
setValue(key: string, data: any) {
|
||||
return this.putItem({ storeName: 'keyval', key, data });
|
||||
}
|
||||
|
||||
delValue(key: string) {
|
||||
return this.deleteItem({ storeName: 'keyval', key });
|
||||
}
|
||||
|
||||
async clearStore({ storeName, mode = 'readwrite' }: { storeName: string; mode: IDBTransactionMode }) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, mode);
|
||||
|
||||
await (tx.objectStore(storeName).clear as () => Promise<void>)();
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method clearStore has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async createTransactions({
|
||||
storeName,
|
||||
data,
|
||||
mode = 'readwrite',
|
||||
}: {
|
||||
storeName: string;
|
||||
data: any;
|
||||
mode: IDBTransactionMode;
|
||||
}) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, mode);
|
||||
|
||||
await (tx.objectStore(storeName).add as (value: any, key?: any) => Promise<any>)(data);
|
||||
await tx.done;
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method createTransactions has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async createMultipleTransactions({
|
||||
storeName,
|
||||
data,
|
||||
index,
|
||||
mode = 'readwrite',
|
||||
}: {
|
||||
storeName: string;
|
||||
data: any[];
|
||||
index?: any;
|
||||
mode?: IDBTransactionMode;
|
||||
}) {
|
||||
await this.initDB();
|
||||
|
||||
if (!this.db) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const tx = this.db.transaction(storeName, mode);
|
||||
|
||||
for (const item of data) {
|
||||
if (item) {
|
||||
await (tx.store.put as (value: any, key?: any) => Promise<any>)({ ...item, ...index });
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method createMultipleTransactions has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
} catch (err: any) {
|
||||
throw new Error(`Method createMultipleTransactions has error: ${err.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Should check if DB is initialized well
|
||||
*/
|
||||
export async function getIndexedDB(netId?: NetIdType) {
|
||||
// key-value db for settings
|
||||
if (!netId) {
|
||||
const idb = new IndexedDB({ dbName: 'tornado-core' });
|
||||
// key-value db for settings
|
||||
if (!netId) {
|
||||
const idb = new IndexedDB({ dbName: 'tornado-core' });
|
||||
await idb.initDB();
|
||||
return idb;
|
||||
}
|
||||
|
||||
const minimalIndexes = [
|
||||
{
|
||||
name: 'blockNumber',
|
||||
unique: false,
|
||||
},
|
||||
{
|
||||
name: 'transactionHash',
|
||||
unique: false,
|
||||
},
|
||||
];
|
||||
|
||||
const defaultState = [
|
||||
{
|
||||
name: `echo_${netId}`,
|
||||
keyPath: 'eid',
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'address',
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: `encrypted_notes_${netId}`,
|
||||
keyPath: 'eid',
|
||||
indexes: minimalIndexes,
|
||||
},
|
||||
{
|
||||
name: 'lastEvents',
|
||||
keyPath: 'name',
|
||||
indexes: [
|
||||
{
|
||||
name: 'name',
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const config = getConfig(netId);
|
||||
|
||||
const { tokens, nativeCurrency, registryContract, governanceContract } = config;
|
||||
|
||||
const stores = [...defaultState];
|
||||
|
||||
if (registryContract) {
|
||||
stores.push({
|
||||
name: `registered_${netId}`,
|
||||
keyPath: 'ensName',
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'relayerAddress',
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (governanceContract) {
|
||||
stores.push({
|
||||
name: `governance_${netId}`,
|
||||
keyPath: 'eid',
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'event',
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
Object.entries(tokens).forEach(([token, { instanceAddress }]) => {
|
||||
Object.keys(instanceAddress).forEach((amount) => {
|
||||
if (nativeCurrency === token) {
|
||||
stores.push(
|
||||
{
|
||||
name: `stringify_bloom_${netId}_${token}_${amount}`,
|
||||
keyPath: 'hashBloom',
|
||||
indexes: [],
|
||||
},
|
||||
{
|
||||
name: `stringify_tree_${netId}_${token}_${amount}`,
|
||||
keyPath: 'hashTree',
|
||||
indexes: [],
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
stores.push(
|
||||
{
|
||||
name: `deposits_${netId}_${token}_${amount}`,
|
||||
keyPath: 'leafIndex', // the key by which it refers to the object must be in all instances of the storage
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'commitment',
|
||||
unique: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: `withdrawals_${netId}_${token}_${amount}`,
|
||||
keyPath: 'eid',
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'nullifierHash',
|
||||
unique: true,
|
||||
}, // keys on which the index is created
|
||||
],
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const idb = new IndexedDB({
|
||||
dbName: `tornado_core_${netId}`,
|
||||
stores,
|
||||
});
|
||||
|
||||
await idb.initDB();
|
||||
|
||||
return idb;
|
||||
}
|
||||
|
||||
const minimalIndexes = [
|
||||
{
|
||||
name: 'blockNumber',
|
||||
unique: false,
|
||||
},
|
||||
{
|
||||
name: 'transactionHash',
|
||||
unique: false,
|
||||
},
|
||||
];
|
||||
|
||||
const defaultState = [
|
||||
{
|
||||
name: `echo_${netId}`,
|
||||
keyPath: 'eid',
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'address',
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: `encrypted_notes_${netId}`,
|
||||
keyPath: 'eid',
|
||||
indexes: minimalIndexes,
|
||||
},
|
||||
{
|
||||
name: 'lastEvents',
|
||||
keyPath: 'name',
|
||||
indexes: [
|
||||
{
|
||||
name: 'name',
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const config = getConfig(netId);
|
||||
|
||||
const { tokens, nativeCurrency, registryContract, governanceContract } = config;
|
||||
|
||||
const stores = [...defaultState];
|
||||
|
||||
if (registryContract) {
|
||||
stores.push({
|
||||
name: `registered_${netId}`,
|
||||
keyPath: 'ensName',
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'relayerAddress',
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
if (governanceContract) {
|
||||
stores.push({
|
||||
name: `governance_${netId}`,
|
||||
keyPath: 'eid',
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'event',
|
||||
unique: false,
|
||||
},
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
Object.entries(tokens).forEach(([token, { instanceAddress }]) => {
|
||||
Object.keys(instanceAddress).forEach((amount) => {
|
||||
if (nativeCurrency === token) {
|
||||
stores.push(
|
||||
{
|
||||
name: `stringify_bloom_${netId}_${token}_${amount}`,
|
||||
keyPath: 'hashBloom',
|
||||
indexes: [],
|
||||
},
|
||||
{
|
||||
name: `stringify_tree_${netId}_${token}_${amount}`,
|
||||
keyPath: 'hashTree',
|
||||
indexes: [],
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
stores.push(
|
||||
{
|
||||
name: `deposits_${netId}_${token}_${amount}`,
|
||||
keyPath: 'leafIndex', // the key by which it refers to the object must be in all instances of the storage
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'commitment',
|
||||
unique: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: `withdrawals_${netId}_${token}_${amount}`,
|
||||
keyPath: 'eid',
|
||||
indexes: [
|
||||
...minimalIndexes,
|
||||
{
|
||||
name: 'nullifierHash',
|
||||
unique: true,
|
||||
}, // keys on which the index is created
|
||||
],
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
const idb = new IndexedDB({
|
||||
dbName: `tornado_core_${netId}`,
|
||||
stores,
|
||||
});
|
||||
|
||||
await idb.initDB();
|
||||
|
||||
return idb;
|
||||
}
|
||||
|
||||
14
src/ip.ts
14
src/ip.ts
@@ -1,14 +1,14 @@
|
||||
import { fetchData } from './providers';
|
||||
|
||||
export interface IPResult {
|
||||
ip: string;
|
||||
iso?: string;
|
||||
tor?: boolean;
|
||||
ip: string;
|
||||
iso?: string;
|
||||
tor?: boolean;
|
||||
}
|
||||
|
||||
export async function fetchIp(ipEcho: string) {
|
||||
return (await fetchData(ipEcho, {
|
||||
method: 'GET',
|
||||
timeout: 30000,
|
||||
})) as IPResult;
|
||||
return (await fetchData(ipEcho, {
|
||||
method: 'GET',
|
||||
timeout: 30000,
|
||||
})) as IPResult;
|
||||
}
|
||||
|
||||
@@ -8,195 +8,195 @@ import type { DepositsEvents } from './events';
|
||||
import type { NetIdType } from './networkConfig';
|
||||
|
||||
export interface MerkleTreeConstructor extends DepositType {
|
||||
Tornado: Tornado;
|
||||
commitmentHex?: string;
|
||||
merkleTreeHeight?: number;
|
||||
emptyElement?: string;
|
||||
merkleWorkerPath?: string;
|
||||
Tornado: Tornado;
|
||||
commitmentHex?: string;
|
||||
merkleTreeHeight?: number;
|
||||
emptyElement?: string;
|
||||
merkleWorkerPath?: string;
|
||||
}
|
||||
|
||||
export class MerkleTreeService {
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
Tornado: Tornado;
|
||||
commitmentHex?: string;
|
||||
instanceName: string;
|
||||
currency: string;
|
||||
amount: string;
|
||||
netId: NetIdType;
|
||||
Tornado: Tornado;
|
||||
commitmentHex?: string;
|
||||
instanceName: string;
|
||||
|
||||
merkleTreeHeight: number;
|
||||
emptyElement: string;
|
||||
merkleTreeHeight: number;
|
||||
emptyElement: string;
|
||||
|
||||
merkleWorkerPath?: string;
|
||||
merkleWorkerPath?: string;
|
||||
|
||||
constructor({
|
||||
netId,
|
||||
amount,
|
||||
currency,
|
||||
Tornado,
|
||||
commitmentHex,
|
||||
merkleTreeHeight = 20,
|
||||
emptyElement = '21663839004416932945382355908790599225266501822907911457504978515578255421292',
|
||||
merkleWorkerPath,
|
||||
}: MerkleTreeConstructor) {
|
||||
const instanceName = `${netId}_${currency}_${amount}`;
|
||||
constructor({
|
||||
netId,
|
||||
amount,
|
||||
currency,
|
||||
Tornado,
|
||||
commitmentHex,
|
||||
merkleTreeHeight = 20,
|
||||
emptyElement = '21663839004416932945382355908790599225266501822907911457504978515578255421292',
|
||||
merkleWorkerPath,
|
||||
}: MerkleTreeConstructor) {
|
||||
const instanceName = `${netId}_${currency}_${amount}`;
|
||||
|
||||
this.currency = currency;
|
||||
this.amount = amount;
|
||||
this.netId = Number(netId);
|
||||
this.currency = currency;
|
||||
this.amount = amount;
|
||||
this.netId = Number(netId);
|
||||
|
||||
this.Tornado = Tornado;
|
||||
this.instanceName = instanceName;
|
||||
this.commitmentHex = commitmentHex;
|
||||
this.Tornado = Tornado;
|
||||
this.instanceName = instanceName;
|
||||
this.commitmentHex = commitmentHex;
|
||||
|
||||
this.merkleTreeHeight = merkleTreeHeight;
|
||||
this.emptyElement = emptyElement;
|
||||
this.merkleWorkerPath = merkleWorkerPath;
|
||||
}
|
||||
this.merkleTreeHeight = merkleTreeHeight;
|
||||
this.emptyElement = emptyElement;
|
||||
this.merkleWorkerPath = merkleWorkerPath;
|
||||
}
|
||||
|
||||
async createTree(events: Element[]) {
|
||||
const { hash: hashFunction } = await mimc.getHash();
|
||||
async createTree(events: Element[]) {
|
||||
const { hash: hashFunction } = await mimc.getHash();
|
||||
|
||||
if (this.merkleWorkerPath) {
|
||||
console.log('Using merkleWorker\n');
|
||||
if (this.merkleWorkerPath) {
|
||||
console.log('Using merkleWorker\n');
|
||||
|
||||
try {
|
||||
if (isNode) {
|
||||
const merkleWorkerPromise = new Promise((resolve, reject) => {
|
||||
const worker = new NodeWorker(this.merkleWorkerPath as string, {
|
||||
workerData: {
|
||||
merkleTreeHeight: this.merkleTreeHeight,
|
||||
elements: events,
|
||||
zeroElement: this.emptyElement,
|
||||
},
|
||||
});
|
||||
worker.on('message', resolve);
|
||||
worker.on('error', reject);
|
||||
worker.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`Worker stopped with exit code ${code}`));
|
||||
}
|
||||
});
|
||||
}) as Promise<string>;
|
||||
try {
|
||||
if (isNode) {
|
||||
const merkleWorkerPromise = new Promise((resolve, reject) => {
|
||||
const worker = new NodeWorker(this.merkleWorkerPath as string, {
|
||||
workerData: {
|
||||
merkleTreeHeight: this.merkleTreeHeight,
|
||||
elements: events,
|
||||
zeroElement: this.emptyElement,
|
||||
},
|
||||
});
|
||||
worker.on('message', resolve);
|
||||
worker.on('error', reject);
|
||||
worker.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`Worker stopped with exit code ${code}`));
|
||||
}
|
||||
});
|
||||
}) as Promise<string>;
|
||||
|
||||
return MerkleTree.deserialize(JSON.parse(await merkleWorkerPromise), hashFunction);
|
||||
} else {
|
||||
const merkleWorkerPromise = new Promise((resolve, reject) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const worker = new (Worker as any)(this.merkleWorkerPath);
|
||||
return MerkleTree.deserialize(JSON.parse(await merkleWorkerPromise), hashFunction);
|
||||
} else {
|
||||
const merkleWorkerPromise = new Promise((resolve, reject) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const worker = new (Worker as any)(this.merkleWorkerPath);
|
||||
|
||||
worker.onmessage = (e: { data: string }) => {
|
||||
resolve(e.data);
|
||||
};
|
||||
worker.onmessage = (e: { data: string }) => {
|
||||
resolve(e.data);
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
worker.onerror = (e: any) => {
|
||||
reject(e);
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
worker.onerror = (e: any) => {
|
||||
reject(e);
|
||||
};
|
||||
|
||||
worker.postMessage({
|
||||
merkleTreeHeight: this.merkleTreeHeight,
|
||||
elements: events,
|
||||
zeroElement: this.emptyElement,
|
||||
});
|
||||
}) as Promise<string>;
|
||||
worker.postMessage({
|
||||
merkleTreeHeight: this.merkleTreeHeight,
|
||||
elements: events,
|
||||
zeroElement: this.emptyElement,
|
||||
});
|
||||
}) as Promise<string>;
|
||||
|
||||
return MerkleTree.deserialize(JSON.parse(await merkleWorkerPromise), hashFunction);
|
||||
return MerkleTree.deserialize(JSON.parse(await merkleWorkerPromise), hashFunction);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('merkleWorker failed, falling back to synchronous merkle tree');
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('merkleWorker failed, falling back to synchronous merkle tree');
|
||||
console.log(err);
|
||||
}
|
||||
|
||||
return new MerkleTree(this.merkleTreeHeight, events, {
|
||||
zeroElement: this.emptyElement,
|
||||
hashFunction,
|
||||
});
|
||||
}
|
||||
|
||||
return new MerkleTree(this.merkleTreeHeight, events, {
|
||||
zeroElement: this.emptyElement,
|
||||
hashFunction,
|
||||
});
|
||||
}
|
||||
async createPartialTree({ edge, elements }: { edge: TreeEdge; elements: Element[] }) {
|
||||
const { hash: hashFunction } = await mimc.getHash();
|
||||
|
||||
async createPartialTree({ edge, elements }: { edge: TreeEdge; elements: Element[] }) {
|
||||
const { hash: hashFunction } = await mimc.getHash();
|
||||
if (this.merkleWorkerPath) {
|
||||
console.log('Using merkleWorker\n');
|
||||
|
||||
if (this.merkleWorkerPath) {
|
||||
console.log('Using merkleWorker\n');
|
||||
try {
|
||||
if (isNode) {
|
||||
const merkleWorkerPromise = new Promise((resolve, reject) => {
|
||||
const worker = new NodeWorker(this.merkleWorkerPath as string, {
|
||||
workerData: {
|
||||
merkleTreeHeight: this.merkleTreeHeight,
|
||||
edge,
|
||||
elements,
|
||||
zeroElement: this.emptyElement,
|
||||
},
|
||||
});
|
||||
worker.on('message', resolve);
|
||||
worker.on('error', reject);
|
||||
worker.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`Worker stopped with exit code ${code}`));
|
||||
}
|
||||
});
|
||||
}) as Promise<string>;
|
||||
|
||||
try {
|
||||
if (isNode) {
|
||||
const merkleWorkerPromise = new Promise((resolve, reject) => {
|
||||
const worker = new NodeWorker(this.merkleWorkerPath as string, {
|
||||
workerData: {
|
||||
merkleTreeHeight: this.merkleTreeHeight,
|
||||
edge,
|
||||
elements,
|
||||
zeroElement: this.emptyElement,
|
||||
},
|
||||
});
|
||||
worker.on('message', resolve);
|
||||
worker.on('error', reject);
|
||||
worker.on('exit', (code) => {
|
||||
if (code !== 0) {
|
||||
reject(new Error(`Worker stopped with exit code ${code}`));
|
||||
}
|
||||
});
|
||||
}) as Promise<string>;
|
||||
return PartialMerkleTree.deserialize(JSON.parse(await merkleWorkerPromise), hashFunction);
|
||||
} else {
|
||||
const merkleWorkerPromise = new Promise((resolve, reject) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const worker = new (Worker as any)(this.merkleWorkerPath);
|
||||
|
||||
return PartialMerkleTree.deserialize(JSON.parse(await merkleWorkerPromise), hashFunction);
|
||||
} else {
|
||||
const merkleWorkerPromise = new Promise((resolve, reject) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const worker = new (Worker as any)(this.merkleWorkerPath);
|
||||
worker.onmessage = (e: { data: string }) => {
|
||||
resolve(e.data);
|
||||
};
|
||||
|
||||
worker.onmessage = (e: { data: string }) => {
|
||||
resolve(e.data);
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
worker.onerror = (e: any) => {
|
||||
reject(e);
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
worker.onerror = (e: any) => {
|
||||
reject(e);
|
||||
};
|
||||
worker.postMessage({
|
||||
merkleTreeHeight: this.merkleTreeHeight,
|
||||
edge,
|
||||
elements,
|
||||
zeroElement: this.emptyElement,
|
||||
});
|
||||
}) as Promise<string>;
|
||||
|
||||
worker.postMessage({
|
||||
merkleTreeHeight: this.merkleTreeHeight,
|
||||
edge,
|
||||
elements,
|
||||
zeroElement: this.emptyElement,
|
||||
});
|
||||
}) as Promise<string>;
|
||||
|
||||
return PartialMerkleTree.deserialize(JSON.parse(await merkleWorkerPromise), hashFunction);
|
||||
return PartialMerkleTree.deserialize(JSON.parse(await merkleWorkerPromise), hashFunction);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('merkleWorker failed, falling back to synchronous merkle tree');
|
||||
console.log(err);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.log('merkleWorker failed, falling back to synchronous merkle tree');
|
||||
console.log(err);
|
||||
}
|
||||
|
||||
return new PartialMerkleTree(this.merkleTreeHeight, edge, elements, {
|
||||
zeroElement: this.emptyElement,
|
||||
hashFunction,
|
||||
});
|
||||
}
|
||||
|
||||
return new PartialMerkleTree(this.merkleTreeHeight, edge, elements, {
|
||||
zeroElement: this.emptyElement,
|
||||
hashFunction,
|
||||
});
|
||||
}
|
||||
async verifyTree(events: DepositsEvents[]) {
|
||||
console.log(
|
||||
`\nCreating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while\n`,
|
||||
);
|
||||
|
||||
async verifyTree(events: DepositsEvents[]) {
|
||||
console.log(
|
||||
`\nCreating deposit tree for ${this.netId} ${this.amount} ${this.currency.toUpperCase()} would take a while\n`,
|
||||
);
|
||||
const timeStart = Date.now();
|
||||
|
||||
const timeStart = Date.now();
|
||||
const tree = await this.createTree(events.map(({ commitment }) => commitment));
|
||||
|
||||
const tree = await this.createTree(events.map(({ commitment }) => commitment));
|
||||
const isKnownRoot = await this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root)));
|
||||
|
||||
const isKnownRoot = await this.Tornado.isKnownRoot(toFixedHex(BigInt(tree.root)));
|
||||
if (!isKnownRoot) {
|
||||
const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
if (!isKnownRoot) {
|
||||
const errMsg = `Deposit Event ${this.netId} ${this.amount} ${this.currency} is invalid`;
|
||||
throw new Error(errMsg);
|
||||
console.log(
|
||||
`\nCreated ${this.netId} ${this.amount} ${this.currency.toUpperCase()} tree in ${Date.now() - timeStart}ms\n`,
|
||||
);
|
||||
|
||||
return tree;
|
||||
}
|
||||
|
||||
console.log(
|
||||
`\nCreated ${this.netId} ${this.amount} ${this.currency.toUpperCase()} tree in ${Date.now() - timeStart}ms\n`,
|
||||
);
|
||||
|
||||
return tree;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,66 +5,66 @@ import { mimc } from './mimc';
|
||||
import { isNode } from './utils';
|
||||
|
||||
interface WorkData {
|
||||
merkleTreeHeight: number;
|
||||
edge?: TreeEdge;
|
||||
elements: Element[];
|
||||
zeroElement: string;
|
||||
merkleTreeHeight: number;
|
||||
edge?: TreeEdge;
|
||||
elements: Element[];
|
||||
zeroElement: string;
|
||||
}
|
||||
|
||||
async function nodePostWork() {
|
||||
const { hash: hashFunction } = await mimc.getHash();
|
||||
const { merkleTreeHeight, edge, elements, zeroElement } = workerThreads.workerData as WorkData;
|
||||
|
||||
if (edge) {
|
||||
const merkleTree = new PartialMerkleTree(merkleTreeHeight, edge, elements, {
|
||||
zeroElement,
|
||||
hashFunction,
|
||||
});
|
||||
|
||||
(workerThreads.parentPort as workerThreads.MessagePort).postMessage(merkleTree.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
const merkleTree = new MerkleTree(merkleTreeHeight, elements, {
|
||||
zeroElement,
|
||||
hashFunction,
|
||||
});
|
||||
|
||||
(workerThreads.parentPort as workerThreads.MessagePort).postMessage(merkleTree.toString());
|
||||
}
|
||||
|
||||
if (isNode && workerThreads) {
|
||||
nodePostWork();
|
||||
} else if (!isNode && typeof addEventListener === 'function' && typeof postMessage === 'function') {
|
||||
addEventListener('message', async (e: any) => {
|
||||
let data;
|
||||
|
||||
if (e.data) {
|
||||
data = e.data;
|
||||
} else {
|
||||
data = e;
|
||||
}
|
||||
|
||||
const { hash: hashFunction } = await mimc.getHash();
|
||||
const { merkleTreeHeight, edge, elements, zeroElement } = data as WorkData;
|
||||
const { merkleTreeHeight, edge, elements, zeroElement } = workerThreads.workerData as WorkData;
|
||||
|
||||
if (edge) {
|
||||
const merkleTree = new PartialMerkleTree(merkleTreeHeight, edge, elements, {
|
||||
zeroElement,
|
||||
hashFunction,
|
||||
});
|
||||
const merkleTree = new PartialMerkleTree(merkleTreeHeight, edge, elements, {
|
||||
zeroElement,
|
||||
hashFunction,
|
||||
});
|
||||
|
||||
postMessage(merkleTree.toString());
|
||||
return;
|
||||
(workerThreads.parentPort as workerThreads.MessagePort).postMessage(merkleTree.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
const merkleTree = new MerkleTree(merkleTreeHeight, elements, {
|
||||
zeroElement,
|
||||
hashFunction,
|
||||
zeroElement,
|
||||
hashFunction,
|
||||
});
|
||||
|
||||
postMessage(merkleTree.toString());
|
||||
});
|
||||
} else {
|
||||
throw new Error('This browser / environment does not support workers!');
|
||||
(workerThreads.parentPort as workerThreads.MessagePort).postMessage(merkleTree.toString());
|
||||
}
|
||||
|
||||
if (isNode && workerThreads) {
|
||||
nodePostWork();
|
||||
} else if (!isNode && typeof addEventListener === 'function' && typeof postMessage === 'function') {
|
||||
addEventListener('message', async (e: any) => {
|
||||
let data;
|
||||
|
||||
if (e.data) {
|
||||
data = e.data;
|
||||
} else {
|
||||
data = e;
|
||||
}
|
||||
|
||||
const { hash: hashFunction } = await mimc.getHash();
|
||||
const { merkleTreeHeight, edge, elements, zeroElement } = data as WorkData;
|
||||
|
||||
if (edge) {
|
||||
const merkleTree = new PartialMerkleTree(merkleTreeHeight, edge, elements, {
|
||||
zeroElement,
|
||||
hashFunction,
|
||||
});
|
||||
|
||||
postMessage(merkleTree.toString());
|
||||
return;
|
||||
}
|
||||
|
||||
const merkleTree = new MerkleTree(merkleTreeHeight, elements, {
|
||||
zeroElement,
|
||||
hashFunction,
|
||||
});
|
||||
|
||||
postMessage(merkleTree.toString());
|
||||
});
|
||||
} else {
|
||||
throw new Error('This browser / environment does not support workers!');
|
||||
}
|
||||
|
||||
34
src/mimc.ts
34
src/mimc.ts
@@ -2,27 +2,27 @@ import { MimcSponge, buildMimcSponge } from 'circomlibjs';
|
||||
import type { Element, HashFunction } from '@tornado/fixed-merkle-tree';
|
||||
|
||||
export class Mimc {
|
||||
sponge?: MimcSponge;
|
||||
hash?: HashFunction<Element>;
|
||||
mimcPromise: Promise<void>;
|
||||
sponge?: MimcSponge;
|
||||
hash?: HashFunction<Element>;
|
||||
mimcPromise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
this.mimcPromise = this.initMimc();
|
||||
}
|
||||
constructor() {
|
||||
this.mimcPromise = this.initMimc();
|
||||
}
|
||||
|
||||
async initMimc() {
|
||||
this.sponge = await buildMimcSponge();
|
||||
this.hash = (left, right) => this.sponge?.F.toString(this.sponge?.multiHash([BigInt(left), BigInt(right)]));
|
||||
}
|
||||
async initMimc() {
|
||||
this.sponge = await buildMimcSponge();
|
||||
this.hash = (left, right) => this.sponge?.F.toString(this.sponge?.multiHash([BigInt(left), BigInt(right)]));
|
||||
}
|
||||
|
||||
async getHash() {
|
||||
await this.mimcPromise;
|
||||
async getHash() {
|
||||
await this.mimcPromise;
|
||||
|
||||
return {
|
||||
sponge: this.sponge,
|
||||
hash: this.hash,
|
||||
};
|
||||
}
|
||||
return {
|
||||
sponge: this.sponge,
|
||||
hash: this.hash,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export const mimc = new Mimc();
|
||||
|
||||
@@ -2,36 +2,36 @@ import { BaseContract, Interface } from 'ethers';
|
||||
import { Multicall } from './typechain';
|
||||
|
||||
export interface Call3 {
|
||||
contract?: BaseContract;
|
||||
address?: string;
|
||||
interface?: Interface;
|
||||
name: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
params?: any[];
|
||||
allowFailure?: boolean;
|
||||
contract?: BaseContract;
|
||||
address?: string;
|
||||
interface?: Interface;
|
||||
name: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
params?: any[];
|
||||
allowFailure?: boolean;
|
||||
}
|
||||
|
||||
export async function multicall(Multicall: Multicall, calls: Call3[]) {
|
||||
const calldata = calls.map((call) => {
|
||||
const target = (call.contract?.target || call.address) as string;
|
||||
const callInterface = (call.contract?.interface || call.interface) as Interface;
|
||||
const calldata = calls.map((call) => {
|
||||
const target = (call.contract?.target || call.address) as string;
|
||||
const callInterface = (call.contract?.interface || call.interface) as Interface;
|
||||
|
||||
return {
|
||||
target,
|
||||
callData: callInterface.encodeFunctionData(call.name, call.params),
|
||||
allowFailure: call.allowFailure ?? false,
|
||||
};
|
||||
});
|
||||
return {
|
||||
target,
|
||||
callData: callInterface.encodeFunctionData(call.name, call.params),
|
||||
allowFailure: call.allowFailure ?? false,
|
||||
};
|
||||
});
|
||||
|
||||
const returnData = await Multicall.aggregate3.staticCall(calldata);
|
||||
const returnData = await Multicall.aggregate3.staticCall(calldata);
|
||||
|
||||
const res = returnData.map((call, i) => {
|
||||
const callInterface = (calls[i].contract?.interface || calls[i].interface) as Interface;
|
||||
const [result, data] = call;
|
||||
const decodeResult =
|
||||
result && data && data !== '0x' ? callInterface.decodeFunctionResult(calls[i].name, data) : null;
|
||||
return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult;
|
||||
});
|
||||
const res = returnData.map((call, i) => {
|
||||
const callInterface = (calls[i].contract?.interface || calls[i].interface) as Interface;
|
||||
const [result, data] = call;
|
||||
const decodeResult =
|
||||
result && data && data !== '0x' ? callInterface.decodeFunctionResult(calls[i].name, data) : null;
|
||||
return !decodeResult ? null : decodeResult.length === 1 ? decodeResult[0] : decodeResult;
|
||||
});
|
||||
|
||||
return res;
|
||||
return res;
|
||||
}
|
||||
|
||||
1294
src/networkConfig.ts
1294
src/networkConfig.ts
File diff suppressed because it is too large
Load Diff
@@ -1,32 +1,32 @@
|
||||
import { BabyJub, PedersenHash, Point, buildPedersenHash } from 'circomlibjs';
|
||||
|
||||
export class Pedersen {
|
||||
pedersenHash?: PedersenHash;
|
||||
babyJub?: BabyJub;
|
||||
pedersenPromise: Promise<void>;
|
||||
pedersenHash?: PedersenHash;
|
||||
babyJub?: BabyJub;
|
||||
pedersenPromise: Promise<void>;
|
||||
|
||||
constructor() {
|
||||
this.pedersenPromise = this.initPedersen();
|
||||
}
|
||||
constructor() {
|
||||
this.pedersenPromise = this.initPedersen();
|
||||
}
|
||||
|
||||
async initPedersen() {
|
||||
this.pedersenHash = await buildPedersenHash();
|
||||
this.babyJub = this.pedersenHash.babyJub;
|
||||
}
|
||||
async initPedersen() {
|
||||
this.pedersenHash = await buildPedersenHash();
|
||||
this.babyJub = this.pedersenHash.babyJub;
|
||||
}
|
||||
|
||||
async unpackPoint(buffer: Uint8Array) {
|
||||
await this.pedersenPromise;
|
||||
return this.babyJub?.unpackPoint(this.pedersenHash?.hash(buffer) as Uint8Array);
|
||||
}
|
||||
async unpackPoint(buffer: Uint8Array) {
|
||||
await this.pedersenPromise;
|
||||
return this.babyJub?.unpackPoint(this.pedersenHash?.hash(buffer) as Uint8Array);
|
||||
}
|
||||
|
||||
toStringBuffer(buffer: Uint8Array): string {
|
||||
return this.babyJub?.F.toString(buffer);
|
||||
}
|
||||
toStringBuffer(buffer: Uint8Array): string {
|
||||
return this.babyJub?.F.toString(buffer);
|
||||
}
|
||||
}
|
||||
|
||||
export const pedersen = new Pedersen();
|
||||
|
||||
export async function buffPedersenHash(buffer: Uint8Array): Promise<string> {
|
||||
const [hash] = (await pedersen.unpackPoint(buffer)) as Point;
|
||||
return pedersen.toStringBuffer(hash);
|
||||
const [hash] = (await pedersen.unpackPoint(buffer)) as Point;
|
||||
return pedersen.toStringBuffer(hash);
|
||||
}
|
||||
|
||||
428
src/permit.ts
428
src/permit.ts
@@ -1,28 +1,28 @@
|
||||
import { ERC20Permit, ERC20Mock, TORN, PermitTornado } from '@tornado/contracts';
|
||||
import {
|
||||
BaseContract,
|
||||
MaxUint256,
|
||||
Provider,
|
||||
Signature,
|
||||
Signer,
|
||||
solidityPackedKeccak256,
|
||||
TypedDataEncoder,
|
||||
TypedDataField,
|
||||
BaseContract,
|
||||
MaxUint256,
|
||||
Provider,
|
||||
Signature,
|
||||
Signer,
|
||||
solidityPackedKeccak256,
|
||||
TypedDataEncoder,
|
||||
TypedDataField,
|
||||
} from 'ethers';
|
||||
import { rBigInt } from './utils';
|
||||
|
||||
export interface PermitValue {
|
||||
spender: string;
|
||||
value: bigint;
|
||||
nonce?: bigint;
|
||||
deadline?: bigint;
|
||||
spender: string;
|
||||
value: bigint;
|
||||
nonce?: bigint;
|
||||
deadline?: bigint;
|
||||
}
|
||||
|
||||
export interface PermitCommitments {
|
||||
denomination: bigint;
|
||||
commitments: string[];
|
||||
nonce?: bigint;
|
||||
deadline?: bigint;
|
||||
denomination: bigint;
|
||||
commitments: string[];
|
||||
nonce?: bigint;
|
||||
deadline?: bigint;
|
||||
}
|
||||
|
||||
export const permit2Address = '0x000000000022D473030F116dDEE9F6B43aC78BA3';
|
||||
@@ -31,212 +31,212 @@ export const permit2Address = '0x000000000022D473030F116dDEE9F6B43aC78BA3';
|
||||
* From @uniswap/permit2-sdk ported for ethers.js v6
|
||||
*/
|
||||
export interface Witness {
|
||||
witnessTypeName: string;
|
||||
witnessType: {
|
||||
[key: string]: TypedDataField[];
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
witness: any;
|
||||
witnessTypeName: string;
|
||||
witnessType: {
|
||||
[key: string]: TypedDataField[];
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
witness: any;
|
||||
}
|
||||
|
||||
export async function getPermitSignature({
|
||||
Token,
|
||||
signer,
|
||||
spender,
|
||||
value,
|
||||
nonce,
|
||||
deadline,
|
||||
}: PermitValue & {
|
||||
Token: ERC20Permit | ERC20Mock | TORN;
|
||||
signer?: Signer;
|
||||
}) {
|
||||
const sigSigner = (signer || Token.runner) as Signer & { address: string };
|
||||
const provider = sigSigner.provider as Provider;
|
||||
|
||||
const [name, lastNonce, { chainId }] = await Promise.all([
|
||||
Token.name(),
|
||||
Token.nonces(sigSigner.address),
|
||||
provider.getNetwork(),
|
||||
]);
|
||||
|
||||
const DOMAIN_SEPARATOR = {
|
||||
name,
|
||||
version: '1',
|
||||
chainId,
|
||||
verifyingContract: Token.target as string,
|
||||
};
|
||||
|
||||
const PERMIT_TYPE = {
|
||||
Permit: [
|
||||
{ name: 'owner', type: 'address' },
|
||||
{ name: 'spender', type: 'address' },
|
||||
{ name: 'value', type: 'uint256' },
|
||||
{ name: 'nonce', type: 'uint256' },
|
||||
{ name: 'deadline', type: 'uint256' },
|
||||
],
|
||||
};
|
||||
|
||||
return Signature.from(
|
||||
await sigSigner.signTypedData(DOMAIN_SEPARATOR, PERMIT_TYPE, {
|
||||
owner: sigSigner.address,
|
||||
spender,
|
||||
value,
|
||||
nonce: nonce || lastNonce,
|
||||
deadline: deadline || MaxUint256,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getPermitCommitmentsSignature({
|
||||
PermitTornado,
|
||||
Token,
|
||||
signer,
|
||||
denomination,
|
||||
commitments,
|
||||
nonce,
|
||||
}: PermitCommitments & {
|
||||
PermitTornado: PermitTornado;
|
||||
Token: ERC20Permit | ERC20Mock | TORN;
|
||||
signer?: Signer;
|
||||
}) {
|
||||
const value = BigInt(commitments.length) * denomination;
|
||||
const commitmentsHash = solidityPackedKeccak256(['bytes32[]'], [commitments]);
|
||||
|
||||
return await getPermitSignature({
|
||||
Token,
|
||||
signer,
|
||||
spender: PermitTornado.target as string,
|
||||
value,
|
||||
nonce,
|
||||
deadline: BigInt(commitmentsHash),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPermit2Signature({
|
||||
Token,
|
||||
signer,
|
||||
spender,
|
||||
value: amount,
|
||||
nonce,
|
||||
deadline,
|
||||
witness,
|
||||
}: PermitValue & {
|
||||
Token: BaseContract;
|
||||
signer?: Signer;
|
||||
witness?: Witness;
|
||||
}) {
|
||||
const sigSigner = (signer || Token.runner) as Signer & { address: string };
|
||||
const provider = sigSigner.provider as Provider;
|
||||
|
||||
const domain = {
|
||||
name: 'Permit2',
|
||||
chainId: (await provider.getNetwork()).chainId,
|
||||
verifyingContract: permit2Address,
|
||||
};
|
||||
|
||||
const types: {
|
||||
[key: string]: TypedDataField[];
|
||||
} = !witness
|
||||
? {
|
||||
PermitTransferFrom: [
|
||||
{ name: 'permitted', type: 'TokenPermissions' },
|
||||
{ name: 'spender', type: 'address' },
|
||||
{ name: 'nonce', type: 'uint256' },
|
||||
{ name: 'deadline', type: 'uint256' },
|
||||
],
|
||||
TokenPermissions: [
|
||||
{ name: 'token', type: 'address' },
|
||||
{ name: 'amount', type: 'uint256' },
|
||||
],
|
||||
}
|
||||
: {
|
||||
PermitWitnessTransferFrom: [
|
||||
{ name: 'permitted', type: 'TokenPermissions' },
|
||||
{ name: 'spender', type: 'address' },
|
||||
{ name: 'nonce', type: 'uint256' },
|
||||
{ name: 'deadline', type: 'uint256' },
|
||||
{ name: 'witness', type: witness.witnessTypeName },
|
||||
],
|
||||
TokenPermissions: [
|
||||
{ name: 'token', type: 'address' },
|
||||
{ name: 'amount', type: 'uint256' },
|
||||
],
|
||||
...witness.witnessType,
|
||||
};
|
||||
|
||||
const values: {
|
||||
permitted: {
|
||||
token: string;
|
||||
amount: bigint;
|
||||
};
|
||||
spender: string;
|
||||
nonce: bigint;
|
||||
deadline: bigint;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
witness?: any;
|
||||
} = {
|
||||
permitted: {
|
||||
token: Token.target as string,
|
||||
amount,
|
||||
},
|
||||
spender,
|
||||
// Sorted nonce are not required for Permit2
|
||||
nonce: nonce || rBigInt(16),
|
||||
deadline: deadline || MaxUint256,
|
||||
};
|
||||
|
||||
if (witness) {
|
||||
values.witness = witness.witness;
|
||||
}
|
||||
|
||||
const hash = new TypedDataEncoder(types).hash(values);
|
||||
|
||||
const signature = Signature.from(await sigSigner.signTypedData(domain, types, values));
|
||||
|
||||
return {
|
||||
domain,
|
||||
types,
|
||||
values,
|
||||
hash,
|
||||
signature,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPermit2CommitmentsSignature({
|
||||
PermitTornado,
|
||||
Token,
|
||||
signer,
|
||||
denomination,
|
||||
commitments,
|
||||
nonce,
|
||||
deadline,
|
||||
}: PermitCommitments & {
|
||||
PermitTornado: PermitTornado;
|
||||
Token: BaseContract;
|
||||
signer?: Signer;
|
||||
}) {
|
||||
const value = BigInt(commitments.length) * denomination;
|
||||
const commitmentsHash = solidityPackedKeccak256(['bytes32[]'], [commitments]);
|
||||
|
||||
return await getPermit2Signature({
|
||||
Token,
|
||||
signer,
|
||||
spender: PermitTornado.target as string,
|
||||
value,
|
||||
nonce,
|
||||
deadline,
|
||||
witness: {
|
||||
witnessTypeName: 'PermitCommitments',
|
||||
witnessType: {
|
||||
PermitCommitments: [
|
||||
{ name: 'instance', type: 'address' },
|
||||
{ name: 'commitmentsHash', type: 'bytes32' },
|
||||
}: PermitValue & {
|
||||
Token: ERC20Permit | ERC20Mock | TORN;
|
||||
signer?: Signer;
|
||||
}) {
|
||||
const sigSigner = (signer || Token.runner) as Signer & { address: string };
|
||||
const provider = sigSigner.provider as Provider;
|
||||
|
||||
const [name, lastNonce, { chainId }] = await Promise.all([
|
||||
Token.name(),
|
||||
Token.nonces(sigSigner.address),
|
||||
provider.getNetwork(),
|
||||
]);
|
||||
|
||||
const DOMAIN_SEPARATOR = {
|
||||
name,
|
||||
version: '1',
|
||||
chainId,
|
||||
verifyingContract: Token.target as string,
|
||||
};
|
||||
|
||||
const PERMIT_TYPE = {
|
||||
Permit: [
|
||||
{ name: 'owner', type: 'address' },
|
||||
{ name: 'spender', type: 'address' },
|
||||
{ name: 'value', type: 'uint256' },
|
||||
{ name: 'nonce', type: 'uint256' },
|
||||
{ name: 'deadline', type: 'uint256' },
|
||||
],
|
||||
},
|
||||
witness: {
|
||||
instance: PermitTornado.target,
|
||||
commitmentsHash,
|
||||
},
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return Signature.from(
|
||||
await sigSigner.signTypedData(DOMAIN_SEPARATOR, PERMIT_TYPE, {
|
||||
owner: sigSigner.address,
|
||||
spender,
|
||||
value,
|
||||
nonce: nonce || lastNonce,
|
||||
deadline: deadline || MaxUint256,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export async function getPermitCommitmentsSignature({
|
||||
PermitTornado,
|
||||
Token,
|
||||
signer,
|
||||
denomination,
|
||||
commitments,
|
||||
nonce,
|
||||
}: PermitCommitments & {
|
||||
PermitTornado: PermitTornado;
|
||||
Token: ERC20Permit | ERC20Mock | TORN;
|
||||
signer?: Signer;
|
||||
}) {
|
||||
const value = BigInt(commitments.length) * denomination;
|
||||
const commitmentsHash = solidityPackedKeccak256(['bytes32[]'], [commitments]);
|
||||
|
||||
return await getPermitSignature({
|
||||
Token,
|
||||
signer,
|
||||
spender: PermitTornado.target as string,
|
||||
value,
|
||||
nonce,
|
||||
deadline: BigInt(commitmentsHash),
|
||||
});
|
||||
}
|
||||
|
||||
export async function getPermit2Signature({
|
||||
Token,
|
||||
signer,
|
||||
spender,
|
||||
value: amount,
|
||||
nonce,
|
||||
deadline,
|
||||
witness,
|
||||
}: PermitValue & {
|
||||
Token: BaseContract;
|
||||
signer?: Signer;
|
||||
witness?: Witness;
|
||||
}) {
|
||||
const sigSigner = (signer || Token.runner) as Signer & { address: string };
|
||||
const provider = sigSigner.provider as Provider;
|
||||
|
||||
const domain = {
|
||||
name: 'Permit2',
|
||||
chainId: (await provider.getNetwork()).chainId,
|
||||
verifyingContract: permit2Address,
|
||||
};
|
||||
|
||||
const types: {
|
||||
[key: string]: TypedDataField[];
|
||||
} = !witness
|
||||
? {
|
||||
PermitTransferFrom: [
|
||||
{ name: 'permitted', type: 'TokenPermissions' },
|
||||
{ name: 'spender', type: 'address' },
|
||||
{ name: 'nonce', type: 'uint256' },
|
||||
{ name: 'deadline', type: 'uint256' },
|
||||
],
|
||||
TokenPermissions: [
|
||||
{ name: 'token', type: 'address' },
|
||||
{ name: 'amount', type: 'uint256' },
|
||||
],
|
||||
}
|
||||
: {
|
||||
PermitWitnessTransferFrom: [
|
||||
{ name: 'permitted', type: 'TokenPermissions' },
|
||||
{ name: 'spender', type: 'address' },
|
||||
{ name: 'nonce', type: 'uint256' },
|
||||
{ name: 'deadline', type: 'uint256' },
|
||||
{ name: 'witness', type: witness.witnessTypeName },
|
||||
],
|
||||
TokenPermissions: [
|
||||
{ name: 'token', type: 'address' },
|
||||
{ name: 'amount', type: 'uint256' },
|
||||
],
|
||||
...witness.witnessType,
|
||||
};
|
||||
|
||||
const values: {
|
||||
permitted: {
|
||||
token: string;
|
||||
amount: bigint;
|
||||
};
|
||||
spender: string;
|
||||
nonce: bigint;
|
||||
deadline: bigint;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
witness?: any;
|
||||
} = {
|
||||
permitted: {
|
||||
token: Token.target as string,
|
||||
amount,
|
||||
},
|
||||
spender,
|
||||
// Sorted nonce are not required for Permit2
|
||||
nonce: nonce || rBigInt(16),
|
||||
deadline: deadline || MaxUint256,
|
||||
};
|
||||
|
||||
if (witness) {
|
||||
values.witness = witness.witness;
|
||||
}
|
||||
|
||||
const hash = new TypedDataEncoder(types).hash(values);
|
||||
|
||||
const signature = Signature.from(await sigSigner.signTypedData(domain, types, values));
|
||||
|
||||
return {
|
||||
domain,
|
||||
types,
|
||||
values,
|
||||
hash,
|
||||
signature,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getPermit2CommitmentsSignature({
|
||||
PermitTornado,
|
||||
Token,
|
||||
signer,
|
||||
denomination,
|
||||
commitments,
|
||||
nonce,
|
||||
deadline,
|
||||
}: PermitCommitments & {
|
||||
PermitTornado: PermitTornado;
|
||||
Token: BaseContract;
|
||||
signer?: Signer;
|
||||
}) {
|
||||
const value = BigInt(commitments.length) * denomination;
|
||||
const commitmentsHash = solidityPackedKeccak256(['bytes32[]'], [commitments]);
|
||||
|
||||
return await getPermit2Signature({
|
||||
Token,
|
||||
signer,
|
||||
spender: PermitTornado.target as string,
|
||||
value,
|
||||
nonce,
|
||||
deadline,
|
||||
witness: {
|
||||
witnessTypeName: 'PermitCommitments',
|
||||
witnessType: {
|
||||
PermitCommitments: [
|
||||
{ name: 'instance', type: 'address' },
|
||||
{ name: 'commitmentsHash', type: 'bytes32' },
|
||||
],
|
||||
},
|
||||
witness: {
|
||||
instance: PermitTornado.target,
|
||||
commitmentsHash,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
170
src/prices.ts
170
src/prices.ts
@@ -3,99 +3,101 @@ import { ERC20__factory, OffchainOracle, Multicall } from './typechain';
|
||||
import { multicall, Call3 } from './multicall';
|
||||
|
||||
export class TokenPriceOracle {
|
||||
oracle?: OffchainOracle;
|
||||
multicall: Multicall;
|
||||
provider: Provider;
|
||||
oracle?: OffchainOracle;
|
||||
multicall: Multicall;
|
||||
provider: Provider;
|
||||
|
||||
fallbackPrice: bigint;
|
||||
fallbackPrice: bigint;
|
||||
|
||||
constructor(provider: Provider, multicall: Multicall, oracle?: OffchainOracle) {
|
||||
this.provider = provider;
|
||||
this.multicall = multicall;
|
||||
this.oracle = oracle;
|
||||
this.fallbackPrice = parseEther('0.0001');
|
||||
}
|
||||
|
||||
buildCalls(
|
||||
tokens: {
|
||||
tokenAddress: string;
|
||||
decimals: number;
|
||||
}[],
|
||||
): Call3[] {
|
||||
return tokens.map(({ tokenAddress }) => ({
|
||||
contract: this.oracle,
|
||||
name: 'getRateToEth',
|
||||
params: [tokenAddress, true],
|
||||
allowFailure: true,
|
||||
}));
|
||||
}
|
||||
|
||||
buildStable(stablecoinAddress: string): Call3[] {
|
||||
const stablecoin = ERC20__factory.connect(stablecoinAddress, this.provider);
|
||||
|
||||
return [
|
||||
{
|
||||
contract: stablecoin,
|
||||
name: 'decimals',
|
||||
},
|
||||
{
|
||||
contract: this.oracle,
|
||||
name: 'getRateToEth',
|
||||
params: [stablecoin.target, true],
|
||||
allowFailure: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async fetchPrice(tokenAddress: string, decimals: number): Promise<bigint> {
|
||||
// setup mock price for testnets
|
||||
if (!this.oracle) {
|
||||
return new Promise((resolve) => resolve(this.fallbackPrice));
|
||||
constructor(provider: Provider, multicall: Multicall, oracle?: OffchainOracle) {
|
||||
this.provider = provider;
|
||||
this.multicall = multicall;
|
||||
this.oracle = oracle;
|
||||
this.fallbackPrice = parseEther('0.0001');
|
||||
}
|
||||
|
||||
try {
|
||||
const price = await this.oracle.getRateToEth(tokenAddress, true);
|
||||
|
||||
return (price * BigInt(10 ** decimals)) / BigInt(10 ** 18);
|
||||
} catch (err) {
|
||||
console.log(`Failed to fetch oracle price for ${tokenAddress}, will use fallback price ${this.fallbackPrice}`);
|
||||
console.log(err);
|
||||
return this.fallbackPrice;
|
||||
}
|
||||
}
|
||||
|
||||
async fetchPrices(
|
||||
tokens: {
|
||||
tokenAddress: string;
|
||||
decimals: number;
|
||||
}[],
|
||||
): Promise<bigint[]> {
|
||||
// setup mock price for testnets
|
||||
if (!this.oracle) {
|
||||
return new Promise((resolve) => resolve(tokens.map(() => this.fallbackPrice)));
|
||||
buildCalls(
|
||||
tokens: {
|
||||
tokenAddress: string;
|
||||
decimals: number;
|
||||
}[],
|
||||
): Call3[] {
|
||||
return tokens.map(({ tokenAddress }) => ({
|
||||
contract: this.oracle,
|
||||
name: 'getRateToEth',
|
||||
params: [tokenAddress, true],
|
||||
allowFailure: true,
|
||||
}));
|
||||
}
|
||||
|
||||
const prices = (await multicall(this.multicall, this.buildCalls(tokens))) as (bigint | null)[];
|
||||
buildStable(stablecoinAddress: string): Call3[] {
|
||||
const stablecoin = ERC20__factory.connect(stablecoinAddress, this.provider);
|
||||
|
||||
return prices.map((price, index) => {
|
||||
if (!price) {
|
||||
price = this.fallbackPrice;
|
||||
}
|
||||
return (price * BigInt(10 ** tokens[index].decimals)) / BigInt(10 ** 18);
|
||||
});
|
||||
}
|
||||
|
||||
async fetchEthUSD(stablecoinAddress: string): Promise<number> {
|
||||
// setup mock price for testnets
|
||||
if (!this.oracle) {
|
||||
return new Promise((resolve) => resolve(10 ** 18 / Number(this.fallbackPrice)));
|
||||
return [
|
||||
{
|
||||
contract: stablecoin,
|
||||
name: 'decimals',
|
||||
},
|
||||
{
|
||||
contract: this.oracle,
|
||||
name: 'getRateToEth',
|
||||
params: [stablecoin.target, true],
|
||||
allowFailure: true,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
const [decimals, price] = await multicall(this.multicall, this.buildStable(stablecoinAddress));
|
||||
async fetchPrice(tokenAddress: string, decimals: number): Promise<bigint> {
|
||||
// setup mock price for testnets
|
||||
if (!this.oracle) {
|
||||
return new Promise((resolve) => resolve(this.fallbackPrice));
|
||||
}
|
||||
|
||||
// eth wei price of usdc token
|
||||
const ethPrice = ((price || this.fallbackPrice) * BigInt(10n ** decimals)) / BigInt(10 ** 18);
|
||||
try {
|
||||
const price = await this.oracle.getRateToEth(tokenAddress, true);
|
||||
|
||||
return 1 / Number(formatEther(ethPrice));
|
||||
}
|
||||
return (price * BigInt(10 ** decimals)) / BigInt(10 ** 18);
|
||||
} catch (err) {
|
||||
console.log(
|
||||
`Failed to fetch oracle price for ${tokenAddress}, will use fallback price ${this.fallbackPrice}`,
|
||||
);
|
||||
console.log(err);
|
||||
return this.fallbackPrice;
|
||||
}
|
||||
}
|
||||
|
||||
async fetchPrices(
|
||||
tokens: {
|
||||
tokenAddress: string;
|
||||
decimals: number;
|
||||
}[],
|
||||
): Promise<bigint[]> {
|
||||
// setup mock price for testnets
|
||||
if (!this.oracle) {
|
||||
return new Promise((resolve) => resolve(tokens.map(() => this.fallbackPrice)));
|
||||
}
|
||||
|
||||
const prices = (await multicall(this.multicall, this.buildCalls(tokens))) as (bigint | null)[];
|
||||
|
||||
return prices.map((price, index) => {
|
||||
if (!price) {
|
||||
price = this.fallbackPrice;
|
||||
}
|
||||
return (price * BigInt(10 ** tokens[index].decimals)) / BigInt(10 ** 18);
|
||||
});
|
||||
}
|
||||
|
||||
async fetchEthUSD(stablecoinAddress: string): Promise<number> {
|
||||
// setup mock price for testnets
|
||||
if (!this.oracle) {
|
||||
return new Promise((resolve) => resolve(10 ** 18 / Number(this.fallbackPrice)));
|
||||
}
|
||||
|
||||
const [decimals, price] = await multicall(this.multicall, this.buildStable(stablecoinAddress));
|
||||
|
||||
// eth wei price of usdc token
|
||||
const ethPrice = ((price || this.fallbackPrice) * BigInt(10n ** decimals)) / BigInt(10 ** 18);
|
||||
|
||||
return 1 / Number(formatEther(ethPrice));
|
||||
}
|
||||
}
|
||||
|
||||
804
src/providers.ts
804
src/providers.ts
@@ -2,23 +2,23 @@ import type { EventEmitter } from 'stream';
|
||||
import type { RequestOptions } from 'http';
|
||||
import crossFetch from 'cross-fetch';
|
||||
import {
|
||||
FetchRequest,
|
||||
JsonRpcApiProvider,
|
||||
JsonRpcProvider,
|
||||
Wallet,
|
||||
HDNodeWallet,
|
||||
FetchGetUrlFunc,
|
||||
Provider,
|
||||
SigningKey,
|
||||
TransactionRequest,
|
||||
JsonRpcSigner,
|
||||
BrowserProvider,
|
||||
Networkish,
|
||||
Eip1193Provider,
|
||||
VoidSigner,
|
||||
Network,
|
||||
EnsPlugin,
|
||||
GasCostPlugin,
|
||||
FetchRequest,
|
||||
JsonRpcApiProvider,
|
||||
JsonRpcProvider,
|
||||
Wallet,
|
||||
HDNodeWallet,
|
||||
FetchGetUrlFunc,
|
||||
Provider,
|
||||
SigningKey,
|
||||
TransactionRequest,
|
||||
JsonRpcSigner,
|
||||
BrowserProvider,
|
||||
Networkish,
|
||||
Eip1193Provider,
|
||||
VoidSigner,
|
||||
Network,
|
||||
EnsPlugin,
|
||||
GasCostPlugin,
|
||||
} from 'ethers';
|
||||
import type { RequestInfo, RequestInit, Response, HeadersInit } from 'node-fetch';
|
||||
// Temporary workaround until @types/node-fetch is compatible with @types/node
|
||||
@@ -27,9 +27,9 @@ import { isNode, sleep } from './utils';
|
||||
import type { Config, NetIdType } from './networkConfig';
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
ethereum?: Eip1193Provider & EventEmitter;
|
||||
}
|
||||
interface Window {
|
||||
ethereum?: Eip1193Provider & EventEmitter;
|
||||
}
|
||||
}
|
||||
|
||||
// Update this for every Tor Browser release
|
||||
@@ -40,432 +40,432 @@ export const fetch = crossFetch as unknown as nodeFetch;
|
||||
export type nodeFetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
export type fetchDataOptions = RequestInit & {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
headers?: HeadersInit | any;
|
||||
maxRetry?: number;
|
||||
retryOn?: number;
|
||||
userAgent?: string;
|
||||
timeout?: number;
|
||||
proxy?: string;
|
||||
torPort?: number;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
||||
debug?: Function;
|
||||
returnResponse?: boolean;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
headers?: HeadersInit | any;
|
||||
maxRetry?: number;
|
||||
retryOn?: number;
|
||||
userAgent?: string;
|
||||
timeout?: number;
|
||||
proxy?: string;
|
||||
torPort?: number;
|
||||
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
||||
debug?: Function;
|
||||
returnResponse?: boolean;
|
||||
};
|
||||
|
||||
export type NodeAgent = RequestOptions['agent'] | ((parsedUrl: URL) => RequestOptions['agent']);
|
||||
|
||||
export function getHttpAgent({
|
||||
fetchUrl,
|
||||
proxyUrl,
|
||||
torPort,
|
||||
retry,
|
||||
fetchUrl,
|
||||
proxyUrl,
|
||||
torPort,
|
||||
retry,
|
||||
}: {
|
||||
fetchUrl: string;
|
||||
proxyUrl?: string;
|
||||
torPort?: number;
|
||||
retry: number;
|
||||
fetchUrl: string;
|
||||
proxyUrl?: string;
|
||||
torPort?: number;
|
||||
retry: number;
|
||||
}): NodeAgent | undefined {
|
||||
/* eslint-disable @typescript-eslint/no-require-imports */
|
||||
const { HttpProxyAgent } = require('http-proxy-agent');
|
||||
const { HttpsProxyAgent } = require('https-proxy-agent');
|
||||
const { SocksProxyAgent } = require('socks-proxy-agent');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
/* eslint-disable @typescript-eslint/no-require-imports */
|
||||
const { HttpProxyAgent } = require('http-proxy-agent');
|
||||
const { HttpsProxyAgent } = require('https-proxy-agent');
|
||||
const { SocksProxyAgent } = require('socks-proxy-agent');
|
||||
/* eslint-enable @typescript-eslint/no-require-imports */
|
||||
|
||||
if (torPort) {
|
||||
return new SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`);
|
||||
}
|
||||
|
||||
if (!proxyUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isHttps = fetchUrl.includes('https://');
|
||||
|
||||
if (proxyUrl.includes('socks://') || proxyUrl.includes('socks4://') || proxyUrl.includes('socks5://')) {
|
||||
return new SocksProxyAgent(proxyUrl);
|
||||
}
|
||||
|
||||
if (proxyUrl.includes('http://') || proxyUrl.includes('https://')) {
|
||||
if (isHttps) {
|
||||
return new HttpsProxyAgent(proxyUrl);
|
||||
if (torPort) {
|
||||
return new SocksProxyAgent(`socks5h://tor${retry}@127.0.0.1:${torPort}`);
|
||||
}
|
||||
|
||||
if (!proxyUrl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const isHttps = fetchUrl.includes('https://');
|
||||
|
||||
if (proxyUrl.includes('socks://') || proxyUrl.includes('socks4://') || proxyUrl.includes('socks5://')) {
|
||||
return new SocksProxyAgent(proxyUrl);
|
||||
}
|
||||
|
||||
if (proxyUrl.includes('http://') || proxyUrl.includes('https://')) {
|
||||
if (isHttps) {
|
||||
return new HttpsProxyAgent(proxyUrl);
|
||||
}
|
||||
return new HttpProxyAgent(proxyUrl);
|
||||
}
|
||||
return new HttpProxyAgent(proxyUrl);
|
||||
}
|
||||
}
|
||||
|
||||
export async function fetchData(url: string, options: fetchDataOptions = {}) {
|
||||
const MAX_RETRY = options.maxRetry ?? 3;
|
||||
const RETRY_ON = options.retryOn ?? 500;
|
||||
const userAgent = options.userAgent ?? defaultUserAgent;
|
||||
const MAX_RETRY = options.maxRetry ?? 3;
|
||||
const RETRY_ON = options.retryOn ?? 500;
|
||||
const userAgent = options.userAgent ?? defaultUserAgent;
|
||||
|
||||
let retry = 0;
|
||||
let errorObject;
|
||||
let retry = 0;
|
||||
let errorObject;
|
||||
|
||||
if (!options.method) {
|
||||
if (!options.body) {
|
||||
options.method = 'GET';
|
||||
} else {
|
||||
options.method = 'POST';
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.headers) {
|
||||
options.headers = {};
|
||||
}
|
||||
|
||||
if (isNode && !options.headers['User-Agent']) {
|
||||
options.headers['User-Agent'] = userAgent;
|
||||
}
|
||||
|
||||
while (retry < MAX_RETRY + 1) {
|
||||
let timeout;
|
||||
|
||||
// Define promise timeout when the options.timeout is available
|
||||
if (!options.signal && options.timeout) {
|
||||
const controller = new AbortController();
|
||||
|
||||
// Temporary workaround until @types/node-fetch is compatible with @types/node
|
||||
options.signal = controller.signal as FetchAbortSignal;
|
||||
|
||||
// Define timeout in seconds
|
||||
timeout = setTimeout(() => {
|
||||
controller.abort();
|
||||
}, options.timeout);
|
||||
if (!options.method) {
|
||||
if (!options.body) {
|
||||
options.method = 'GET';
|
||||
} else {
|
||||
options.method = 'POST';
|
||||
}
|
||||
}
|
||||
|
||||
if (!options.agent && isNode && (options.proxy || options.torPort)) {
|
||||
options.agent = getHttpAgent({
|
||||
fetchUrl: url,
|
||||
proxyUrl: options.proxy,
|
||||
torPort: options.torPort,
|
||||
retry,
|
||||
});
|
||||
if (!options.headers) {
|
||||
options.headers = {};
|
||||
}
|
||||
|
||||
if (isNode && !options.headers['User-Agent']) {
|
||||
options.headers['User-Agent'] = userAgent;
|
||||
}
|
||||
|
||||
while (retry < MAX_RETRY + 1) {
|
||||
let timeout;
|
||||
|
||||
// Define promise timeout when the options.timeout is available
|
||||
if (!options.signal && options.timeout) {
|
||||
const controller = new AbortController();
|
||||
|
||||
// Temporary workaround until @types/node-fetch is compatible with @types/node
|
||||
options.signal = controller.signal as FetchAbortSignal;
|
||||
|
||||
// Define timeout in seconds
|
||||
timeout = setTimeout(() => {
|
||||
controller.abort();
|
||||
}, options.timeout);
|
||||
}
|
||||
|
||||
if (!options.agent && isNode && (options.proxy || options.torPort)) {
|
||||
options.agent = getHttpAgent({
|
||||
fetchUrl: url,
|
||||
proxyUrl: options.proxy,
|
||||
torPort: options.torPort,
|
||||
retry,
|
||||
});
|
||||
}
|
||||
|
||||
if (options.debug && typeof options.debug === 'function') {
|
||||
options.debug('request', {
|
||||
url,
|
||||
retry,
|
||||
errorObject,
|
||||
options,
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await fetch(url, {
|
||||
method: options.method,
|
||||
headers: options.headers,
|
||||
body: options.body,
|
||||
redirect: options.redirect,
|
||||
signal: options.signal,
|
||||
agent: options.agent,
|
||||
});
|
||||
|
||||
if (options.debug && typeof options.debug === 'function') {
|
||||
options.debug('response', resp);
|
||||
}
|
||||
|
||||
if (!resp.ok) {
|
||||
const errMsg = `Request to ${url} failed with error code ${resp.status}:\n` + (await resp.text());
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
if (options.returnResponse) {
|
||||
return resp;
|
||||
}
|
||||
|
||||
const contentType = resp.headers.get('content-type');
|
||||
|
||||
// If server returns JSON object, parse it and return as an object
|
||||
if (contentType?.includes('application/json')) {
|
||||
return await resp.json();
|
||||
}
|
||||
|
||||
// Else if the server returns text parse it as a string
|
||||
if (contentType?.includes('text')) {
|
||||
return await resp.text();
|
||||
}
|
||||
|
||||
// Return as a response object https://developer.mozilla.org/en-US/docs/Web/API/Response
|
||||
return resp;
|
||||
} catch (error) {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
errorObject = error;
|
||||
|
||||
retry++;
|
||||
|
||||
await sleep(RETRY_ON);
|
||||
} finally {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (options.debug && typeof options.debug === 'function') {
|
||||
options.debug('request', {
|
||||
url,
|
||||
retry,
|
||||
errorObject,
|
||||
options,
|
||||
});
|
||||
options.debug('error', errorObject);
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await fetch(url, {
|
||||
method: options.method,
|
||||
headers: options.headers,
|
||||
body: options.body,
|
||||
redirect: options.redirect,
|
||||
signal: options.signal,
|
||||
agent: options.agent,
|
||||
});
|
||||
|
||||
if (options.debug && typeof options.debug === 'function') {
|
||||
options.debug('response', resp);
|
||||
}
|
||||
|
||||
if (!resp.ok) {
|
||||
const errMsg = `Request to ${url} failed with error code ${resp.status}:\n` + (await resp.text());
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
if (options.returnResponse) {
|
||||
return resp;
|
||||
}
|
||||
|
||||
const contentType = resp.headers.get('content-type');
|
||||
|
||||
// If server returns JSON object, parse it and return as an object
|
||||
if (contentType?.includes('application/json')) {
|
||||
return await resp.json();
|
||||
}
|
||||
|
||||
// Else if the server returns text parse it as a string
|
||||
if (contentType?.includes('text')) {
|
||||
return await resp.text();
|
||||
}
|
||||
|
||||
// Return as a response object https://developer.mozilla.org/en-US/docs/Web/API/Response
|
||||
return resp;
|
||||
} catch (error) {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
|
||||
errorObject = error;
|
||||
|
||||
retry++;
|
||||
|
||||
await sleep(RETRY_ON);
|
||||
} finally {
|
||||
if (timeout) {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (options.debug && typeof options.debug === 'function') {
|
||||
options.debug('error', errorObject);
|
||||
}
|
||||
|
||||
throw errorObject;
|
||||
throw errorObject;
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
export const fetchGetUrlFunc =
|
||||
(options: fetchDataOptions = {}): FetchGetUrlFunc =>
|
||||
async (req, _signal) => {
|
||||
let signal;
|
||||
(options: fetchDataOptions = {}): FetchGetUrlFunc =>
|
||||
async (req, _signal) => {
|
||||
let signal;
|
||||
|
||||
if (_signal) {
|
||||
const controller = new AbortController();
|
||||
// Temporary workaround until @types/node-fetch is compatible with @types/node
|
||||
signal = controller.signal as FetchAbortSignal;
|
||||
_signal.addListener(() => {
|
||||
controller.abort();
|
||||
});
|
||||
}
|
||||
if (_signal) {
|
||||
const controller = new AbortController();
|
||||
// Temporary workaround until @types/node-fetch is compatible with @types/node
|
||||
signal = controller.signal as FetchAbortSignal;
|
||||
_signal.addListener(() => {
|
||||
controller.abort();
|
||||
});
|
||||
}
|
||||
|
||||
const init = {
|
||||
...options,
|
||||
method: req.method || 'POST',
|
||||
headers: req.headers,
|
||||
body: req.body || undefined,
|
||||
signal,
|
||||
returnResponse: true,
|
||||
const init = {
|
||||
...options,
|
||||
method: req.method || 'POST',
|
||||
headers: req.headers,
|
||||
body: req.body || undefined,
|
||||
signal,
|
||||
returnResponse: true,
|
||||
};
|
||||
|
||||
const resp = await fetchData(req.url, init);
|
||||
|
||||
const headers = {} as { [key in string]: any };
|
||||
resp.headers.forEach((value: any, key: string) => {
|
||||
headers[key.toLowerCase()] = value;
|
||||
});
|
||||
|
||||
const respBody = await resp.arrayBuffer();
|
||||
const body = respBody == null ? null : new Uint8Array(respBody);
|
||||
|
||||
return {
|
||||
statusCode: resp.status,
|
||||
statusMessage: resp.statusText,
|
||||
headers,
|
||||
body,
|
||||
};
|
||||
};
|
||||
|
||||
const resp = await fetchData(req.url, init);
|
||||
|
||||
const headers = {} as { [key in string]: any };
|
||||
resp.headers.forEach((value: any, key: string) => {
|
||||
headers[key.toLowerCase()] = value;
|
||||
});
|
||||
|
||||
const respBody = await resp.arrayBuffer();
|
||||
const body = respBody == null ? null : new Uint8Array(respBody);
|
||||
|
||||
return {
|
||||
statusCode: resp.status,
|
||||
statusMessage: resp.statusText,
|
||||
headers,
|
||||
body,
|
||||
};
|
||||
};
|
||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
||||
|
||||
export type getProviderOptions = fetchDataOptions & {
|
||||
// NetId to check against rpc
|
||||
netId?: NetIdType;
|
||||
pollingInterval?: number;
|
||||
// NetId to check against rpc
|
||||
netId?: NetIdType;
|
||||
pollingInterval?: number;
|
||||
};
|
||||
|
||||
export async function getProvider(rpcUrl: string, fetchOptions?: getProviderOptions): Promise<JsonRpcProvider> {
|
||||
const fetchReq = new FetchRequest(rpcUrl);
|
||||
const fetchReq = new FetchRequest(rpcUrl);
|
||||
|
||||
fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions);
|
||||
fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions);
|
||||
|
||||
const staticNetwork = await new JsonRpcProvider(fetchReq).getNetwork();
|
||||
const staticNetwork = await new JsonRpcProvider(fetchReq).getNetwork();
|
||||
|
||||
const chainId = Number(staticNetwork.chainId);
|
||||
const chainId = Number(staticNetwork.chainId);
|
||||
|
||||
if (fetchOptions?.netId && fetchOptions.netId !== chainId) {
|
||||
const errMsg = `Wrong network for ${rpcUrl}, wants ${fetchOptions.netId} got ${chainId}`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
if (fetchOptions?.netId && fetchOptions.netId !== chainId) {
|
||||
const errMsg = `Wrong network for ${rpcUrl}, wants ${fetchOptions.netId} got ${chainId}`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
return new JsonRpcProvider(fetchReq, staticNetwork, {
|
||||
staticNetwork,
|
||||
pollingInterval: fetchOptions?.pollingInterval || 1000,
|
||||
});
|
||||
return new JsonRpcProvider(fetchReq, staticNetwork, {
|
||||
staticNetwork,
|
||||
pollingInterval: fetchOptions?.pollingInterval || 1000,
|
||||
});
|
||||
}
|
||||
|
||||
export function getProviderWithNetId(
|
||||
netId: NetIdType,
|
||||
rpcUrl: string,
|
||||
config: Config,
|
||||
fetchOptions?: getProviderOptions,
|
||||
netId: NetIdType,
|
||||
rpcUrl: string,
|
||||
config: Config,
|
||||
fetchOptions?: getProviderOptions,
|
||||
): JsonRpcProvider {
|
||||
const { networkName, reverseRecordsContract, pollInterval } = config;
|
||||
const hasEns = Boolean(reverseRecordsContract);
|
||||
const { networkName, reverseRecordsContract, pollInterval } = config;
|
||||
const hasEns = Boolean(reverseRecordsContract);
|
||||
|
||||
const fetchReq = new FetchRequest(rpcUrl);
|
||||
fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions);
|
||||
const staticNetwork = new Network(networkName, netId);
|
||||
if (hasEns) {
|
||||
staticNetwork.attachPlugin(new EnsPlugin(null, Number(netId)));
|
||||
}
|
||||
staticNetwork.attachPlugin(new GasCostPlugin());
|
||||
const fetchReq = new FetchRequest(rpcUrl);
|
||||
fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions);
|
||||
const staticNetwork = new Network(networkName, netId);
|
||||
if (hasEns) {
|
||||
staticNetwork.attachPlugin(new EnsPlugin(null, Number(netId)));
|
||||
}
|
||||
staticNetwork.attachPlugin(new GasCostPlugin());
|
||||
|
||||
const provider = new JsonRpcProvider(fetchReq, staticNetwork, {
|
||||
staticNetwork,
|
||||
pollingInterval: fetchOptions?.pollingInterval || pollInterval * 1000,
|
||||
});
|
||||
const provider = new JsonRpcProvider(fetchReq, staticNetwork, {
|
||||
staticNetwork,
|
||||
pollingInterval: fetchOptions?.pollingInterval || pollInterval * 1000,
|
||||
});
|
||||
|
||||
return provider;
|
||||
return provider;
|
||||
}
|
||||
|
||||
export const populateTransaction = async (
|
||||
signer: TornadoWallet | TornadoVoidSigner | TornadoRpcSigner,
|
||||
tx: TransactionRequest,
|
||||
signer: TornadoWallet | TornadoVoidSigner | TornadoRpcSigner,
|
||||
tx: TransactionRequest,
|
||||
) => {
|
||||
const provider = signer.provider as Provider;
|
||||
const provider = signer.provider as Provider;
|
||||
|
||||
if (!tx.from) {
|
||||
tx.from = signer.address;
|
||||
} else if (tx.from !== signer.address) {
|
||||
const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
const [feeData, nonce] = await Promise.all([
|
||||
tx.maxFeePerGas || tx.gasPrice ? undefined : provider.getFeeData(),
|
||||
tx.nonce ? undefined : provider.getTransactionCount(signer.address, 'pending'),
|
||||
]);
|
||||
|
||||
if (feeData) {
|
||||
// EIP-1559
|
||||
if (feeData.maxFeePerGas) {
|
||||
if (!tx.type) {
|
||||
tx.type = 2;
|
||||
}
|
||||
|
||||
tx.maxFeePerGas = (feeData.maxFeePerGas * (BigInt(10000) + BigInt(signer.gasPriceBump))) / BigInt(10000);
|
||||
tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
|
||||
delete tx.gasPrice;
|
||||
} else if (feeData.gasPrice) {
|
||||
if (!tx.type) {
|
||||
tx.type = 0;
|
||||
}
|
||||
tx.gasPrice = feeData.gasPrice;
|
||||
delete tx.maxFeePerGas;
|
||||
delete tx.maxPriorityFeePerGas;
|
||||
if (!tx.from) {
|
||||
tx.from = signer.address;
|
||||
} else if (tx.from !== signer.address) {
|
||||
const errMsg = `populateTransaction: signer mismatch for tx, wants ${tx.from} have ${signer.address}`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
}
|
||||
|
||||
if (nonce) {
|
||||
tx.nonce = nonce;
|
||||
}
|
||||
const [feeData, nonce] = await Promise.all([
|
||||
tx.maxFeePerGas || tx.gasPrice ? undefined : provider.getFeeData(),
|
||||
tx.nonce ? undefined : provider.getTransactionCount(signer.address, 'pending'),
|
||||
]);
|
||||
|
||||
if (!tx.gasLimit) {
|
||||
try {
|
||||
const gasLimit = await provider.estimateGas(tx);
|
||||
if (feeData) {
|
||||
// EIP-1559
|
||||
if (feeData.maxFeePerGas) {
|
||||
if (!tx.type) {
|
||||
tx.type = 2;
|
||||
}
|
||||
|
||||
tx.gasLimit =
|
||||
gasLimit === BigInt(21000)
|
||||
? gasLimit
|
||||
: (gasLimit * (BigInt(10000) + BigInt(signer.gasLimitBump))) / BigInt(10000);
|
||||
} catch (error) {
|
||||
if (signer.gasFailover) {
|
||||
console.log('populateTransaction: warning gas estimation failed falling back to 3M gas');
|
||||
// Gas failover
|
||||
tx.gasLimit = BigInt('3000000');
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
tx.maxFeePerGas = (feeData.maxFeePerGas * (BigInt(10000) + BigInt(signer.gasPriceBump))) / BigInt(10000);
|
||||
tx.maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
|
||||
delete tx.gasPrice;
|
||||
} else if (feeData.gasPrice) {
|
||||
if (!tx.type) {
|
||||
tx.type = 0;
|
||||
}
|
||||
tx.gasPrice = feeData.gasPrice;
|
||||
delete tx.maxFeePerGas;
|
||||
delete tx.maxPriorityFeePerGas;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tx;
|
||||
if (nonce) {
|
||||
tx.nonce = nonce;
|
||||
}
|
||||
|
||||
if (!tx.gasLimit) {
|
||||
try {
|
||||
const gasLimit = await provider.estimateGas(tx);
|
||||
|
||||
tx.gasLimit =
|
||||
gasLimit === BigInt(21000)
|
||||
? gasLimit
|
||||
: (gasLimit * (BigInt(10000) + BigInt(signer.gasLimitBump))) / BigInt(10000);
|
||||
} catch (error) {
|
||||
if (signer.gasFailover) {
|
||||
console.log('populateTransaction: warning gas estimation failed falling back to 3M gas');
|
||||
// Gas failover
|
||||
tx.gasLimit = BigInt('3000000');
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tx;
|
||||
};
|
||||
|
||||
export interface TornadoWalletOptions {
|
||||
gasPriceBump?: number;
|
||||
gasLimitBump?: number;
|
||||
gasFailover?: boolean;
|
||||
bumpNonce?: boolean;
|
||||
gasPriceBump?: number;
|
||||
gasLimitBump?: number;
|
||||
gasFailover?: boolean;
|
||||
bumpNonce?: boolean;
|
||||
}
|
||||
|
||||
export class TornadoWallet extends Wallet {
|
||||
nonce?: number;
|
||||
gasPriceBump: number;
|
||||
gasLimitBump: number;
|
||||
gasFailover: boolean;
|
||||
bumpNonce: boolean;
|
||||
constructor(
|
||||
key: string | SigningKey,
|
||||
provider?: Provider,
|
||||
{ gasPriceBump, gasLimitBump, gasFailover, bumpNonce }: TornadoWalletOptions = {},
|
||||
) {
|
||||
super(key, provider);
|
||||
// 10% bump from the recommended fee
|
||||
this.gasPriceBump = gasPriceBump ?? 0;
|
||||
// 30% bump from the recommended gaslimit
|
||||
this.gasLimitBump = gasLimitBump ?? 3000;
|
||||
this.gasFailover = gasFailover ?? false;
|
||||
// Disable bump nonce feature unless being used by the server environment
|
||||
this.bumpNonce = bumpNonce ?? false;
|
||||
}
|
||||
nonce?: number;
|
||||
gasPriceBump: number;
|
||||
gasLimitBump: number;
|
||||
gasFailover: boolean;
|
||||
bumpNonce: boolean;
|
||||
constructor(
|
||||
key: string | SigningKey,
|
||||
provider?: Provider,
|
||||
{ gasPriceBump, gasLimitBump, gasFailover, bumpNonce }: TornadoWalletOptions = {},
|
||||
) {
|
||||
super(key, provider);
|
||||
// 10% bump from the recommended fee
|
||||
this.gasPriceBump = gasPriceBump ?? 0;
|
||||
// 30% bump from the recommended gaslimit
|
||||
this.gasLimitBump = gasLimitBump ?? 3000;
|
||||
this.gasFailover = gasFailover ?? false;
|
||||
// Disable bump nonce feature unless being used by the server environment
|
||||
this.bumpNonce = bumpNonce ?? false;
|
||||
}
|
||||
|
||||
static fromMnemonic(mneomnic: string, provider: Provider, index = 0, options?: TornadoWalletOptions) {
|
||||
const defaultPath = `m/44'/60'/0'/0/${index}`;
|
||||
const { privateKey } = HDNodeWallet.fromPhrase(mneomnic, undefined, defaultPath);
|
||||
return new TornadoWallet(privateKey as unknown as SigningKey, provider, options);
|
||||
}
|
||||
static fromMnemonic(mneomnic: string, provider: Provider, index = 0, options?: TornadoWalletOptions) {
|
||||
const defaultPath = `m/44'/60'/0'/0/${index}`;
|
||||
const { privateKey } = HDNodeWallet.fromPhrase(mneomnic, undefined, defaultPath);
|
||||
return new TornadoWallet(privateKey as unknown as SigningKey, provider, options);
|
||||
}
|
||||
|
||||
async populateTransaction(tx: TransactionRequest) {
|
||||
const txObject = await populateTransaction(this, tx);
|
||||
this.nonce = Number(txObject.nonce);
|
||||
async populateTransaction(tx: TransactionRequest) {
|
||||
const txObject = await populateTransaction(this, tx);
|
||||
this.nonce = Number(txObject.nonce);
|
||||
|
||||
return super.populateTransaction(txObject);
|
||||
}
|
||||
return super.populateTransaction(txObject);
|
||||
}
|
||||
}
|
||||
|
||||
export class TornadoVoidSigner extends VoidSigner {
|
||||
nonce?: number;
|
||||
gasPriceBump: number;
|
||||
gasLimitBump: number;
|
||||
gasFailover: boolean;
|
||||
bumpNonce: boolean;
|
||||
constructor(
|
||||
address: string,
|
||||
provider?: Provider,
|
||||
{ gasPriceBump, gasLimitBump, gasFailover, bumpNonce }: TornadoWalletOptions = {},
|
||||
) {
|
||||
super(address, provider);
|
||||
// 10% bump from the recommended fee
|
||||
this.gasPriceBump = gasPriceBump ?? 0;
|
||||
// 30% bump from the recommended gaslimit
|
||||
this.gasLimitBump = gasLimitBump ?? 3000;
|
||||
this.gasFailover = gasFailover ?? false;
|
||||
// turn off bumpNonce feature for view only wallet
|
||||
this.bumpNonce = bumpNonce ?? false;
|
||||
}
|
||||
nonce?: number;
|
||||
gasPriceBump: number;
|
||||
gasLimitBump: number;
|
||||
gasFailover: boolean;
|
||||
bumpNonce: boolean;
|
||||
constructor(
|
||||
address: string,
|
||||
provider?: Provider,
|
||||
{ gasPriceBump, gasLimitBump, gasFailover, bumpNonce }: TornadoWalletOptions = {},
|
||||
) {
|
||||
super(address, provider);
|
||||
// 10% bump from the recommended fee
|
||||
this.gasPriceBump = gasPriceBump ?? 0;
|
||||
// 30% bump from the recommended gaslimit
|
||||
this.gasLimitBump = gasLimitBump ?? 3000;
|
||||
this.gasFailover = gasFailover ?? false;
|
||||
// turn off bumpNonce feature for view only wallet
|
||||
this.bumpNonce = bumpNonce ?? false;
|
||||
}
|
||||
|
||||
async populateTransaction(tx: TransactionRequest) {
|
||||
const txObject = await populateTransaction(this, tx);
|
||||
this.nonce = Number(txObject.nonce);
|
||||
async populateTransaction(tx: TransactionRequest) {
|
||||
const txObject = await populateTransaction(this, tx);
|
||||
this.nonce = Number(txObject.nonce);
|
||||
|
||||
return super.populateTransaction(txObject);
|
||||
}
|
||||
return super.populateTransaction(txObject);
|
||||
}
|
||||
}
|
||||
|
||||
export class TornadoRpcSigner extends JsonRpcSigner {
|
||||
nonce?: number;
|
||||
gasPriceBump: number;
|
||||
gasLimitBump: number;
|
||||
gasFailover: boolean;
|
||||
bumpNonce: boolean;
|
||||
constructor(
|
||||
provider: JsonRpcApiProvider,
|
||||
address: string,
|
||||
{ gasPriceBump, gasLimitBump, gasFailover, bumpNonce }: TornadoWalletOptions = {},
|
||||
) {
|
||||
super(provider, address);
|
||||
// 10% bump from the recommended fee
|
||||
this.gasPriceBump = gasPriceBump ?? 0;
|
||||
// 30% bump from the recommended gaslimit
|
||||
this.gasLimitBump = gasLimitBump ?? 3000;
|
||||
this.gasFailover = gasFailover ?? false;
|
||||
// turn off bumpNonce feature for browser wallet
|
||||
this.bumpNonce = bumpNonce ?? false;
|
||||
}
|
||||
nonce?: number;
|
||||
gasPriceBump: number;
|
||||
gasLimitBump: number;
|
||||
gasFailover: boolean;
|
||||
bumpNonce: boolean;
|
||||
constructor(
|
||||
provider: JsonRpcApiProvider,
|
||||
address: string,
|
||||
{ gasPriceBump, gasLimitBump, gasFailover, bumpNonce }: TornadoWalletOptions = {},
|
||||
) {
|
||||
super(provider, address);
|
||||
// 10% bump from the recommended fee
|
||||
this.gasPriceBump = gasPriceBump ?? 0;
|
||||
// 30% bump from the recommended gaslimit
|
||||
this.gasLimitBump = gasLimitBump ?? 3000;
|
||||
this.gasFailover = gasFailover ?? false;
|
||||
// turn off bumpNonce feature for browser wallet
|
||||
this.bumpNonce = bumpNonce ?? false;
|
||||
}
|
||||
|
||||
async sendUncheckedTransaction(tx: TransactionRequest) {
|
||||
return super.sendUncheckedTransaction(await populateTransaction(this, tx));
|
||||
}
|
||||
async sendUncheckedTransaction(tx: TransactionRequest) {
|
||||
return super.sendUncheckedTransaction(await populateTransaction(this, tx));
|
||||
}
|
||||
}
|
||||
|
||||
/* eslint-disable @typescript-eslint/no-explicit-any */
|
||||
@@ -475,43 +475,43 @@ export type handleWalletFunc = (...args: any[]) => void;
|
||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
||||
|
||||
export interface TornadoBrowserProviderOptions extends TornadoWalletOptions {
|
||||
netId?: NetIdType;
|
||||
connectWallet?: connectWalletFunc;
|
||||
handleNetworkChanges?: handleWalletFunc;
|
||||
handleAccountChanges?: handleWalletFunc;
|
||||
handleAccountDisconnect?: handleWalletFunc;
|
||||
netId?: NetIdType;
|
||||
connectWallet?: connectWalletFunc;
|
||||
handleNetworkChanges?: handleWalletFunc;
|
||||
handleAccountChanges?: handleWalletFunc;
|
||||
handleAccountDisconnect?: handleWalletFunc;
|
||||
}
|
||||
|
||||
export class TornadoBrowserProvider extends BrowserProvider {
|
||||
options?: TornadoBrowserProviderOptions;
|
||||
constructor(ethereum: Eip1193Provider, network?: Networkish, options?: TornadoBrowserProviderOptions) {
|
||||
super(ethereum, network);
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
async getSigner(address: string): Promise<TornadoRpcSigner> {
|
||||
const signerAddress = (await super.getSigner(address)).address;
|
||||
|
||||
if (
|
||||
this.options?.netId &&
|
||||
this.options?.connectWallet &&
|
||||
Number(await super.send('net_version', [])) !== this.options?.netId
|
||||
) {
|
||||
await this.options.connectWallet(this.options?.netId);
|
||||
options?: TornadoBrowserProviderOptions;
|
||||
constructor(ethereum: Eip1193Provider, network?: Networkish, options?: TornadoBrowserProviderOptions) {
|
||||
super(ethereum, network);
|
||||
this.options = options;
|
||||
}
|
||||
|
||||
if (this.options?.handleNetworkChanges) {
|
||||
window?.ethereum?.on('chainChanged', this.options.handleNetworkChanges);
|
||||
}
|
||||
async getSigner(address: string): Promise<TornadoRpcSigner> {
|
||||
const signerAddress = (await super.getSigner(address)).address;
|
||||
|
||||
if (this.options?.handleAccountChanges) {
|
||||
window?.ethereum?.on('accountsChanged', this.options.handleAccountChanges);
|
||||
}
|
||||
if (
|
||||
this.options?.netId &&
|
||||
this.options?.connectWallet &&
|
||||
Number(await super.send('net_version', [])) !== this.options?.netId
|
||||
) {
|
||||
await this.options.connectWallet(this.options?.netId);
|
||||
}
|
||||
|
||||
if (this.options?.handleAccountDisconnect) {
|
||||
window?.ethereum?.on('disconnect', this.options.handleAccountDisconnect);
|
||||
}
|
||||
if (this.options?.handleNetworkChanges) {
|
||||
window?.ethereum?.on('chainChanged', this.options.handleNetworkChanges);
|
||||
}
|
||||
|
||||
return new TornadoRpcSigner(this, signerAddress, this.options);
|
||||
}
|
||||
if (this.options?.handleAccountChanges) {
|
||||
window?.ethereum?.on('accountsChanged', this.options.handleAccountChanges);
|
||||
}
|
||||
|
||||
if (this.options?.handleAccountDisconnect) {
|
||||
window?.ethereum?.on('disconnect', this.options.handleAccountDisconnect);
|
||||
}
|
||||
|
||||
return new TornadoRpcSigner(this, signerAddress, this.options);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,88 +13,88 @@ export const MAX_FEE = 0.9;
|
||||
export const MIN_STAKE_BALANCE = parseEther('500');
|
||||
|
||||
export interface RelayerParams {
|
||||
ensName: string;
|
||||
relayerAddress: string;
|
||||
ensName: string;
|
||||
relayerAddress: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Info from relayer status
|
||||
*/
|
||||
export interface RelayerInfo extends RelayerParams {
|
||||
netId: NetIdType;
|
||||
url: string;
|
||||
hostname: string;
|
||||
rewardAccount: string;
|
||||
instances: string[];
|
||||
stakeBalance?: string;
|
||||
gasPrice?: number;
|
||||
ethPrices?: {
|
||||
[key in string]: string;
|
||||
};
|
||||
currentQueue: number;
|
||||
tornadoServiceFee: number;
|
||||
netId: NetIdType;
|
||||
url: string;
|
||||
hostname: string;
|
||||
rewardAccount: string;
|
||||
instances: string[];
|
||||
stakeBalance?: string;
|
||||
gasPrice?: number;
|
||||
ethPrices?: {
|
||||
[key in string]: string;
|
||||
};
|
||||
currentQueue: number;
|
||||
tornadoServiceFee: number;
|
||||
}
|
||||
|
||||
export interface RelayerError {
|
||||
hostname: string;
|
||||
relayerAddress?: string;
|
||||
errorMessage?: string;
|
||||
hasError: boolean;
|
||||
hostname: string;
|
||||
relayerAddress?: string;
|
||||
errorMessage?: string;
|
||||
hasError: boolean;
|
||||
}
|
||||
|
||||
export interface RelayerStatus {
|
||||
url: string;
|
||||
rewardAccount: string;
|
||||
instances: {
|
||||
[key in string]: {
|
||||
instanceAddress: {
|
||||
[key in string]: string;
|
||||
};
|
||||
tokenAddress?: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
url: string;
|
||||
rewardAccount: string;
|
||||
instances: {
|
||||
[key in string]: {
|
||||
instanceAddress: {
|
||||
[key in string]: string;
|
||||
};
|
||||
tokenAddress?: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
};
|
||||
};
|
||||
};
|
||||
gasPrices?: {
|
||||
fast: number;
|
||||
additionalProperties?: number;
|
||||
};
|
||||
netId: NetIdType;
|
||||
ethPrices?: {
|
||||
[key in string]: string;
|
||||
};
|
||||
tornadoServiceFee: number;
|
||||
latestBlock?: number;
|
||||
version: string;
|
||||
health: {
|
||||
status: string;
|
||||
error: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
errorsLog: any[];
|
||||
};
|
||||
currentQueue: number;
|
||||
gasPrices?: {
|
||||
fast: number;
|
||||
additionalProperties?: number;
|
||||
};
|
||||
netId: NetIdType;
|
||||
ethPrices?: {
|
||||
[key in string]: string;
|
||||
};
|
||||
tornadoServiceFee: number;
|
||||
latestBlock?: number;
|
||||
version: string;
|
||||
health: {
|
||||
status: string;
|
||||
error: string;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
errorsLog: any[];
|
||||
};
|
||||
currentQueue: number;
|
||||
}
|
||||
|
||||
export interface TornadoWithdrawParams extends snarkProofs {
|
||||
contract: string;
|
||||
contract: string;
|
||||
}
|
||||
|
||||
export interface RelayerTornadoWithdraw {
|
||||
id?: string;
|
||||
error?: string;
|
||||
id?: string;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
export interface RelayerTornadoJobs {
|
||||
error?: string;
|
||||
id: string;
|
||||
type?: string;
|
||||
status: string;
|
||||
contract?: string;
|
||||
proof?: string;
|
||||
args?: string[];
|
||||
txHash?: string;
|
||||
confirmations?: number;
|
||||
failedReason?: string;
|
||||
error?: string;
|
||||
id: string;
|
||||
type?: string;
|
||||
status: string;
|
||||
contract?: string;
|
||||
proof?: string;
|
||||
args?: string[];
|
||||
txHash?: string;
|
||||
confirmations?: number;
|
||||
failedReason?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -126,290 +126,295 @@ export function isRelayerUpdated(relayerVersion: string, netId: NetIdType) {
|
||||
**/
|
||||
|
||||
export function calculateScore({ stakeBalance, tornadoServiceFee }: RelayerInfo) {
|
||||
if (tornadoServiceFee < MIN_FEE) {
|
||||
tornadoServiceFee = MIN_FEE;
|
||||
} else if (tornadoServiceFee >= MAX_FEE) {
|
||||
return BigInt(0);
|
||||
}
|
||||
if (tornadoServiceFee < MIN_FEE) {
|
||||
tornadoServiceFee = MIN_FEE;
|
||||
} else if (tornadoServiceFee >= MAX_FEE) {
|
||||
return BigInt(0);
|
||||
}
|
||||
|
||||
const serviceFeeCoefficient = (tornadoServiceFee - MIN_FEE) ** 2;
|
||||
const feeDiffCoefficient = 1 / (MAX_FEE - MIN_FEE) ** 2;
|
||||
const coefficientsMultiplier = 1 - feeDiffCoefficient * serviceFeeCoefficient;
|
||||
const serviceFeeCoefficient = (tornadoServiceFee - MIN_FEE) ** 2;
|
||||
const feeDiffCoefficient = 1 / (MAX_FEE - MIN_FEE) ** 2;
|
||||
const coefficientsMultiplier = 1 - feeDiffCoefficient * serviceFeeCoefficient;
|
||||
|
||||
return BigInt(Math.floor(Number(stakeBalance || '0') * coefficientsMultiplier));
|
||||
return BigInt(Math.floor(Number(stakeBalance || '0') * coefficientsMultiplier));
|
||||
}
|
||||
|
||||
export function getWeightRandom(weightsScores: bigint[], random: bigint) {
|
||||
for (let i = 0; i < weightsScores.length; i++) {
|
||||
if (random < weightsScores[i]) {
|
||||
return i;
|
||||
for (let i = 0; i < weightsScores.length; i++) {
|
||||
if (random < weightsScores[i]) {
|
||||
return i;
|
||||
}
|
||||
random = random - weightsScores[i];
|
||||
}
|
||||
random = random - weightsScores[i];
|
||||
}
|
||||
return Math.floor(Math.random() * weightsScores.length);
|
||||
return Math.floor(Math.random() * weightsScores.length);
|
||||
}
|
||||
|
||||
export interface RelayerInstanceList {
|
||||
[key: string]: {
|
||||
instanceAddress: {
|
||||
[key: string]: string;
|
||||
[key: string]: {
|
||||
instanceAddress: {
|
||||
[key: string]: string;
|
||||
};
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export function getSupportedInstances(instanceList: RelayerInstanceList) {
|
||||
const rawList = Object.values(instanceList)
|
||||
.map(({ instanceAddress }) => {
|
||||
return Object.values(instanceAddress);
|
||||
})
|
||||
.flat();
|
||||
const rawList = Object.values(instanceList)
|
||||
.map(({ instanceAddress }) => {
|
||||
return Object.values(instanceAddress);
|
||||
})
|
||||
.flat();
|
||||
|
||||
return rawList.map((l) => getAddress(l));
|
||||
return rawList.map((l) => getAddress(l));
|
||||
}
|
||||
|
||||
export function pickWeightedRandomRelayer(relayers: RelayerInfo[]) {
|
||||
const weightsScores = relayers.map((el) => calculateScore(el));
|
||||
const totalWeight = weightsScores.reduce((acc, curr) => {
|
||||
return (acc = acc + curr);
|
||||
}, BigInt('0'));
|
||||
const weightsScores = relayers.map((el) => calculateScore(el));
|
||||
const totalWeight = weightsScores.reduce((acc, curr) => {
|
||||
return (acc = acc + curr);
|
||||
}, BigInt('0'));
|
||||
|
||||
const random = BigInt(Math.floor(Number(totalWeight) * Math.random()));
|
||||
const weightRandomIndex = getWeightRandom(weightsScores, random);
|
||||
const random = BigInt(Math.floor(Number(totalWeight) * Math.random()));
|
||||
const weightRandomIndex = getWeightRandom(weightsScores, random);
|
||||
|
||||
return relayers[weightRandomIndex];
|
||||
return relayers[weightRandomIndex];
|
||||
}
|
||||
|
||||
export interface RelayerClientConstructor {
|
||||
netId: NetIdType;
|
||||
config: Config;
|
||||
fetchDataOptions?: fetchDataOptions;
|
||||
netId: NetIdType;
|
||||
config: Config;
|
||||
fetchDataOptions?: fetchDataOptions;
|
||||
}
|
||||
|
||||
export class RelayerClient {
|
||||
netId: NetIdType;
|
||||
config: Config;
|
||||
selectedRelayer?: RelayerInfo;
|
||||
fetchDataOptions?: fetchDataOptions;
|
||||
tovarish: boolean;
|
||||
netId: NetIdType;
|
||||
config: Config;
|
||||
selectedRelayer?: RelayerInfo;
|
||||
fetchDataOptions?: fetchDataOptions;
|
||||
tovarish: boolean;
|
||||
|
||||
constructor({ netId, config, fetchDataOptions }: RelayerClientConstructor) {
|
||||
this.netId = netId;
|
||||
this.config = config;
|
||||
this.fetchDataOptions = fetchDataOptions;
|
||||
this.tovarish = false;
|
||||
}
|
||||
|
||||
async askRelayerStatus({
|
||||
hostname,
|
||||
url,
|
||||
relayerAddress,
|
||||
}: {
|
||||
hostname?: string;
|
||||
// optional url if entered manually
|
||||
url?: string;
|
||||
// relayerAddress from registry contract to prevent cheating
|
||||
relayerAddress?: string;
|
||||
}): Promise<RelayerStatus> {
|
||||
if (!url && hostname) {
|
||||
url = `https://${!hostname.endsWith('/') ? hostname + '/' : hostname}`;
|
||||
} else if (url && !url.endsWith('/')) {
|
||||
url += '/';
|
||||
} else {
|
||||
url = '';
|
||||
constructor({ netId, config, fetchDataOptions }: RelayerClientConstructor) {
|
||||
this.netId = netId;
|
||||
this.config = config;
|
||||
this.fetchDataOptions = fetchDataOptions;
|
||||
this.tovarish = false;
|
||||
}
|
||||
|
||||
const rawStatus = (await fetchData(`${url}status`, {
|
||||
...this.fetchDataOptions,
|
||||
headers: {
|
||||
'Content-Type': 'application/json, application/x-www-form-urlencoded',
|
||||
},
|
||||
timeout: 30000,
|
||||
maxRetry: this.fetchDataOptions?.torPort ? 2 : 0,
|
||||
})) as object;
|
||||
|
||||
const statusValidator = ajv.compile(getStatusSchema(this.netId, this.config, this.tovarish));
|
||||
|
||||
if (!statusValidator(rawStatus)) {
|
||||
throw new Error('Invalid status schema');
|
||||
}
|
||||
|
||||
const status = {
|
||||
...rawStatus,
|
||||
url,
|
||||
} as RelayerStatus;
|
||||
|
||||
if (status.currentQueue > 5) {
|
||||
throw new Error('Withdrawal queue is overloaded');
|
||||
}
|
||||
|
||||
if (status.netId !== this.netId) {
|
||||
throw new Error('This relayer serves a different network');
|
||||
}
|
||||
|
||||
if (relayerAddress && this.netId === NetId.MAINNET && status.rewardAccount !== relayerAddress) {
|
||||
throw new Error('The Relayer reward address must match registered address');
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
async filterRelayer(relayer: CachedRelayerInfo): Promise<RelayerInfo | RelayerError | undefined> {
|
||||
const hostname = relayer.hostnames[this.netId];
|
||||
const { ensName, relayerAddress } = relayer;
|
||||
|
||||
if (!hostname) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await this.askRelayerStatus({ hostname, relayerAddress });
|
||||
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
async askRelayerStatus({
|
||||
hostname,
|
||||
ensName,
|
||||
url,
|
||||
relayerAddress,
|
||||
rewardAccount: getAddress(status.rewardAccount),
|
||||
instances: getSupportedInstances(status.instances),
|
||||
stakeBalance: relayer.stakeBalance,
|
||||
gasPrice: status.gasPrices?.fast,
|
||||
ethPrices: status.ethPrices,
|
||||
currentQueue: status.currentQueue,
|
||||
tornadoServiceFee: status.tornadoServiceFee,
|
||||
} as RelayerInfo;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (err: any) {
|
||||
return {
|
||||
hostname,
|
||||
relayerAddress,
|
||||
errorMessage: err.message,
|
||||
hasError: true,
|
||||
} as RelayerError;
|
||||
}
|
||||
}
|
||||
|
||||
async getValidRelayers(relayers: CachedRelayerInfo[]): Promise<{
|
||||
validRelayers: RelayerInfo[];
|
||||
invalidRelayers: RelayerError[];
|
||||
}> {
|
||||
const invalidRelayers: RelayerError[] = [];
|
||||
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if ((r as RelayerError).hasError) {
|
||||
invalidRelayers.push(r as RelayerError);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}) as RelayerInfo[];
|
||||
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers,
|
||||
};
|
||||
}
|
||||
|
||||
pickWeightedRandomRelayer(relayers: RelayerInfo[]) {
|
||||
return pickWeightedRandomRelayer(relayers);
|
||||
}
|
||||
|
||||
async tornadoWithdraw(
|
||||
{ contract, proof, args }: TornadoWithdrawParams,
|
||||
callback?: (jobResp: RelayerTornadoWithdraw | RelayerTornadoJobs) => void,
|
||||
) {
|
||||
const { url } = this.selectedRelayer as RelayerInfo;
|
||||
|
||||
/**
|
||||
* Request new job
|
||||
*/
|
||||
|
||||
const withdrawResponse = (await fetchData(`${url}v1/tornadoWithdraw`, {
|
||||
...this.fetchDataOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
contract,
|
||||
proof,
|
||||
args,
|
||||
}),
|
||||
})) as RelayerTornadoWithdraw;
|
||||
|
||||
const { id, error } = withdrawResponse;
|
||||
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
const jobValidator = ajv.compile(jobRequestSchema);
|
||||
|
||||
if (!jobValidator(withdrawResponse)) {
|
||||
const errMsg = `${url}v1/tornadoWithdraw has an invalid job response`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
callback(withdrawResponse as unknown as RelayerTornadoWithdraw);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get job status
|
||||
*/
|
||||
|
||||
let relayerStatus: string | undefined;
|
||||
|
||||
const jobUrl = `${url}v1/jobs/${id}`;
|
||||
|
||||
console.log(`Job submitted: ${jobUrl}\n`);
|
||||
|
||||
while (!relayerStatus || !['FAILED', 'CONFIRMED'].includes(relayerStatus)) {
|
||||
const jobResponse = await fetchData(jobUrl, {
|
||||
...this.fetchDataOptions,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (jobResponse.error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
const jobValidator = ajv.compile(jobsSchema);
|
||||
|
||||
if (!jobValidator(jobResponse)) {
|
||||
const errMsg = `${jobUrl} has an invalid job response`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
const { status, txHash, confirmations, failedReason } = jobResponse as unknown as RelayerTornadoJobs;
|
||||
|
||||
if (relayerStatus !== status) {
|
||||
if (status === 'FAILED') {
|
||||
const errMsg = `Job ${status}: ${jobUrl} failed reason: ${failedReason}`;
|
||||
throw new Error(errMsg);
|
||||
} else if (status === 'SENT') {
|
||||
console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}\n`);
|
||||
} else if (status === 'MINED') {
|
||||
console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations}\n`);
|
||||
} else if (status === 'CONFIRMED') {
|
||||
console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations}\n`);
|
||||
}: {
|
||||
hostname?: string;
|
||||
// optional url if entered manually
|
||||
url?: string;
|
||||
// relayerAddress from registry contract to prevent cheating
|
||||
relayerAddress?: string;
|
||||
}): Promise<RelayerStatus> {
|
||||
if (!url && hostname) {
|
||||
url = `https://${!hostname.endsWith('/') ? hostname + '/' : hostname}`;
|
||||
} else if (url && !url.endsWith('/')) {
|
||||
url += '/';
|
||||
} else {
|
||||
console.log(`Job ${status}: ${jobUrl}\n`);
|
||||
url = '';
|
||||
}
|
||||
|
||||
relayerStatus = status;
|
||||
const rawStatus = (await fetchData(`${url}status`, {
|
||||
...this.fetchDataOptions,
|
||||
headers: {
|
||||
'Content-Type': 'application/json, application/x-www-form-urlencoded',
|
||||
},
|
||||
timeout: 30000,
|
||||
maxRetry: this.fetchDataOptions?.torPort ? 2 : 0,
|
||||
})) as object;
|
||||
|
||||
const statusValidator = ajv.compile(getStatusSchema(this.netId, this.config, this.tovarish));
|
||||
|
||||
if (!statusValidator(rawStatus)) {
|
||||
throw new Error('Invalid status schema');
|
||||
}
|
||||
|
||||
const status = {
|
||||
...rawStatus,
|
||||
url,
|
||||
} as RelayerStatus;
|
||||
|
||||
if (status.currentQueue > 5) {
|
||||
throw new Error('Withdrawal queue is overloaded');
|
||||
}
|
||||
|
||||
if (status.netId !== this.netId) {
|
||||
throw new Error('This relayer serves a different network');
|
||||
}
|
||||
|
||||
if (relayerAddress && this.netId === NetId.MAINNET && status.rewardAccount !== relayerAddress) {
|
||||
throw new Error('The Relayer reward address must match registered address');
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
async filterRelayer(relayer: CachedRelayerInfo): Promise<RelayerInfo | RelayerError | undefined> {
|
||||
const hostname = relayer.hostnames[this.netId];
|
||||
const { ensName, relayerAddress } = relayer;
|
||||
|
||||
if (!hostname) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const status = await this.askRelayerStatus({
|
||||
hostname,
|
||||
relayerAddress,
|
||||
});
|
||||
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
hostname,
|
||||
ensName,
|
||||
relayerAddress,
|
||||
rewardAccount: getAddress(status.rewardAccount),
|
||||
instances: getSupportedInstances(status.instances),
|
||||
stakeBalance: relayer.stakeBalance,
|
||||
gasPrice: status.gasPrices?.fast,
|
||||
ethPrices: status.ethPrices,
|
||||
currentQueue: status.currentQueue,
|
||||
tornadoServiceFee: status.tornadoServiceFee,
|
||||
} as RelayerInfo;
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (err: any) {
|
||||
return {
|
||||
hostname,
|
||||
relayerAddress,
|
||||
errorMessage: err.message,
|
||||
hasError: true,
|
||||
} as RelayerError;
|
||||
}
|
||||
}
|
||||
|
||||
async getValidRelayers(relayers: CachedRelayerInfo[]): Promise<{
|
||||
validRelayers: RelayerInfo[];
|
||||
invalidRelayers: RelayerError[];
|
||||
}> {
|
||||
const invalidRelayers: RelayerError[] = [];
|
||||
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter(
|
||||
(r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if ((r as RelayerError).hasError) {
|
||||
invalidRelayers.push(r as RelayerError);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
) as RelayerInfo[];
|
||||
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers,
|
||||
};
|
||||
}
|
||||
|
||||
pickWeightedRandomRelayer(relayers: RelayerInfo[]) {
|
||||
return pickWeightedRandomRelayer(relayers);
|
||||
}
|
||||
|
||||
async tornadoWithdraw(
|
||||
{ contract, proof, args }: TornadoWithdrawParams,
|
||||
callback?: (jobResp: RelayerTornadoWithdraw | RelayerTornadoJobs) => void,
|
||||
) {
|
||||
const { url } = this.selectedRelayer as RelayerInfo;
|
||||
|
||||
/**
|
||||
* Request new job
|
||||
*/
|
||||
|
||||
const withdrawResponse = (await fetchData(`${url}v1/tornadoWithdraw`, {
|
||||
...this.fetchDataOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
contract,
|
||||
proof,
|
||||
args,
|
||||
}),
|
||||
})) as RelayerTornadoWithdraw;
|
||||
|
||||
const { id, error } = withdrawResponse;
|
||||
|
||||
if (error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
const jobValidator = ajv.compile(jobRequestSchema);
|
||||
|
||||
if (!jobValidator(withdrawResponse)) {
|
||||
const errMsg = `${url}v1/tornadoWithdraw has an invalid job response`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
callback(jobResponse as unknown as RelayerTornadoJobs);
|
||||
callback(withdrawResponse as unknown as RelayerTornadoWithdraw);
|
||||
}
|
||||
}
|
||||
|
||||
await sleep(3000);
|
||||
/**
|
||||
* Get job status
|
||||
*/
|
||||
|
||||
let relayerStatus: string | undefined;
|
||||
|
||||
const jobUrl = `${url}v1/jobs/${id}`;
|
||||
|
||||
console.log(`Job submitted: ${jobUrl}\n`);
|
||||
|
||||
while (!relayerStatus || !['FAILED', 'CONFIRMED'].includes(relayerStatus)) {
|
||||
const jobResponse = await fetchData(jobUrl, {
|
||||
...this.fetchDataOptions,
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
});
|
||||
|
||||
if (jobResponse.error) {
|
||||
throw new Error(error);
|
||||
}
|
||||
|
||||
const jobValidator = ajv.compile(jobsSchema);
|
||||
|
||||
if (!jobValidator(jobResponse)) {
|
||||
const errMsg = `${jobUrl} has an invalid job response`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
const { status, txHash, confirmations, failedReason } = jobResponse as unknown as RelayerTornadoJobs;
|
||||
|
||||
if (relayerStatus !== status) {
|
||||
if (status === 'FAILED') {
|
||||
const errMsg = `Job ${status}: ${jobUrl} failed reason: ${failedReason}`;
|
||||
throw new Error(errMsg);
|
||||
} else if (status === 'SENT') {
|
||||
console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}\n`);
|
||||
} else if (status === 'MINED') {
|
||||
console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations}\n`);
|
||||
} else if (status === 'CONFIRMED') {
|
||||
console.log(`Job ${status}: ${jobUrl}, txhash: ${txHash}, confirmations: ${confirmations}\n`);
|
||||
} else {
|
||||
console.log(`Job ${status}: ${jobUrl}\n`);
|
||||
}
|
||||
|
||||
relayerStatus = status;
|
||||
|
||||
if (typeof callback === 'function') {
|
||||
callback(jobResponse as unknown as RelayerTornadoJobs);
|
||||
}
|
||||
}
|
||||
|
||||
await sleep(3000);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,28 +4,28 @@ import { BigNumberish, isAddress } from 'ethers';
|
||||
export const ajv = new Ajv({ allErrors: true });
|
||||
|
||||
ajv.addKeyword({
|
||||
keyword: 'BN',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
validate: (schema: any, data: BigNumberish) => {
|
||||
try {
|
||||
BigInt(data);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
errors: true,
|
||||
keyword: 'BN',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
validate: (schema: any, data: BigNumberish) => {
|
||||
try {
|
||||
BigInt(data);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
errors: true,
|
||||
});
|
||||
|
||||
ajv.addKeyword({
|
||||
keyword: 'isAddress',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
validate: (schema: any, data: string) => {
|
||||
try {
|
||||
return isAddress(data);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
errors: true,
|
||||
keyword: 'isAddress',
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
validate: (schema: any, data: string) => {
|
||||
try {
|
||||
return isAddress(data);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
errors: true,
|
||||
});
|
||||
|
||||
@@ -3,183 +3,192 @@ import { ajv } from './ajv';
|
||||
import { addressSchemaType, bnSchemaType, bytes32SchemaType } from './types';
|
||||
|
||||
const baseEventsSchemaProperty = {
|
||||
blockNumber: {
|
||||
type: 'number',
|
||||
},
|
||||
logIndex: {
|
||||
type: 'number',
|
||||
},
|
||||
transactionHash: bytes32SchemaType,
|
||||
blockNumber: {
|
||||
type: 'number',
|
||||
},
|
||||
logIndex: {
|
||||
type: 'number',
|
||||
},
|
||||
transactionHash: bytes32SchemaType,
|
||||
} as const;
|
||||
|
||||
const baseEventsSchemaRequired = Object.keys(baseEventsSchemaProperty) as string[];
|
||||
|
||||
export const governanceEventsSchema = {
|
||||
type: 'array',
|
||||
items: {
|
||||
anyOf: [
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
event: { type: 'string' },
|
||||
id: { type: 'number' },
|
||||
proposer: addressSchemaType,
|
||||
target: addressSchemaType,
|
||||
startTime: { type: 'number' },
|
||||
endTime: { type: 'number' },
|
||||
description: { type: 'string' },
|
||||
},
|
||||
required: [
|
||||
...baseEventsSchemaRequired,
|
||||
'event',
|
||||
'id',
|
||||
'proposer',
|
||||
'target',
|
||||
'startTime',
|
||||
'endTime',
|
||||
'description',
|
||||
type: 'array',
|
||||
items: {
|
||||
anyOf: [
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
event: { type: 'string' },
|
||||
id: { type: 'number' },
|
||||
proposer: addressSchemaType,
|
||||
target: addressSchemaType,
|
||||
startTime: { type: 'number' },
|
||||
endTime: { type: 'number' },
|
||||
description: { type: 'string' },
|
||||
},
|
||||
required: [
|
||||
...baseEventsSchemaRequired,
|
||||
'event',
|
||||
'id',
|
||||
'proposer',
|
||||
'target',
|
||||
'startTime',
|
||||
'endTime',
|
||||
'description',
|
||||
],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
event: { type: 'string' },
|
||||
proposalId: { type: 'number' },
|
||||
voter: addressSchemaType,
|
||||
support: { type: 'boolean' },
|
||||
votes: { type: 'string' },
|
||||
from: addressSchemaType,
|
||||
input: { type: 'string' },
|
||||
},
|
||||
required: [
|
||||
...baseEventsSchemaRequired,
|
||||
'event',
|
||||
'proposalId',
|
||||
'voter',
|
||||
'support',
|
||||
'votes',
|
||||
'from',
|
||||
'input',
|
||||
],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
event: { type: 'string' },
|
||||
account: addressSchemaType,
|
||||
delegateTo: addressSchemaType,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'account', 'delegateTo'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
event: { type: 'string' },
|
||||
account: addressSchemaType,
|
||||
delegateFrom: addressSchemaType,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'account', 'delegateFrom'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
event: { type: 'string' },
|
||||
proposalId: { type: 'number' },
|
||||
voter: addressSchemaType,
|
||||
support: { type: 'boolean' },
|
||||
votes: { type: 'string' },
|
||||
from: addressSchemaType,
|
||||
input: { type: 'string' },
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'event', 'proposalId', 'voter', 'support', 'votes', 'from', 'input'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
event: { type: 'string' },
|
||||
account: addressSchemaType,
|
||||
delegateTo: addressSchemaType,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'account', 'delegateTo'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
event: { type: 'string' },
|
||||
account: addressSchemaType,
|
||||
delegateFrom: addressSchemaType,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'account', 'delegateFrom'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const registeredEventsSchema = {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
ensName: { type: 'string' },
|
||||
relayerAddress: addressSchemaType,
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
ensName: { type: 'string' },
|
||||
relayerAddress: addressSchemaType,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'ensName', 'relayerAddress'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'ensName', 'relayerAddress'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const depositsEventsSchema = {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
commitment: bytes32SchemaType,
|
||||
leafIndex: { type: 'number' },
|
||||
timestamp: { type: 'number' },
|
||||
from: addressSchemaType,
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
commitment: bytes32SchemaType,
|
||||
leafIndex: { type: 'number' },
|
||||
timestamp: { type: 'number' },
|
||||
from: addressSchemaType,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'commitment', 'leafIndex', 'timestamp', 'from'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'commitment', 'leafIndex', 'timestamp', 'from'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const withdrawalsEventsSchema = {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
nullifierHash: bytes32SchemaType,
|
||||
to: addressSchemaType,
|
||||
fee: bnSchemaType,
|
||||
timestamp: { type: 'number' },
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
nullifierHash: bytes32SchemaType,
|
||||
to: addressSchemaType,
|
||||
fee: bnSchemaType,
|
||||
timestamp: { type: 'number' },
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'nullifierHash', 'to', 'fee', 'timestamp'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'nullifierHash', 'to', 'fee', 'timestamp'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const echoEventsSchema = {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
address: addressSchemaType,
|
||||
encryptedAccount: { type: 'string' },
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
address: addressSchemaType,
|
||||
encryptedAccount: { type: 'string' },
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'address', 'encryptedAccount'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'address', 'encryptedAccount'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export const encryptedNotesSchema = {
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
encryptedNote: { type: 'string' },
|
||||
type: 'array',
|
||||
items: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
...baseEventsSchemaProperty,
|
||||
encryptedNote: { type: 'string' },
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'encryptedNote'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
required: [...baseEventsSchemaRequired, 'encryptedNote'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
} as const;
|
||||
|
||||
export function getEventsSchemaValidator(type: string) {
|
||||
if (type === DEPOSIT) {
|
||||
return ajv.compile(depositsEventsSchema);
|
||||
}
|
||||
if (type === DEPOSIT) {
|
||||
return ajv.compile(depositsEventsSchema);
|
||||
}
|
||||
|
||||
if (type === WITHDRAWAL) {
|
||||
return ajv.compile(withdrawalsEventsSchema);
|
||||
}
|
||||
if (type === WITHDRAWAL) {
|
||||
return ajv.compile(withdrawalsEventsSchema);
|
||||
}
|
||||
|
||||
if (type === 'governance') {
|
||||
return ajv.compile(governanceEventsSchema);
|
||||
}
|
||||
if (type === 'governance') {
|
||||
return ajv.compile(governanceEventsSchema);
|
||||
}
|
||||
|
||||
if (type === 'registered') {
|
||||
return ajv.compile(registeredEventsSchema);
|
||||
}
|
||||
if (type === 'registered') {
|
||||
return ajv.compile(registeredEventsSchema);
|
||||
}
|
||||
|
||||
if (type === 'echo') {
|
||||
return ajv.compile(echoEventsSchema);
|
||||
}
|
||||
if (type === 'echo') {
|
||||
return ajv.compile(echoEventsSchema);
|
||||
}
|
||||
|
||||
if (type === 'encrypted_notes') {
|
||||
return ajv.compile(encryptedNotesSchema);
|
||||
}
|
||||
if (type === 'encrypted_notes') {
|
||||
return ajv.compile(encryptedNotesSchema);
|
||||
}
|
||||
|
||||
throw new Error('Unsupported event type for schema validation');
|
||||
throw new Error('Unsupported event type for schema validation');
|
||||
}
|
||||
|
||||
@@ -1,64 +1,64 @@
|
||||
export interface jobsSchema {
|
||||
type: string;
|
||||
properties: {
|
||||
error: {
|
||||
type: string;
|
||||
type: string;
|
||||
properties: {
|
||||
error: {
|
||||
type: string;
|
||||
};
|
||||
id: {
|
||||
type: string;
|
||||
};
|
||||
type: {
|
||||
type: string;
|
||||
};
|
||||
status: {
|
||||
type: string;
|
||||
};
|
||||
contract: {
|
||||
type: string;
|
||||
};
|
||||
proof: {
|
||||
type: string;
|
||||
};
|
||||
args: {
|
||||
type: string;
|
||||
items: {
|
||||
type: string;
|
||||
};
|
||||
};
|
||||
txHash: {
|
||||
type: string;
|
||||
};
|
||||
confirmations: {
|
||||
type: string;
|
||||
};
|
||||
failedReason: {
|
||||
type: string;
|
||||
};
|
||||
};
|
||||
id: {
|
||||
type: string;
|
||||
};
|
||||
type: {
|
||||
type: string;
|
||||
};
|
||||
status: {
|
||||
type: string;
|
||||
};
|
||||
contract: {
|
||||
type: string;
|
||||
};
|
||||
proof: {
|
||||
type: string;
|
||||
};
|
||||
args: {
|
||||
type: string;
|
||||
items: {
|
||||
type: string;
|
||||
};
|
||||
};
|
||||
txHash: {
|
||||
type: string;
|
||||
};
|
||||
confirmations: {
|
||||
type: string;
|
||||
};
|
||||
failedReason: {
|
||||
type: string;
|
||||
};
|
||||
};
|
||||
required: string[];
|
||||
required: string[];
|
||||
}
|
||||
|
||||
export const jobsSchema: jobsSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
error: { type: 'string' },
|
||||
id: { type: 'string' },
|
||||
type: { type: 'string' },
|
||||
status: { type: 'string' },
|
||||
contract: { type: 'string' },
|
||||
proof: { type: 'string' },
|
||||
args: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
type: 'object',
|
||||
properties: {
|
||||
error: { type: 'string' },
|
||||
id: { type: 'string' },
|
||||
type: { type: 'string' },
|
||||
status: { type: 'string' },
|
||||
contract: { type: 'string' },
|
||||
proof: { type: 'string' },
|
||||
args: {
|
||||
type: 'array',
|
||||
items: { type: 'string' },
|
||||
},
|
||||
txHash: { type: 'string' },
|
||||
confirmations: { type: 'number' },
|
||||
failedReason: { type: 'string' },
|
||||
},
|
||||
txHash: { type: 'string' },
|
||||
confirmations: { type: 'number' },
|
||||
failedReason: { type: 'string' },
|
||||
},
|
||||
required: ['id', 'status'],
|
||||
required: ['id', 'status'],
|
||||
};
|
||||
|
||||
export const jobRequestSchema: jobsSchema = {
|
||||
...jobsSchema,
|
||||
required: ['id'],
|
||||
...jobsSchema,
|
||||
required: ['id'],
|
||||
};
|
||||
|
||||
@@ -2,212 +2,220 @@ import { Config, NetId, NetIdType } from '../networkConfig';
|
||||
import { addressSchemaType, bnSchemaType } from '.';
|
||||
|
||||
export interface statusInstanceType {
|
||||
type: string;
|
||||
properties: {
|
||||
instanceAddress: {
|
||||
type: string;
|
||||
properties: {
|
||||
[key in string]: typeof addressSchemaType;
|
||||
};
|
||||
required: string[];
|
||||
type: string;
|
||||
properties: {
|
||||
instanceAddress: {
|
||||
type: string;
|
||||
properties: {
|
||||
[key in string]: typeof addressSchemaType;
|
||||
};
|
||||
required: string[];
|
||||
};
|
||||
tokenAddress?: typeof addressSchemaType;
|
||||
symbol?: { enum: string[] };
|
||||
decimals: { enum: number[] };
|
||||
};
|
||||
tokenAddress?: typeof addressSchemaType;
|
||||
symbol?: { enum: string[] };
|
||||
decimals: { enum: number[] };
|
||||
};
|
||||
required: string[];
|
||||
required: string[];
|
||||
}
|
||||
|
||||
export interface statusInstancesType {
|
||||
type: string;
|
||||
properties: {
|
||||
[key in string]: statusInstanceType;
|
||||
};
|
||||
required: string[];
|
||||
type: string;
|
||||
properties: {
|
||||
[key in string]: statusInstanceType;
|
||||
};
|
||||
required: string[];
|
||||
}
|
||||
|
||||
export interface statusEthPricesType {
|
||||
type: string;
|
||||
properties: {
|
||||
[key in string]: typeof bnSchemaType;
|
||||
};
|
||||
required?: string[];
|
||||
type: string;
|
||||
properties: {
|
||||
[key in string]: typeof bnSchemaType;
|
||||
};
|
||||
required?: string[];
|
||||
}
|
||||
|
||||
export interface statusSchema {
|
||||
type: string;
|
||||
properties: {
|
||||
rewardAccount: typeof addressSchemaType;
|
||||
instances?: statusInstancesType;
|
||||
gasPrices: {
|
||||
type: string;
|
||||
properties: {
|
||||
[key in string]: {
|
||||
type: string;
|
||||
type: string;
|
||||
properties: {
|
||||
rewardAccount: typeof addressSchemaType;
|
||||
instances?: statusInstancesType;
|
||||
gasPrices: {
|
||||
type: string;
|
||||
properties: {
|
||||
[key in string]: {
|
||||
type: string;
|
||||
};
|
||||
};
|
||||
required: string[];
|
||||
};
|
||||
netId: {
|
||||
type: string;
|
||||
};
|
||||
ethPrices?: statusEthPricesType;
|
||||
tornadoServiceFee?: {
|
||||
type: string;
|
||||
maximum: number;
|
||||
minimum: number;
|
||||
};
|
||||
latestBlock: {
|
||||
type: string;
|
||||
};
|
||||
latestBalance: {
|
||||
type: string;
|
||||
BN: boolean;
|
||||
};
|
||||
version: {
|
||||
type: string;
|
||||
};
|
||||
health: {
|
||||
type: string;
|
||||
properties: {
|
||||
status: { const: string };
|
||||
error: { type: string };
|
||||
};
|
||||
required: string[];
|
||||
};
|
||||
syncStatus: {
|
||||
type: string;
|
||||
properties: {
|
||||
events: { type: string };
|
||||
tokenPrice: { type: string };
|
||||
gasPrice: { type: string };
|
||||
};
|
||||
required: string[];
|
||||
};
|
||||
onSyncEvents: { type: string };
|
||||
currentQueue: {
|
||||
type: string;
|
||||
};
|
||||
};
|
||||
required: string[];
|
||||
};
|
||||
netId: {
|
||||
type: string;
|
||||
};
|
||||
ethPrices?: statusEthPricesType;
|
||||
tornadoServiceFee?: {
|
||||
type: string;
|
||||
maximum: number;
|
||||
minimum: number;
|
||||
};
|
||||
latestBlock: {
|
||||
type: string;
|
||||
};
|
||||
latestBalance: {
|
||||
type: string;
|
||||
BN: boolean;
|
||||
};
|
||||
version: {
|
||||
type: string;
|
||||
};
|
||||
health: {
|
||||
type: string;
|
||||
properties: {
|
||||
status: { const: string };
|
||||
error: { type: string };
|
||||
};
|
||||
required: string[];
|
||||
};
|
||||
syncStatus: {
|
||||
type: string;
|
||||
properties: {
|
||||
events: { type: string };
|
||||
tokenPrice: { type: string };
|
||||
gasPrice: { type: string };
|
||||
};
|
||||
required: string[];
|
||||
};
|
||||
onSyncEvents: { type: string };
|
||||
currentQueue: {
|
||||
type: string;
|
||||
};
|
||||
};
|
||||
required: string[];
|
||||
required: string[];
|
||||
}
|
||||
|
||||
const statusSchema: statusSchema = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
rewardAccount: addressSchemaType,
|
||||
gasPrices: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
fast: { type: 'number' },
|
||||
additionalProperties: { type: 'number' },
|
||||
},
|
||||
required: ['fast'],
|
||||
type: 'object',
|
||||
properties: {
|
||||
rewardAccount: addressSchemaType,
|
||||
gasPrices: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
fast: { type: 'number' },
|
||||
additionalProperties: { type: 'number' },
|
||||
},
|
||||
required: ['fast'],
|
||||
},
|
||||
netId: { type: 'integer' },
|
||||
tornadoServiceFee: { type: 'number', maximum: 20, minimum: 0 },
|
||||
latestBlock: { type: 'number' },
|
||||
latestBalance: bnSchemaType,
|
||||
version: { type: 'string' },
|
||||
health: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
status: { const: 'true' },
|
||||
error: { type: 'string' },
|
||||
},
|
||||
required: ['status'],
|
||||
},
|
||||
syncStatus: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
events: { type: 'boolean' },
|
||||
tokenPrice: { type: 'boolean' },
|
||||
gasPrice: { type: 'boolean' },
|
||||
},
|
||||
required: ['events', 'tokenPrice', 'gasPrice'],
|
||||
},
|
||||
onSyncEvents: { type: 'boolean' },
|
||||
currentQueue: { type: 'number' },
|
||||
},
|
||||
netId: { type: 'integer' },
|
||||
tornadoServiceFee: { type: 'number', maximum: 20, minimum: 0 },
|
||||
latestBlock: { type: 'number' },
|
||||
latestBalance: bnSchemaType,
|
||||
version: { type: 'string' },
|
||||
health: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
status: { const: 'true' },
|
||||
error: { type: 'string' },
|
||||
},
|
||||
required: ['status'],
|
||||
},
|
||||
syncStatus: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
events: { type: 'boolean' },
|
||||
tokenPrice: { type: 'boolean' },
|
||||
gasPrice: { type: 'boolean' },
|
||||
},
|
||||
required: ['events', 'tokenPrice', 'gasPrice'],
|
||||
},
|
||||
onSyncEvents: { type: 'boolean' },
|
||||
currentQueue: { type: 'number' },
|
||||
},
|
||||
required: ['rewardAccount', 'instances', 'netId', 'tornadoServiceFee', 'version', 'health', 'currentQueue'],
|
||||
required: ['rewardAccount', 'instances', 'netId', 'tornadoServiceFee', 'version', 'health', 'currentQueue'],
|
||||
};
|
||||
|
||||
export function getStatusSchema(netId: NetIdType, config: Config, tovarish: boolean) {
|
||||
const { tokens, optionalTokens, disabledTokens, nativeCurrency } = config;
|
||||
const { tokens, optionalTokens, disabledTokens, nativeCurrency } = config;
|
||||
|
||||
// deep copy schema
|
||||
const schema = JSON.parse(JSON.stringify(statusSchema)) as statusSchema;
|
||||
// deep copy schema
|
||||
const schema = JSON.parse(JSON.stringify(statusSchema)) as statusSchema;
|
||||
|
||||
const instances = Object.keys(tokens).reduce(
|
||||
(acc: statusInstancesType, token) => {
|
||||
const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token];
|
||||
const amounts = Object.keys(instanceAddress);
|
||||
const instances = Object.keys(tokens).reduce(
|
||||
(acc: statusInstancesType, token) => {
|
||||
const { instanceAddress, tokenAddress, symbol, decimals, optionalInstances = [] } = tokens[token];
|
||||
const amounts = Object.keys(instanceAddress);
|
||||
|
||||
const instanceProperties: statusInstanceType = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
instanceAddress: {
|
||||
type: 'object',
|
||||
properties: amounts.reduce((acc: { [key in string]: typeof addressSchemaType }, cur) => {
|
||||
acc[cur] = addressSchemaType;
|
||||
return acc;
|
||||
}, {}),
|
||||
required: amounts.filter((amount) => !optionalInstances.includes(amount)),
|
||||
},
|
||||
decimals: { enum: [decimals] },
|
||||
const instanceProperties: statusInstanceType = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
instanceAddress: {
|
||||
type: 'object',
|
||||
properties: amounts.reduce(
|
||||
(
|
||||
acc: {
|
||||
[key in string]: typeof addressSchemaType;
|
||||
},
|
||||
cur,
|
||||
) => {
|
||||
acc[cur] = addressSchemaType;
|
||||
return acc;
|
||||
},
|
||||
{},
|
||||
),
|
||||
required: amounts.filter((amount) => !optionalInstances.includes(amount)),
|
||||
},
|
||||
decimals: { enum: [decimals] },
|
||||
},
|
||||
required: ['instanceAddress', 'decimals'].concat(
|
||||
tokenAddress ? ['tokenAddress'] : [],
|
||||
symbol ? ['symbol'] : [],
|
||||
),
|
||||
};
|
||||
|
||||
if (tokenAddress) {
|
||||
instanceProperties.properties.tokenAddress = addressSchemaType;
|
||||
}
|
||||
if (symbol) {
|
||||
instanceProperties.properties.symbol = { enum: [symbol] };
|
||||
}
|
||||
|
||||
acc.properties[token] = instanceProperties;
|
||||
if (!optionalTokens?.includes(token) && !disabledTokens?.includes(token)) {
|
||||
acc.required.push(token);
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
required: ['instanceAddress', 'decimals'].concat(
|
||||
tokenAddress ? ['tokenAddress'] : [],
|
||||
symbol ? ['symbol'] : [],
|
||||
),
|
||||
};
|
||||
{
|
||||
type: 'object',
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
);
|
||||
|
||||
if (tokenAddress) {
|
||||
instanceProperties.properties.tokenAddress = addressSchemaType;
|
||||
}
|
||||
if (symbol) {
|
||||
instanceProperties.properties.symbol = { enum: [symbol] };
|
||||
}
|
||||
schema.properties.instances = instances;
|
||||
|
||||
acc.properties[token] = instanceProperties;
|
||||
if (!optionalTokens?.includes(token) && !disabledTokens?.includes(token)) {
|
||||
acc.required.push(token);
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{
|
||||
type: 'object',
|
||||
properties: {},
|
||||
required: [],
|
||||
},
|
||||
);
|
||||
const _tokens = Object.keys(tokens).filter(
|
||||
(t) => t !== nativeCurrency && !config.optionalTokens?.includes(t) && !config.disabledTokens?.includes(t),
|
||||
);
|
||||
|
||||
schema.properties.instances = instances;
|
||||
if (netId === NetId.MAINNET) {
|
||||
_tokens.push('torn');
|
||||
}
|
||||
|
||||
const _tokens = Object.keys(tokens).filter(
|
||||
(t) => t !== nativeCurrency && !config.optionalTokens?.includes(t) && !config.disabledTokens?.includes(t),
|
||||
);
|
||||
if (_tokens.length) {
|
||||
const ethPrices: statusEthPricesType = {
|
||||
type: 'object',
|
||||
properties: _tokens.reduce((acc: { [key in string]: typeof bnSchemaType }, token: string) => {
|
||||
acc[token] = bnSchemaType;
|
||||
return acc;
|
||||
}, {}),
|
||||
required: _tokens,
|
||||
};
|
||||
schema.properties.ethPrices = ethPrices;
|
||||
schema.required.push('ethPrices');
|
||||
}
|
||||
|
||||
if (netId === NetId.MAINNET) {
|
||||
_tokens.push('torn');
|
||||
}
|
||||
if (tovarish) {
|
||||
schema.required.push('gasPrices', 'latestBlock', 'latestBalance', 'syncStatus', 'onSyncEvents');
|
||||
}
|
||||
|
||||
if (_tokens.length) {
|
||||
const ethPrices: statusEthPricesType = {
|
||||
type: 'object',
|
||||
properties: _tokens.reduce((acc: { [key in string]: typeof bnSchemaType }, token: string) => {
|
||||
acc[token] = bnSchemaType;
|
||||
return acc;
|
||||
}, {}),
|
||||
required: _tokens,
|
||||
};
|
||||
schema.properties.ethPrices = ethPrices;
|
||||
schema.required.push('ethPrices');
|
||||
}
|
||||
|
||||
if (tovarish) {
|
||||
schema.required.push('gasPrices', 'latestBlock', 'latestBalance', 'syncStatus', 'onSyncEvents');
|
||||
}
|
||||
|
||||
return schema;
|
||||
return schema;
|
||||
}
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
export const addressSchemaType = {
|
||||
type: 'string',
|
||||
pattern: '^0x[a-fA-F0-9]{40}$',
|
||||
isAddress: true,
|
||||
type: 'string',
|
||||
pattern: '^0x[a-fA-F0-9]{40}$',
|
||||
isAddress: true,
|
||||
} as const;
|
||||
export const bnSchemaType = { type: 'string', BN: true } as const;
|
||||
export const proofSchemaType = { type: 'string', pattern: '^0x[a-fA-F0-9]{512}$' } as const;
|
||||
export const bytes32SchemaType = { type: 'string', pattern: '^0x[a-fA-F0-9]{64}$' } as const;
|
||||
export const proofSchemaType = {
|
||||
type: 'string',
|
||||
pattern: '^0x[a-fA-F0-9]{512}$',
|
||||
} as const;
|
||||
export const bytes32SchemaType = {
|
||||
type: 'string',
|
||||
pattern: '^0x[a-fA-F0-9]{64}$',
|
||||
} as const;
|
||||
export const bytes32BNSchemaType = { ...bytes32SchemaType, BN: true } as const;
|
||||
|
||||
146
src/tokens.ts
146
src/tokens.ts
@@ -4,87 +4,87 @@ import { chunk } from './utils';
|
||||
import { Call3, multicall } from './multicall';
|
||||
|
||||
export interface tokenBalances {
|
||||
address: string;
|
||||
name: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
balance: bigint;
|
||||
address: string;
|
||||
name: string;
|
||||
symbol: string;
|
||||
decimals: number;
|
||||
balance: bigint;
|
||||
}
|
||||
|
||||
export async function getTokenBalances({
|
||||
provider,
|
||||
Multicall,
|
||||
currencyName,
|
||||
userAddress,
|
||||
tokenAddresses = [],
|
||||
provider,
|
||||
Multicall,
|
||||
currencyName,
|
||||
userAddress,
|
||||
tokenAddresses = [],
|
||||
}: {
|
||||
provider: Provider;
|
||||
Multicall: Multicall;
|
||||
currencyName: string;
|
||||
userAddress: string;
|
||||
tokenAddresses: string[];
|
||||
provider: Provider;
|
||||
Multicall: Multicall;
|
||||
currencyName: string;
|
||||
userAddress: string;
|
||||
tokenAddresses: string[];
|
||||
}): Promise<tokenBalances[]> {
|
||||
const tokenCalls = tokenAddresses
|
||||
.map((tokenAddress) => {
|
||||
const Token = ERC20__factory.connect(tokenAddress, provider);
|
||||
const tokenCalls = tokenAddresses
|
||||
.map((tokenAddress) => {
|
||||
const Token = ERC20__factory.connect(tokenAddress, provider);
|
||||
|
||||
return [
|
||||
return [
|
||||
{
|
||||
contract: Token,
|
||||
name: 'balanceOf',
|
||||
params: [userAddress],
|
||||
},
|
||||
{
|
||||
contract: Token,
|
||||
name: 'name',
|
||||
},
|
||||
{
|
||||
contract: Token,
|
||||
name: 'symbol',
|
||||
},
|
||||
{
|
||||
contract: Token,
|
||||
name: 'decimals',
|
||||
},
|
||||
];
|
||||
})
|
||||
.flat() as Call3[];
|
||||
|
||||
const multicallResults = await multicall(Multicall, [
|
||||
{
|
||||
contract: Token,
|
||||
name: 'balanceOf',
|
||||
params: [userAddress],
|
||||
contract: Multicall,
|
||||
name: 'getEthBalance',
|
||||
params: [userAddress],
|
||||
},
|
||||
...(tokenCalls.length ? tokenCalls : []),
|
||||
]);
|
||||
|
||||
const ethResults = multicallResults[0];
|
||||
const tokenResults = multicallResults.slice(1).length
|
||||
? chunk(multicallResults.slice(1), tokenCalls.length / tokenAddresses.length)
|
||||
: [];
|
||||
|
||||
const tokenBalances = tokenResults.map((tokenResult, index) => {
|
||||
const [tokenBalance, tokenName, tokenSymbol, tokenDecimals] = tokenResult;
|
||||
const tokenAddress = tokenAddresses[index];
|
||||
|
||||
return {
|
||||
address: tokenAddress,
|
||||
name: tokenName,
|
||||
symbol: tokenSymbol,
|
||||
decimals: Number(tokenDecimals),
|
||||
balance: tokenBalance,
|
||||
};
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
contract: Token,
|
||||
name: 'name',
|
||||
address: ZeroAddress,
|
||||
name: currencyName,
|
||||
symbol: currencyName,
|
||||
decimals: 18,
|
||||
balance: ethResults,
|
||||
},
|
||||
{
|
||||
contract: Token,
|
||||
name: 'symbol',
|
||||
},
|
||||
{
|
||||
contract: Token,
|
||||
name: 'decimals',
|
||||
},
|
||||
];
|
||||
})
|
||||
.flat() as Call3[];
|
||||
|
||||
const multicallResults = await multicall(Multicall, [
|
||||
{
|
||||
contract: Multicall,
|
||||
name: 'getEthBalance',
|
||||
params: [userAddress],
|
||||
},
|
||||
...(tokenCalls.length ? tokenCalls : []),
|
||||
]);
|
||||
|
||||
const ethResults = multicallResults[0];
|
||||
const tokenResults = multicallResults.slice(1).length
|
||||
? chunk(multicallResults.slice(1), tokenCalls.length / tokenAddresses.length)
|
||||
: [];
|
||||
|
||||
const tokenBalances = tokenResults.map((tokenResult, index) => {
|
||||
const [tokenBalance, tokenName, tokenSymbol, tokenDecimals] = tokenResult;
|
||||
const tokenAddress = tokenAddresses[index];
|
||||
|
||||
return {
|
||||
address: tokenAddress,
|
||||
name: tokenName,
|
||||
symbol: tokenSymbol,
|
||||
decimals: Number(tokenDecimals),
|
||||
balance: tokenBalance,
|
||||
};
|
||||
});
|
||||
|
||||
return [
|
||||
{
|
||||
address: ZeroAddress,
|
||||
name: currencyName,
|
||||
symbol: currencyName,
|
||||
decimals: 18,
|
||||
balance: ethResults,
|
||||
},
|
||||
...tokenBalances,
|
||||
];
|
||||
...tokenBalances,
|
||||
];
|
||||
}
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { getAddress } from 'ethers';
|
||||
|
||||
import {
|
||||
RelayerClient,
|
||||
RelayerClientConstructor,
|
||||
RelayerError,
|
||||
RelayerInfo,
|
||||
RelayerStatus,
|
||||
getSupportedInstances,
|
||||
RelayerClient,
|
||||
RelayerClientConstructor,
|
||||
RelayerError,
|
||||
RelayerInfo,
|
||||
RelayerStatus,
|
||||
getSupportedInstances,
|
||||
} from './relayerClient';
|
||||
import { fetchData } from './providers';
|
||||
import { CachedRelayerInfo, MinimalEvents } from './events';
|
||||
@@ -17,262 +17,203 @@ import { enabledChains, getConfig, NetId, NetIdType } from './networkConfig';
|
||||
export const MAX_TOVARISH_EVENTS = 5000;
|
||||
|
||||
export interface EventsStatus {
|
||||
events: number;
|
||||
lastBlock: number;
|
||||
events: number;
|
||||
lastBlock: number;
|
||||
}
|
||||
|
||||
export interface InstanceEventsStatus {
|
||||
[index: string]: {
|
||||
deposits: EventsStatus;
|
||||
withdrawals: EventsStatus;
|
||||
};
|
||||
[index: string]: {
|
||||
deposits: EventsStatus;
|
||||
withdrawals: EventsStatus;
|
||||
};
|
||||
}
|
||||
|
||||
export interface CurrencyEventsStatus {
|
||||
[index: string]: InstanceEventsStatus;
|
||||
[index: string]: InstanceEventsStatus;
|
||||
}
|
||||
|
||||
export interface TovarishEventsStatus {
|
||||
governance?: EventsStatus;
|
||||
registered?: {
|
||||
lastBlock: number;
|
||||
timestamp: number;
|
||||
relayers: number;
|
||||
};
|
||||
echo: EventsStatus;
|
||||
encrypted_notes: EventsStatus;
|
||||
instances: CurrencyEventsStatus;
|
||||
governance?: EventsStatus;
|
||||
registered?: {
|
||||
lastBlock: number;
|
||||
timestamp: number;
|
||||
relayers: number;
|
||||
};
|
||||
echo: EventsStatus;
|
||||
encrypted_notes: EventsStatus;
|
||||
instances: CurrencyEventsStatus;
|
||||
}
|
||||
|
||||
export interface TovarishSyncStatus {
|
||||
events: boolean;
|
||||
tokenPrice: boolean;
|
||||
gasPrice: boolean;
|
||||
events: boolean;
|
||||
tokenPrice: boolean;
|
||||
gasPrice: boolean;
|
||||
}
|
||||
|
||||
// Expected response from /status endpoint
|
||||
export interface TovarishStatus extends RelayerStatus {
|
||||
latestBalance: string;
|
||||
events: TovarishEventsStatus;
|
||||
syncStatus: TovarishSyncStatus;
|
||||
onSyncEvents: boolean;
|
||||
latestBalance: string;
|
||||
events: TovarishEventsStatus;
|
||||
syncStatus: TovarishSyncStatus;
|
||||
onSyncEvents: boolean;
|
||||
}
|
||||
|
||||
// Formatted TovarishStatus for Frontend usage
|
||||
export interface TovarishInfo extends RelayerInfo {
|
||||
latestBlock: number;
|
||||
latestBalance: string;
|
||||
version: string;
|
||||
events: TovarishEventsStatus;
|
||||
syncStatus: TovarishSyncStatus;
|
||||
latestBlock: number;
|
||||
latestBalance: string;
|
||||
version: string;
|
||||
events: TovarishEventsStatus;
|
||||
syncStatus: TovarishSyncStatus;
|
||||
}
|
||||
|
||||
// Query input for TovarishEvents
|
||||
export interface TovarishEventsQuery {
|
||||
type: string;
|
||||
currency?: string;
|
||||
amount?: string;
|
||||
fromBlock: number;
|
||||
recent?: boolean;
|
||||
type: string;
|
||||
currency?: string;
|
||||
amount?: string;
|
||||
fromBlock: number;
|
||||
recent?: boolean;
|
||||
}
|
||||
|
||||
export interface BaseTovarishEvents<T> {
|
||||
events: T[];
|
||||
lastSyncBlock: number;
|
||||
events: T[];
|
||||
lastSyncBlock: number;
|
||||
}
|
||||
|
||||
export class TovarishClient extends RelayerClient {
|
||||
declare selectedRelayer?: TovarishInfo;
|
||||
declare selectedRelayer?: TovarishInfo;
|
||||
|
||||
constructor(clientConstructor: RelayerClientConstructor) {
|
||||
super(clientConstructor);
|
||||
this.tovarish = true;
|
||||
}
|
||||
|
||||
async askRelayerStatus({
|
||||
hostname,
|
||||
url,
|
||||
relayerAddress,
|
||||
}: {
|
||||
hostname?: string;
|
||||
// optional url if entered manually
|
||||
url?: string;
|
||||
// relayerAddress from registry contract to prevent cheating
|
||||
relayerAddress?: string;
|
||||
}): Promise<TovarishStatus> {
|
||||
const status = (await super.askRelayerStatus({ hostname, url, relayerAddress })) as TovarishStatus;
|
||||
|
||||
if (!status.version.includes('tovarish')) {
|
||||
throw new Error('Not a tovarish relayer!');
|
||||
constructor(clientConstructor: RelayerClientConstructor) {
|
||||
super(clientConstructor);
|
||||
this.tovarish = true;
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask status for all enabled chains for tovarish relayer
|
||||
*/
|
||||
async askAllStatus({
|
||||
hostname,
|
||||
url,
|
||||
relayerAddress,
|
||||
}: {
|
||||
hostname?: string;
|
||||
// optional url if entered manually
|
||||
url?: string;
|
||||
// relayerAddress from registry contract to prevent cheating
|
||||
relayerAddress?: string;
|
||||
}): Promise<TovarishStatus[]> {
|
||||
if (!url && hostname) {
|
||||
url = `https://${!hostname.endsWith('/') ? hostname + '/' : hostname}`;
|
||||
} else if (url && !url.endsWith('/')) {
|
||||
url += '/';
|
||||
} else {
|
||||
url = '';
|
||||
}
|
||||
|
||||
const statusArray = (await fetchData(`${url}status`, {
|
||||
...this.fetchDataOptions,
|
||||
headers: {
|
||||
'Content-Type': 'application/json, application/x-www-form-urlencoded',
|
||||
},
|
||||
timeout: 30000,
|
||||
maxRetry: this.fetchDataOptions?.torPort ? 2 : 0,
|
||||
})) as object;
|
||||
|
||||
if (!Array.isArray(statusArray)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const tovarishStatus: TovarishStatus[] = [];
|
||||
|
||||
for (const rawStatus of statusArray) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const netId = (rawStatus as any).netId as NetIdType;
|
||||
const config = getConfig(netId);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const statusValidator = ajv.compile(getStatusSchema((rawStatus as any).netId, config, this.tovarish));
|
||||
|
||||
if (!statusValidator) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const status = {
|
||||
...rawStatus,
|
||||
url: `${url}${netId}/`,
|
||||
} as TovarishStatus;
|
||||
|
||||
if (status.currentQueue > 5) {
|
||||
throw new Error('Withdrawal queue is overloaded');
|
||||
}
|
||||
|
||||
if (!enabledChains.includes(status.netId)) {
|
||||
throw new Error('This relayer serves a different network');
|
||||
}
|
||||
|
||||
if (relayerAddress && status.netId === NetId.MAINNET && status.rewardAccount !== relayerAddress) {
|
||||
throw new Error('The Relayer reward address must match registered address');
|
||||
}
|
||||
|
||||
if (!status.version.includes('tovarish')) {
|
||||
throw new Error('Not a tovarish relayer!');
|
||||
}
|
||||
|
||||
tovarishStatus.push(status);
|
||||
}
|
||||
|
||||
return tovarishStatus;
|
||||
}
|
||||
|
||||
async filterRelayer(relayer: CachedRelayerInfo): Promise<TovarishInfo | RelayerError | undefined> {
|
||||
const { ensName, relayerAddress, tovarishHost, tovarishNetworks } = relayer;
|
||||
|
||||
if (!tovarishHost || !tovarishNetworks?.includes(this.netId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hostname = `${tovarishHost}/${this.netId}`;
|
||||
|
||||
try {
|
||||
const status = await this.askRelayerStatus({ hostname, relayerAddress });
|
||||
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
async askRelayerStatus({
|
||||
hostname,
|
||||
ensName,
|
||||
url,
|
||||
relayerAddress,
|
||||
rewardAccount: getAddress(status.rewardAccount),
|
||||
instances: getSupportedInstances(status.instances),
|
||||
stakeBalance: relayer.stakeBalance,
|
||||
gasPrice: status.gasPrices?.fast,
|
||||
ethPrices: status.ethPrices,
|
||||
currentQueue: status.currentQueue,
|
||||
tornadoServiceFee: status.tornadoServiceFee,
|
||||
// Additional fields for tovarish relayer
|
||||
latestBlock: Number(status.latestBlock),
|
||||
latestBalance: status.latestBalance,
|
||||
version: status.version,
|
||||
events: status.events,
|
||||
syncStatus: status.syncStatus,
|
||||
} as TovarishInfo;
|
||||
}: {
|
||||
hostname?: string;
|
||||
// optional url if entered manually
|
||||
url?: string;
|
||||
// relayerAddress from registry contract to prevent cheating
|
||||
relayerAddress?: string;
|
||||
}): Promise<TovarishStatus> {
|
||||
const status = (await super.askRelayerStatus({
|
||||
hostname,
|
||||
url,
|
||||
relayerAddress,
|
||||
})) as TovarishStatus;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (err: any) {
|
||||
return {
|
||||
hostname,
|
||||
relayerAddress,
|
||||
errorMessage: err.message,
|
||||
hasError: true,
|
||||
} as RelayerError;
|
||||
if (!status.version.includes('tovarish')) {
|
||||
throw new Error('Not a tovarish relayer!');
|
||||
}
|
||||
|
||||
return status;
|
||||
}
|
||||
}
|
||||
|
||||
async getValidRelayers(relayers: CachedRelayerInfo[]): Promise<{
|
||||
validRelayers: TovarishInfo[];
|
||||
invalidRelayers: RelayerError[];
|
||||
}> {
|
||||
const invalidRelayers: RelayerError[] = [];
|
||||
/**
|
||||
* Ask status for all enabled chains for tovarish relayer
|
||||
*/
|
||||
async askAllStatus({
|
||||
hostname,
|
||||
url,
|
||||
relayerAddress,
|
||||
}: {
|
||||
hostname?: string;
|
||||
// optional url if entered manually
|
||||
url?: string;
|
||||
// relayerAddress from registry contract to prevent cheating
|
||||
relayerAddress?: string;
|
||||
}): Promise<TovarishStatus[]> {
|
||||
if (!url && hostname) {
|
||||
url = `https://${!hostname.endsWith('/') ? hostname + '/' : hostname}`;
|
||||
} else if (url && !url.endsWith('/')) {
|
||||
url += '/';
|
||||
} else {
|
||||
url = '';
|
||||
}
|
||||
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if ((r as RelayerError).hasError) {
|
||||
invalidRelayers.push(r as RelayerError);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}) as TovarishInfo[];
|
||||
const statusArray = (await fetchData(`${url}status`, {
|
||||
...this.fetchDataOptions,
|
||||
headers: {
|
||||
'Content-Type': 'application/json, application/x-www-form-urlencoded',
|
||||
},
|
||||
timeout: 30000,
|
||||
maxRetry: this.fetchDataOptions?.torPort ? 2 : 0,
|
||||
})) as object;
|
||||
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers,
|
||||
};
|
||||
}
|
||||
if (!Array.isArray(statusArray)) {
|
||||
return [];
|
||||
}
|
||||
|
||||
async getTovarishRelayers(relayers: CachedRelayerInfo[]): Promise<{
|
||||
validRelayers: TovarishInfo[];
|
||||
invalidRelayers: RelayerError[];
|
||||
}> {
|
||||
const validRelayers: TovarishInfo[] = [];
|
||||
const invalidRelayers: RelayerError[] = [];
|
||||
const tovarishStatus: TovarishStatus[] = [];
|
||||
|
||||
await Promise.all(
|
||||
relayers
|
||||
.filter((r) => r.tovarishHost && r.tovarishNetworks?.length)
|
||||
.map(async (relayer) => {
|
||||
const { ensName, relayerAddress, tovarishHost } = relayer;
|
||||
for (const rawStatus of statusArray) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const netId = (rawStatus as any).netId as NetIdType;
|
||||
const config = getConfig(netId);
|
||||
|
||||
try {
|
||||
const statusArray = await this.askAllStatus({ hostname: tovarishHost as string, relayerAddress });
|
||||
const statusValidator = ajv.compile(
|
||||
getStatusSchema(
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(rawStatus as any).netId,
|
||||
config,
|
||||
this.tovarish,
|
||||
),
|
||||
);
|
||||
|
||||
for (const status of statusArray) {
|
||||
validRelayers.push({
|
||||
if (!statusValidator) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const status = {
|
||||
...rawStatus,
|
||||
url: `${url}${netId}/`,
|
||||
} as TovarishStatus;
|
||||
|
||||
if (status.currentQueue > 5) {
|
||||
throw new Error('Withdrawal queue is overloaded');
|
||||
}
|
||||
|
||||
if (!enabledChains.includes(status.netId)) {
|
||||
throw new Error('This relayer serves a different network');
|
||||
}
|
||||
|
||||
if (relayerAddress && status.netId === NetId.MAINNET && status.rewardAccount !== relayerAddress) {
|
||||
throw new Error('The Relayer reward address must match registered address');
|
||||
}
|
||||
|
||||
if (!status.version.includes('tovarish')) {
|
||||
throw new Error('Not a tovarish relayer!');
|
||||
}
|
||||
|
||||
tovarishStatus.push(status);
|
||||
}
|
||||
|
||||
return tovarishStatus;
|
||||
}
|
||||
|
||||
async filterRelayer(relayer: CachedRelayerInfo): Promise<TovarishInfo | RelayerError | undefined> {
|
||||
const { ensName, relayerAddress, tovarishHost, tovarishNetworks } = relayer;
|
||||
|
||||
if (!tovarishHost || !tovarishNetworks?.includes(this.netId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const hostname = `${tovarishHost}/${this.netId}`;
|
||||
|
||||
try {
|
||||
const status = await this.askRelayerStatus({
|
||||
hostname,
|
||||
relayerAddress,
|
||||
});
|
||||
|
||||
return {
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
hostname: tovarishHost as string,
|
||||
hostname,
|
||||
ensName,
|
||||
relayerAddress,
|
||||
rewardAccount: getAddress(status.rewardAccount),
|
||||
@@ -288,108 +229,185 @@ export class TovarishClient extends RelayerClient {
|
||||
version: status.version,
|
||||
events: status.events,
|
||||
syncStatus: status.syncStatus,
|
||||
});
|
||||
}
|
||||
} as TovarishInfo;
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (err: any) {
|
||||
invalidRelayers.push({
|
||||
hostname: tovarishHost as string,
|
||||
relayerAddress,
|
||||
errorMessage: err.message,
|
||||
hasError: true,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers,
|
||||
};
|
||||
}
|
||||
|
||||
async getEvents<T extends MinimalEvents>({
|
||||
type,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
recent,
|
||||
}: TovarishEventsQuery): Promise<BaseTovarishEvents<T>> {
|
||||
const url = `${this.selectedRelayer?.url}events`;
|
||||
|
||||
const schemaValidator = getEventsSchemaValidator(type);
|
||||
|
||||
try {
|
||||
const events = [];
|
||||
let lastSyncBlock = fromBlock;
|
||||
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
// eslint-disable-next-line prefer-const
|
||||
let { events: fetchedEvents, lastSyncBlock: currentBlock } = (await fetchData(url, {
|
||||
...this.fetchDataOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
type,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
recent,
|
||||
}),
|
||||
})) as BaseTovarishEvents<T>;
|
||||
|
||||
if (!schemaValidator(fetchedEvents)) {
|
||||
const errMsg = `Schema validation failed for ${type} events`;
|
||||
throw new Error(errMsg);
|
||||
} catch (err: any) {
|
||||
return {
|
||||
hostname,
|
||||
relayerAddress,
|
||||
errorMessage: err.message,
|
||||
hasError: true,
|
||||
} as RelayerError;
|
||||
}
|
||||
}
|
||||
|
||||
async getValidRelayers(relayers: CachedRelayerInfo[]): Promise<{
|
||||
validRelayers: TovarishInfo[];
|
||||
invalidRelayers: RelayerError[];
|
||||
}> {
|
||||
const invalidRelayers: RelayerError[] = [];
|
||||
|
||||
const validRelayers = (await Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter(
|
||||
(r) => {
|
||||
if (!r) {
|
||||
return false;
|
||||
}
|
||||
if ((r as RelayerError).hasError) {
|
||||
invalidRelayers.push(r as RelayerError);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
) as TovarishInfo[];
|
||||
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers,
|
||||
};
|
||||
}
|
||||
|
||||
async getTovarishRelayers(relayers: CachedRelayerInfo[]): Promise<{
|
||||
validRelayers: TovarishInfo[];
|
||||
invalidRelayers: RelayerError[];
|
||||
}> {
|
||||
const validRelayers: TovarishInfo[] = [];
|
||||
const invalidRelayers: RelayerError[] = [];
|
||||
|
||||
await Promise.all(
|
||||
relayers
|
||||
.filter((r) => r.tovarishHost && r.tovarishNetworks?.length)
|
||||
.map(async (relayer) => {
|
||||
const { ensName, relayerAddress, tovarishHost } = relayer;
|
||||
|
||||
try {
|
||||
const statusArray = await this.askAllStatus({
|
||||
hostname: tovarishHost as string,
|
||||
relayerAddress,
|
||||
});
|
||||
|
||||
for (const status of statusArray) {
|
||||
validRelayers.push({
|
||||
netId: status.netId,
|
||||
url: status.url,
|
||||
hostname: tovarishHost as string,
|
||||
ensName,
|
||||
relayerAddress,
|
||||
rewardAccount: getAddress(status.rewardAccount),
|
||||
instances: getSupportedInstances(status.instances),
|
||||
stakeBalance: relayer.stakeBalance,
|
||||
gasPrice: status.gasPrices?.fast,
|
||||
ethPrices: status.ethPrices,
|
||||
currentQueue: status.currentQueue,
|
||||
tornadoServiceFee: status.tornadoServiceFee,
|
||||
// Additional fields for tovarish relayer
|
||||
latestBlock: Number(status.latestBlock),
|
||||
latestBalance: status.latestBalance,
|
||||
version: status.version,
|
||||
events: status.events,
|
||||
syncStatus: status.syncStatus,
|
||||
});
|
||||
}
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
} catch (err: any) {
|
||||
invalidRelayers.push({
|
||||
hostname: tovarishHost as string,
|
||||
relayerAddress,
|
||||
errorMessage: err.message,
|
||||
hasError: true,
|
||||
});
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
validRelayers,
|
||||
invalidRelayers,
|
||||
};
|
||||
}
|
||||
|
||||
async getEvents<T extends MinimalEvents>({
|
||||
type,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
recent,
|
||||
}: TovarishEventsQuery): Promise<BaseTovarishEvents<T>> {
|
||||
const url = `${this.selectedRelayer?.url}events`;
|
||||
|
||||
const schemaValidator = getEventsSchemaValidator(type);
|
||||
|
||||
try {
|
||||
const events = [];
|
||||
let lastSyncBlock = fromBlock;
|
||||
|
||||
// eslint-disable-next-line no-constant-condition
|
||||
while (true) {
|
||||
// eslint-disable-next-line prefer-const
|
||||
let { events: fetchedEvents, lastSyncBlock: currentBlock } = (await fetchData(url, {
|
||||
...this.fetchDataOptions,
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
type,
|
||||
currency,
|
||||
amount,
|
||||
fromBlock,
|
||||
recent,
|
||||
}),
|
||||
})) as BaseTovarishEvents<T>;
|
||||
|
||||
if (!schemaValidator(fetchedEvents)) {
|
||||
const errMsg = `Schema validation failed for ${type} events`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
if (recent) {
|
||||
return {
|
||||
events: fetchedEvents,
|
||||
lastSyncBlock: currentBlock,
|
||||
};
|
||||
}
|
||||
|
||||
lastSyncBlock = currentBlock;
|
||||
|
||||
if (!Array.isArray(fetchedEvents) || !fetchedEvents.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
fetchedEvents = fetchedEvents.sort((a, b) => {
|
||||
if (a.blockNumber === b.blockNumber) {
|
||||
return a.logIndex - b.logIndex;
|
||||
}
|
||||
return a.blockNumber - b.blockNumber;
|
||||
});
|
||||
|
||||
const [lastEvent] = fetchedEvents.slice(-1);
|
||||
|
||||
if (fetchedEvents.length < MAX_TOVARISH_EVENTS - 100) {
|
||||
events.push(...fetchedEvents);
|
||||
break;
|
||||
}
|
||||
|
||||
fetchedEvents = fetchedEvents.filter((e) => e.blockNumber !== lastEvent.blockNumber);
|
||||
fromBlock = Number(lastEvent.blockNumber);
|
||||
|
||||
events.push(...fetchedEvents);
|
||||
}
|
||||
|
||||
return {
|
||||
events,
|
||||
lastSyncBlock,
|
||||
};
|
||||
} catch (err) {
|
||||
console.log('Error from TovarishClient events endpoint');
|
||||
console.log(err);
|
||||
return {
|
||||
events: [],
|
||||
lastSyncBlock: fromBlock,
|
||||
};
|
||||
}
|
||||
|
||||
if (recent) {
|
||||
return {
|
||||
events: fetchedEvents,
|
||||
lastSyncBlock: currentBlock,
|
||||
};
|
||||
}
|
||||
|
||||
lastSyncBlock = currentBlock;
|
||||
|
||||
if (!Array.isArray(fetchedEvents) || !fetchedEvents.length) {
|
||||
break;
|
||||
}
|
||||
|
||||
fetchedEvents = fetchedEvents.sort((a, b) => {
|
||||
if (a.blockNumber === b.blockNumber) {
|
||||
return a.logIndex - b.logIndex;
|
||||
}
|
||||
return a.blockNumber - b.blockNumber;
|
||||
});
|
||||
|
||||
const [lastEvent] = fetchedEvents.slice(-1);
|
||||
|
||||
if (fetchedEvents.length < MAX_TOVARISH_EVENTS - 100) {
|
||||
events.push(...fetchedEvents);
|
||||
break;
|
||||
}
|
||||
|
||||
fetchedEvents = fetchedEvents.filter((e) => e.blockNumber !== lastEvent.blockNumber);
|
||||
fromBlock = Number(lastEvent.blockNumber);
|
||||
|
||||
events.push(...fetchedEvents);
|
||||
}
|
||||
|
||||
return {
|
||||
events,
|
||||
lastSyncBlock,
|
||||
};
|
||||
} catch (err) {
|
||||
console.log('Error from TovarishClient events endpoint');
|
||||
console.log(err);
|
||||
return {
|
||||
events: [],
|
||||
lastSyncBlock: fromBlock,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
170
src/utils.ts
170
src/utils.ts
@@ -4,172 +4,172 @@ import type { BigNumberish } from 'ethers';
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
(BigInt.prototype as any).toJSON = function () {
|
||||
return this.toString();
|
||||
return this.toString();
|
||||
};
|
||||
|
||||
type bnInput = number | string | number[] | Uint8Array | Buffer | BN;
|
||||
|
||||
export const isNode =
|
||||
!(
|
||||
process as typeof process & {
|
||||
browser?: boolean;
|
||||
}
|
||||
).browser && typeof globalThis.window === 'undefined';
|
||||
!(
|
||||
process as typeof process & {
|
||||
browser?: boolean;
|
||||
}
|
||||
).browser && typeof globalThis.window === 'undefined';
|
||||
|
||||
export const crypto = isNode ? webcrypto : (globalThis.crypto as typeof webcrypto);
|
||||
|
||||
export const chunk = <T>(arr: T[], size: number): T[][] =>
|
||||
[...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i));
|
||||
[...Array(Math.ceil(arr.length / size))].map((_, i) => arr.slice(size * i, size + size * i));
|
||||
|
||||
export function sleep(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export function validateUrl(url: string, protocols?: string[]) {
|
||||
try {
|
||||
const parsedUrl = new URL(url);
|
||||
if (protocols && protocols.length) {
|
||||
return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol);
|
||||
try {
|
||||
const parsedUrl = new URL(url);
|
||||
if (protocols && protocols.length) {
|
||||
return protocols.map((p) => p.toLowerCase()).includes(parsedUrl.protocol);
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function concatBytes(...arrays: Uint8Array[]): Uint8Array {
|
||||
const totalSize = arrays.reduce((acc, e) => acc + e.length, 0);
|
||||
const merged = new Uint8Array(totalSize);
|
||||
const totalSize = arrays.reduce((acc, e) => acc + e.length, 0);
|
||||
const merged = new Uint8Array(totalSize);
|
||||
|
||||
arrays.forEach((array, i, arrays) => {
|
||||
const offset = arrays.slice(0, i).reduce((acc, e) => acc + e.length, 0);
|
||||
merged.set(array, offset);
|
||||
});
|
||||
arrays.forEach((array, i, arrays) => {
|
||||
const offset = arrays.slice(0, i).reduce((acc, e) => acc + e.length, 0);
|
||||
merged.set(array, offset);
|
||||
});
|
||||
|
||||
return merged;
|
||||
return merged;
|
||||
}
|
||||
|
||||
export function bufferToBytes(b: Buffer) {
|
||||
return new Uint8Array(b.buffer);
|
||||
return new Uint8Array(b.buffer);
|
||||
}
|
||||
|
||||
export function bytesToBase64(bytes: Uint8Array) {
|
||||
return btoa(bytes.reduce((data, byte) => data + String.fromCharCode(byte), ''));
|
||||
return btoa(bytes.reduce((data, byte) => data + String.fromCharCode(byte), ''));
|
||||
}
|
||||
|
||||
export function base64ToBytes(base64: string) {
|
||||
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
|
||||
return Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
|
||||
}
|
||||
|
||||
export function bytesToHex(bytes: Uint8Array) {
|
||||
return (
|
||||
'0x' +
|
||||
Array.from(bytes)
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
);
|
||||
return (
|
||||
'0x' +
|
||||
Array.from(bytes)
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
);
|
||||
}
|
||||
|
||||
export function hexToBytes(hexString: string) {
|
||||
if (hexString.slice(0, 2) === '0x') {
|
||||
hexString = hexString.slice(2);
|
||||
}
|
||||
if (hexString.length % 2 !== 0) {
|
||||
hexString = '0' + hexString;
|
||||
}
|
||||
return Uint8Array.from((hexString.match(/.{1,2}/g) as string[]).map((byte) => parseInt(byte, 16)));
|
||||
if (hexString.slice(0, 2) === '0x') {
|
||||
hexString = hexString.slice(2);
|
||||
}
|
||||
if (hexString.length % 2 !== 0) {
|
||||
hexString = '0' + hexString;
|
||||
}
|
||||
return Uint8Array.from((hexString.match(/.{1,2}/g) as string[]).map((byte) => parseInt(byte, 16)));
|
||||
}
|
||||
|
||||
// Convert BE encoded bytes (Buffer | Uint8Array) array to BigInt
|
||||
export function bytesToBN(bytes: Uint8Array) {
|
||||
return BigInt(bytesToHex(bytes));
|
||||
return BigInt(bytesToHex(bytes));
|
||||
}
|
||||
|
||||
// Convert BigInt to BE encoded Uint8Array type
|
||||
export function bnToBytes(bigint: bigint | string) {
|
||||
// Parse bigint to hex string
|
||||
let hexString: string = typeof bigint === 'bigint' ? bigint.toString(16) : bigint;
|
||||
// Remove hex string prefix if exists
|
||||
if (hexString.slice(0, 2) === '0x') {
|
||||
hexString = hexString.slice(2);
|
||||
}
|
||||
// Hex string length should be a multiplier of two (To make correct bytes)
|
||||
if (hexString.length % 2 !== 0) {
|
||||
hexString = '0' + hexString;
|
||||
}
|
||||
return Uint8Array.from((hexString.match(/.{1,2}/g) as string[]).map((byte) => parseInt(byte, 16)));
|
||||
// Parse bigint to hex string
|
||||
let hexString: string = typeof bigint === 'bigint' ? bigint.toString(16) : bigint;
|
||||
// Remove hex string prefix if exists
|
||||
if (hexString.slice(0, 2) === '0x') {
|
||||
hexString = hexString.slice(2);
|
||||
}
|
||||
// Hex string length should be a multiplier of two (To make correct bytes)
|
||||
if (hexString.length % 2 !== 0) {
|
||||
hexString = '0' + hexString;
|
||||
}
|
||||
return Uint8Array.from((hexString.match(/.{1,2}/g) as string[]).map((byte) => parseInt(byte, 16)));
|
||||
}
|
||||
|
||||
// Convert LE encoded bytes (Buffer | Uint8Array) array to BigInt
|
||||
export function leBuff2Int(bytes: Uint8Array) {
|
||||
return new BN(bytes, 16, 'le');
|
||||
return new BN(bytes, 16, 'le');
|
||||
}
|
||||
|
||||
// Convert BigInt to LE encoded Uint8Array type
|
||||
export function leInt2Buff(bigint: bnInput | bigint) {
|
||||
return Uint8Array.from(new BN(bigint as bnInput).toArray('le', 31));
|
||||
return Uint8Array.from(new BN(bigint as bnInput).toArray('le', 31));
|
||||
}
|
||||
|
||||
// Inherited from tornado-core and tornado-cli
|
||||
export function toFixedHex(numberish: BigNumberish, length = 32) {
|
||||
return (
|
||||
'0x' +
|
||||
BigInt(numberish)
|
||||
.toString(16)
|
||||
.padStart(length * 2, '0')
|
||||
);
|
||||
return (
|
||||
'0x' +
|
||||
BigInt(numberish)
|
||||
.toString(16)
|
||||
.padStart(length * 2, '0')
|
||||
);
|
||||
}
|
||||
|
||||
export function toFixedLength(string: string, length: number = 32) {
|
||||
string = string.replace('0x', '');
|
||||
return '0x' + string.padStart(length * 2, '0');
|
||||
string = string.replace('0x', '');
|
||||
return '0x' + string.padStart(length * 2, '0');
|
||||
}
|
||||
|
||||
// Random BigInt in a range of bytes
|
||||
export function rBigInt(nbytes: number = 31) {
|
||||
return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes)));
|
||||
return bytesToBN(crypto.getRandomValues(new Uint8Array(nbytes)));
|
||||
}
|
||||
|
||||
export function rHex(nbytes: number = 32) {
|
||||
return bytesToHex(crypto.getRandomValues(new Uint8Array(nbytes)));
|
||||
return bytesToHex(crypto.getRandomValues(new Uint8Array(nbytes)));
|
||||
}
|
||||
|
||||
// Used for JSON.stringify(value, bigIntReplacer, space)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export function bigIntReplacer(key: any, value: any) {
|
||||
return typeof value === 'bigint' ? value.toString() : value;
|
||||
return typeof value === 'bigint' ? value.toString() : value;
|
||||
}
|
||||
|
||||
export function substring(str: string, length: number = 10) {
|
||||
if (str.length < length * 2) {
|
||||
return str;
|
||||
}
|
||||
if (str.length < length * 2) {
|
||||
return str;
|
||||
}
|
||||
|
||||
return `${str.substring(0, length)}...${str.substring(str.length - length)}`;
|
||||
return `${str.substring(0, length)}...${str.substring(str.length - length)}`;
|
||||
}
|
||||
|
||||
export async function digest(bytes: Uint8Array, algo: string = 'SHA-384') {
|
||||
return new Uint8Array(await crypto.subtle.digest(algo, bytes));
|
||||
return new Uint8Array(await crypto.subtle.digest(algo, bytes));
|
||||
}
|
||||
|
||||
export function numberFormatter(num: string | number | bigint, digits: number = 3): string {
|
||||
const lookup = [
|
||||
{ value: 1, symbol: '' },
|
||||
{ value: 1e3, symbol: 'K' },
|
||||
{ value: 1e6, symbol: 'M' },
|
||||
{ value: 1e9, symbol: 'G' },
|
||||
{ value: 1e12, symbol: 'T' },
|
||||
{ value: 1e15, symbol: 'P' },
|
||||
{ value: 1e18, symbol: 'E' },
|
||||
];
|
||||
const regexp = /\.0+$|(?<=\.[0-9]*[1-9])0+$/;
|
||||
const item = lookup
|
||||
.slice()
|
||||
.reverse()
|
||||
.find((item) => Number(num) >= item.value);
|
||||
return item ? (Number(num) / item.value).toFixed(digits).replace(regexp, '').concat(item.symbol) : '0';
|
||||
const lookup = [
|
||||
{ value: 1, symbol: '' },
|
||||
{ value: 1e3, symbol: 'K' },
|
||||
{ value: 1e6, symbol: 'M' },
|
||||
{ value: 1e9, symbol: 'G' },
|
||||
{ value: 1e12, symbol: 'T' },
|
||||
{ value: 1e15, symbol: 'P' },
|
||||
{ value: 1e18, symbol: 'E' },
|
||||
];
|
||||
const regexp = /\.0+$|(?<=\.[0-9]*[1-9])0+$/;
|
||||
const item = lookup
|
||||
.slice()
|
||||
.reverse()
|
||||
.find((item) => Number(num) >= item.value);
|
||||
return item ? (Number(num) / item.value).toFixed(digits).replace(regexp, '').concat(item.symbol) : '0';
|
||||
}
|
||||
|
||||
export function isHex(value: string) {
|
||||
return /^0x[0-9a-fA-F]*$/.test(value);
|
||||
return /^0x[0-9a-fA-F]*$/.test(value);
|
||||
}
|
||||
|
||||
110
src/websnark.ts
110
src/websnark.ts
@@ -6,81 +6,81 @@ import type { Element } from '@tornado/fixed-merkle-tree';
|
||||
import { toFixedHex } from './utils';
|
||||
|
||||
export interface snarkInputs {
|
||||
// Public snark inputs
|
||||
root: Element;
|
||||
nullifierHex: string;
|
||||
recipient: string;
|
||||
relayer: string;
|
||||
fee: bigint;
|
||||
refund: bigint;
|
||||
// Public snark inputs
|
||||
root: Element;
|
||||
nullifierHex: string;
|
||||
recipient: string;
|
||||
relayer: string;
|
||||
fee: bigint;
|
||||
refund: bigint;
|
||||
|
||||
// Private snark inputs
|
||||
nullifier: bigint;
|
||||
secret: bigint;
|
||||
pathElements: Element[];
|
||||
pathIndices: Element[];
|
||||
// Private snark inputs
|
||||
nullifier: bigint;
|
||||
secret: bigint;
|
||||
pathElements: Element[];
|
||||
pathIndices: Element[];
|
||||
}
|
||||
|
||||
export type snarkArgs = [
|
||||
_root: string,
|
||||
_nullifierHash: string,
|
||||
_recipient: string,
|
||||
_relayer: string,
|
||||
_fee: string,
|
||||
_refund: string,
|
||||
_root: string,
|
||||
_nullifierHash: string,
|
||||
_recipient: string,
|
||||
_relayer: string,
|
||||
_fee: string,
|
||||
_refund: string,
|
||||
];
|
||||
|
||||
export interface snarkProofs {
|
||||
proof: string;
|
||||
args: snarkArgs;
|
||||
proof: string;
|
||||
args: snarkArgs;
|
||||
}
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
let groth16: any;
|
||||
|
||||
export async function initGroth16() {
|
||||
if (!groth16) {
|
||||
groth16 = await websnarkGroth({ wasmInitialMemory: 2000 });
|
||||
}
|
||||
if (!groth16) {
|
||||
groth16 = await websnarkGroth({ wasmInitialMemory: 2000 });
|
||||
}
|
||||
}
|
||||
|
||||
export async function calculateSnarkProof(
|
||||
input: snarkInputs,
|
||||
circuit: object,
|
||||
provingKey: ArrayBuffer,
|
||||
input: snarkInputs,
|
||||
circuit: object,
|
||||
provingKey: ArrayBuffer,
|
||||
): Promise<snarkProofs> {
|
||||
if (!groth16) {
|
||||
await initGroth16();
|
||||
}
|
||||
if (!groth16) {
|
||||
await initGroth16();
|
||||
}
|
||||
|
||||
const snarkInput = {
|
||||
root: input.root,
|
||||
nullifierHash: BigInt(input.nullifierHex).toString(),
|
||||
recipient: BigInt(input.recipient as string),
|
||||
relayer: BigInt(input.relayer as string),
|
||||
fee: input.fee,
|
||||
refund: input.refund,
|
||||
const snarkInput = {
|
||||
root: input.root,
|
||||
nullifierHash: BigInt(input.nullifierHex).toString(),
|
||||
recipient: BigInt(input.recipient as string),
|
||||
relayer: BigInt(input.relayer as string),
|
||||
fee: input.fee,
|
||||
refund: input.refund,
|
||||
|
||||
nullifier: input.nullifier,
|
||||
secret: input.secret,
|
||||
pathElements: input.pathElements,
|
||||
pathIndices: input.pathIndices,
|
||||
};
|
||||
nullifier: input.nullifier,
|
||||
secret: input.secret,
|
||||
pathElements: input.pathElements,
|
||||
pathIndices: input.pathIndices,
|
||||
};
|
||||
|
||||
console.log('Start generating SNARK proof', snarkInput);
|
||||
console.time('SNARK proof time');
|
||||
const proofData = await websnarkUtils.genWitnessAndProve(await groth16, snarkInput, circuit, provingKey);
|
||||
const proof = websnarkUtils.toSolidityInput(proofData).proof;
|
||||
console.timeEnd('SNARK proof time');
|
||||
console.log('Start generating SNARK proof', snarkInput);
|
||||
console.time('SNARK proof time');
|
||||
const proofData = await websnarkUtils.genWitnessAndProve(await groth16, snarkInput, circuit, provingKey);
|
||||
const proof = websnarkUtils.toSolidityInput(proofData).proof;
|
||||
console.timeEnd('SNARK proof time');
|
||||
|
||||
const args = [
|
||||
toFixedHex(input.root, 32),
|
||||
toFixedHex(input.nullifierHex, 32),
|
||||
input.recipient,
|
||||
input.relayer,
|
||||
toFixedHex(input.fee, 32),
|
||||
toFixedHex(input.refund, 32),
|
||||
] as snarkArgs;
|
||||
const args = [
|
||||
toFixedHex(input.root, 32),
|
||||
toFixedHex(input.nullifierHex, 32),
|
||||
input.recipient,
|
||||
input.relayer,
|
||||
toFixedHex(input.fee, 32),
|
||||
toFixedHex(input.refund, 32),
|
||||
] as snarkArgs;
|
||||
|
||||
return { proof, args };
|
||||
return { proof, args };
|
||||
}
|
||||
|
||||
86
src/zip.ts
86
src/zip.ts
@@ -3,66 +3,66 @@ import { fetchData } from './providers';
|
||||
import { bytesToBase64, digest } from './utils';
|
||||
|
||||
export function zipAsync(file: AsyncZippable): Promise<Uint8Array> {
|
||||
return new Promise((res, rej) => {
|
||||
zip(file, { mtime: new Date('1/1/1980') }, (err, data) => {
|
||||
if (err) {
|
||||
rej(err);
|
||||
return;
|
||||
}
|
||||
res(data);
|
||||
return new Promise((res, rej) => {
|
||||
zip(file, { mtime: new Date('1/1/1980') }, (err, data) => {
|
||||
if (err) {
|
||||
rej(err);
|
||||
return;
|
||||
}
|
||||
res(data);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function unzipAsync(data: Uint8Array): Promise<Unzipped> {
|
||||
return new Promise((res, rej) => {
|
||||
unzip(data, {}, (err, data) => {
|
||||
if (err) {
|
||||
rej(err);
|
||||
return;
|
||||
}
|
||||
res(data);
|
||||
return new Promise((res, rej) => {
|
||||
unzip(data, {}, (err, data) => {
|
||||
if (err) {
|
||||
rej(err);
|
||||
return;
|
||||
}
|
||||
res(data);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export async function downloadZip<T>({
|
||||
staticUrl = '',
|
||||
zipName,
|
||||
zipDigest,
|
||||
parseJson = true,
|
||||
staticUrl = '',
|
||||
zipName,
|
||||
zipDigest,
|
||||
parseJson = true,
|
||||
}: {
|
||||
staticUrl?: string;
|
||||
zipName: string;
|
||||
zipDigest?: string;
|
||||
parseJson?: boolean;
|
||||
staticUrl?: string;
|
||||
zipName: string;
|
||||
zipDigest?: string;
|
||||
parseJson?: boolean;
|
||||
}): Promise<T> {
|
||||
const url = `${staticUrl}/${zipName}.zip`;
|
||||
const url = `${staticUrl}/${zipName}.zip`;
|
||||
|
||||
const resp = (await fetchData(url, {
|
||||
method: 'GET',
|
||||
returnResponse: true,
|
||||
})) as Response;
|
||||
const resp = (await fetchData(url, {
|
||||
method: 'GET',
|
||||
returnResponse: true,
|
||||
})) as Response;
|
||||
|
||||
const data = new Uint8Array(await resp.arrayBuffer());
|
||||
const data = new Uint8Array(await resp.arrayBuffer());
|
||||
|
||||
// If the zip has digest value, compare it
|
||||
if (zipDigest) {
|
||||
const hash = 'sha384-' + bytesToBase64(await digest(data));
|
||||
// If the zip has digest value, compare it
|
||||
if (zipDigest) {
|
||||
const hash = 'sha384-' + bytesToBase64(await digest(data));
|
||||
|
||||
if (zipDigest !== hash) {
|
||||
const errMsg = `Invalid digest hash for file ${url}, wants ${zipDigest} has ${hash}`;
|
||||
throw new Error(errMsg);
|
||||
if (zipDigest !== hash) {
|
||||
const errMsg = `Invalid digest hash for file ${url}, wants ${zipDigest} has ${hash}`;
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const { [zipName]: content } = await unzipAsync(data);
|
||||
const { [zipName]: content } = await unzipAsync(data);
|
||||
|
||||
console.log(`Downloaded ${url}${zipDigest ? ` ( Digest: ${zipDigest} )` : ''}`);
|
||||
console.log(`Downloaded ${url}${zipDigest ? ` ( Digest: ${zipDigest} )` : ''}`);
|
||||
|
||||
if (parseJson) {
|
||||
return JSON.parse(new TextDecoder().decode(content)) as T;
|
||||
}
|
||||
if (parseJson) {
|
||||
return JSON.parse(new TextDecoder().decode(content)) as T;
|
||||
}
|
||||
|
||||
return content as T;
|
||||
return content as T;
|
||||
}
|
||||
|
||||
@@ -12,47 +12,57 @@ const { getSigners } = ethers;
|
||||
const NOTES_COUNT = 100;
|
||||
|
||||
describe('./src/deposit.ts', function () {
|
||||
const instanceFixture = async () => {
|
||||
const [owner] = await getSigners();
|
||||
const instanceFixture = async () => {
|
||||
const [owner] = await getSigners();
|
||||
|
||||
const Hasher = (await (await deployHasher(owner)).wait())?.contractAddress as string;
|
||||
const Hasher = (await (await deployHasher(owner)).wait())?.contractAddress as string;
|
||||
|
||||
const Verifier = await new Verifier__factory(owner).deploy();
|
||||
const Verifier = await new Verifier__factory(owner).deploy();
|
||||
|
||||
const Instance = await new ETHTornado__factory(owner).deploy(Verifier.target, Hasher, 1n, 20);
|
||||
const Instance = await new ETHTornado__factory(owner).deploy(Verifier.target, Hasher, 1n, 20);
|
||||
|
||||
return { Instance };
|
||||
};
|
||||
return { Instance };
|
||||
};
|
||||
|
||||
it('Deposit New Note', async function () {
|
||||
const { Instance } = await loadFixture(instanceFixture);
|
||||
it('Deposit New Note', async function () {
|
||||
const { Instance } = await loadFixture(instanceFixture);
|
||||
|
||||
const [owner] = await getSigners();
|
||||
const [owner] = await getSigners();
|
||||
|
||||
const netId = Number((await owner.provider.getNetwork()).chainId);
|
||||
const netId = Number((await owner.provider.getNetwork()).chainId);
|
||||
|
||||
const deposit = await Deposit.createNote({ currency: 'eth', amount: formatEther(1), netId });
|
||||
const deposit = await Deposit.createNote({
|
||||
currency: 'eth',
|
||||
amount: formatEther(1),
|
||||
netId,
|
||||
});
|
||||
|
||||
const resp = await Instance.deposit(deposit.commitmentHex, { value: 1n });
|
||||
const resp = await Instance.deposit(deposit.commitmentHex, {
|
||||
value: 1n,
|
||||
});
|
||||
|
||||
await expect(resp).to.emit(Instance, 'Deposit').withArgs(deposit.commitmentHex, 0, anyValue);
|
||||
await expect(resp).to.emit(Instance, 'Deposit').withArgs(deposit.commitmentHex, 0, anyValue);
|
||||
|
||||
expect(await Instance.commitments(deposit.commitmentHex)).to.be.true;
|
||||
});
|
||||
|
||||
xit(`Creating ${NOTES_COUNT} random notes`, async function () {
|
||||
const notes = (await Promise.all(
|
||||
// eslint-disable-next-line prefer-spread
|
||||
Array.apply(null, Array(NOTES_COUNT)).map(() =>
|
||||
Deposit.createNote({ currency: 'eth', amount: '0.1', netId: 31337 }),
|
||||
),
|
||||
)) as Deposit[];
|
||||
|
||||
notes.forEach(({ noteHex, commitmentHex, nullifierHex }) => {
|
||||
// ((secret.length: 31) + (nullifier.length: 31)) * 2 + (prefix: 2) = 126
|
||||
expect(noteHex.length === 126).to.be.true;
|
||||
expect(commitmentHex.length === 66).to.be.true;
|
||||
expect(nullifierHex.length === 66).to.be.true;
|
||||
expect(await Instance.commitments(deposit.commitmentHex)).to.be.true;
|
||||
});
|
||||
|
||||
xit(`Creating ${NOTES_COUNT} random notes`, async function () {
|
||||
const notes = (await Promise.all(
|
||||
// eslint-disable-next-line prefer-spread
|
||||
Array.apply(null, Array(NOTES_COUNT)).map(() =>
|
||||
Deposit.createNote({
|
||||
currency: 'eth',
|
||||
amount: '0.1',
|
||||
netId: 31337,
|
||||
}),
|
||||
),
|
||||
)) as Deposit[];
|
||||
|
||||
notes.forEach(({ noteHex, commitmentHex, nullifierHex }) => {
|
||||
// ((secret.length: 31) + (nullifier.length: 31)) * 2 + (prefix: 2) = 126
|
||||
expect(noteHex.length === 126).to.be.true;
|
||||
expect(commitmentHex.length === 66).to.be.true;
|
||||
expect(nullifierHex.length === 66).to.be.true;
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,13 +2,13 @@ import { describe } from 'mocha';
|
||||
import { ethers } from 'hardhat';
|
||||
|
||||
describe('Tornado Core', function () {
|
||||
it('Get Provider', async function () {
|
||||
const [owner] = await ethers.getSigners();
|
||||
it('Get Provider', async function () {
|
||||
const [owner] = await ethers.getSigners();
|
||||
|
||||
console.log(owner);
|
||||
console.log(owner);
|
||||
|
||||
const { provider } = owner;
|
||||
const { provider } = owner;
|
||||
|
||||
console.log(await provider.getBlock('latest'));
|
||||
});
|
||||
console.log(await provider.getBlock('latest'));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,171 +3,171 @@ const path = require('path');
|
||||
const NodePolyfillPlugin = require('node-polyfill-webpack-plugin');
|
||||
|
||||
const esbuildLoader = {
|
||||
test: /\.ts?$/,
|
||||
loader: 'esbuild-loader',
|
||||
options: {
|
||||
loader: 'ts',
|
||||
target: 'es2022',
|
||||
}
|
||||
test: /\.ts?$/,
|
||||
loader: 'esbuild-loader',
|
||||
options: {
|
||||
loader: 'ts',
|
||||
target: 'es2022',
|
||||
}
|
||||
}
|
||||
|
||||
const commonAlias = {
|
||||
fs: false,
|
||||
'path': false,
|
||||
'url': false,
|
||||
'worker_threads': false,
|
||||
'fflate': 'fflate/browser',
|
||||
'http-proxy-agent': false,
|
||||
'https-proxy-agent': false,
|
||||
'socks-proxy-agent': false,
|
||||
fs: false,
|
||||
'path': false,
|
||||
'url': false,
|
||||
'worker_threads': false,
|
||||
'fflate': 'fflate/browser',
|
||||
'http-proxy-agent': false,
|
||||
'https-proxy-agent': false,
|
||||
'socks-proxy-agent': false,
|
||||
}
|
||||
|
||||
module.exports = [
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/index.ts',
|
||||
output: {
|
||||
filename: 'tornado.umd.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
library: 'Tornado',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
optimization: {
|
||||
minimize: false,
|
||||
}
|
||||
},
|
||||
entry: './src/index.ts',
|
||||
output: {
|
||||
filename: 'tornado.umd.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
library: 'Tornado',
|
||||
libraryTarget: 'umd'
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/index.ts',
|
||||
output: {
|
||||
filename: 'tornado.umd.min.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
library: 'Tornado',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/merkleTreeWorker.ts',
|
||||
output: {
|
||||
filename: 'merkleTreeWorker.umd.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
new BannerPlugin({
|
||||
banner: 'globalThis.process = { browser: true, env: {}, };\n',
|
||||
raw: true,
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
optimization: {
|
||||
minimize: false,
|
||||
}
|
||||
},
|
||||
optimization: {
|
||||
minimize: false,
|
||||
}
|
||||
},
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/merkleTreeWorker.ts',
|
||||
output: {
|
||||
filename: 'merkleTreeWorker.umd.min.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
new BannerPlugin({
|
||||
banner: 'globalThis.process = { browser: true, env: {}, };',
|
||||
raw: true,
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
},
|
||||
entry: './src/index.ts',
|
||||
output: {
|
||||
filename: 'tornado.umd.min.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
library: 'Tornado',
|
||||
libraryTarget: 'umd'
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/contracts.ts',
|
||||
output: {
|
||||
filename: 'tornadoContracts.umd.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
library: 'TornadoContracts',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
optimization: {
|
||||
minimize: false,
|
||||
}
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/contracts.ts',
|
||||
output: {
|
||||
filename: 'tornadoContracts.umd.min.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
library: 'TornadoContracts',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/merkleTreeWorker.ts',
|
||||
output: {
|
||||
filename: 'merkleTreeWorker.umd.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
new BannerPlugin({
|
||||
banner: 'globalThis.process = { browser: true, env: {}, };\n',
|
||||
raw: true,
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
optimization: {
|
||||
minimize: false,
|
||||
}
|
||||
},
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/merkleTreeWorker.ts',
|
||||
output: {
|
||||
filename: 'merkleTreeWorker.umd.min.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
new BannerPlugin({
|
||||
banner: 'globalThis.process = { browser: true, env: {}, };',
|
||||
raw: true,
|
||||
}),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/contracts.ts',
|
||||
output: {
|
||||
filename: 'tornadoContracts.umd.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
library: 'TornadoContracts',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
optimization: {
|
||||
minimize: false,
|
||||
}
|
||||
},
|
||||
{
|
||||
mode: 'production',
|
||||
module: {
|
||||
rules: [esbuildLoader]
|
||||
},
|
||||
entry: './src/contracts.ts',
|
||||
output: {
|
||||
filename: 'tornadoContracts.umd.min.js',
|
||||
path: path.resolve(__dirname, './dist'),
|
||||
library: 'TornadoContracts',
|
||||
libraryTarget: 'umd'
|
||||
},
|
||||
plugins: [
|
||||
new NodePolyfillPlugin(),
|
||||
],
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
alias: {
|
||||
...commonAlias,
|
||||
}
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
Reference in New Issue
Block a user