@provex/utils 1.0.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +287 -0
  2. package/dist/scripts/convert-svg.d.ts +1 -0
  3. package/dist/scripts/convert-svg.js +17 -0
  4. package/dist/src/chain.d.ts +14 -0
  5. package/dist/src/chain.js +18 -0
  6. package/dist/src/contracts.d.ts +30 -0
  7. package/dist/src/contracts.js +64 -0
  8. package/dist/src/conversionRates.d.ts +124 -0
  9. package/dist/src/conversionRates.js +219 -0
  10. package/dist/src/currencies.d.ts +144 -0
  11. package/dist/src/currencies.js +234 -0
  12. package/dist/src/data/countries.json +1099 -0
  13. package/dist/src/deposit.d.ts +1 -0
  14. package/dist/src/deposit.js +1 -0
  15. package/dist/src/events.d.ts +3 -0
  16. package/dist/src/events.js +16 -0
  17. package/dist/src/flags.d.ts +2 -0
  18. package/dist/src/flags.js +3 -0
  19. package/dist/src/ids.d.ts +72 -0
  20. package/dist/src/ids.js +81 -0
  21. package/dist/src/index.d.ts +16 -0
  22. package/dist/src/index.js +16 -0
  23. package/dist/src/input.d.ts +7 -0
  24. package/dist/src/input.js +35 -0
  25. package/dist/src/intent.d.ts +14 -0
  26. package/dist/src/intent.js +1 -0
  27. package/dist/src/json.d.ts +18 -0
  28. package/dist/src/json.js +44 -0
  29. package/dist/src/participants.d.ts +7 -0
  30. package/dist/src/participants.js +13 -0
  31. package/dist/src/payment.d.ts +164 -0
  32. package/dist/src/payment.js +439 -0
  33. package/dist/src/profit.d.ts +28 -0
  34. package/dist/src/profit.js +34 -0
  35. package/dist/src/sort.d.ts +36 -0
  36. package/dist/src/sort.js +39 -0
  37. package/dist/src/stats.d.ts +7 -0
  38. package/dist/src/stats.js +8 -0
  39. package/dist/src/time.d.ts +54 -0
  40. package/dist/src/time.js +106 -0
  41. package/dist/src/tokens.d.ts +3675 -0
  42. package/dist/src/tokens.js +134 -0
  43. package/dist/src/units.d.ts +17 -0
  44. package/dist/src/units.js +79 -0
  45. package/dist/src/zkp2p-types.d.ts +48 -0
  46. package/dist/src/zkp2p-types.js +1 -0
  47. package/dist/tsconfig.tsbuildinfo +1 -0
  48. package/package.json +45 -0
  49. package/scripts/convert-svg.ts +22 -0
  50. package/src/chain.ts +27 -0
  51. package/src/contracts.ts +89 -0
  52. package/src/conversionRates.ts +356 -0
  53. package/src/currencies.ts +286 -0
  54. package/src/data/countries.json +1099 -0
  55. package/src/deposit.ts +2 -0
  56. package/src/events.ts +21 -0
  57. package/src/flags/eur.svg +4 -0
  58. package/src/flags/usd.svg +25 -0
  59. package/src/flags.ts +4 -0
  60. package/src/global.d.ts +9 -0
  61. package/src/ids.ts +137 -0
  62. package/src/index.ts +16 -0
  63. package/src/input.ts +35 -0
  64. package/src/intent.ts +15 -0
  65. package/src/json.ts +42 -0
  66. package/src/participants.ts +14 -0
  67. package/src/payment.ts +573 -0
  68. package/src/profit.ts +55 -0
  69. package/src/sort.ts +49 -0
  70. package/src/stats.ts +10 -0
  71. package/src/time.ts +123 -0
  72. package/src/tokens.ts +159 -0
  73. package/src/units.ts +120 -0
  74. package/src/zkp2p-types.ts +55 -0
  75. package/tsconfig.json +18 -0
