Optimize mainnet fees

This commit is contained in:
Tornado Contrib 2024-10-10 23:23:55 +00:00
parent 2eb489979c
commit 0a305433ba
Signed by: tornadocontrib
GPG Key ID: 60B4DF1A076C64B1
4 changed files with 185 additions and 141 deletions

269
dist/cli.js vendored

@ -178283,7 +178283,7 @@ var groth16 = __webpack_require__(36336);
var __async$h = (__this, __arguments, generator) => { var __async$i = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -178392,7 +178392,7 @@ function substring(str, length = 10) {
return `${str.substring(0, length)}...${str.substring(str.length - length)}`; return `${str.substring(0, length)}...${str.substring(str.length - length)}`;
} }
function digest(bytes, algo = "SHA-384") { function digest(bytes, algo = "SHA-384") {
return __async$h(this, null, function* () { return __async$i(this, null, function* () {
return new Uint8Array(yield dist_crypto.subtle.digest(algo, bytes)); return new Uint8Array(yield dist_crypto.subtle.digest(algo, bytes));
}); });
} }
@ -178419,7 +178419,7 @@ var __spreadValues$8 = (a, b) => {
}; };
var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b)); var __spreadProps$6 = (a, b) => __defProps$6(a, __getOwnPropDescs$6(b));
var __superGet$2 = (cls, obj, key) => __reflectGet$2(__getProtoOf$2(cls), key, obj); var __superGet$2 = (cls, obj, key) => __reflectGet$2(__getProtoOf$2(cls), key, obj);
var __async$g = (__this, __arguments, generator) => { var __async$h = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -178468,7 +178468,7 @@ function getHttpAgent({
} }
} }
function fetchData(_0) { function fetchData(_0) {
return __async$g(this, arguments, function* (url, options = {}) { return __async$h(this, arguments, function* (url, options = {}) {
var _a, _b, _c; var _a, _b, _c;
const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3; const MAX_RETRY = (_a = options.maxRetry) != null ? _a : 3;
const RETRY_ON = (_b = options.retryOn) != null ? _b : 500; const RETRY_ON = (_b = options.retryOn) != null ? _b : 500;
@ -178560,7 +178560,7 @@ function fetchData(_0) {
throw errorObject; throw errorObject;
}); });
} }
const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$g(void 0, null, function* () { const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$h(void 0, null, function* () {
let signal; let signal;
if (_signal) { if (_signal) {
const controller = new AbortController(); const controller = new AbortController();
@ -178591,7 +178591,7 @@ const fetchGetUrlFunc = (options = {}) => (req, _signal) => __async$g(void 0, nu
}; };
}); });
function dist_getProvider(rpcUrl, fetchOptions) { function dist_getProvider(rpcUrl, fetchOptions) {
return __async$g(this, null, function* () { return __async$h(this, null, function* () {
const fetchReq = new fetch_FetchRequest(rpcUrl); const fetchReq = new fetch_FetchRequest(rpcUrl);
fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions); fetchReq.getUrlFunc = fetchGetUrlFunc(fetchOptions);
const staticNetwork = yield new provider_jsonrpc_JsonRpcProvider(fetchReq).getNetwork(); const staticNetwork = yield new provider_jsonrpc_JsonRpcProvider(fetchReq).getNetwork();
@ -178622,7 +178622,7 @@ function getProviderWithNetId(netId, rpcUrl, config, fetchOptions) {
}); });
return provider; return provider;
} }
const populateTransaction = (signer, tx) => __async$g(void 0, null, function* () { const populateTransaction = (signer, tx) => __async$h(void 0, null, function* () {
const provider = signer.provider; const provider = signer.provider;
if (!tx.from) { if (!tx.from) {
tx.from = signer.address; tx.from = signer.address;
@ -178683,7 +178683,7 @@ class TornadoWallet extends Wallet {
return new TornadoWallet(privateKey, provider, options); return new TornadoWallet(privateKey, provider, options);
} }
populateTransaction(tx) { populateTransaction(tx) {
return __async$g(this, null, function* () { return __async$h(this, null, function* () {
const txObject = yield populateTransaction(this, tx); const txObject = yield populateTransaction(this, tx);
this.nonce = Number(txObject.nonce); this.nonce = Number(txObject.nonce);
return __superGet$2(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject); return __superGet$2(TornadoWallet.prototype, this, "populateTransaction").call(this, txObject);
@ -178699,7 +178699,7 @@ class TornadoVoidSigner extends VoidSigner {
this.bumpNonce = bumpNonce != null ? bumpNonce : false; this.bumpNonce = bumpNonce != null ? bumpNonce : false;
} }
populateTransaction(tx) { populateTransaction(tx) {
return __async$g(this, null, function* () { return __async$h(this, null, function* () {
const txObject = yield populateTransaction(this, tx); const txObject = yield populateTransaction(this, tx);
this.nonce = Number(txObject.nonce); this.nonce = Number(txObject.nonce);
return __superGet$2(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject); return __superGet$2(TornadoVoidSigner.prototype, this, "populateTransaction").call(this, txObject);
@ -178715,7 +178715,7 @@ class TornadoRpcSigner extends JsonRpcSigner {
this.bumpNonce = bumpNonce != null ? bumpNonce : false; this.bumpNonce = bumpNonce != null ? bumpNonce : false;
} }
sendUncheckedTransaction(tx) { sendUncheckedTransaction(tx) {
return __async$g(this, null, function* () { return __async$h(this, null, function* () {
return __superGet$2(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx)); return __superGet$2(TornadoRpcSigner.prototype, this, "sendUncheckedTransaction").call(this, yield populateTransaction(this, tx));
}); });
} }
@ -178726,7 +178726,7 @@ class TornadoBrowserProvider extends BrowserProvider {
this.options = options; this.options = options;
} }
getSigner(address) { getSigner(address) {
return __async$g(this, null, function* () { return __async$h(this, null, function* () {
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j; var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
const signerAddress = (yield __superGet$2(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address; const signerAddress = (yield __superGet$2(TornadoBrowserProvider.prototype, this, "getSigner").call(this, address)).address;
if (((_a = this.options) == null ? void 0 : _a.netId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet$2(TornadoBrowserProvider.prototype, this, "send").call(this, "net_version", [])) !== ((_c = this.options) == null ? void 0 : _c.netId)) { if (((_a = this.options) == null ? void 0 : _a.netId) && ((_b = this.options) == null ? void 0 : _b.connectWallet) && Number(yield __superGet$2(TornadoBrowserProvider.prototype, this, "send").call(this, "net_version", [])) !== ((_c = this.options) == null ? void 0 : _c.netId)) {
@ -178954,7 +178954,7 @@ var __spreadValues$7 = (a, b) => {
return a; return a;
}; };
var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b)); var __spreadProps$5 = (a, b) => __defProps$5(a, __getOwnPropDescs$5(b));
var __async$f = (__this, __arguments, generator) => { var __async$g = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -178977,7 +178977,7 @@ var __async$f = (__this, __arguments, generator) => {
const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length; const isEmptyArray = (arr) => !Array.isArray(arr) || !arr.length;
const GRAPHQL_LIMIT = 1e3; const GRAPHQL_LIMIT = 1e3;
function queryGraph(_0) { function queryGraph(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
query, query,
@ -179006,7 +179006,7 @@ function queryGraph(_0) {
}); });
} }
function getStatistic(_0) { function getStatistic(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
currency, currency,
@ -179053,7 +179053,7 @@ function getStatistic(_0) {
}); });
} }
function getMeta(_0) { function getMeta(_0) {
return __async$f(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) { return __async$g(this, arguments, function* ({ graphApi, subgraphName, fetchDataOptions: fetchDataOptions2 }) {
try { try {
const { const {
_meta: { _meta: {
@ -179098,7 +179098,7 @@ function getRegisters({
}); });
} }
function getAllRegisters(_0) { function getAllRegisters(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
fromBlock, fromBlock,
@ -179187,7 +179187,7 @@ function getDeposits({
}); });
} }
function getAllDeposits(_0) { function getAllDeposits(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
currency, currency,
@ -179284,7 +179284,7 @@ function getWithdrawals({
}); });
} }
function getAllWithdrawals(_0) { function getAllWithdrawals(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
currency, currency,
@ -179360,7 +179360,7 @@ function getAllWithdrawals(_0) {
}); });
} }
function getNoteAccounts(_0) { function getNoteAccounts(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
address, address,
@ -179413,7 +179413,7 @@ function getGraphEchoEvents({
}); });
} }
function getAllGraphEchoEvents(_0) { function getAllGraphEchoEvents(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
fromBlock, fromBlock,
@ -179502,7 +179502,7 @@ function getEncryptedNotes({
}); });
} }
function getAllEncryptedNotes(_0) { function getAllEncryptedNotes(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
fromBlock, fromBlock,
@ -179587,7 +179587,7 @@ function getGovernanceEvents({
}); });
} }
function getAllGovernanceEvents(_0) { function getAllGovernanceEvents(_0) {
return __async$f(this, arguments, function* ({ return __async$g(this, arguments, function* ({
graphApi, graphApi,
subgraphName, subgraphName,
fromBlock, fromBlock,
@ -179746,7 +179746,7 @@ var graph = /*#__PURE__*/Object.freeze({
queryGraph: queryGraph queryGraph: queryGraph
}); });
var __async$e = (__this, __arguments, generator) => { var __async$f = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -179785,7 +179785,7 @@ class BatchBlockService {
this.retryOn = retryOn; this.retryOn = retryOn;
} }
getBlock(blockTag) { getBlock(blockTag) {
return __async$e(this, null, function* () { return __async$f(this, null, function* () {
const blockObject = yield this.provider.getBlock(blockTag); const blockObject = yield this.provider.getBlock(blockTag);
if (!blockObject) { if (!blockObject) {
const errMsg = `No block for ${blockTag}`; const errMsg = `No block for ${blockTag}`;
@ -179795,9 +179795,9 @@ class BatchBlockService {
}); });
} }
createBatchRequest(batchArray) { createBatchRequest(batchArray) {
return batchArray.map((blocks, index) => __async$e(this, null, function* () { return batchArray.map((blocks, index) => __async$f(this, null, function* () {
yield dist_sleep(20 * index); yield dist_sleep(20 * index);
return (() => __async$e(this, null, function* () { return (() => __async$f(this, null, function* () {
let retries = 0; let retries = 0;
let err; let err;
while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) {
@ -179814,7 +179814,7 @@ class BatchBlockService {
})); }));
} }
getBatchBlocks(blocks) { getBatchBlocks(blocks) {
return __async$e(this, null, function* () { return __async$f(this, null, function* () {
let blockCount = 0; let blockCount = 0;
const results = []; const results = [];
for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) { for (const chunks of chunk(blocks, this.concurrencySize * this.batchSize)) {
@ -179852,7 +179852,7 @@ class BatchTransactionService {
this.retryOn = retryOn; this.retryOn = retryOn;
} }
getTransaction(txHash) { getTransaction(txHash) {
return __async$e(this, null, function* () { return __async$f(this, null, function* () {
const txObject = yield this.provider.getTransaction(txHash); const txObject = yield this.provider.getTransaction(txHash);
if (!txObject) { if (!txObject) {
const errMsg = `No transaction for ${txHash}`; const errMsg = `No transaction for ${txHash}`;
@ -179862,9 +179862,9 @@ class BatchTransactionService {
}); });
} }
createBatchRequest(batchArray) { createBatchRequest(batchArray) {
return batchArray.map((txs, index) => __async$e(this, null, function* () { return batchArray.map((txs, index) => __async$f(this, null, function* () {
yield dist_sleep(20 * index); yield dist_sleep(20 * index);
return (() => __async$e(this, null, function* () { return (() => __async$f(this, null, function* () {
let retries = 0; let retries = 0;
let err; let err;
while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) {
@ -179881,7 +179881,7 @@ class BatchTransactionService {
})); }));
} }
getBatchTransactions(txs) { getBatchTransactions(txs) {
return __async$e(this, null, function* () { return __async$f(this, null, function* () {
let txCount = 0; let txCount = 0;
const results = []; const results = [];
for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) { for (const chunks of chunk(txs, this.concurrencySize * this.batchSize)) {
@ -179917,7 +179917,7 @@ class BatchEventsService {
this.retryOn = retryOn; this.retryOn = retryOn;
} }
getPastEvents(_0) { getPastEvents(_0) {
return __async$e(this, arguments, function* ({ fromBlock, toBlock, type }) { return __async$f(this, arguments, function* ({ fromBlock, toBlock, type }) {
let err; let err;
let retries = 0; let retries = 0;
while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) { while (!this.shouldRetry && retries === 0 || this.shouldRetry && retries < this.retryMax) {
@ -179937,13 +179937,13 @@ class BatchEventsService {
}); });
} }
createBatchRequest(batchArray) { createBatchRequest(batchArray) {
return batchArray.map((event, index) => __async$e(this, null, function* () { return batchArray.map((event, index) => __async$f(this, null, function* () {
yield dist_sleep(20 * index); yield dist_sleep(20 * index);
return this.getPastEvents(event); return this.getPastEvents(event);
})); }));
} }
getBatchEvents(_0) { getBatchEvents(_0) {
return __async$e(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) { return __async$f(this, arguments, function* ({ fromBlock, toBlock, type = "*" }) {
if (!toBlock) { if (!toBlock) {
toBlock = yield this.provider.getBlockNumber(); toBlock = yield this.provider.getBlockNumber();
} }
@ -180984,7 +180984,7 @@ var __spreadValues$3 = (a, b) => {
return a; return a;
}; };
var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b)); var __spreadProps$2 = (a, b) => __defProps$2(a, __getOwnPropDescs$2(b));
var __async$d = (__this, __arguments, generator) => { var __async$e = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -181050,7 +181050,7 @@ class RelayerClient {
this.tovarish = false; this.tovarish = false;
} }
askRelayerStatus(_0) { askRelayerStatus(_0) {
return __async$d(this, arguments, function* ({ return __async$e(this, arguments, function* ({
hostname, hostname,
url, url,
relayerAddress relayerAddress
@ -181090,7 +181090,7 @@ class RelayerClient {
}); });
} }
filterRelayer(relayer) { filterRelayer(relayer) {
return __async$d(this, null, function* () { return __async$e(this, null, function* () {
var _a; var _a;
const hostname = relayer.hostnames[this.netId]; const hostname = relayer.hostnames[this.netId];
const { ensName, relayerAddress } = relayer; const { ensName, relayerAddress } = relayer;
@ -181124,7 +181124,7 @@ class RelayerClient {
}); });
} }
getValidRelayers(relayers) { getValidRelayers(relayers) {
return __async$d(this, null, function* () { return __async$e(this, null, function* () {
const invalidRelayers = []; const invalidRelayers = [];
const validRelayers = (yield Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => { const validRelayers = (yield Promise.all(relayers.map((relayer) => this.filterRelayer(relayer)))).filter((r) => {
if (!r) { if (!r) {
@ -181146,7 +181146,7 @@ class RelayerClient {
return pickWeightedRandomRelayer(relayers); return pickWeightedRandomRelayer(relayers);
} }
tornadoWithdraw(_0, _1) { tornadoWithdraw(_0, _1) {
return __async$d(this, arguments, function* ({ contract, proof, args }, callback) { return __async$e(this, arguments, function* ({ contract, proof, args }, callback) {
const { url } = this.selectedRelayer; const { url } = this.selectedRelayer;
const withdrawResponse = yield fetchData(`${url}v1/tornadoWithdraw`, __spreadProps$2(__spreadValues$3({}, this.fetchDataOptions), { const withdrawResponse = yield fetchData(`${url}v1/tornadoWithdraw`, __spreadProps$2(__spreadValues$3({}, this.fetchDataOptions), {
method: "POST", method: "POST",
@ -181233,7 +181233,7 @@ var __spreadValues$2 = (a, b) => {
}; };
var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b)); var __spreadProps$1 = (a, b) => __defProps$1(a, __getOwnPropDescs$1(b));
var __superGet$1 = (cls, obj, key) => __reflectGet$1(__getProtoOf$1(cls), key, obj); var __superGet$1 = (cls, obj, key) => __reflectGet$1(__getProtoOf$1(cls), key, obj);
var __async$c = (__this, __arguments, generator) => { var __async$d = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -181313,7 +181313,7 @@ class BaseEventsService {
} }
/* eslint-enable @typescript-eslint/no-unused-vars */ /* eslint-enable @typescript-eslint/no-unused-vars */
formatEvents(events) { formatEvents(events) {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
return yield new Promise((resolve) => resolve(events)); return yield new Promise((resolve) => resolve(events));
}); });
} }
@ -181321,7 +181321,7 @@ class BaseEventsService {
* Get saved or cached events * Get saved or cached events
*/ */
getEventsFromDB() { getEventsFromDB() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
return { return {
events: [], events: [],
lastBlock: 0 lastBlock: 0
@ -181332,7 +181332,7 @@ class BaseEventsService {
* Events from remote cache (Either from local cache, CDN, or from IPFS) * Events from remote cache (Either from local cache, CDN, or from IPFS)
*/ */
getEventsFromCache() { getEventsFromCache() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
return { return {
events: [], events: [],
lastBlock: 0, lastBlock: 0,
@ -181341,7 +181341,7 @@ class BaseEventsService {
}); });
} }
getSavedEvents() { getSavedEvents() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
let dbEvents = yield this.getEventsFromDB(); let dbEvents = yield this.getEventsFromDB();
if (!dbEvents.lastBlock) { if (!dbEvents.lastBlock) {
dbEvents = yield this.getEventsFromCache(); dbEvents = yield this.getEventsFromCache();
@ -181353,7 +181353,7 @@ class BaseEventsService {
* Get latest events * Get latest events
*/ */
getEventsFromGraph(_0) { getEventsFromGraph(_0) {
return __async$c(this, arguments, function* ({ return __async$d(this, arguments, function* ({
fromBlock, fromBlock,
methodName = "" methodName = ""
}) { }) {
@ -181373,7 +181373,7 @@ class BaseEventsService {
}); });
} }
getEventsFromRpc(_0) { getEventsFromRpc(_0) {
return __async$c(this, arguments, function* ({ return __async$d(this, arguments, function* ({
fromBlock, fromBlock,
toBlock toBlock
}) { }) {
@ -181405,7 +181405,7 @@ class BaseEventsService {
}); });
} }
getLatestEvents(_0) { getLatestEvents(_0) {
return __async$c(this, arguments, function* ({ fromBlock }) { return __async$d(this, arguments, function* ({ fromBlock }) {
var _a; var _a;
if (((_a = this.tovarishClient) == null ? void 0 : _a.selectedRelayer) && ![DEPOSIT, WITHDRAWAL].includes(this.type.toLowerCase())) { if (((_a = this.tovarishClient) == null ? void 0 : _a.selectedRelayer) && ![DEPOSIT, WITHDRAWAL].includes(this.type.toLowerCase())) {
const { events, lastSyncBlock: lastBlock } = yield this.tovarishClient.getEvents({ const { events, lastSyncBlock: lastBlock } = yield this.tovarishClient.getEvents({
@ -181434,14 +181434,14 @@ class BaseEventsService {
*/ */
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
saveEvents(_0) { saveEvents(_0) {
return __async$c(this, arguments, function* ({ events, lastBlock }) { return __async$d(this, arguments, function* ({ events, lastBlock }) {
}); });
} }
/** /**
* Trigger saving and receiving latest events * Trigger saving and receiving latest events
*/ */
updateEvents() { updateEvents() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
var _a; var _a;
const savedEvents = yield this.getSavedEvents(); const savedEvents = yield this.getSavedEvents();
let fromBlock = this.deployedBlock; let fromBlock = this.deployedBlock;
@ -181526,7 +181526,7 @@ class BaseTornadoService extends BaseEventsService {
}; };
} }
formatEvents(events) { formatEvents(events) {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
const type = this.getType().toLowerCase(); const type = this.getType().toLowerCase();
if (type === DEPOSIT) { if (type === DEPOSIT) {
const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { const formattedEvents = events.map(({ blockNumber, index: logIndex, transactionHash, args }) => {
@ -181583,7 +181583,7 @@ class BaseTornadoService extends BaseEventsService {
} }
} }
getLatestEvents(_0) { getLatestEvents(_0) {
return __async$c(this, arguments, function* ({ fromBlock }) { return __async$d(this, arguments, function* ({ fromBlock }) {
var _a; var _a;
if ((_a = this.tovarishClient) == null ? void 0 : _a.selectedRelayer) { if ((_a = this.tovarishClient) == null ? void 0 : _a.selectedRelayer) {
const { events, lastSyncBlock: lastBlock } = yield this.tovarishClient.getEvents({ const { events, lastSyncBlock: lastBlock } = yield this.tovarishClient.getEvents({
@ -181633,7 +181633,7 @@ class BaseEchoService extends BaseEventsService {
return "getAllGraphEchoEvents"; return "getAllGraphEchoEvents";
} }
formatEvents(events) { formatEvents(events) {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => {
const { who, data } = args; const { who, data } = args;
if (who && data) { if (who && data) {
@ -181651,7 +181651,7 @@ class BaseEchoService extends BaseEventsService {
}); });
} }
getEventsFromGraph(_0) { getEventsFromGraph(_0) {
return __async$c(this, arguments, function* ({ fromBlock }) { return __async$d(this, arguments, function* ({ fromBlock }) {
if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) { if (!this.graphApi || this.graphApi.includes("api.thegraph.com")) {
return { return {
events: [], events: [],
@ -181697,7 +181697,7 @@ class BaseEncryptedNotesService extends BaseEventsService {
return "getAllEncryptedNotes"; return "getAllEncryptedNotes";
} }
formatEvents(events) { formatEvents(events) {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => {
const { encryptedNote } = args; const { encryptedNote } = args;
if (encryptedNote && encryptedNote !== "0x") { if (encryptedNote && encryptedNote !== "0x") {
@ -181753,7 +181753,7 @@ class BaseGovernanceService extends BaseEventsService {
return "getAllGovernanceEvents"; return "getAllGovernanceEvents";
} }
formatEvents(events) { formatEvents(events) {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
const proposalEvents = []; const proposalEvents = [];
const votedEvents = []; const votedEvents = [];
const delegatedEvents = []; const delegatedEvents = [];
@ -181820,7 +181820,7 @@ class BaseGovernanceService extends BaseEventsService {
}); });
} }
getEventsFromGraph(_0) { getEventsFromGraph(_0) {
return __async$c(this, arguments, function* ({ fromBlock }) { return __async$d(this, arguments, function* ({ fromBlock }) {
if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) { if (!this.graphApi || !this.subgraphName || this.graphApi.includes("api.thegraph.com")) {
return { return {
events: [], events: [],
@ -181832,9 +181832,9 @@ class BaseGovernanceService extends BaseEventsService {
} }
} }
function getTovarishNetworks(registryService, relayers) { function getTovarishNetworks(registryService, relayers) {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
yield Promise.all( yield Promise.all(
relayers.filter((r) => r.tovarishHost).map((relayer) => __async$c(this, null, function* () { relayers.filter((r) => r.tovarishHost).map((relayer) => __async$d(this, null, function* () {
var _a; var _a;
try { try {
relayer.tovarishNetworks = yield fetchData(relayer.tovarishHost, __spreadProps$1(__spreadValues$2({}, registryService.fetchDataOptions), { relayer.tovarishNetworks = yield fetchData(relayer.tovarishHost, __spreadProps$1(__spreadValues$2({}, registryService.fetchDataOptions), {
@ -181902,7 +181902,7 @@ class BaseRegistryService extends BaseEventsService {
return "getAllRegisters"; return "getAllRegisters";
} }
formatEvents(events) { formatEvents(events) {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => { return events.map(({ blockNumber, index: logIndex, transactionHash, args }) => {
const eventObjects = { const eventObjects = {
blockNumber, blockNumber,
@ -181920,7 +181920,7 @@ class BaseRegistryService extends BaseEventsService {
* Get saved or cached relayers * Get saved or cached relayers
*/ */
getRelayersFromDB() { getRelayersFromDB() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
return { return {
lastBlock: 0, lastBlock: 0,
timestamp: 0, timestamp: 0,
@ -181932,7 +181932,7 @@ class BaseRegistryService extends BaseEventsService {
* Relayers from remote cache (Either from local cache, CDN, or from IPFS) * Relayers from remote cache (Either from local cache, CDN, or from IPFS)
*/ */
getRelayersFromCache() { getRelayersFromCache() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
return { return {
lastBlock: 0, lastBlock: 0,
timestamp: 0, timestamp: 0,
@ -181942,7 +181942,7 @@ class BaseRegistryService extends BaseEventsService {
}); });
} }
getSavedRelayers() { getSavedRelayers() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
let cachedRelayers = yield this.getRelayersFromDB(); let cachedRelayers = yield this.getRelayersFromDB();
if (!cachedRelayers || !cachedRelayers.relayers.length) { if (!cachedRelayers || !cachedRelayers.relayers.length) {
cachedRelayers = yield this.getRelayersFromCache(); cachedRelayers = yield this.getRelayersFromCache();
@ -181951,7 +181951,7 @@ class BaseRegistryService extends BaseEventsService {
}); });
} }
getLatestRelayers() { getLatestRelayers() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
const { events, lastBlock } = yield this.updateEvents(); const { events, lastBlock } = yield this.updateEvents();
const subdomains = Object.values(this.relayerEnsSubdomains); const subdomains = Object.values(this.relayerEnsSubdomains);
const registerSet = /* @__PURE__ */ new Set(); const registerSet = /* @__PURE__ */ new Set();
@ -182011,14 +182011,14 @@ class BaseRegistryService extends BaseEventsService {
*/ */
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
saveRelayers(_0) { saveRelayers(_0) {
return __async$c(this, arguments, function* ({ lastBlock, timestamp, relayers }) { return __async$d(this, arguments, function* ({ lastBlock, timestamp, relayers }) {
}); });
} }
/** /**
* Get cached or latest relayer and save to local * Get cached or latest relayer and save to local
*/ */
updateRelayers() { updateRelayers() {
return __async$c(this, null, function* () { return __async$d(this, null, function* () {
let { lastBlock, timestamp, relayers, fromCache } = yield this.getSavedRelayers(); let { lastBlock, timestamp, relayers, fromCache } = yield this.getSavedRelayers();
let shouldSave = fromCache != null ? fromCache : false; let shouldSave = fromCache != null ? fromCache : false;
if (!relayers.length || timestamp + this.updateInterval < Math.floor(Date.now() / 1e3)) { if (!relayers.length || timestamp + this.updateInterval < Math.floor(Date.now() / 1e3)) {
@ -182034,7 +182034,7 @@ class BaseRegistryService extends BaseEventsService {
} }
} }
var __async$b = (__this, __arguments, generator) => { var __async$c = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -182077,7 +182077,7 @@ function unzipAsync(data) {
}); });
} }
function downloadZip(_0) { function downloadZip(_0) {
return __async$b(this, arguments, function* ({ return __async$c(this, arguments, function* ({
staticUrl = "", staticUrl = "",
zipName, zipName,
zipDigest, zipDigest,
@ -182105,7 +182105,7 @@ function downloadZip(_0) {
}); });
} }
var __async$a = (__this, __arguments, generator) => { var __async$b = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -182126,7 +182126,7 @@ var __async$a = (__this, __arguments, generator) => {
}); });
}; };
function saveDBEvents(_0) { function saveDBEvents(_0) {
return __async$a(this, arguments, function* ({ return __async$b(this, arguments, function* ({
idb, idb,
instanceName, instanceName,
events, events,
@ -182151,7 +182151,7 @@ function saveDBEvents(_0) {
}); });
} }
function loadDBEvents(_0) { function loadDBEvents(_0) {
return __async$a(this, arguments, function* ({ return __async$b(this, arguments, function* ({
idb, idb,
instanceName instanceName
}) { }) {
@ -182181,7 +182181,7 @@ function loadDBEvents(_0) {
}); });
} }
function loadRemoteEvents(_0) { function loadRemoteEvents(_0) {
return __async$a(this, arguments, function* ({ return __async$b(this, arguments, function* ({
staticUrl, staticUrl,
instanceName, instanceName,
deployedBlock, deployedBlock,
@ -182222,7 +182222,7 @@ class DBTornadoService extends BaseTornadoService {
this.idb = params.idb; this.idb = params.idb;
} }
getEventsFromDB() { getEventsFromDB() {
return __async$a(this, null, function* () { return __async$b(this, null, function* () {
return yield loadDBEvents({ return yield loadDBEvents({
idb: this.idb, idb: this.idb,
instanceName: this.getInstanceName() instanceName: this.getInstanceName()
@ -182230,7 +182230,7 @@ class DBTornadoService extends BaseTornadoService {
}); });
} }
getEventsFromCache() { getEventsFromCache() {
return __async$a(this, null, function* () { return __async$b(this, null, function* () {
return yield loadRemoteEvents({ return yield loadRemoteEvents({
staticUrl: this.staticUrl, staticUrl: this.staticUrl,
instanceName: this.getInstanceName(), instanceName: this.getInstanceName(),
@ -182240,7 +182240,7 @@ class DBTornadoService extends BaseTornadoService {
}); });
} }
saveEvents(_0) { saveEvents(_0) {
return __async$a(this, arguments, function* ({ events, lastBlock }) { return __async$b(this, arguments, function* ({ events, lastBlock }) {
yield saveDBEvents({ yield saveDBEvents({
idb: this.idb, idb: this.idb,
instanceName: this.getInstanceName(), instanceName: this.getInstanceName(),
@ -184588,7 +184588,7 @@ var dist_index = /*#__PURE__*/Object.freeze({
ReverseRecords__factory: ReverseRecords__factory ReverseRecords__factory: ReverseRecords__factory
}); });
var __async$9 = (__this, __arguments, generator) => { var __async$a = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -184613,13 +184613,13 @@ class Pedersen {
this.pedersenPromise = this.initPedersen(); this.pedersenPromise = this.initPedersen();
} }
initPedersen() { initPedersen() {
return __async$9(this, null, function* () { return __async$a(this, null, function* () {
this.pedersenHash = yield pedersen_hash_buildPedersenHash(); this.pedersenHash = yield pedersen_hash_buildPedersenHash();
this.babyJub = this.pedersenHash.babyJub; this.babyJub = this.pedersenHash.babyJub;
}); });
} }
unpackPoint(buffer) { unpackPoint(buffer) {
return __async$9(this, null, function* () { return __async$a(this, null, function* () {
var _a, _b; var _a, _b;
yield this.pedersenPromise; yield this.pedersenPromise;
return (_b = this.babyJub) == null ? void 0 : _b.unpackPoint((_a = this.pedersenHash) == null ? void 0 : _a.hash(buffer)); return (_b = this.babyJub) == null ? void 0 : _b.unpackPoint((_a = this.pedersenHash) == null ? void 0 : _a.hash(buffer));
@ -184632,13 +184632,13 @@ class Pedersen {
} }
const pedersen = new Pedersen(); const pedersen = new Pedersen();
function buffPedersenHash(buffer) { function buffPedersenHash(buffer) {
return __async$9(this, null, function* () { return __async$a(this, null, function* () {
const [hash] = yield pedersen.unpackPoint(buffer); const [hash] = yield pedersen.unpackPoint(buffer);
return pedersen.toStringBuffer(hash); return pedersen.toStringBuffer(hash);
}); });
} }
var __async$8 = (__this, __arguments, generator) => { var __async$9 = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
var fulfilled = (value) => { var fulfilled = (value) => {
try { try {
@ -184659,7 +184659,7 @@ var __async$8 = (__this, __arguments, generator) => {
}); });
}; };
function createDeposit(_0) { function createDeposit(_0) {
return __async$8(this, arguments, function* ({ nullifier, secret }) { return __async$9(this, arguments, function* ({ nullifier, secret }) {
const preimage = new Uint8Array([...dist_leInt2Buff(nullifier), ...dist_leInt2Buff(secret)]); const preimage = new Uint8Array([...dist_leInt2Buff(nullifier), ...dist_leInt2Buff(secret)]);
const noteHex = toFixedHex(bytesToBN(preimage), 62); const noteHex = toFixedHex(bytesToBN(preimage), 62);
const commitment = BigInt(yield buffPedersenHash(preimage)); const commitment = BigInt(yield buffPedersenHash(preimage));
@ -184719,7 +184719,7 @@ class Deposit {
); );
} }
static createNote(_0) { static createNote(_0) {
return __async$8(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) { return __async$9(this, arguments, function* ({ currency, amount, netId, nullifier, secret }) {
if (!nullifier) { if (!nullifier) {
nullifier = rBigInt(31); nullifier = rBigInt(31);
} }
@ -184746,7 +184746,7 @@ class Deposit {
}); });
} }
static parseNote(noteString) { static parseNote(noteString) {
return __async$8(this, null, function* () { return __async$9(this, null, function* () {
const noteRegex = new RegExp("tornado-(?<currency>\\w+)-(?<amount>[\\d.]+)-(?<netId>\\d+)-0x(?<note>[0-9a-fA-F]{124})", "g"); const noteRegex = new RegExp("tornado-(?<currency>\\w+)-(?<amount>[\\d.]+)-(?<netId>\\d+)-0x(?<note>[0-9a-fA-F]{124})", "g");
const match = noteRegex.exec(noteString); const match = noteRegex.exec(noteString);
if (!match) { if (!match) {
@ -184931,6 +184931,26 @@ class NoteAccount {
} }
} }
var __async$8 = (__this, __arguments, generator) => {
return new Promise((resolve, reject) => {
var fulfilled = (value) => {
try {
step(generator.next(value));
} catch (e) {
reject(e);
}
};
var rejected = (value) => {
try {
step(generator.throw(value));
} catch (e) {
reject(e);
}
};
var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
step((generator = generator.apply(__this, __arguments)).next());
});
};
const DUMMY_ADDRESS = "0x1111111111111111111111111111111111111111"; const DUMMY_ADDRESS = "0x1111111111111111111111111111111111111111";
const DUMMY_NONCE = 1024; const DUMMY_NONCE = 1024;
const DUMMY_WITHDRAW_DATA = "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111"; const DUMMY_WITHDRAW_DATA = "0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111";
@ -184939,11 +184959,41 @@ function convertETHToTokenAmount(amountInWei, tokenPriceInWei, tokenDecimals = 1
return BigInt(amountInWei) * tokenDecimalsMultiplier / BigInt(tokenPriceInWei); return BigInt(amountInWei) * tokenDecimalsMultiplier / BigInt(tokenPriceInWei);
} }
class TornadoFeeOracle { class TornadoFeeOracle {
constructor(ovmGasPriceOracle) { constructor(provider, ovmGasPriceOracle) {
this.provider = provider;
if (ovmGasPriceOracle) { if (ovmGasPriceOracle) {
this.ovmGasPriceOracle = 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)
*/
gasPrice() {
return __async$8(this, null, function* () {
const [block, getGasPrice, getPriorityFee] = yield Promise.all([
this.provider.getBlock("latest"),
(() => __async$8(this, null, function* () {
try {
return BigInt(yield this.provider.send("eth_gasPrice", []));
} catch (e) {
return parseUnits("1", "gwei");
}
}))(),
(() => __async$8(this, null, function* () {
try {
return BigInt(yield this.provider.send("eth_maxPriorityFeePerGas", []));
} catch (e) {
return BigInt(0);
}
}))()
]);
return (block == null ? void 0 : block.baseFeePerGas) ? block.baseFeePerGas * BigInt(15) / BigInt(10) + getPriorityFee : getGasPrice;
});
}
/** /**
* Calculate L1 fee for op-stack chains * Calculate L1 fee for op-stack chains
* *
@ -187815,7 +187865,7 @@ function tornadoProgram() {
"Withdraw a note to a recipient account using relayer or specified private key. \n\nYou can exchange some of your deposit`s tokens to ETH during the withdrawal by specifing ETH_purchase (e.g. 0.01) to pay for gas in future transactions. \n\nAlso see the --relayer option.\n\n" "Withdraw a note to a recipient account using relayer or specified private key. \n\nYou can exchange some of your deposit`s tokens to ETH during the withdrawal by specifing ETH_purchase (e.g. 0.01) to pay for gas in future transactions. \n\nAlso see the --relayer option.\n\n"
).argument("<note>", "Tornado Cash Deposit Note").argument("<recipient>", "Recipient to receive withdrawn amount", parseAddress).argument("[ETH_purchase]", "ETH to purchase", parseNumber).action( ).argument("<note>", "Tornado Cash Deposit Note").argument("<recipient>", "Recipient to receive withdrawn amount", parseAddress).argument("[ETH_purchase]", "ETH to purchase", parseNumber).action(
(note, recipient, ethPurchase, cmdOptions) => program_async(this, null, function* () { (note, recipient, ethPurchase, cmdOptions) => program_async(this, null, function* () {
var _a; var _a, _b, _c, _d;
const { options, fetchDataOptions: fetchDataOptions2 } = yield getProgramOptions(cmdOptions); const { options, fetchDataOptions: fetchDataOptions2 } = yield getProgramOptions(cmdOptions);
const { rpc, walletWithdrawal, disableTovarish } = options; const { rpc, walletWithdrawal, disableTovarish } = options;
initGroth16(); initGroth16();
@ -187861,6 +187911,11 @@ function tornadoProgram() {
Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null ? void 0 : _a.url} Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null ? void 0 : _a.url}
`); `);
} }
if (!walletWithdrawal && !(relayerClient == null ? void 0 : relayerClient.selectedRelayer)) {
throw new Error(
"No valid relayer found for the network, you can either try again, or find any relayers using the relayers command and set with --relayer option"
);
}
const signer = getProgramSigner({ const signer = getProgramSigner({
options, options,
provider provider
@ -187874,6 +187929,7 @@ Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null
const TornadoProxy = TornadoRouter__factory.connect(routerContract, !walletWithdrawal ? provider : signer); const TornadoProxy = TornadoRouter__factory.connect(routerContract, !walletWithdrawal ? provider : signer);
const Multicall = Multicall__factory.connect(multicallContract, provider); const Multicall = Multicall__factory.connect(multicallContract, provider);
const tornadoFeeOracle = new TornadoFeeOracle( const tornadoFeeOracle = new TornadoFeeOracle(
provider,
ovmGasPriceOracleContract ? OvmGasPriceOracle__factory.connect(ovmGasPriceOracleContract, provider) : void 0 ovmGasPriceOracleContract ? OvmGasPriceOracle__factory.connect(ovmGasPriceOracleContract, provider) : void 0
); );
const tokenPriceOracle = new TokenPriceOracle( const tokenPriceOracle = new TokenPriceOracle(
@ -187910,7 +187966,7 @@ Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null
merkleWorkerPath merkleWorkerPath
}); });
const depositEvents = (yield depositsService.updateEvents()).events; const depositEvents = (yield depositsService.updateEvents()).events;
const depositTreePromise = merkleTreeService.verifyTree(depositEvents); const tree = yield merkleTreeService.verifyTree(depositEvents);
const withdrawalEvents = (yield withdrawalsService.updateEvents()).events; const withdrawalEvents = (yield withdrawalsService.updateEvents()).events;
const depositEvent = depositEvents.find(({ commitment }) => commitment === commitmentHex); const depositEvent = depositEvents.find(({ commitment }) => commitment === commitmentHex);
const withdrawalEvent = withdrawalEvents.find(({ nullifierHash }) => nullifierHash === nullifierHex); const withdrawalEvent = withdrawalEvents.find(({ nullifierHash }) => nullifierHash === nullifierHex);
@ -187950,21 +188006,15 @@ Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null
if (withdrawalEvent) { if (withdrawalEvent) {
throw new Error("Note is already spent"); throw new Error("Note is already spent");
} }
const [circuit, provingKey, tree, l1Fee, tokenPriceInWei, feeData] = yield Promise.all([ const [circuit, provingKey, netGasPrice, l1Fee, tokenPriceInWei] = yield Promise.all([
(0,promises_namespaceObject.readFile)(CIRCUIT_PATH, { encoding: "utf8" }).then((s) => JSON.parse(s)), (0,promises_namespaceObject.readFile)(CIRCUIT_PATH, { encoding: "utf8" }).then((s) => JSON.parse(s)),
(0,promises_namespaceObject.readFile)(KEY_PATH).then((b) => new Uint8Array(b).buffer), (0,promises_namespaceObject.readFile)(KEY_PATH).then((b) => new Uint8Array(b).buffer),
depositTreePromise, tornadoFeeOracle.gasPrice(),
tornadoFeeOracle.fetchL1OptimismFee(), tornadoFeeOracle.fetchL1OptimismFee(),
!isEth ? tokenPriceOracle.fetchPrices([{ tokenAddress, decimals }]).then((p) => p[0]) : BigInt(0), !isEth ? tokenPriceOracle.fetchPrices([{ tokenAddress, decimals }]).then((p) => p[0]) : BigInt(0)
provider.getFeeData()
]); ]);
const { pathElements, pathIndices } = tree.path(depositEvent.leafIndex); const { pathElements, pathIndices } = tree.path(depositEvent.leafIndex);
if (!walletWithdrawal && !(relayerClient == null ? void 0 : relayerClient.selectedRelayer)) { let gasPrice = netGasPrice;
throw new Error(
"No valid relayer found for the network, you can either try again, or find any relayers using the relayers command and set with --relayer option"
);
}
let gasPrice = feeData.maxFeePerGas ? feeData.maxFeePerGas + (feeData.maxPriorityFeePerGas || BigInt(0)) : feeData.gasPrice;
if (!walletWithdrawal && !tovarishClient && netId === NetId.BSC) { if (!walletWithdrawal && !tovarishClient && netId === NetId.BSC) {
gasPrice = parseUnits("3.3", "gwei"); gasPrice = parseUnits("3.3", "gwei");
} }
@ -187973,14 +188023,14 @@ Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null
const refundGasLimit = isFirstAmount && tokenGasLimit ? BigInt(tokenGasLimit) : void 0; const refundGasLimit = isFirstAmount && tokenGasLimit ? BigInt(tokenGasLimit) : void 0;
function getProof() { function getProof() {
return program_async(this, null, function* () { return program_async(this, null, function* () {
let relayer2 = ZeroAddress; let relayer = ZeroAddress;
let fee2 = BigInt(0); let fee2 = BigInt(0);
let refund2 = BigInt(0); let refund2 = BigInt(0);
const { url: url2, rewardAccount, tornadoServiceFee } = (relayerClient == null ? void 0 : relayerClient.selectedRelayer) || {};
if (!walletWithdrawal) { if (!walletWithdrawal) {
if (!isEth) { if (!isEth) {
refund2 = ethPurchase ? parseEther(`${ethPurchase}`) : tornadoFeeOracle.defaultEthRefund(gasPrice, refundGasLimit); refund2 = ethPurchase ? parseEther(`${ethPurchase}`) : tornadoFeeOracle.defaultEthRefund(gasPrice, refundGasLimit);
} }
const { rewardAccount, tornadoServiceFee: relayerFeePercent } = (relayerClient == null ? void 0 : relayerClient.selectedRelayer) || {};
fee2 = tornadoFeeOracle.calculateRelayerFee({ fee2 = tornadoFeeOracle.calculateRelayerFee({
gasPrice, gasPrice,
gasLimit, gasLimit,
@ -187989,10 +188039,10 @@ Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null
ethRefund: refund2, ethRefund: refund2,
tokenPriceInWei, tokenPriceInWei,
tokenDecimals: decimals, tokenDecimals: decimals,
relayerFeePercent: tornadoServiceFee, relayerFeePercent,
isEth isEth
}); });
relayer2 = rewardAccount; relayer = rewardAccount;
if (fee2 > denomination) { if (fee2 > denomination) {
const errMsg = `Relayer fee ${formatUnits(fee2, decimals)} ${currency.toUpperCase()} exceeds the deposit amount ${amount} ${currency.toUpperCase()}.`; const errMsg = `Relayer fee ${formatUnits(fee2, decimals)} ${currency.toUpperCase()} exceeds the deposit amount ${amount} ${currency.toUpperCase()}.`;
throw new Error(errMsg); throw new Error(errMsg);
@ -188003,7 +188053,7 @@ Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null
root: tree.root, root: tree.root,
nullifierHex, nullifierHex,
recipient, recipient,
relayer: relayer2, relayer,
fee: fee2, fee: fee2,
refund: refund2, refund: refund2,
nullifier, nullifier,
@ -188015,38 +188065,35 @@ Connected with Tovarish Relayer ${(_a = tovarishClient.selectedRelayer) == null
provingKey provingKey
); );
return { return {
url: url2,
relayer: relayer2,
fee: fee2, fee: fee2,
feePercent: tornadoServiceFee,
refund: refund2, refund: refund2,
proof: proof2, proof: proof2,
args: args2 args: args2
}; };
}); });
} }
let { url, relayer, fee, feePercent, refund, proof, args } = yield getProof(); let { fee, refund, proof, args } = yield getProof();
const withdrawOverrides = { const withdrawOverrides = {
from: !walletWithdrawal ? relayer : signer == null ? void 0 : signer.address, from: !walletWithdrawal ? (_b = relayerClient == null ? void 0 : relayerClient.selectedRelayer) == null ? void 0 : _b.rewardAccount : signer == null ? void 0 : signer.address,
value: args[5] || 0 value: args[5] || 0
}; };
gasLimit = yield TornadoProxy.withdraw.estimateGas(instanceAddress, proof, ...args, withdrawOverrides); gasLimit = yield TornadoProxy.withdraw.estimateGas(instanceAddress, proof, ...args, withdrawOverrides);
if (gasLimit > defaultGasLimit) { if (fee) {
({ url, relayer, fee, feePercent, refund, proof, args } = yield getProof()); ({ fee, refund, proof, args } = yield getProof());
gasLimit = yield TornadoProxy.withdraw.estimateGas(instanceAddress, proof, ...args, withdrawOverrides); yield TornadoProxy.withdraw.estimateGas(instanceAddress, proof, ...args, withdrawOverrides);
} }
const withdrawTable = new (cli_table3_default())(); const withdrawTable = new (cli_table3_default())();
withdrawTable.push([{ colSpan: 2, content: "Withdrawal Info", hAlign: "center" }]); withdrawTable.push([{ colSpan: 2, content: "Withdrawal Info", hAlign: "center" }]);
if (!walletWithdrawal && (relayerClient == null ? void 0 : relayerClient.selectedRelayer)) { if (!walletWithdrawal) {
withdrawTable.push( withdrawTable.push(
[{ colSpan: 2, content: "Withdraw", hAlign: "center" }], [{ colSpan: 2, content: "Withdraw", hAlign: "center" }],
["Withdrawal", `${amount} ${currency.toUpperCase()}`], ["Withdrawal", `${amount} ${currency.toUpperCase()}`],
["Relayer", `${url}`], ["Relayer", `${(_c = relayerClient == null ? void 0 : relayerClient.selectedRelayer) == null ? void 0 : _c.url}`],
[ [
"Relayer Fee", "Relayer Fee",
`${formatUnits(fee, decimals)} ${currency.toUpperCase()} (${(Number(fee) / Number(denomination) * 100).toFixed(5)}%)` `${formatUnits(fee, decimals)} ${currency.toUpperCase()} (${(Number(fee) / Number(denomination) * 100).toFixed(5)}%)`
], ],
["Relayer Fee Percent", `${feePercent}%`], ["Relayer Fee Percent", `${(_d = relayerClient == null ? void 0 : relayerClient.selectedRelayer) == null ? void 0 : _d.tornadoServiceFee}%`],
[ [
"Amount to receive", "Amount to receive",
`${Number(formatUnits(denomination - fee, decimals)).toFixed(5)} ${currency.toUpperCase()}` `${Number(formatUnits(denomination - fee, decimals)).toFixed(5)} ${currency.toUpperCase()}`

@ -51,7 +51,7 @@
"optionalDependencies": {}, "optionalDependencies": {},
"devDependencies": { "devDependencies": {
"@colors/colors": "^1.6.0", "@colors/colors": "^1.6.0",
"@tornado/core": "git+https://git.tornado.ws/tornadocontrib/tornado-core.git#d87e6c51f7fddc9e03d62cb0247cea78a8d588a3", "@tornado/core": "git+https://git.tornado.ws/tornadocontrib/tornado-core.git#4f0aaea790ff26bb8902bbf60f101ec240704685",
"@typechain/ethers-v6": "^0.5.1", "@typechain/ethers-v6": "^0.5.1",
"@types/figlet": "^1.7.0", "@types/figlet": "^1.7.0",
"@typescript-eslint/eslint-plugin": "^8.8.1", "@typescript-eslint/eslint-plugin": "^8.8.1",

@ -978,6 +978,12 @@ export function tornadoProgram() {
console.log(`\nConnected with Tovarish Relayer ${tovarishClient.selectedRelayer?.url}\n`); console.log(`\nConnected with Tovarish Relayer ${tovarishClient.selectedRelayer?.url}\n`);
} }
if (!walletWithdrawal && !relayerClient?.selectedRelayer) {
throw new Error(
'No valid relayer found for the network, you can either try again, or find any relayers using the relayers command and set with --relayer option',
);
}
const signer = getProgramSigner({ const signer = getProgramSigner({
options, options,
provider, provider,
@ -995,6 +1001,7 @@ export function tornadoProgram() {
const Multicall = Multicall__factory.connect(multicallContract, provider); const Multicall = Multicall__factory.connect(multicallContract, provider);
const tornadoFeeOracle = new TornadoFeeOracle( const tornadoFeeOracle = new TornadoFeeOracle(
provider,
ovmGasPriceOracleContract ovmGasPriceOracleContract
? OvmGasPriceOracle__factory.connect(ovmGasPriceOracleContract, provider) ? OvmGasPriceOracle__factory.connect(ovmGasPriceOracleContract, provider)
: undefined, : undefined,
@ -1043,7 +1050,7 @@ export function tornadoProgram() {
const depositEvents = (await depositsService.updateEvents()).events as DepositsEvents[]; const depositEvents = (await depositsService.updateEvents()).events as DepositsEvents[];
// Create tree using node workers which would spawn another dedicated thread to create trees // Create tree using node workers which would spawn another dedicated thread to create trees
const depositTreePromise = merkleTreeService.verifyTree(depositEvents); const tree = await merkleTreeService.verifyTree(depositEvents);
const withdrawalEvents = (await withdrawalsService.updateEvents()).events as WithdrawalsEvents[]; const withdrawalEvents = (await withdrawalsService.updateEvents()).events as WithdrawalsEvents[];
@ -1095,28 +1102,19 @@ export function tornadoProgram() {
throw new Error('Note is already spent'); throw new Error('Note is already spent');
} }
const [circuit, provingKey, tree, l1Fee, tokenPriceInWei, feeData] = await Promise.all([ const [circuit, provingKey, netGasPrice, l1Fee, tokenPriceInWei] = await Promise.all([
readFile(CIRCUIT_PATH, { encoding: 'utf8' }).then((s) => JSON.parse(s)), readFile(CIRCUIT_PATH, { encoding: 'utf8' }).then((s) => JSON.parse(s)),
readFile(KEY_PATH).then((b) => new Uint8Array(b).buffer), readFile(KEY_PATH).then((b) => new Uint8Array(b).buffer),
depositTreePromise, tornadoFeeOracle.gasPrice(),
tornadoFeeOracle.fetchL1OptimismFee(), tornadoFeeOracle.fetchL1OptimismFee(),
!isEth !isEth
? tokenPriceOracle.fetchPrices([{ tokenAddress: tokenAddress as string, decimals }]).then((p) => p[0]) ? tokenPriceOracle.fetchPrices([{ tokenAddress: tokenAddress as string, decimals }]).then((p) => p[0])
: BigInt(0), : BigInt(0),
provider.getFeeData(),
]); ]);
const { pathElements, pathIndices } = tree.path((depositEvent as DepositsEvents).leafIndex); const { pathElements, pathIndices } = tree.path((depositEvent as DepositsEvents).leafIndex);
if (!walletWithdrawal && !relayerClient?.selectedRelayer) { let gasPrice = netGasPrice;
throw new Error(
'No valid relayer found for the network, you can either try again, or find any relayers using the relayers command and set with --relayer option',
);
}
let gasPrice: bigint = feeData.maxFeePerGas
? feeData.maxFeePerGas + (feeData.maxPriorityFeePerGas || BigInt(0))
: (feeData.gasPrice as bigint);
if (!walletWithdrawal && !tovarishClient && netId === NetId.BSC) { if (!walletWithdrawal && !tovarishClient && netId === NetId.BSC) {
gasPrice = parseUnits('3.3', 'gwei'); gasPrice = parseUnits('3.3', 'gwei');
@ -1134,8 +1132,6 @@ export function tornadoProgram() {
let fee = BigInt(0); let fee = BigInt(0);
let refund = BigInt(0); let refund = BigInt(0);
const { url, rewardAccount, tornadoServiceFee } = relayerClient?.selectedRelayer || {};
if (!walletWithdrawal) { if (!walletWithdrawal) {
if (!isEth) { if (!isEth) {
refund = ethPurchase refund = ethPurchase
@ -1143,6 +1139,8 @@ export function tornadoProgram() {
: tornadoFeeOracle.defaultEthRefund(gasPrice, refundGasLimit); : tornadoFeeOracle.defaultEthRefund(gasPrice, refundGasLimit);
} }
const { rewardAccount, tornadoServiceFee: relayerFeePercent } = relayerClient?.selectedRelayer || {};
fee = tornadoFeeOracle.calculateRelayerFee({ fee = tornadoFeeOracle.calculateRelayerFee({
gasPrice, gasPrice,
gasLimit, gasLimit,
@ -1151,7 +1149,7 @@ export function tornadoProgram() {
ethRefund: refund, ethRefund: refund,
tokenPriceInWei, tokenPriceInWei,
tokenDecimals: decimals, tokenDecimals: decimals,
relayerFeePercent: tornadoServiceFee, relayerFeePercent,
isEth, isEth,
}); });
@ -1183,45 +1181,44 @@ export function tornadoProgram() {
); );
return { return {
url,
relayer,
fee, fee,
feePercent: tornadoServiceFee,
refund, refund,
proof, proof,
args, args,
}; };
} }
let { url, relayer, fee, feePercent, refund, proof, args } = await getProof(); let { fee, refund, proof, args } = await getProof();
const withdrawOverrides = { const withdrawOverrides = {
from: !walletWithdrawal ? relayer : (signer?.address as string), from: !walletWithdrawal ? relayerClient?.selectedRelayer?.rewardAccount : (signer?.address as string),
value: args[5] || 0, value: args[5] || 0,
}; };
gasLimit = await TornadoProxy.withdraw.estimateGas(instanceAddress, proof, ...args, withdrawOverrides); gasLimit = await TornadoProxy.withdraw.estimateGas(instanceAddress, proof, ...args, withdrawOverrides);
if (gasLimit > defaultGasLimit) { if (fee) {
({ url, relayer, fee, feePercent, refund, proof, args } = await getProof()); ({ fee, refund, proof, args } = await getProof());
gasLimit = await TornadoProxy.withdraw.estimateGas(instanceAddress, proof, ...args, withdrawOverrides);
// Verify if our recalculated proof can be withdrawn
await TornadoProxy.withdraw.estimateGas(instanceAddress, proof, ...args, withdrawOverrides);
} }
const withdrawTable = new Table(); const withdrawTable = new Table();
withdrawTable.push([{ colSpan: 2, content: 'Withdrawal Info', hAlign: 'center' }]); withdrawTable.push([{ colSpan: 2, content: 'Withdrawal Info', hAlign: 'center' }]);
// withdraw using relayer // withdraw using relayer
if (!walletWithdrawal && relayerClient?.selectedRelayer) { if (!walletWithdrawal) {
withdrawTable.push( withdrawTable.push(
[{ colSpan: 2, content: 'Withdraw', hAlign: 'center' }], [{ colSpan: 2, content: 'Withdraw', hAlign: 'center' }],
['Withdrawal', `${amount} ${currency.toUpperCase()}`], ['Withdrawal', `${amount} ${currency.toUpperCase()}`],
['Relayer', `${url}`], ['Relayer', `${relayerClient?.selectedRelayer?.url}`],
[ [
'Relayer Fee', 'Relayer Fee',
`${formatUnits(fee, decimals)} ${currency.toUpperCase()} ` + `${formatUnits(fee, decimals)} ${currency.toUpperCase()} ` +
`(${((Number(fee) / Number(denomination)) * 100).toFixed(5)}%)`, `(${((Number(fee) / Number(denomination)) * 100).toFixed(5)}%)`,
], ],
['Relayer Fee Percent', `${feePercent}%`], ['Relayer Fee Percent', `${relayerClient?.selectedRelayer?.tornadoServiceFee}%`],
[ [
'Amount to receive', 'Amount to receive',
`${Number(formatUnits(denomination - fee, decimals)).toFixed(5)} ${currency.toUpperCase()}`, `${Number(formatUnits(denomination - fee, decimals)).toFixed(5)} ${currency.toUpperCase()}`,

@ -786,9 +786,9 @@
"@openzeppelin/contracts-v3" "npm:@openzeppelin/contracts@3.2.0-rc.0" "@openzeppelin/contracts-v3" "npm:@openzeppelin/contracts@3.2.0-rc.0"
ethers "^6.4.0" ethers "^6.4.0"
"@tornado/core@git+https://git.tornado.ws/tornadocontrib/tornado-core.git#d87e6c51f7fddc9e03d62cb0247cea78a8d588a3": "@tornado/core@git+https://git.tornado.ws/tornadocontrib/tornado-core.git#4f0aaea790ff26bb8902bbf60f101ec240704685":
version "1.0.19" version "1.0.19"
resolved "git+https://git.tornado.ws/tornadocontrib/tornado-core.git#d87e6c51f7fddc9e03d62cb0247cea78a8d588a3" resolved "git+https://git.tornado.ws/tornadocontrib/tornado-core.git#4f0aaea790ff26bb8902bbf60f101ec240704685"
dependencies: dependencies:
"@metamask/eth-sig-util" "^7.0.3" "@metamask/eth-sig-util" "^7.0.3"
"@tornado/contracts" "^1.0.1" "@tornado/contracts" "^1.0.1"