-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathZkSyncLite.ts
More file actions
475 lines (405 loc) · 20.8 KB
/
Copy pathZkSyncLite.ts
File metadata and controls
475 lines (405 loc) · 20.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
import { noSavings } from "../constants"
import customFetch from "../customfetch"
import EthFees from "../ethfees"
/**
* ZkSyncLite class calculates savings for ZkSync Lite (the old ZkSync).
*
* ======== Methodology ========
*
* ZkSync Lite is a rollup using zero knowledge proofs. Its not EVM equivalent,
* although ZkSync ERA is.
*
* Transactions have specific types, such as "transfer", "swap", "mint".
* The most convenient way to calculate the savings is to hard code gas
* amounts for each transaction type.
*
* ZkSync Lite also allows users to pay fees with any supported ERC20 token. If the token
* price is known, it is converted to ETH.
*
* Transactions that are L2 specific are not considered.
*
*
*
* Fetch 100 Transactions
* ┌─────────┐ ┌─────────────┐
* │L2Savings├───────────┬──────────────►api.zksync.io│
* └─────────┘ │ └──────┬──────┘
* │ │ Zero Transactions? ┌──────┐ L2 -> L1 Gas Mapping
* │ ├────────────────────────┤Return│ ┌─────────────────────────┐
* ├───────────◄─────────┘ └──────┘ │ ETH Transfer -> 21,000 │
* │ Request until there are │ ERC20 Transfer -> 50,000│
* │ no more txs or max limit reached │ Swap -> 105,000 │
* Append to Array │ │ Mint NFT -> 210,000 │
* │ └─────────────┬───────────┘
* │ │
* │ │
* ┌──▼──┐ ┌─────────────┐ For Each Tx ┌───────────┐ │
* │Array├───►Reverse Array├─▲──────────────►Transaction│ │ ┌─────────────┐
* └──┬──┘ └─────────────┘ │ └─────┬─────┘ {Deposit} │ │Average daily│
* │ │ │ {Withdraw} │ │gas data │
* │ │ Yes ┌───────┴──────┐ {WithdrawNFT} │ └──────┬──────┘
* Get ETH prices in range │ └────────────┤Is irrelevant?│====== {ForcedExit} │ │
* of first and last │ └───────┬──────┘ {ChangePubKey} │ │
* transaction dates │ │ │ │
* │ No ├───────────────────────┐ │ │
* ┌──────▼─────┐ Convert fees to ether with │ │ │ │
* _\|/^ │ Graph API ├─────────────┐respect to ether ┌─────▼────────┐ ┌───────▼─────▼─┐ │
* (_oo / └────────────┘ │price on tx date │Fees paid with│ │Predict L1 gas │ │
* /-|--/ │ ┌──────────────┤stablecoins? │ │from tx type │ │
* \ | │ │ └──────┬───────┘ └──────────┬────┘ │
* /--i │ │ │ │ │
* / L ┌─▼──▼─┐ No │ │ │
* L │Tx Fee◄───────────────────┘ │ │
* ▲ ┌──────┐ └───┬──┘ │ │
* │ Return Data │ │ │ ┌──────────┐ │ │
* └───────────────┤ Data ◄──────────────────┼───────────────────┤Fees if on│ Gas * Gas Price │ │
* │ │ │ │ Mainnet ◄─────────────────┴─────────────────┘
* └──▲───┘ │ └────┬─────┘
* │ ┌──────▼──┐ │
* └───────────────┤Fee saved◄─────────────────────┘ Website Used: https://asciiflow.com/
* └─────────┘ Stickman Art: https://ascii.co.uk/art/stickman
*/
export default class ZkSyncLite implements L2 {
/**
* The address that the data will be collected for
*/
private address: string
/**
* The callback to call when the savings of a transaction is calculated
*/
private onSavingCalculated: (progress: CalcProgress) => void
/**
* Maximum amount of supported transactions
*/
private readonly MAX_SUPPORTED_TRANSACTIONS = 1000
/**
* The mapping for transaction type => gas
*/
private readonly gasMap = {
ETHTransfer: {
nativeGasSpent: 1045,
L1gasSpent: 21_000,
},
ERC20Transfer: {
nativeGasSpent: 1045,
L1gasSpent: 50_000,
},
Swap: {
nativeGasSpent: 2350,
L1gasSpent: 105_000,
},
MintNFT: {
nativeGasSpent: 2874,
L1gasSpent: 210_000,
},
}
/**
* Optional abort signal, used to cancel the request
*/
private signal?: AbortSignal
/**
* @param address a valid 20 byte address as hex string with 0x prefix, 42 characters total
* @param onTransactionCalculated a callback to call when the savings of a transaction is calculated
*/
public constructor(
address: string,
onTransactionCalculated: (progress: CalcProgress) => void,
signal?: AbortSignal
) {
this.address = address
this.onSavingCalculated = onTransactionCalculated
this.signal = signal
}
/**
* Calculates and sets savings
* @return Savings
*/
public async calculateSavings(): Promise<Savings> {
let from: string = "latest"
let fetchedTxCount = 0
const allTransactions: any[][] = []
while (fetchedTxCount < this.MAX_SUPPORTED_TRANSACTIONS) {
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
const transactions: any[] = (
await customFetch(
`https://api.zksync.io/api/v0.2/accounts/${this.address}/transactions?from=${from}&limit=100&direction=older`
)
).result.list
if (transactions.length === 0 && fetchedTxCount === 0) {
this.onSavingCalculated({
text: "Calculated savings",
current: 0,
total: 0,
})
return JSON.parse(JSON.stringify(noSavings)) as Savings
}
allTransactions.push(transactions)
if (transactions.length === 100) {
from = transactions[transactions.length - 1].txHash
fetchedTxCount += 100
} else {
break
}
}
// Rerversing the transasctions array helps take batch transactions into account
const reversedTransactions = allTransactions
.map(arr => arr.reverse())
.reverse()
.flat()
let totalTransactionsLength = reversedTransactions.filter(
tx => tx.op.type === "Transfer" || tx.op.type === "Swap" || tx.op.type === "MintNFT"
).length
// Try to predict the total transaction count after irrelevant transactions
const seenBatchIds = new Set<number>()
for (const { batchId } of reversedTransactions) {
if (seenBatchIds.has(batchId)) {
continue
}
totalTransactionsLength--
seenBatchIds.add(batchId)
}
totalTransactionsLength--
if (totalTransactionsLength < 0) {
// Something went wrong
totalTransactionsLength = 0
}
this.onSavingCalculated({
text: "Fetching transaction receipts",
current: 0,
total: totalTransactionsLength,
})
let totalL1Fees = 0
let totalL2Fees = 0
let totalL1GasPredicted = 0
let totalL2GasPredicted = 0
let batchSize = 0
const allSavings: TransactionSavings[] = []
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
EthFees.cacheGasTimestamps(
reversedTransactions.map(tx => Math.round(new Date(tx.createdAt).getTime() / 1000))
)
let transactionsCalculated = 0
for (const transaction of reversedTransactions) {
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
const op = transaction.op
let feeToken = op.feeToken || 0
const txTimestamp = Math.round(new Date(transaction.createdAt).getTime() / 1000)
const transactionType: ZkSyncLiteTransaction = op.type
switch (true) {
case transactionType === "Transfer" &&
op.from.toLowerCase() === this.address.toLowerCase(): {
feeToken = feeToken || transaction.op.token
const transferType = op.token === 0 ? "ETHTransfer" : "ERC20Transfer"
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
// Calculate the batch transaction price
if (transaction.batchId) {
const batchIsFinal = !(EthFees.weiToEther(op.fee) === 0)
if (!batchIsFinal) {
batchSize++
continue
} else {
batchSize = batchSize === 0 ? 1 : batchSize
// the last tx of the batch
// batch count doesn't have to be increased again, because
// the value transferred is zero. It is assumed that
// every value transfer === ether transfer (21K gas on mainnet).
//
// fees paid include batch fees on zksync api
const L2Fee = await this.zkSyncFee(
feeToken,
EthFees.weiToEther(op.fee),
txTimestamp,
false
)
const L1Fee =
batchSize *
(await EthFees.averageDailyFee(
txTimestamp,
transferType === "ETHTransfer" ? "ethTransfer" : "erc20Transfer"
))
totalL2Fees += L2Fee
totalL2GasPredicted +=
this.gasMap[transferType].nativeGasSpent * batchSize
totalL1GasPredicted += this.gasMap[transferType].L1gasSpent * batchSize
totalL1Fees += L1Fee
transactionsCalculated++
this.onSavingCalculated({
text: "Calculating fees",
current: transactionsCalculated,
total: totalTransactionsLength,
})
allSavings.push({
L2: "zkSyncLite",
hash: transaction.txHash,
L2Fee,
L1Fee,
saved: L1Fee - L2Fee,
timesCheaper: L1Fee / L2Fee,
})
// reset batch size
batchSize = 0
continue
}
}
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
const L2Fee = await this.zkSyncFee(
feeToken,
EthFees.weiToEther(op.fee),
txTimestamp,
false
)
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
const L1Fee = await EthFees.averageDailyFee(
txTimestamp,
transferType === "ETHTransfer" ? "ethTransfer" : "erc20Transfer"
)
totalL2Fees += L2Fee
totalL2GasPredicted += this.gasMap[transferType].nativeGasSpent * batchSize
totalL1GasPredicted += this.gasMap[transferType].L1gasSpent * batchSize
totalL1Fees += L1Fee
transactionsCalculated++
this.onSavingCalculated({
text: "Calculating fees",
current: transactionsCalculated,
total: totalTransactionsLength,
})
allSavings.push({
L2: "zkSyncLite",
hash: transaction.txHash,
L2Fee,
L1Fee,
saved: L1Fee - L2Fee,
timesCheaper: L1Fee / L2Fee,
})
break
}
case transactionType === "Swap" || transactionType === "MintNFT": {
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
const L2Fee = await this.zkSyncFee(
feeToken,
EthFees.weiToEther(op.fee),
txTimestamp,
true
)
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
const L1Fee = await EthFees.averageDailyFee(
txTimestamp,
transactionType === "Swap" ? "swap" : "mint"
)
totalL1Fees += L1Fee
totalL2Fees += L2Fee
totalL2GasPredicted += (this.gasMap as any)[transactionType].nativeGasSpent
totalL1GasPredicted += (this.gasMap as any)[transactionType].L1gasSpent
transactionsCalculated++
this.onSavingCalculated({
text: "Calculating fees",
current: transactionsCalculated,
total:
totalTransactionsLength > transactionsCalculated
? totalTransactionsLength
: transactionsCalculated,
})
allSavings.push({
L2: "zkSyncLite",
hash: transaction.txHash,
L2Fee,
L1Fee,
saved: L1Fee - L2Fee,
timesCheaper: L1Fee / L2Fee,
})
break
}
default: // Transaction is irrelevant
continue
}
}
this.onSavingCalculated({
text: "Calculated savings",
current: allSavings.length,
total: allSavings.length,
})
if (this.signal && this.signal.aborted) {
throw new Error("Aborted: ZkSyncLite")
}
const totalL1FeesUsd = await EthFees.ethToUsd(totalL1Fees)
const totalL2FeesUsd = await EthFees.ethToUsd(totalL2Fees)
return {
L1: {
gasSpent: totalL1GasPredicted,
feesSpent: {
ether: totalL1Fees,
usd: totalL1FeesUsd,
},
},
L2: {
transactionsSent: allSavings.length,
gasSpent: totalL2GasPredicted,
feesSpent: {
ether: totalL2Fees,
usd: totalL2FeesUsd,
},
},
saved: {
ether: totalL1Fees - totalL2Fees,
usd: totalL1FeesUsd - totalL2FeesUsd,
timesCheaper: totalL1Fees / totalL2Fees,
},
details: allSavings,
}
}
/**
* ZkSync allows users to pay in multiple tokens. The API returns the "token ID". This function
* returns token ID, amount, and date to Ether. Average daily ETH price data is used unless the
* date is not found, in which the current ETH price of the asset is returned.
* https://zkscan.io/explorer/tokens/
* @param tokenId token ID of ERC20 token
* @param fee the amount of fee paid in ether
* @param timestamp the timestamp of transaction
* @param isExpensive return estimated random transaction price based on isExpensive
* @return estimated ZkSync fee paid
*/
private async zkSyncFee(tokenId: number, fee: number, timestamp: number, isExpensive: boolean) {
if (tokenId === 0) {
return fee
}
// Both NFT, ERC20 and Ether transfers are classified under the "transfer" function type.
// If id = 0, it's an ether transfer. If the id is in token ID's, it's a token, otherwise an nft.
// NFT token id's are usually "big" ~6 digits. The biggest token ID as of now is 173.
// To avoid fetching https://api.zksync.io/api/v0.2/tokens/<id> each time to check whether a
// transfer is an NFT transfer or not, ID size can be checked.
if (tokenId <= 6 || tokenId >= 500) {
// Token ID <= 6 all stables
if (tokenId === 2 || tokenId === 4) {
fee *= 10 ** 12 // USDC and USDT have 6 decimal places
}
return fee / (await EthFees.ethPriceAt(timestamp))
}
// If fees are paid with an unknown token id, return a randomly chosen estimate
if (isExpensive) {
console.warn(
`Fees paid in unsupported token ID ${tokenId} for ZkSync. Assumed 0.0002Ξ TX Fee`
)
return 0.0002
}
console.warn(
`Fees paid in unsupported token ID ${tokenId} for ZkSync. Assumed 0.0001Ξ TX Fee`
)
return 0.0001
}
}