@@ -0,0 +1,439 @@
1
+ import { getAddress, parseUnits, zeroAddress } from "viem";
2
+ import { base, pulsechain } from "viem/chains";
3
+ import { contractsByChainId, getContracts } from "./contracts.js";
4
+ import { formatUnits } from "./units.js";
5
+ import { SUPPORTED_CURRENCIES } from "./currencies.js";
6
+ /**
7
+ * Payment providers, including manual
8
+ */
9
+ export const providers = {
10
+ VENMO: 'venmo',
11
+ ZELLE: 'zelle',
12
+ CASHAPP: 'cashapp',
13
+ REVOLUT: 'revolut',
14
+ WISE: 'wise',
15
+ MERCADOPAGO: 'mercadopago',
16
+ MANUAL: 'manual',
17
+ PAYPAL: 'paypal',
18
+ MONZO: 'monzo',
19
+ };
20
+ /** Distinct keys for payment sub-providers (currently only used by Zelle) */
21
+ export const subProviders = {
22
+ CHASE: 'chase',
23
+ BANK_OF_AMERICA: 'bank_of_america',
24
+ CITI: 'citi',
25
+ };
26
+ /** Provider key to validation key */
27
+ export const providerKeyToValidationKey = {
28
+ venmo: 'venmoUsername',
29
+ zelle: 'zelleEmail',
30
+ cashapp: 'cashtag',
31
+ revolut: 'revolutUsername',
32
+ wise: 'wisetag',
33
+ mercadopago: 'cvu',
34
+ paypal: 'paypalEmail',
35
+ monzo: 'monzoMeUsername',
36
+ };
37
+ /** Data encoding for zelle urls */
38
+ export const dataEncoding = (data) => {
39
+ return btoa(JSON.stringify({
40
+ name: '',
41
+ action: 'payment',
42
+ token: data,
43
+ }));
44
+ };
45
+ /** Default Zelle send link */
46
+ export const defaultZelleSendLink = (options) => (!options.username ? null
47
+ : `https://enroll.zellepay.com/qr-codes?data=${dataEncoding(options.username)}`);
48
+ /** Global configuration for all supported sub-providers. Other modules can import this directly. */
49
+ export const subProviderConfigs = {
50
+ zelle: {
51
+ chase: {
52
+ paymentMethod: 0,
53
+ key: subProviders.CHASE,
54
+ name: 'Chase',
55
+ icon: 'simple-icons:chase',
56
+ verifiers: (chain) => getContracts(chain).zelleChaseReclaimVerifier,
57
+ sendLink: (opts) => {
58
+ if (opts.qrCode) {
59
+ return defaultZelleSendLink(opts);
60
+ }
61
+ return 'https://secure.chase.com/web/auth/dashboard#/dashboard/singleDoor/singleDoorController/index';
62
+ },
63
+ },
64
+ bank_of_america: {
65
+ paymentMethod: 1,
66
+ key: subProviders.BANK_OF_AMERICA,
67
+ name: 'Bank of America',
68
+ icon: 'simple-icons:bankofamerica',
69
+ verifiers: (chain) => getContracts(chain).zelleBoAReclaimVerifier,
70
+ sendLink: (opts) => {
71
+ if (opts.qrCode) {
72
+ return `https://www.bankofamerica.com/movemoney`;
73
+ }
74
+ return 'https://www.bankofamerica.com/';
75
+ },
76
+ },
77
+ citi: {
78
+ paymentMethod: 2,
79
+ key: subProviders.CITI,
80
+ name: 'Citi',
81
+ icon: 'arcticons:citi-mobile',
82
+ verifiers: (chain) => getContracts(chain).zelleCitiReclaimVerifier,
83
+ sendLink: (opts) => {
84
+ if (opts.qrCode) {
85
+ return defaultZelleSendLink(opts);
86
+ }
87
+ return 'https://online.citi.com/US/nga/zelle/transfer';
88
+ },
89
+ },
90
+ },
91
+ };
92
+ /** Payment method icon mappings */
93
+ export const providerConfigs = (chainId) => {
94
+ const contracts = getContracts(chainId);
95
+ return {
96
+ venmo: {
97
+ key: providers.VENMO,
98
+ icon: 'ion:logo-venmo',
99
+ name: 'Venmo',
100
+ usernameType: 'Venmo Username',
101
+ validationKey: providerKeyToValidationKey.venmo,
102
+ color: 'rgb(0, 116, 222)',
103
+ verifiers: contracts.venmoReclaimVerifier,
104
+ limits: {
105
+ min: 1.0,
106
+ },
107
+ subProviders: new Set(),
108
+ sendLink: (options) => {
109
+ if (options.qrCode) {
110
+ return `venmo://paycharge?txn=pay&recipients=${options.username}&note=cash&amount=${options.amount}`;
111
+ }
112
+ return `https://account.venmo.com/pay?recipients=${options.username}&note=cash&amount=${options.amount}`;
113
+ },
114
+ list: [
115
+ SUPPORTED_CURRENCIES.USD.contractId,
116
+ ],
117
+ },
118
+ zelle: {
119
+ key: providers.ZELLE,
120
+ icon: 'simple-icons:zelle',
121
+ name: 'Zelle',
122
+ color: '#6d1fd4',
123
+ usernameType: 'Zelle Email',
124
+ validationKey: providerKeyToValidationKey.zelle,
125
+ verifiers: contracts.zelleBaseVerifier,
126
+ limits: {
127
+ min: 1.0,
128
+ },
129
+ subProviders: new Set([
130
+ subProviderConfigs.zelle[subProviders.CHASE],
131
+ subProviderConfigs.zelle[subProviders.BANK_OF_AMERICA],
132
+ subProviderConfigs.zelle[subProviders.CITI],
133
+ ]),
134
+ // Delegate to sub-provider specific link when provided, otherwise fall back to generic QR URL
135
+ sendLink: (options) => {
136
+ if (options.subProvider) {
137
+ return subProviderConfigs.zelle[options.subProvider].sendLink(options);
138
+ }
139
+ return defaultZelleSendLink(options);
140
+ },
141
+ list: [
142
+ SUPPORTED_CURRENCIES.USD.contractId,
143
+ ],
144
+ },
145
+ cashapp: {
146
+ key: providers.CASHAPP,
147
+ icon: 'simple-icons:cashapp',
148
+ name: 'Cash App',
149
+ color: 'rgba(0,224,19,1.0)',
150
+ usernameType: 'CashTag',
151
+ validationKey: providerKeyToValidationKey.cashapp,
152
+ verifiers: contracts.cashappReclaimVerifier,
153
+ limits: {
154
+ min: 1.0,
155
+ },
156
+ subProviders: new Set(),
157
+ list: [
158
+ SUPPORTED_CURRENCIES.USD.contractId,
159
+ ],
160
+ sendLink: (options) => {
161
+ const u = options.username.startsWith('$') ? options.username : `$${options.username}`;
162
+ return `https://cash.app/qr/${u}?size=288&margin=0`;
163
+ },
164
+ },
165
+ revolut: {
166
+ key: providers.REVOLUT,
167
+ icon: 'simple-icons:revolut',
168
+ name: 'Revolut',
169
+ color: '#191c1f',
170
+ usernameType: 'RevTag',
171
+ validationKey: providerKeyToValidationKey.revolut,
172
+ verifiers: contracts.revolutReclaimVerifier,
173
+ limits: {
174
+ min: 1.0,
175
+ },
176
+ subProviders: new Set(),
177
+ sendLink: (options) => `https://revolut.me/${options.username}`,
178
+ list: [
179
+ SUPPORTED_CURRENCIES.USD.contractId,
180
+ SUPPORTED_CURRENCIES.EUR.contractId,
181
+ SUPPORTED_CURRENCIES.GBP.contractId,
182
+ SUPPORTED_CURRENCIES.AUD.contractId,
183
+ SUPPORTED_CURRENCIES.CAD.contractId,
184
+ SUPPORTED_CURRENCIES.HKD.contractId,
185
+ SUPPORTED_CURRENCIES.MXN.contractId,
186
+ SUPPORTED_CURRENCIES.NZD.contractId,
187
+ SUPPORTED_CURRENCIES.PLN.contractId,
188
+ SUPPORTED_CURRENCIES.SAR.contractId,
189
+ SUPPORTED_CURRENCIES.SGD.contractId,
190
+ SUPPORTED_CURRENCIES.ZAR.contractId,
191
+ SUPPORTED_CURRENCIES.CHF.contractId,
192
+ SUPPORTED_CURRENCIES.THB.contractId,
193
+ SUPPORTED_CURRENCIES.TRY.contractId,
194
+ SUPPORTED_CURRENCIES.AED.contractId,
195
+ ],
196
+ },
197
+ wise: {
198
+ key: providers.WISE,
199
+ icon: 'simple-icons:wise',
200
+ name: 'Wise',
201
+ color: '#9fe870',
202
+ usernameType: 'WiseTag',
203
+ validationKey: providerKeyToValidationKey.wise,
204
+ verifiers: contracts.wiseReclaimVerifier,
205
+ limits: {
206
+ min: 1.0,
207
+ },
208
+ subProviders: new Set(),
209
+ sendLink: (options) => `https://wise.com/pay/me/${options.username}`,
210
+ list: [
211
+ SUPPORTED_CURRENCIES.USD.contractId,
212
+ SUPPORTED_CURRENCIES.EUR.contractId,
213
+ SUPPORTED_CURRENCIES.GBP.contractId,
214
+ SUPPORTED_CURRENCIES.AUD.contractId,
215
+ SUPPORTED_CURRENCIES.CAD.contractId,
216
+ SUPPORTED_CURRENCIES.CNY.contractId,
217
+ SUPPORTED_CURRENCIES.HKD.contractId,
218
+ SUPPORTED_CURRENCIES.IDR.contractId,
219
+ SUPPORTED_CURRENCIES.ILS.contractId,
220
+ SUPPORTED_CURRENCIES.JPY.contractId,
221
+ SUPPORTED_CURRENCIES.KES.contractId,
222
+ SUPPORTED_CURRENCIES.MYR.contractId,
223
+ SUPPORTED_CURRENCIES.MXN.contractId,
224
+ SUPPORTED_CURRENCIES.NZD.contractId,
225
+ SUPPORTED_CURRENCIES.PLN.contractId,
226
+ SUPPORTED_CURRENCIES.SGD.contractId,
227
+ SUPPORTED_CURRENCIES.ZAR.contractId,
228
+ SUPPORTED_CURRENCIES.CHF.contractId,
229
+ SUPPORTED_CURRENCIES.THB.contractId,
230
+ SUPPORTED_CURRENCIES.TRY.contractId,
231
+ SUPPORTED_CURRENCIES.UGX.contractId,
232
+ SUPPORTED_CURRENCIES.AED.contractId,
233
+ SUPPORTED_CURRENCIES.VND.contractId,
234
+ ],
235
+ },
236
+ mercadopago: {
237
+ key: providers.MERCADOPAGO,
238
+ icon: 'simple-icons:mercadopago',
239
+ name: 'Mercado Pago',
240
+ usernameType: 'Mercado Pago / Bank CVU',
241
+ color: '#ffe600',
242
+ validationKey: providerKeyToValidationKey.mercadopago,
243
+ verifiers: contracts.mercadopagoReclaimVerifier,
244
+ limits: {
245
+ min: 1.0,
246
+ },
247
+ subProviders: new Set(),
248
+ sendLink: () => `https://www.mercadopago.com.ar/money-out/transfer/`,
249
+ list: [
250
+ SUPPORTED_CURRENCIES.ARS.contractId,
251
+ ],
252
+ },
253
+ paypal: {
254
+ key: providers.PAYPAL,
255
+ icon: 'simple-icons:paypal',
256
+ name: 'PayPal',
257
+ usernameType: 'PayPal Email',
258
+ validationKey: providerKeyToValidationKey.paypal,
259
+ verifiers: contracts.paypalReclaimVerifier,
260
+ limits: {
261
+ min: 1.0,
262
+ },
263
+ subProviders: new Set(),
264
+ color: '#0070BA',
265
+ sendLink: (options) => {
266
+ if (options.qrCode) {
267
+ return `paypal://`;
268
+ }
269
+ return `https://www.paypal.com/myaccount/transfer/homepage`;
270
+ },
271
+ list: [
272
+ SUPPORTED_CURRENCIES.USD.contractId,
273
+ SUPPORTED_CURRENCIES.EUR.contractId,
274
+ SUPPORTED_CURRENCIES.GBP.contractId,
275
+ SUPPORTED_CURRENCIES.AUD.contractId,
276
+ SUPPORTED_CURRENCIES.NZD.contractId,
277
+ SUPPORTED_CURRENCIES.CAD.contractId,
278
+ SUPPORTED_CURRENCIES.SGD.contractId,
279
+ ],
280
+ },
281
+ monzo: {
282
+ key: providers.MONZO,
283
+ icon: 'simple-icons:monzo',
284
+ name: 'Monzo',
285
+ usernameType: 'Monzo Me Username',
286
+ validationKey: providerKeyToValidationKey.monzo,
287
+ verifiers: contracts.monzoReclaimVerifier,
288
+ limits: {
289
+ min: 1.0,
290
+ },
291
+ subProviders: new Set(),
292
+ sendLink: (options) => `https://monzo.me/${options.username}`,
293
+ list: [
294
+ SUPPORTED_CURRENCIES.GBP.contractId,
295
+ ],
296
+ color: '#FC427B',
297
+ },
298
+ manual: {
299
+ key: providers.MANUAL,
300
+ icon: 'mdi:help-circle',
301
+ name: 'Manual Release',
302
+ color: 'gray',
303
+ usernameType: '',
304
+ validationKey: null,
305
+ verifiers: [zeroAddress],
306
+ limits: {
307
+ min: 0.0,
308
+ },
309
+ subProviders: new Set(),
310
+ list: [],
311
+ },
312
+ };
313
+ };
314
+ /** Payment verifier to key map */
315
+ export const paymentVerifierToKey = (chainId) => (new Map(Object.values(chainId ? [chainId] : [...contractsByChainId.keys()]).flatMap(chainId => (Object.values(providerConfigs(chainId)).flatMap(config => {
316
+ return config.verifiers.map(verifier => [getAddress(verifier), config.key]);
317
+ })))));
318
+ /** Provider key to verifiers map */
319
+ export const providerKeyToVerifiersMap = (chainId) => (new Map(Object.entries(providerConfigs(chainId)).map(([key, config]) => [key, config.verifiers])));
320
+ /** Provider key to verifiers */
321
+ export const providerKeyToVerifiers = (chainId, providerKey) => {
322
+ return providerKeyToVerifiersMap(chainId).get(providerKey) ?? null;
323
+ };
324
+ /** Verifier gets key */
325
+ export const verifierGetsKey = (chainId, verifierAddress) => {
326
+ try {
327
+ return paymentVerifierToKey(chainId).get(getAddress(verifierAddress)) ?? providers.MANUAL;
328
+ }
329
+ catch (error) {
330
+ return providers.MANUAL;
331
+ }
332
+ };
333
+ /**
334
+ * Utility function to get payment method icon
335
+ * @param key - The provider key
336
+ * @returns The icon string used for iconify
337
+ */
338
+ export const getPaymentIcon = (chainId, key) => {
339
+ const config = providerConfigs(chainId ?? pulsechain.id);
340
+ return config[key]?.icon || config[providers.MANUAL].icon;
341
+ };
342
+ /**
343
+ * Utility function to get payment method configuration by verifier address
344
+ * @param verifierAddress - The verifier address
345
+ * @returns The payment method configuration
346
+ */
347
+ export const getPaymentMethodConfig = (chainId, verifierAddress) => {
348
+ return (chainId ? [chainId] : [...contractsByChainId.keys()]).reduce((result, chainId) => (result ?? Object.values(providerConfigs(chainId)).reduce((r, config) => (r ?? (config.verifiers.includes(getAddress(verifierAddress)) ? config : null)), result)), null);
349
+ };
350
+ /**
351
+ * Utility function to get payment method minimum limit by verifier address
352
+ * @param key - The provider key
353
+ * @returns The minimum limit
354
+ */
355
+ export const getPaymentMethodMinimum = (chainId, key) => {
356
+ const config = providerConfigs(chainId ?? base.id)[key];
357
+ return config?.limits?.min ?? 0;
358
+ };
359
+ /**
360
+ * Utility function to get payment method name by verifier address
361
+ */
362
+ export const getPaymentMethodName = (chainId, verifierAddress) => {
363
+ const providerKey = verifierAddress;
364
+ const providerConfig = providerConfigs(chainId ?? base.id)[providerKey];
365
+ if (providerConfig) {
366
+ return providerConfig.name;
367
+ }
368
+ const config = providerConfigs(chainId ?? base.id)[verifierAddress] ?? getPaymentMethodConfig(chainId ?? base.id, verifierAddress);
369
+ return config?.name || 'Unknown';
370
+ };
371
+ /**
372
+ * Calculate effective minimum amount (higher of user minimum or payment provider minimum)
373
+ * @param userMinAmountWei - The user minimum amount
374
+ * @param tokenInfo - The token info
375
+ * @param providerRates - The provider rates
376
+ * @returns The effective minimum amount
377
+ */
378
+ export function calculateEffectiveMinimum(chainId, userMinAmountWei, tokenInfo, providerRates) {
379
+ const userMinAmountWeiBigInt = BigInt(userMinAmountWei);
380
+ let providerMinAmountWei = 0n;
381
+ if (providerRates) {
382
+ // Get unique payment providers from the rates
383
+ const paymentProviders = new Set();
384
+ for (const [providerKey] of providerRates.entries()) {
385
+ paymentProviders.add(providerKey);
386
+ }
387
+ // Calculate the highest provider minimum limit
388
+ for (const providerKey of paymentProviders) {
389
+ const providerConfig = providerConfigs(chainId)[providerKey];
390
+ if (providerConfig?.limits?.min) {
391
+ const providerMinWei = parseUnits(providerConfig.limits.min.toString(), tokenInfo.decimals);
392
+ if (providerMinWei > providerMinAmountWei) {
393
+ providerMinAmountWei = providerMinWei;
394
+ }
395
+ }
396
+ }
397
+ }
398
+ const effectiveMinAmountWei = userMinAmountWeiBigInt > providerMinAmountWei
399
+ ? userMinAmountWeiBigInt
400
+ : providerMinAmountWei;
401
+ const formattedEffectiveMin = formatUnits(effectiveMinAmountWei, { decimals: tokenInfo.decimals });
402
+ return {
403
+ userMinAmountWei: userMinAmountWeiBigInt,
404
+ providerMinAmountWei,
405
+ effectiveMinAmountWei,
406
+ formattedEffectiveMin
407
+ };
408
+ }
409
+ /**
410
+ * Helper function to get payment provider minimum limit (returns decimal number for config)
411
+ * @param key - The provider key
412
+ * @returns The minimum limit
413
+ */
414
+ export function getPaymentProviderMinimum(chainId, key) {
415
+ return getPaymentMethodMinimum(chainId, key) ?? 0;
416
+ }
417
+ /**
418
+ * Check if a payment method is known
419
+ * @param chainId - The chain ID
420
+ * @param verifierAddress - The verifier address
421
+ * @returns True if the payment method is known, false otherwise
422
+ */
423
+ export const isPaymentMethodKnown = (chainId, verifierAddress) => {
424
+ return !!getPaymentMethodConfig(chainId, verifierAddress);
425
+ };
426
+ /**
427
+ * Get all payment methods
428
+ * @returns All payment methods
429
+ */
430
+ export const getAllPaymentMethods = (chainId) => {
431
+ return Object.keys(providerConfigs(chainId));
432
+ };
433
+ /**
434
+ * Get all verifiable payment methods
435
+ * @returns All verifiable payment methods
436
+ */
437
+ export const verifiablePaymentMethods = (chainId) => {
438
+ return getAllPaymentMethods(chainId).filter(key => key !== providers.MANUAL);
439
+ };
@@ -0,0 +1,28 @@
1
+ import type { ChainId } from "./chain.js";
2
+ /** BigIntish type */
3
+ export type BigIntish = string | bigint | number;
4
+ /** Profit calculation input */
5
+ export interface ProfitCalculationInput {
6
+ amount: BigIntish;
7
+ chainId: ChainId;
8
+ conversionRate: {
9
+ value: BigIntish;
10
+ currency: string;
11
+ };
12
+ }
13
+ /**
14
+ * Calculate the profit of an intent fulfilled event
15
+ * @param param0.amount - The amount
16
+ * @param param0.conversionRate - The conversion rate
17
+ * @returns The profit
18
+ */
19
+ export declare const calculateProfit: ({ amount: amountInput, conversionRate, chainId, }: ProfitCalculationInput) => bigint | null;
20
+ /**
21
+ * Calculate the profits for a list of inputs
22
+ * @param inputs - The inputs to calculate the profits for a series of intents
23
+ * @returns The profits
24
+ */
25
+ export declare const calculateProfits: (inputs: ProfitCalculationInput[]) => {
26
+ profit: bigint;
27
+ nullAmounts: number;
28
+ };
@@ -0,0 +1,34 @@
1
+ import { getCurrencyByContractId } from "./currencies.js";
2
+ import { getDefaultToken } from "./tokens.js";
3
+ /**
4
+ * Calculate the profit of an intent fulfilled event
5
+ * @param param0.amount - The amount
6
+ * @param param0.conversionRate - The conversion rate
7
+ * @returns The profit
8
+ */
9
+ export const calculateProfit = ({ amount: amountInput, conversionRate, chainId, }) => {
10
+ const rate = BigInt(conversionRate.value);
11
+ const amount = BigInt(amountInput);
12
+ const valueReceived = amount * rate / 10n ** 18n;
13
+ const currency = getCurrencyByContractId(conversionRate.currency);
14
+ const inputTokenInfo = getDefaultToken(chainId);
15
+ const isOneForOne = currency.ticker === 'USD';
16
+ if (inputTokenInfo && isOneForOne) {
17
+ return valueReceived - amount;
18
+ }
19
+ return null;
20
+ };
21
+ /**
22
+ * Calculate the profits for a list of inputs
23
+ * @param inputs - The inputs to calculate the profits for a series of intents
24
+ * @returns The profits
25
+ */
26
+ export const calculateProfits = (inputs) => {
27
+ const profitAmounts = inputs.map(calculateProfit);
28
+ const nullAmounts = profitAmounts.filter((amount) => amount === null).length;
29
+ const profit = profitAmounts.reduce((acc, curr) => !!curr ? acc + curr : acc, 0n);
30
+ return {
31
+ profit,
32
+ nullAmounts,
33
+ };
34
+ };
@@ -0,0 +1,36 @@
1
+ export type SortDirection = 'asc' | 'desc';
2
+ export type Sortable = string | number | bigint;
3
+ /**
4
+ * Ordered sort
5
+ * @param aVal - The first value
6
+ * @param bVal - The second value
7
+ * @param orderDirection - The order direction
8
+ * @returns The sorted value
9
+ */
10
+ export declare const orderedSort: (aVal: Sortable, bVal: Sortable, orderDirection: SortDirection) => number;
11
+ /**
12
+ * Ordered sort then by deposit ID
13
+ * @param param0 - The parameters
14
+ * @returns The sorted value
15
+ */
16
+ export declare const orderedSortThenById: ({ aVal, bVal, orderDirection, a, b, }: {
17
+ aVal: Sortable;
18
+ bVal: Sortable;
19
+ orderDirection: SortDirection;
20
+ a: {
21
+ depositId: bigint;
22
+ transaction: {
23
+ block: {
24
+ timestamp: string;
25
+ };
26
+ };
27
+ };
28
+ b: {
29
+ depositId: bigint;
30
+ transaction: {
31
+ block: {
32
+ timestamp: string;
33
+ };
34
+ };
35
+ };
36
+ }) => number;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Ordered sort
3
+ * @param aVal - The first value
4
+ * @param bVal - The second value
5
+ * @param orderDirection - The order direction
6
+ * @returns The sorted value
7
+ */
8
+ export const orderedSort = (aVal, bVal, orderDirection) => {
9
+ if (typeof aVal === 'bigint' && typeof bVal === 'bigint') {
10
+ const compareResult = aVal < bVal ? -1 : aVal > bVal ? 1 : 0;
11
+ return orderDirection === 'asc' ? compareResult : -compareResult;
12
+ }
13
+ else if (typeof aVal === 'string' && typeof bVal === 'string') {
14
+ const compareResult = aVal.localeCompare(bVal);
15
+ return orderDirection === 'asc' ? compareResult : -compareResult;
16
+ }
17
+ else if (typeof aVal === 'number' && typeof bVal === 'number') {
18
+ const compareResult = aVal - bVal;
19
+ return orderDirection === 'asc' ? compareResult : -compareResult;
20
+ }
21
+ else {
22
+ const compareResult = String(aVal).localeCompare(String(bVal));
23
+ return orderDirection === 'asc' ? compareResult : -compareResult;
24
+ }
25
+ };
26
+ /**
27
+ * Ordered sort then by deposit ID
28
+ * @param param0 - The parameters
29
+ * @returns The sorted value
30
+ */
31
+ export const orderedSortThenById = ({ aVal, bVal, orderDirection, a, b, }) => {
32
+ let result = orderedSort(aVal, bVal, orderDirection);
33
+ if (result !== 0)
34
+ return result;
35
+ result = orderedSort(BigInt(a.transaction.block.timestamp), BigInt(b.transaction.block.timestamp), 'asc');
36
+ if (result !== 0)
37
+ return result;
38
+ return orderedSort(a.depositId, b.depositId, 'asc');
39
+ };
@@ -0,0 +1,7 @@
1
+ export declare const statAction: {
2
+ readonly deposit: "deposit";
3
+ readonly withdrawal: "withdrawal";
4
+ readonly exchange: "exchange";
5
+ };
6
+ export type StatAction = (typeof statAction)[keyof typeof statAction];
7
+ export declare const isStatAction: (action: string) => action is StatAction;
@@ -0,0 +1,8 @@
1
+ export const statAction = {
2
+ deposit: 'deposit',
3
+ withdrawal: 'withdrawal',
4
+ exchange: 'exchange',
5
+ };
6
+ export const isStatAction = (action) => {
7
+ return action in statAction;
8
+ };
@@ -0,0 +1,54 @@
1
+ /** Interval in milliseconds */
2
+ export declare const intervalIn: {
3
+ readonly yearInDays: 365;
4
+ readonly quarterInMonths: 3;
5
+ readonly monthInDays: 30;
6
+ readonly hourInDays: 24;
7
+ readonly daysInWeek: 7;
8
+ readonly minuteInHours: 60;
9
+ readonly secondInMinutes: 60;
10
+ readonly millisecondInSecond: 1000;
11
+ };
12
+ /** Intervals in milliseconds */
13
+ export declare const interval: {
14
+ readonly second: 1000;
15
+ readonly minute: number;
16
+ readonly hour: number;
17
+ readonly day: number;
18
+ readonly month: number;
19
+ readonly year: number;
20
+ };
21
+ /** Default display intervals */
22
+ export declare const defaultDisplayInterval: {
23
+ readonly hour: number;
24
+ readonly day: number;
25
+ readonly month: 60;
26
+ };
27
+ /**
28
+ * Format a timestamp
29
+ * @param timestamp - The timestamp to format
30
+ * @param param1.anchor - The anchor date
31
+ * @param param1.showSeconds - Whether to show seconds
32
+ * @returns The formatted timestamp
33
+ */
34
+ export declare const formatTimestamp: (timestamp: number | Date | string, { anchor, showSeconds, }?: {
35
+ anchor?: Date;
36
+ showSeconds?: boolean;
37
+ }) => string;
38
+ /**
39
+ * Format a duration
40
+ * @param param0.start - The start date
41
+ * @param param0.until - The end date
42
+ * @returns The formatted duration
43
+ */
44
+ export declare const formatDuration: ({ start, until, }?: {
45
+ start?: Date;
46
+ until?: Date;
47
+ }) => string;
48
+ /**
49
+ * Sleep for a given number of milliseconds
50
+ * @param ms - The number of milliseconds to sleep
51
+ * @returns A promise that resolves after the given number of milliseconds
52
+ */
53
+ export declare const sleep: (ms: number) => Promise<unknown>;
54
+ export type TimeResolutionKey = "hour" | "day" | "month";