@metamask/transaction-controller 46.0.0 → 47.0.0
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.
- package/CHANGELOG.md +31 -1
- package/dist/TransactionController.cjs +121 -40
- package/dist/TransactionController.cjs.map +1 -1
- package/dist/TransactionController.d.cts +81 -72
- package/dist/TransactionController.d.cts.map +1 -1
- package/dist/TransactionController.d.mts +81 -72
- package/dist/TransactionController.d.mts.map +1 -1
- package/dist/TransactionController.mjs +122 -41
- package/dist/TransactionController.mjs.map +1 -1
- package/dist/api/accounts-api.cjs +2 -0
- package/dist/api/accounts-api.cjs.map +1 -1
- package/dist/api/accounts-api.d.cts +2 -0
- package/dist/api/accounts-api.d.cts.map +1 -1
- package/dist/api/accounts-api.d.mts +2 -0
- package/dist/api/accounts-api.d.mts.map +1 -1
- package/dist/api/accounts-api.mjs +2 -0
- package/dist/api/accounts-api.mjs.map +1 -1
- package/dist/constants.cjs +20 -1
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +15 -0
- package/dist/constants.d.cts.map +1 -1
- package/dist/constants.d.mts +15 -0
- package/dist/constants.d.mts.map +1 -1
- package/dist/constants.mjs +19 -0
- package/dist/constants.mjs.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.cjs +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.mjs +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs +1 -1
- package/dist/gas-flows/OptimismLayer1GasFeeFlow.mjs.map +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.cjs +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.cjs.map +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.cts +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.cts.map +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.mts +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.d.mts.map +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.mjs +1 -1
- package/dist/gas-flows/ScrollLayer1GasFeeFlow.mjs.map +1 -1
- package/dist/helpers/GasFeePoller.cjs +1 -0
- package/dist/helpers/GasFeePoller.cjs.map +1 -1
- package/dist/helpers/GasFeePoller.d.cts +1 -0
- package/dist/helpers/GasFeePoller.d.cts.map +1 -1
- package/dist/helpers/GasFeePoller.d.mts +1 -0
- package/dist/helpers/GasFeePoller.d.mts.map +1 -1
- package/dist/helpers/GasFeePoller.mjs +1 -0
- package/dist/helpers/GasFeePoller.mjs.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.cjs.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.d.cts.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.d.mts.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -1
- package/dist/helpers/MethodDataHelper.cjs.map +1 -1
- package/dist/helpers/MethodDataHelper.d.cts.map +1 -1
- package/dist/helpers/MethodDataHelper.d.mts.map +1 -1
- package/dist/helpers/MethodDataHelper.mjs.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.cjs +1 -21
- package/dist/helpers/MultichainTrackingHelper.cjs.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.d.cts.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.d.mts.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.mjs +1 -21
- package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -1
- package/dist/helpers/PendingTransactionTracker.cjs.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.cts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.d.mts.map +1 -1
- package/dist/helpers/PendingTransactionTracker.mjs.map +1 -1
- package/dist/helpers/TransactionPoller.cjs +2 -0
- package/dist/helpers/TransactionPoller.cjs.map +1 -1
- package/dist/helpers/TransactionPoller.d.cts +2 -0
- package/dist/helpers/TransactionPoller.d.cts.map +1 -1
- package/dist/helpers/TransactionPoller.d.mts +2 -0
- package/dist/helpers/TransactionPoller.d.mts.map +1 -1
- package/dist/helpers/TransactionPoller.mjs +2 -0
- package/dist/helpers/TransactionPoller.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs +5 -0
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +51 -0
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +51 -0
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs +5 -0
- package/dist/types.mjs.map +1 -1
- package/dist/utils/batch.cjs +89 -0
- package/dist/utils/batch.cjs.map +1 -0
- package/dist/utils/batch.d.cts +33 -0
- package/dist/utils/batch.d.cts.map +1 -0
- package/dist/utils/batch.d.mts +33 -0
- package/dist/utils/batch.d.mts.map +1 -0
- package/dist/utils/batch.mjs +84 -0
- package/dist/utils/batch.mjs.map +1 -0
- package/dist/utils/eip7702.cjs +84 -2
- package/dist/utils/eip7702.cjs.map +1 -1
- package/dist/utils/eip7702.d.cts +35 -10
- package/dist/utils/eip7702.d.cts.map +1 -1
- package/dist/utils/eip7702.d.mts +35 -10
- package/dist/utils/eip7702.d.mts.map +1 -1
- package/dist/utils/eip7702.mjs +82 -3
- package/dist/utils/eip7702.mjs.map +1 -1
- package/dist/utils/feature-flags.cjs +53 -0
- package/dist/utils/feature-flags.cjs.map +1 -0
- package/dist/utils/feature-flags.d.cts +39 -0
- package/dist/utils/feature-flags.d.cts.map +1 -0
- package/dist/utils/feature-flags.d.mts +39 -0
- package/dist/utils/feature-flags.d.mts.map +1 -0
- package/dist/utils/feature-flags.mjs +47 -0
- package/dist/utils/feature-flags.mjs.map +1 -0
- package/dist/utils/gas-fees.cjs +48 -3
- package/dist/utils/gas-fees.cjs.map +1 -1
- package/dist/utils/gas-fees.d.cts +11 -0
- package/dist/utils/gas-fees.d.cts.map +1 -1
- package/dist/utils/gas-fees.d.mts +11 -0
- package/dist/utils/gas-fees.d.mts.map +1 -1
- package/dist/utils/gas-fees.mjs +48 -3
- package/dist/utils/gas-fees.mjs.map +1 -1
- package/dist/utils/gas-flow.cjs +4 -0
- package/dist/utils/gas-flow.cjs.map +1 -1
- package/dist/utils/gas-flow.d.cts +1 -0
- package/dist/utils/gas-flow.d.cts.map +1 -1
- package/dist/utils/gas-flow.d.mts +1 -0
- package/dist/utils/gas-flow.d.mts.map +1 -1
- package/dist/utils/gas-flow.mjs +4 -0
- package/dist/utils/gas-flow.mjs.map +1 -1
- package/dist/utils/gas.cjs +50 -1
- package/dist/utils/gas.cjs.map +1 -1
- package/dist/utils/gas.d.cts +22 -0
- package/dist/utils/gas.d.cts.map +1 -1
- package/dist/utils/gas.d.mts +22 -0
- package/dist/utils/gas.d.mts.map +1 -1
- package/dist/utils/gas.mjs +50 -1
- package/dist/utils/gas.mjs.map +1 -1
- package/dist/utils/layer1-gas-fee-flow.cjs +5 -1
- package/dist/utils/layer1-gas-fee-flow.cjs.map +1 -1
- package/dist/utils/layer1-gas-fee-flow.d.cts +4 -1
- package/dist/utils/layer1-gas-fee-flow.d.cts.map +1 -1
- package/dist/utils/layer1-gas-fee-flow.d.mts +4 -1
- package/dist/utils/layer1-gas-fee-flow.d.mts.map +1 -1
- package/dist/utils/layer1-gas-fee-flow.mjs +5 -1
- package/dist/utils/layer1-gas-fee-flow.mjs.map +1 -1
- package/dist/utils/retry.cjs +4 -0
- package/dist/utils/retry.cjs.map +1 -1
- package/dist/utils/retry.d.cts +1 -0
- package/dist/utils/retry.d.cts.map +1 -1
- package/dist/utils/retry.d.mts +1 -0
- package/dist/utils/retry.d.mts.map +1 -1
- package/dist/utils/retry.mjs +4 -0
- package/dist/utils/retry.mjs.map +1 -1
- package/dist/utils/simulation-api.cjs +6 -0
- package/dist/utils/simulation-api.cjs.map +1 -1
- package/dist/utils/simulation-api.d.cts +2 -0
- package/dist/utils/simulation-api.d.cts.map +1 -1
- package/dist/utils/simulation-api.d.mts +2 -0
- package/dist/utils/simulation-api.d.mts.map +1 -1
- package/dist/utils/simulation-api.mjs +6 -0
- package/dist/utils/simulation-api.mjs.map +1 -1
- package/dist/utils/simulation.cjs +19 -5
- package/dist/utils/simulation.cjs.map +1 -1
- package/dist/utils/simulation.d.cts +3 -1
- package/dist/utils/simulation.d.cts.map +1 -1
- package/dist/utils/simulation.d.mts +3 -1
- package/dist/utils/simulation.d.mts.map +1 -1
- package/dist/utils/simulation.mjs +19 -5
- package/dist/utils/simulation.mjs.map +1 -1
- package/dist/utils/swaps.cjs +2 -1
- package/dist/utils/swaps.cjs.map +1 -1
- package/dist/utils/swaps.d.cts +1 -0
- package/dist/utils/swaps.d.cts.map +1 -1
- package/dist/utils/swaps.d.mts +1 -0
- package/dist/utils/swaps.d.mts.map +1 -1
- package/dist/utils/swaps.mjs +2 -1
- package/dist/utils/swaps.mjs.map +1 -1
- package/dist/utils/transaction-type.cjs +3 -1
- package/dist/utils/transaction-type.cjs.map +1 -1
- package/dist/utils/transaction-type.mjs +3 -1
- package/dist/utils/transaction-type.mjs.map +1 -1
- package/dist/utils/validation.cjs +34 -5
- package/dist/utils/validation.cjs.map +1 -1
- package/dist/utils/validation.d.cts +19 -3
- package/dist/utils/validation.d.cts.map +1 -1
- package/dist/utils/validation.d.mts +19 -3
- package/dist/utils/validation.d.mts.map +1 -1
- package/dist/utils/validation.mjs +33 -5
- package/dist/utils/validation.mjs.map +1 -1
- package/package.json +7 -5
|
@@ -2,21 +2,17 @@ import { Interface } from "@ethersproject/abi";
|
|
|
2
2
|
import { hexToBN, toHex } from "@metamask/controller-utils";
|
|
3
3
|
import { abiERC20, abiERC721, abiERC1155 } from "@metamask/metamask-eth-abis";
|
|
4
4
|
import { createModuleLogger } from "@metamask/utils";
|
|
5
|
+
import { simulateTransactions } from "./simulation-api.mjs";
|
|
5
6
|
import { ABI_SIMULATION_ERC20_WRAPPED, ABI_SIMULATION_ERC721_LEGACY } from "../constants.mjs";
|
|
6
7
|
import { SimulationError, SimulationInvalidResponseError, SimulationRevertedError } from "../errors.mjs";
|
|
7
8
|
import { projectLogger } from "../logger.mjs";
|
|
8
9
|
import { SimulationTokenStandard } from "../types.mjs";
|
|
9
|
-
import { simulateTransactions } from "./simulation-api.mjs";
|
|
10
10
|
export var SupportedToken;
|
|
11
11
|
(function (SupportedToken) {
|
|
12
12
|
SupportedToken["ERC20"] = "erc20";
|
|
13
13
|
SupportedToken["ERC721"] = "erc721";
|
|
14
14
|
SupportedToken["ERC1155"] = "erc1155";
|
|
15
|
-
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
16
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
17
15
|
SupportedToken["ERC20_WRAPPED"] = "erc20Wrapped";
|
|
18
|
-
// TODO: Either fix this lint violation or explain why it's necessary to ignore.
|
|
19
|
-
// eslint-disable-next-line @typescript-eslint/naming-convention
|
|
20
16
|
SupportedToken["ERC721_LEGACY"] = "erc721Legacy";
|
|
21
17
|
})(SupportedToken || (SupportedToken = {}));
|
|
22
18
|
const log = createModuleLogger(projectLogger, 'simulation');
|
|
@@ -52,6 +48,7 @@ const SUPPORTED_TOKEN_ABIS = {
|
|
|
52
48
|
const REVERTED_ERRORS = ['execution reverted', 'insufficient funds for gas'];
|
|
53
49
|
/**
|
|
54
50
|
* Generate simulation data for a transaction.
|
|
51
|
+
*
|
|
55
52
|
* @param request - The transaction to simulate.
|
|
56
53
|
* @param request.chainId - The chain ID of the transaction.
|
|
57
54
|
* @param request.from - The sender of the transaction.
|
|
@@ -117,6 +114,7 @@ export async function getSimulationData(request, options = {}) {
|
|
|
117
114
|
}
|
|
118
115
|
/**
|
|
119
116
|
* Extract the native balance change from a simulation response.
|
|
117
|
+
*
|
|
120
118
|
* @param userAddress - The user's account address.
|
|
121
119
|
* @param response - The simulation response.
|
|
122
120
|
* @returns The native balance change or undefined if unchanged.
|
|
@@ -137,6 +135,7 @@ function getNativeBalanceChange(userAddress, response) {
|
|
|
137
135
|
}
|
|
138
136
|
/**
|
|
139
137
|
* Extract events from a simulation response.
|
|
138
|
+
*
|
|
140
139
|
* @param response - The simulation response.
|
|
141
140
|
* @returns The parsed events.
|
|
142
141
|
*/
|
|
@@ -177,6 +176,7 @@ export function getEvents(response) {
|
|
|
177
176
|
}
|
|
178
177
|
/**
|
|
179
178
|
* Normalize event arguments using ABI input definitions.
|
|
179
|
+
*
|
|
180
180
|
* @param args - The raw event arguments.
|
|
181
181
|
* @param abiInputs - The ABI input definitions.
|
|
182
182
|
* @returns The normalized event arguments.
|
|
@@ -191,6 +191,7 @@ function normalizeEventArgs(args, abiInputs) {
|
|
|
191
191
|
}
|
|
192
192
|
/**
|
|
193
193
|
* Normalize an event argument value.
|
|
194
|
+
*
|
|
194
195
|
* @param value - The event argument value.
|
|
195
196
|
* @returns The normalized event argument value.
|
|
196
197
|
*/
|
|
@@ -206,6 +207,7 @@ function normalizeEventArgValue(value) {
|
|
|
206
207
|
}
|
|
207
208
|
/**
|
|
208
209
|
* Generate token balance changes from parsed events.
|
|
210
|
+
*
|
|
209
211
|
* @param request - The transaction that was simulated.
|
|
210
212
|
* @param events - The parsed events.
|
|
211
213
|
* @param options - Additional options.
|
|
@@ -259,6 +261,7 @@ async function getTokenBalanceChanges(request, events, options) {
|
|
|
259
261
|
}
|
|
260
262
|
/**
|
|
261
263
|
* Generate transactions to check token balances.
|
|
264
|
+
*
|
|
262
265
|
* @param request - The transaction that was simulated.
|
|
263
266
|
* @param events - The parsed events.
|
|
264
267
|
* @returns A map of token balance transactions keyed by token.
|
|
@@ -303,6 +306,7 @@ function getTokenBalanceTransactions(request, events) {
|
|
|
303
306
|
}
|
|
304
307
|
/**
|
|
305
308
|
* Check if an event needs to check the previous balance.
|
|
309
|
+
*
|
|
306
310
|
* @param event - The parsed event.
|
|
307
311
|
* @returns True if the prior balance check should be skipped.
|
|
308
312
|
*/
|
|
@@ -315,6 +319,7 @@ function skipPriorBalanceCheck(event) {
|
|
|
315
319
|
}
|
|
316
320
|
/**
|
|
317
321
|
* Extract token IDs from a parsed event.
|
|
322
|
+
*
|
|
318
323
|
* @param event - The parsed event.
|
|
319
324
|
* @returns An array of token IDs.
|
|
320
325
|
*/
|
|
@@ -335,6 +340,7 @@ function getEventTokenIds(event) {
|
|
|
335
340
|
}
|
|
336
341
|
/**
|
|
337
342
|
* Get the interface for a token standard.
|
|
343
|
+
*
|
|
338
344
|
* @param tokenStandard - The token standard.
|
|
339
345
|
* @returns The interface for the token standard.
|
|
340
346
|
*/
|
|
@@ -350,6 +356,7 @@ function getContractInterface(tokenStandard) {
|
|
|
350
356
|
}
|
|
351
357
|
/**
|
|
352
358
|
* Extract the value from a balance transaction response using the correct ABI.
|
|
359
|
+
*
|
|
353
360
|
* @param from - The address to check the balance of.
|
|
354
361
|
* @param token - The token to check the balance of.
|
|
355
362
|
* @param response - The balance transaction response.
|
|
@@ -373,6 +380,7 @@ function getAmountFromBalanceTransactionResult(from, token, response) {
|
|
|
373
380
|
}
|
|
374
381
|
/**
|
|
375
382
|
* Generate the balance transaction data for a token.
|
|
383
|
+
*
|
|
376
384
|
* @param tokenStandard - The token standard.
|
|
377
385
|
* @param from - The address to check the balance of.
|
|
378
386
|
* @param tokenId - The token ID to check the balance of.
|
|
@@ -391,6 +399,7 @@ function getBalanceTransactionData(tokenStandard, from, tokenId) {
|
|
|
391
399
|
}
|
|
392
400
|
/**
|
|
393
401
|
* Parse a raw event log using known ABIs.
|
|
402
|
+
*
|
|
394
403
|
* @param eventLog - The raw event log.
|
|
395
404
|
* @param interfaces - The contract interfaces.
|
|
396
405
|
* @returns The parsed event log or undefined if it could not be parsed.
|
|
@@ -406,6 +415,8 @@ function parseLog(eventLog, interfaces) {
|
|
|
406
415
|
abi,
|
|
407
416
|
standard,
|
|
408
417
|
};
|
|
418
|
+
// Not used
|
|
419
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
409
420
|
}
|
|
410
421
|
catch (e) {
|
|
411
422
|
continue;
|
|
@@ -415,6 +426,7 @@ function parseLog(eventLog, interfaces) {
|
|
|
415
426
|
}
|
|
416
427
|
/**
|
|
417
428
|
* Extract all logs from a call trace tree.
|
|
429
|
+
*
|
|
418
430
|
* @param call - The root call trace.
|
|
419
431
|
* @returns An array of logs.
|
|
420
432
|
*/
|
|
@@ -430,6 +442,7 @@ function extractLogs(call) {
|
|
|
430
442
|
}
|
|
431
443
|
/**
|
|
432
444
|
* Generate balance change data from previous and new balances.
|
|
445
|
+
*
|
|
433
446
|
* @param previousBalance - The previous balance.
|
|
434
447
|
* @param newBalance - The new balance.
|
|
435
448
|
* @returns The balance change data or undefined if unchanged.
|
|
@@ -451,6 +464,7 @@ function getSimulationBalanceChange(previousBalance, newBalance) {
|
|
|
451
464
|
}
|
|
452
465
|
/**
|
|
453
466
|
* Get the contract interfaces for all supported tokens.
|
|
467
|
+
*
|
|
454
468
|
* @returns A map of supported tokens to their contract interfaces.
|
|
455
469
|
*/
|
|
456
470
|
function getContractInterfaces() {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation.mjs","sourceRoot":"","sources":["../../src/utils/simulation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS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AiB,GAAG,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC;QAC7C,OAAO,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;IACxC,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import type { Fragment, LogDescription, Result } from '@ethersproject/abi';\nimport { Interface } from '@ethersproject/abi';\nimport { hexToBN, toHex } from '@metamask/controller-utils';\nimport { abiERC20, abiERC721, abiERC1155 } from '@metamask/metamask-eth-abis';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport {\n ABI_SIMULATION_ERC20_WRAPPED,\n ABI_SIMULATION_ERC721_LEGACY,\n} from '../constants';\nimport {\n SimulationError,\n SimulationInvalidResponseError,\n SimulationRevertedError,\n} from '../errors';\nimport { projectLogger } from '../logger';\nimport type {\n SimulationBalanceChange,\n SimulationData,\n SimulationTokenBalanceChange,\n SimulationToken,\n} from '../types';\nimport { SimulationTokenStandard } from '../types';\nimport { simulateTransactions } from './simulation-api';\nimport type {\n SimulationResponseLog,\n SimulationRequestTransaction,\n SimulationResponse,\n SimulationResponseCallTrace,\n SimulationResponseTransaction,\n} from './simulation-api';\n\nexport enum SupportedToken {\n ERC20 = 'erc20',\n ERC721 = 'erc721',\n ERC1155 = 'erc1155',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ERC20_WRAPPED = 'erc20Wrapped',\n // TODO: Either fix this lint violation or explain why it's necessary to ignore.\n // eslint-disable-next-line @typescript-eslint/naming-convention\n ERC721_LEGACY = 'erc721Legacy',\n}\n\ntype ABI = Fragment[];\n\nexport type GetSimulationDataRequest = {\n chainId: Hex;\n data?: Hex;\n from: Hex;\n to?: Hex;\n value?: Hex;\n};\n\ntype ParsedEvent = {\n contractAddress: Hex;\n tokenStandard: SimulationTokenStandard;\n name: string;\n args: Record<string, Hex | Hex[]>;\n abi: ABI;\n};\n\ntype GetSimulationDataOptions = {\n blockTime?: number;\n};\n\nconst log = createModuleLogger(projectLogger, 'simulation');\n\nconst SUPPORTED_EVENTS = [\n 'Transfer',\n 'TransferSingle',\n 'TransferBatch',\n 'Deposit',\n 'Withdrawal',\n];\n\nconst SUPPORTED_TOKEN_ABIS = {\n [SupportedToken.ERC20]: {\n abi: abiERC20,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721]: {\n abi: abiERC721,\n standard: SimulationTokenStandard.erc721,\n },\n [SupportedToken.ERC1155]: {\n abi: abiERC1155,\n standard: SimulationTokenStandard.erc1155,\n },\n [SupportedToken.ERC20_WRAPPED]: {\n abi: ABI_SIMULATION_ERC20_WRAPPED,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721_LEGACY]: {\n abi: ABI_SIMULATION_ERC721_LEGACY,\n standard: SimulationTokenStandard.erc721,\n },\n};\n\nconst REVERTED_ERRORS = ['execution reverted', 'insufficient funds for gas'];\n\ntype BalanceTransactionMap = Map<SimulationToken, SimulationRequestTransaction>;\n\n/**\n * Generate simulation data for a transaction.\n * @param request - The transaction to simulate.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.from - The sender of the transaction.\n * @param request.to - The recipient of the transaction.\n * @param request.value - The value of the transaction.\n * @param request.data - The data of the transaction.\n * @param options - Additional options.\n * @param options.blockTime - An optional block time to simulate the transaction at.\n * @returns The simulation data.\n */\nexport async function getSimulationData(\n request: GetSimulationDataRequest,\n options: GetSimulationDataOptions = {},\n): Promise<SimulationData> {\n const { chainId, from, to, value, data } = request;\n const { blockTime } = options;\n\n log('Getting simulation data', request);\n\n try {\n const response = await simulateTransactions(chainId, {\n transactions: [\n {\n data,\n from,\n maxFeePerGas: '0x0',\n maxPriorityFeePerGas: '0x0',\n to,\n value,\n },\n ],\n withCallTrace: true,\n withLogs: true,\n ...(blockTime && {\n blockOverrides: {\n time: toHex(blockTime),\n },\n }),\n });\n\n const transactionError = response.transactions?.[0]?.error;\n\n if (transactionError) {\n throw new SimulationError(transactionError);\n }\n\n const nativeBalanceChange = getNativeBalanceChange(request.from, response);\n const events = getEvents(response);\n\n log('Parsed events', events);\n\n const tokenBalanceChanges = await getTokenBalanceChanges(\n request,\n events,\n options,\n );\n\n return {\n nativeBalanceChange,\n tokenBalanceChanges,\n };\n } catch (error) {\n log('Failed to get simulation data', error, request);\n\n let simulationError = error as SimulationError;\n\n if (\n REVERTED_ERRORS.some((revertErrorMessage) =>\n simulationError.message?.includes(revertErrorMessage),\n )\n ) {\n simulationError = new SimulationRevertedError();\n }\n\n const { code, message } = simulationError;\n\n return {\n tokenBalanceChanges: [],\n error: {\n code,\n message,\n },\n };\n }\n}\n\n/**\n * Extract the native balance change from a simulation response.\n * @param userAddress - The user's account address.\n * @param response - The simulation response.\n * @returns The native balance change or undefined if unchanged.\n */\nfunction getNativeBalanceChange(\n userAddress: Hex,\n response: SimulationResponse,\n): SimulationBalanceChange | undefined {\n const transactionResponse = response.transactions[0];\n\n /* istanbul ignore next */\n if (!transactionResponse) {\n return undefined;\n }\n\n const { stateDiff } = transactionResponse;\n const previousBalance = stateDiff?.pre?.[userAddress]?.balance;\n const newBalance = stateDiff?.post?.[userAddress]?.balance;\n\n if (!previousBalance || !newBalance) {\n return undefined;\n }\n\n return getSimulationBalanceChange(previousBalance, newBalance);\n}\n\n/**\n * Extract events from a simulation response.\n * @param response - The simulation response.\n * @returns The parsed events.\n */\nexport function getEvents(response: SimulationResponse): ParsedEvent[] {\n /* istanbul ignore next */\n const logs = extractLogs(\n response.transactions[0]?.callTrace ?? ({} as SimulationResponseCallTrace),\n );\n\n log('Extracted logs', logs);\n\n const interfaces = getContractInterfaces();\n\n return logs\n .map((currentLog) => {\n const event = parseLog(currentLog, interfaces);\n\n if (!event) {\n log('Failed to parse log', currentLog);\n return undefined;\n }\n\n /* istanbul ignore next */\n const inputs = event.abi.find((e) => e.name === event.name)?.inputs;\n\n /* istanbul ignore if */\n if (!inputs) {\n log('Failed to find inputs for event', event);\n return undefined;\n }\n\n if (!SUPPORTED_EVENTS.includes(event.name)) {\n log('Ignoring unsupported event', event.name, event);\n return undefined;\n }\n\n log('Normalizing event args', event.name, event);\n\n const args = normalizeEventArgs(event.args, inputs);\n\n return {\n contractAddress: currentLog.address,\n tokenStandard: event.standard,\n name: event.name,\n args,\n abi: event.abi,\n };\n })\n .filter((e) => e !== undefined) as ParsedEvent[];\n}\n\n/**\n * Normalize event arguments using ABI input definitions.\n * @param args - The raw event arguments.\n * @param abiInputs - The ABI input definitions.\n * @returns The normalized event arguments.\n */\nfunction normalizeEventArgs(\n args: Result,\n abiInputs: { name: string }[],\n): Record<string, Hex | Hex[]> {\n return args.reduce((result, arg, index) => {\n const name = abiInputs[index].name.replace('_', '');\n const value = normalizeEventArgValue(arg);\n\n result[name] = value;\n\n return result;\n }, {});\n}\n\n/**\n * Normalize an event argument value.\n * @param value - The event argument value.\n * @returns The normalized event argument value.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeEventArgValue(value: any): any {\n if (Array.isArray(value)) {\n return value.map(normalizeEventArgValue);\n }\n\n let normalizedValue = value;\n\n normalizedValue = normalizedValue.toHexString?.() ?? normalizedValue;\n normalizedValue = normalizedValue.toLowerCase?.() ?? normalizedValue;\n\n return normalizedValue;\n}\n\n/**\n * Generate token balance changes from parsed events.\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @param options - Additional options.\n * @param options.blockTime - An optional block time to simulate the transaction at.\n * @returns An array of token balance changes.\n */\nasync function getTokenBalanceChanges(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n options: GetSimulationDataOptions,\n): Promise<SimulationTokenBalanceChange[]> {\n const { blockTime } = options;\n const balanceTxs = getTokenBalanceTransactions(request, events);\n\n log('Generated balance transactions', [...balanceTxs.after.values()]);\n\n const transactions = [\n ...balanceTxs.before.values(),\n request,\n ...balanceTxs.after.values(),\n ];\n\n if (transactions.length === 1) {\n return [];\n }\n\n const response = await simulateTransactions(request.chainId as Hex, {\n transactions,\n ...(blockTime && {\n blockOverrides: {\n time: toHex(blockTime),\n },\n }),\n });\n\n log('Balance simulation response', response);\n\n if (response.transactions.length !== transactions.length) {\n throw new SimulationInvalidResponseError();\n }\n\n let prevBalanceTxIndex = 0;\n return [...balanceTxs.after.keys()]\n .map((token, index) => {\n const previousBalanceCheckSkipped = !balanceTxs.before.get(token);\n const previousBalance = previousBalanceCheckSkipped\n ? '0x0'\n : getAmountFromBalanceTransactionResult(\n request.from,\n token,\n // eslint-disable-next-line no-plusplus\n response.transactions[prevBalanceTxIndex++],\n );\n\n const newBalance = getAmountFromBalanceTransactionResult(\n request.from,\n token,\n response.transactions[index + balanceTxs.before.size + 1],\n );\n\n const balanceChange = getSimulationBalanceChange(\n previousBalance,\n newBalance,\n );\n\n if (!balanceChange) {\n return undefined;\n }\n\n return {\n ...token,\n ...balanceChange,\n };\n })\n .filter((change) => change !== undefined) as SimulationTokenBalanceChange[];\n}\n\n/**\n * Generate transactions to check token balances.\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @returns A map of token balance transactions keyed by token.\n */\nfunction getTokenBalanceTransactions(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n): {\n before: BalanceTransactionMap;\n after: BalanceTransactionMap;\n} {\n const tokenKeys = new Set();\n const before = new Map();\n const after = new Map();\n\n const userEvents = events.filter((event) =>\n [event.args.from, event.args.to].includes(request.from),\n );\n\n log('Filtered user events', userEvents);\n\n for (const event of userEvents) {\n const tokenIds = getEventTokenIds(event);\n\n log('Extracted token IDs', tokenIds);\n\n for (const tokenId of tokenIds) {\n const simulationToken: SimulationToken = {\n address: event.contractAddress,\n standard: event.tokenStandard,\n id: tokenId,\n };\n\n const tokenKey = JSON.stringify(simulationToken);\n\n if (tokenKeys.has(tokenKey)) {\n log(\n 'Ignoring additional event with same contract and token ID',\n simulationToken,\n );\n continue;\n }\n\n tokenKeys.add(tokenKey);\n\n const data = getBalanceTransactionData(\n event.tokenStandard,\n request.from,\n tokenId,\n );\n\n const transaction: SimulationRequestTransaction = {\n from: request.from,\n to: event.contractAddress,\n data,\n };\n\n if (skipPriorBalanceCheck(event)) {\n after.set(simulationToken, transaction);\n } else {\n before.set(simulationToken, transaction);\n after.set(simulationToken, transaction);\n }\n }\n }\n\n return { before, after };\n}\n\n/**\n * Check if an event needs to check the previous balance.\n * @param event - The parsed event.\n * @returns True if the prior balance check should be skipped.\n */\nfunction skipPriorBalanceCheck(event: ParsedEvent): boolean {\n // In the case of an NFT mint, we cannot check the NFT owner before the mint\n // as the balance check transaction would revert.\n return (\n event.name === 'Transfer' &&\n event.tokenStandard === SimulationTokenStandard.erc721 &&\n parseInt(event.args.from as string, 16) === 0\n );\n}\n\n/**\n * Extract token IDs from a parsed event.\n * @param event - The parsed event.\n * @returns An array of token IDs.\n */\nfunction getEventTokenIds(event: ParsedEvent): (Hex | undefined)[] {\n if (event.tokenStandard === SimulationTokenStandard.erc721) {\n return [event.args.tokenId as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferSingle'\n ) {\n return [event.args.id as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferBatch'\n ) {\n return event.args.ids as Hex[];\n }\n\n // ERC-20 does not have a token ID so default to undefined.\n return [undefined];\n}\n\n/**\n * Get the interface for a token standard.\n * @param tokenStandard - The token standard.\n * @returns The interface for the token standard.\n */\nfunction getContractInterface(\n tokenStandard: SimulationTokenStandard,\n): Interface {\n switch (tokenStandard) {\n case SimulationTokenStandard.erc721:\n return new Interface(abiERC721);\n case SimulationTokenStandard.erc1155:\n return new Interface(abiERC1155);\n default:\n return new Interface(abiERC20);\n }\n}\n\n/**\n * Extract the value from a balance transaction response using the correct ABI.\n * @param from - The address to check the balance of.\n * @param token - The token to check the balance of.\n * @param response - The balance transaction response.\n * @returns The value of the balance transaction as Hex.\n */\nfunction getAmountFromBalanceTransactionResult(\n from: Hex,\n token: SimulationToken,\n response: SimulationResponseTransaction,\n): Hex {\n const contract = getContractInterface(token.standard);\n\n try {\n if (token.standard === SimulationTokenStandard.erc721) {\n const result = contract.decodeFunctionResult('ownerOf', response.return);\n const owner = result[0];\n return owner.toLowerCase() === from.toLowerCase() ? '0x1' : '0x0';\n }\n\n const result = contract.decodeFunctionResult('balanceOf', response.return);\n return toHex(result[0]);\n } catch (error) {\n log('Failed to decode balance transaction', error, { token, response });\n throw new SimulationError(\n `Failed to decode balance transaction for token ${\n token.address\n }: ${String(error)}`,\n );\n }\n}\n\n/**\n * Generate the balance transaction data for a token.\n * @param tokenStandard - The token standard.\n * @param from - The address to check the balance of.\n * @param tokenId - The token ID to check the balance of.\n * @returns The balance transaction data.\n */\nfunction getBalanceTransactionData(\n tokenStandard: SimulationTokenStandard,\n from: Hex,\n tokenId?: Hex,\n): Hex {\n const contract = getContractInterface(tokenStandard);\n switch (tokenStandard) {\n case SimulationTokenStandard.erc721:\n return contract.encodeFunctionData('ownerOf', [tokenId]) as Hex;\n\n case SimulationTokenStandard.erc1155:\n return contract.encodeFunctionData('balanceOf', [from, tokenId]) as Hex;\n\n default:\n return contract.encodeFunctionData('balanceOf', [from]) as Hex;\n }\n}\n\n/**\n * Parse a raw event log using known ABIs.\n * @param eventLog - The raw event log.\n * @param interfaces - The contract interfaces.\n * @returns The parsed event log or undefined if it could not be parsed.\n */\nfunction parseLog(\n eventLog: SimulationResponseLog,\n interfaces: Map<SupportedToken, Interface>,\n):\n | (LogDescription & { abi: ABI; standard: SimulationTokenStandard })\n | undefined {\n const supportedTokens = Object.values(SupportedToken);\n\n for (const token of supportedTokens) {\n try {\n const contractInterface = interfaces.get(token) as Interface;\n const { abi, standard } = SUPPORTED_TOKEN_ABIS[token];\n\n return {\n ...contractInterface.parseLog(eventLog),\n abi,\n standard,\n };\n } catch (e) {\n continue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract all logs from a call trace tree.\n * @param call - The root call trace.\n * @returns An array of logs.\n */\nfunction extractLogs(\n call: SimulationResponseCallTrace,\n): SimulationResponseLog[] {\n /* istanbul ignore next */\n const logs = call.logs ?? [];\n\n /* istanbul ignore next */\n const nestedCalls = call.calls ?? [];\n\n return [\n ...logs,\n ...nestedCalls.map((nestedCall) => extractLogs(nestedCall)).flat(),\n ];\n}\n\n/**\n * Generate balance change data from previous and new balances.\n * @param previousBalance - The previous balance.\n * @param newBalance - The new balance.\n * @returns The balance change data or undefined if unchanged.\n */\nfunction getSimulationBalanceChange(\n previousBalance: Hex,\n newBalance: Hex,\n): SimulationBalanceChange | undefined {\n const differenceBN = hexToBN(newBalance).sub(hexToBN(previousBalance));\n const isDecrease = differenceBN.isNeg();\n const difference = toHex(differenceBN.abs());\n\n if (differenceBN.isZero()) {\n log('Balance change is zero');\n return undefined;\n }\n\n return {\n previousBalance,\n newBalance,\n difference,\n isDecrease,\n };\n}\n\n/**\n * Get the contract interfaces for all supported tokens.\n * @returns A map of supported tokens to their contract interfaces.\n */\nfunction getContractInterfaces(): Map<SupportedToken, Interface> {\n const supportedTokens = Object.values(SupportedToken);\n\n return new Map(\n supportedTokens.map((tokenType) => {\n const { abi } = SUPPORTED_TOKEN_ABIS[tokenType];\n const contractInterface = new Interface(abi);\n return [tokenType, contractInterface];\n }),\n );\n}\n"]}
|
|
1
|
+
{"version":3,"file":"simulation.mjs","sourceRoot":"","sources":["../../src/utils/simulation.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,2BAA2B;AAC/C,OAAO,EAAE,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAC5D,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,UAAU,EAAE,oCAAoC;AAC9E,OAAO,EAAE,kBAAkB,EAAY,wBAAwB;AAE/D,OAAO,EAAE,oBAAoB,EAAE,6BAAyB;AAQxD,OAAO,EACL,4BAA4B,EAC5B,4BAA4B,EAC7B,yBAAqB;AACtB,OAAO,EACL,eAAe,EACf,8BAA8B,EAC9B,uBAAuB,EACxB,sBAAkB;AACnB,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAO1C,OAAO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EAAE,CAAC,WAAW,CAAC,UAAU,CAAC,CAAC,CAAC,IAAI,EAAE;KACnE,CAAC;AACJ,CAAC;AAED;;;;;;GAMG;AACH,SAAS,0BAA0B,CACjC,eAAoB,EACpB,UAAe;IAEf,MAAM,YAAY,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,eAAe,CAAC,CAAC,CAAC;IACvE,MAAM,UAAU,GAAG,YAAY,CAAC,KAAK,EAAE,CAAC;IACxC,MAAM,UAAU,GAAG,KAAK,CAAC,YAAY,CAAC,GAAG,EAAE,CAAC,CAAC;IAE7C,IAAI,YAAY,CAAC,MAAM,EAAE,EAAE;QACzB,GAAG,CAAC,wBAAwB,CAAC,CAAC;QAC9B,OAAO,SAAS,CAAC;KAClB;IAED,OAAO;QACL,eAAe;QACf,UAAU;QACV,UAAU;QACV,UAAU;KACX,CAAC;AACJ,CAAC;AAED;;;;GAIG;AACH,SAAS,qBAAqB;IAC5B,MAAM,eAAe,GAAG,MAAM,CAAC,MAAM,CAAC,cAAc,CAAC,CAAC;IAEtD,OAAO,IAAI,GAAG,CACZ,eAAe,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE;QAChC,MAAM,EAAE,GAAG,EAAE,GAAG,oBAAoB,CAAC,SAAS,CAAC,CAAC;QAChD,MAAM,iBAAiB,GAAG,IAAI,SAAS,CAAC,GAAG,CAAC,CAAC;QAC7C,OAAO,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;IACxC,CAAC,CAAC,CACH,CAAC;AACJ,CAAC","sourcesContent":["import type { Fragment, LogDescription, Result } from '@ethersproject/abi';\nimport { Interface } from '@ethersproject/abi';\nimport { hexToBN, toHex } from '@metamask/controller-utils';\nimport { abiERC20, abiERC721, abiERC1155 } from '@metamask/metamask-eth-abis';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { simulateTransactions } from './simulation-api';\nimport type {\n SimulationResponseLog,\n SimulationRequestTransaction,\n SimulationResponse,\n SimulationResponseCallTrace,\n SimulationResponseTransaction,\n} from './simulation-api';\nimport {\n ABI_SIMULATION_ERC20_WRAPPED,\n ABI_SIMULATION_ERC721_LEGACY,\n} from '../constants';\nimport {\n SimulationError,\n SimulationInvalidResponseError,\n SimulationRevertedError,\n} from '../errors';\nimport { projectLogger } from '../logger';\nimport type {\n SimulationBalanceChange,\n SimulationData,\n SimulationTokenBalanceChange,\n SimulationToken,\n} from '../types';\nimport { SimulationTokenStandard } from '../types';\n\nexport enum SupportedToken {\n ERC20 = 'erc20',\n ERC721 = 'erc721',\n ERC1155 = 'erc1155',\n ERC20_WRAPPED = 'erc20Wrapped',\n ERC721_LEGACY = 'erc721Legacy',\n}\n\ntype ABI = Fragment[];\n\nexport type GetSimulationDataRequest = {\n chainId: Hex;\n data?: Hex;\n from: Hex;\n to?: Hex;\n value?: Hex;\n};\n\ntype ParsedEvent = {\n contractAddress: Hex;\n tokenStandard: SimulationTokenStandard;\n name: string;\n args: Record<string, Hex | Hex[]>;\n abi: ABI;\n};\n\ntype GetSimulationDataOptions = {\n blockTime?: number;\n};\n\nconst log = createModuleLogger(projectLogger, 'simulation');\n\nconst SUPPORTED_EVENTS = [\n 'Transfer',\n 'TransferSingle',\n 'TransferBatch',\n 'Deposit',\n 'Withdrawal',\n];\n\nconst SUPPORTED_TOKEN_ABIS = {\n [SupportedToken.ERC20]: {\n abi: abiERC20,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721]: {\n abi: abiERC721,\n standard: SimulationTokenStandard.erc721,\n },\n [SupportedToken.ERC1155]: {\n abi: abiERC1155,\n standard: SimulationTokenStandard.erc1155,\n },\n [SupportedToken.ERC20_WRAPPED]: {\n abi: ABI_SIMULATION_ERC20_WRAPPED,\n standard: SimulationTokenStandard.erc20,\n },\n [SupportedToken.ERC721_LEGACY]: {\n abi: ABI_SIMULATION_ERC721_LEGACY,\n standard: SimulationTokenStandard.erc721,\n },\n};\n\nconst REVERTED_ERRORS = ['execution reverted', 'insufficient funds for gas'];\n\ntype BalanceTransactionMap = Map<SimulationToken, SimulationRequestTransaction>;\n\n/**\n * Generate simulation data for a transaction.\n *\n * @param request - The transaction to simulate.\n * @param request.chainId - The chain ID of the transaction.\n * @param request.from - The sender of the transaction.\n * @param request.to - The recipient of the transaction.\n * @param request.value - The value of the transaction.\n * @param request.data - The data of the transaction.\n * @param options - Additional options.\n * @param options.blockTime - An optional block time to simulate the transaction at.\n * @returns The simulation data.\n */\nexport async function getSimulationData(\n request: GetSimulationDataRequest,\n options: GetSimulationDataOptions = {},\n): Promise<SimulationData> {\n const { chainId, from, to, value, data } = request;\n const { blockTime } = options;\n\n log('Getting simulation data', request);\n\n try {\n const response = await simulateTransactions(chainId, {\n transactions: [\n {\n data,\n from,\n maxFeePerGas: '0x0',\n maxPriorityFeePerGas: '0x0',\n to,\n value,\n },\n ],\n withCallTrace: true,\n withLogs: true,\n ...(blockTime && {\n blockOverrides: {\n time: toHex(blockTime),\n },\n }),\n });\n\n const transactionError = response.transactions?.[0]?.error;\n\n if (transactionError) {\n throw new SimulationError(transactionError);\n }\n\n const nativeBalanceChange = getNativeBalanceChange(request.from, response);\n const events = getEvents(response);\n\n log('Parsed events', events);\n\n const tokenBalanceChanges = await getTokenBalanceChanges(\n request,\n events,\n options,\n );\n\n return {\n nativeBalanceChange,\n tokenBalanceChanges,\n };\n } catch (error) {\n log('Failed to get simulation data', error, request);\n\n let simulationError = error as SimulationError;\n\n if (\n REVERTED_ERRORS.some((revertErrorMessage) =>\n simulationError.message?.includes(revertErrorMessage),\n )\n ) {\n simulationError = new SimulationRevertedError();\n }\n\n const { code, message } = simulationError;\n\n return {\n tokenBalanceChanges: [],\n error: {\n code,\n message,\n },\n };\n }\n}\n\n/**\n * Extract the native balance change from a simulation response.\n *\n * @param userAddress - The user's account address.\n * @param response - The simulation response.\n * @returns The native balance change or undefined if unchanged.\n */\nfunction getNativeBalanceChange(\n userAddress: Hex,\n response: SimulationResponse,\n): SimulationBalanceChange | undefined {\n const transactionResponse = response.transactions[0];\n\n /* istanbul ignore next */\n if (!transactionResponse) {\n return undefined;\n }\n\n const { stateDiff } = transactionResponse;\n const previousBalance = stateDiff?.pre?.[userAddress]?.balance;\n const newBalance = stateDiff?.post?.[userAddress]?.balance;\n\n if (!previousBalance || !newBalance) {\n return undefined;\n }\n\n return getSimulationBalanceChange(previousBalance, newBalance);\n}\n\n/**\n * Extract events from a simulation response.\n *\n * @param response - The simulation response.\n * @returns The parsed events.\n */\nexport function getEvents(response: SimulationResponse): ParsedEvent[] {\n /* istanbul ignore next */\n const logs = extractLogs(\n response.transactions[0]?.callTrace ?? ({} as SimulationResponseCallTrace),\n );\n\n log('Extracted logs', logs);\n\n const interfaces = getContractInterfaces();\n\n return logs\n .map((currentLog) => {\n const event = parseLog(currentLog, interfaces);\n\n if (!event) {\n log('Failed to parse log', currentLog);\n return undefined;\n }\n\n /* istanbul ignore next */\n const inputs = event.abi.find((e) => e.name === event.name)?.inputs;\n\n /* istanbul ignore if */\n if (!inputs) {\n log('Failed to find inputs for event', event);\n return undefined;\n }\n\n if (!SUPPORTED_EVENTS.includes(event.name)) {\n log('Ignoring unsupported event', event.name, event);\n return undefined;\n }\n\n log('Normalizing event args', event.name, event);\n\n const args = normalizeEventArgs(event.args, inputs);\n\n return {\n contractAddress: currentLog.address,\n tokenStandard: event.standard,\n name: event.name,\n args,\n abi: event.abi,\n };\n })\n .filter((e) => e !== undefined) as ParsedEvent[];\n}\n\n/**\n * Normalize event arguments using ABI input definitions.\n *\n * @param args - The raw event arguments.\n * @param abiInputs - The ABI input definitions.\n * @returns The normalized event arguments.\n */\nfunction normalizeEventArgs(\n args: Result,\n abiInputs: { name: string }[],\n): Record<string, Hex | Hex[]> {\n return args.reduce((result, arg, index) => {\n const name = abiInputs[index].name.replace('_', '');\n const value = normalizeEventArgValue(arg);\n\n result[name] = value;\n\n return result;\n }, {});\n}\n\n/**\n * Normalize an event argument value.\n *\n * @param value - The event argument value.\n * @returns The normalized event argument value.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalizeEventArgValue(value: any): any {\n if (Array.isArray(value)) {\n return value.map(normalizeEventArgValue);\n }\n\n let normalizedValue = value;\n\n normalizedValue = normalizedValue.toHexString?.() ?? normalizedValue;\n normalizedValue = normalizedValue.toLowerCase?.() ?? normalizedValue;\n\n return normalizedValue;\n}\n\n/**\n * Generate token balance changes from parsed events.\n *\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @param options - Additional options.\n * @param options.blockTime - An optional block time to simulate the transaction at.\n * @returns An array of token balance changes.\n */\nasync function getTokenBalanceChanges(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n options: GetSimulationDataOptions,\n): Promise<SimulationTokenBalanceChange[]> {\n const { blockTime } = options;\n const balanceTxs = getTokenBalanceTransactions(request, events);\n\n log('Generated balance transactions', [...balanceTxs.after.values()]);\n\n const transactions = [\n ...balanceTxs.before.values(),\n request,\n ...balanceTxs.after.values(),\n ];\n\n if (transactions.length === 1) {\n return [];\n }\n\n const response = await simulateTransactions(request.chainId as Hex, {\n transactions,\n ...(blockTime && {\n blockOverrides: {\n time: toHex(blockTime),\n },\n }),\n });\n\n log('Balance simulation response', response);\n\n if (response.transactions.length !== transactions.length) {\n throw new SimulationInvalidResponseError();\n }\n\n let prevBalanceTxIndex = 0;\n return [...balanceTxs.after.keys()]\n .map((token, index) => {\n const previousBalanceCheckSkipped = !balanceTxs.before.get(token);\n const previousBalance = previousBalanceCheckSkipped\n ? '0x0'\n : getAmountFromBalanceTransactionResult(\n request.from,\n token,\n // eslint-disable-next-line no-plusplus\n response.transactions[prevBalanceTxIndex++],\n );\n\n const newBalance = getAmountFromBalanceTransactionResult(\n request.from,\n token,\n response.transactions[index + balanceTxs.before.size + 1],\n );\n\n const balanceChange = getSimulationBalanceChange(\n previousBalance,\n newBalance,\n );\n\n if (!balanceChange) {\n return undefined;\n }\n\n return {\n ...token,\n ...balanceChange,\n };\n })\n .filter((change) => change !== undefined) as SimulationTokenBalanceChange[];\n}\n\n/**\n * Generate transactions to check token balances.\n *\n * @param request - The transaction that was simulated.\n * @param events - The parsed events.\n * @returns A map of token balance transactions keyed by token.\n */\nfunction getTokenBalanceTransactions(\n request: GetSimulationDataRequest,\n events: ParsedEvent[],\n): {\n before: BalanceTransactionMap;\n after: BalanceTransactionMap;\n} {\n const tokenKeys = new Set();\n const before = new Map();\n const after = new Map();\n\n const userEvents = events.filter((event) =>\n [event.args.from, event.args.to].includes(request.from),\n );\n\n log('Filtered user events', userEvents);\n\n for (const event of userEvents) {\n const tokenIds = getEventTokenIds(event);\n\n log('Extracted token IDs', tokenIds);\n\n for (const tokenId of tokenIds) {\n const simulationToken: SimulationToken = {\n address: event.contractAddress,\n standard: event.tokenStandard,\n id: tokenId,\n };\n\n const tokenKey = JSON.stringify(simulationToken);\n\n if (tokenKeys.has(tokenKey)) {\n log(\n 'Ignoring additional event with same contract and token ID',\n simulationToken,\n );\n continue;\n }\n\n tokenKeys.add(tokenKey);\n\n const data = getBalanceTransactionData(\n event.tokenStandard,\n request.from,\n tokenId,\n );\n\n const transaction: SimulationRequestTransaction = {\n from: request.from,\n to: event.contractAddress,\n data,\n };\n\n if (skipPriorBalanceCheck(event)) {\n after.set(simulationToken, transaction);\n } else {\n before.set(simulationToken, transaction);\n after.set(simulationToken, transaction);\n }\n }\n }\n\n return { before, after };\n}\n\n/**\n * Check if an event needs to check the previous balance.\n *\n * @param event - The parsed event.\n * @returns True if the prior balance check should be skipped.\n */\nfunction skipPriorBalanceCheck(event: ParsedEvent): boolean {\n // In the case of an NFT mint, we cannot check the NFT owner before the mint\n // as the balance check transaction would revert.\n return (\n event.name === 'Transfer' &&\n event.tokenStandard === SimulationTokenStandard.erc721 &&\n parseInt(event.args.from as string, 16) === 0\n );\n}\n\n/**\n * Extract token IDs from a parsed event.\n *\n * @param event - The parsed event.\n * @returns An array of token IDs.\n */\nfunction getEventTokenIds(event: ParsedEvent): (Hex | undefined)[] {\n if (event.tokenStandard === SimulationTokenStandard.erc721) {\n return [event.args.tokenId as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferSingle'\n ) {\n return [event.args.id as Hex];\n }\n\n if (\n event.tokenStandard === SimulationTokenStandard.erc1155 &&\n event.name === 'TransferBatch'\n ) {\n return event.args.ids as Hex[];\n }\n\n // ERC-20 does not have a token ID so default to undefined.\n return [undefined];\n}\n\n/**\n * Get the interface for a token standard.\n *\n * @param tokenStandard - The token standard.\n * @returns The interface for the token standard.\n */\nfunction getContractInterface(\n tokenStandard: SimulationTokenStandard,\n): Interface {\n switch (tokenStandard) {\n case SimulationTokenStandard.erc721:\n return new Interface(abiERC721);\n case SimulationTokenStandard.erc1155:\n return new Interface(abiERC1155);\n default:\n return new Interface(abiERC20);\n }\n}\n\n/**\n * Extract the value from a balance transaction response using the correct ABI.\n *\n * @param from - The address to check the balance of.\n * @param token - The token to check the balance of.\n * @param response - The balance transaction response.\n * @returns The value of the balance transaction as Hex.\n */\nfunction getAmountFromBalanceTransactionResult(\n from: Hex,\n token: SimulationToken,\n response: SimulationResponseTransaction,\n): Hex {\n const contract = getContractInterface(token.standard);\n\n try {\n if (token.standard === SimulationTokenStandard.erc721) {\n const result = contract.decodeFunctionResult('ownerOf', response.return);\n const owner = result[0];\n return owner.toLowerCase() === from.toLowerCase() ? '0x1' : '0x0';\n }\n\n const result = contract.decodeFunctionResult('balanceOf', response.return);\n return toHex(result[0]);\n } catch (error) {\n log('Failed to decode balance transaction', error, { token, response });\n throw new SimulationError(\n `Failed to decode balance transaction for token ${\n token.address\n }: ${String(error)}`,\n );\n }\n}\n\n/**\n * Generate the balance transaction data for a token.\n *\n * @param tokenStandard - The token standard.\n * @param from - The address to check the balance of.\n * @param tokenId - The token ID to check the balance of.\n * @returns The balance transaction data.\n */\nfunction getBalanceTransactionData(\n tokenStandard: SimulationTokenStandard,\n from: Hex,\n tokenId?: Hex,\n): Hex {\n const contract = getContractInterface(tokenStandard);\n switch (tokenStandard) {\n case SimulationTokenStandard.erc721:\n return contract.encodeFunctionData('ownerOf', [tokenId]) as Hex;\n\n case SimulationTokenStandard.erc1155:\n return contract.encodeFunctionData('balanceOf', [from, tokenId]) as Hex;\n\n default:\n return contract.encodeFunctionData('balanceOf', [from]) as Hex;\n }\n}\n\n/**\n * Parse a raw event log using known ABIs.\n *\n * @param eventLog - The raw event log.\n * @param interfaces - The contract interfaces.\n * @returns The parsed event log or undefined if it could not be parsed.\n */\nfunction parseLog(\n eventLog: SimulationResponseLog,\n interfaces: Map<SupportedToken, Interface>,\n):\n | (LogDescription & { abi: ABI; standard: SimulationTokenStandard })\n | undefined {\n const supportedTokens = Object.values(SupportedToken);\n\n for (const token of supportedTokens) {\n try {\n const contractInterface = interfaces.get(token) as Interface;\n const { abi, standard } = SUPPORTED_TOKEN_ABIS[token];\n\n return {\n ...contractInterface.parseLog(eventLog),\n abi,\n standard,\n };\n // Not used\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n } catch (e) {\n continue;\n }\n }\n\n return undefined;\n}\n\n/**\n * Extract all logs from a call trace tree.\n *\n * @param call - The root call trace.\n * @returns An array of logs.\n */\nfunction extractLogs(\n call: SimulationResponseCallTrace,\n): SimulationResponseLog[] {\n /* istanbul ignore next */\n const logs = call.logs ?? [];\n\n /* istanbul ignore next */\n const nestedCalls = call.calls ?? [];\n\n return [\n ...logs,\n ...nestedCalls.map((nestedCall) => extractLogs(nestedCall)).flat(),\n ];\n}\n\n/**\n * Generate balance change data from previous and new balances.\n *\n * @param previousBalance - The previous balance.\n * @param newBalance - The new balance.\n * @returns The balance change data or undefined if unchanged.\n */\nfunction getSimulationBalanceChange(\n previousBalance: Hex,\n newBalance: Hex,\n): SimulationBalanceChange | undefined {\n const differenceBN = hexToBN(newBalance).sub(hexToBN(previousBalance));\n const isDecrease = differenceBN.isNeg();\n const difference = toHex(differenceBN.abs());\n\n if (differenceBN.isZero()) {\n log('Balance change is zero');\n return undefined;\n }\n\n return {\n previousBalance,\n newBalance,\n difference,\n isDecrease,\n };\n}\n\n/**\n * Get the contract interfaces for all supported tokens.\n *\n * @returns A map of supported tokens to their contract interfaces.\n */\nfunction getContractInterfaces(): Map<SupportedToken, Interface> {\n const supportedTokens = Object.values(SupportedToken);\n\n return new Map(\n supportedTokens.map((tokenType) => {\n const { abi } = SUPPORTED_TOKEN_ABIS[tokenType];\n const contractInterface = new Interface(abi);\n return [tokenType, contractInterface];\n }),\n );\n}\n"]}
|
package/dist/utils/swaps.cjs
CHANGED
|
@@ -3,10 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.updatePostTransactionBalance = exports.updateSwapsTransaction = exports.SWAP_TRANSACTION_TYPES = exports.SWAPS_CHAINID_DEFAULT_TOKEN_MAP = exports.DEFAULT_TOKEN_ADDRESS = exports.UPDATE_POST_TX_BALANCE_ATTEMPTS = exports.UPDATE_POST_TX_BALANCE_TIMEOUT = void 0;
|
|
4
4
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
5
5
|
const lodash_1 = require("lodash");
|
|
6
|
+
const utils_1 = require("./utils.cjs");
|
|
6
7
|
const constants_1 = require("../constants.cjs");
|
|
7
8
|
const logger_1 = require("../logger.cjs");
|
|
8
9
|
const types_1 = require("../types.cjs");
|
|
9
|
-
const utils_1 = require("./utils.cjs");
|
|
10
10
|
const log = (0, logger_1.createModuleLogger)(logger_1.projectLogger, 'swaps');
|
|
11
11
|
/**
|
|
12
12
|
* Interval in milliseconds between checks of post transaction balance
|
|
@@ -143,6 +143,7 @@ exports.updateSwapsTransaction = updateSwapsTransaction;
|
|
|
143
143
|
* @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object
|
|
144
144
|
* @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state
|
|
145
145
|
* @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function
|
|
146
|
+
* @returns Updated transaction metadata and approval transaction metadata if applicable.
|
|
146
147
|
*/
|
|
147
148
|
async function updatePostTransactionBalance(transactionMeta, { ethQuery, getTransaction, updateTransaction, }) {
|
|
148
149
|
log('Updating post transaction balance', transactionMeta.id);
|
package/dist/utils/swaps.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swaps.cjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAEnD,mCAAuC;AAEvC,gDAAyC;AACzC,0CAA8D;AAG9D,wCAA2C;AAC3C,uCAA0D;AAE1D,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACU,QAAA,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACU,QAAA,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACU,QAAA,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,cAAc;IACpB,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,wBAAwB,GAAqB;IACjD,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,uBAAuB,GAAqB;IAChD,IAAI,EAAE,WAAW;IACjB,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,2BAA2B,GAAqB;IACpD,IAAI,EAAE,YAAY;IAClB,OAAO,EAAE,6BAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,yBAAyB,GAAqB;IAClD,IAAI,EAAE,OAAO;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AI;KACL,CAAC;IACF,gCAAgC;IAChC,8DAA8D;IAC9D,eAAe,GAAG,IAAA,eAAM,EAAC,eAAe,CAAQ,CAAC;IAEjD,OAAO,IAAA,cAAK,EAAC,EAAE,EAAE,eAAe,EAAE,eAAe,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,6BAA6B,CACpC,eAAgC,EAChC,EAAE,IAAI,EAAE,iBAAiB,EAA4B;IAErD,IAAA,uCAA+B,EAC7B,eAAe,EACf,+BAA+B,CAChC,CAAC;IAEF,gCAAgC;IAChC,8DAA8D;IAC9D,IAAI,uBAAuB,GAAG,EAAE,IAAI,EAAE,iBAAiB,EAAS,CAAC;IACjE,uBAAuB,GAAG,IAAA,eAAM,EAAC;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAE/B,OAAO,IAAA,cAAK,EAAC,EAAE,EAAE,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE;QACxB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,OAAO;QACP,uCAA+B,CAC7B,OAAuD,CACxD,EAAE,OAAO,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\nimport { validateIfTransactionUnapproved } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\n\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return merge({}, transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"swaps.cjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAEnD,mCAAuC;AAEvC,uCAA0D;AAC1D,gDAAyC;AACzC,0CAA8D;AAG9D,wCAA2C;AAE3C,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACU,QAAA,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;A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C;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAE/B,OAAO,IAAA,cAAK,EAAC,EAAE,EAAE,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE;QACxB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,OAAO;QACP,uCAA+B,CAC7B,OAAuD,CACxD,EAAE,OAAO,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { validateIfTransactionUnapproved } from './utils';\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\n\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n * @returns Updated transaction metadata and approval transaction metadata if applicable.\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return merge({}, transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
package/dist/utils/swaps.d.cts
CHANGED
|
@@ -71,6 +71,7 @@ export declare function updateSwapsTransaction(transactionMeta: TransactionMeta,
|
|
|
71
71
|
* @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object
|
|
72
72
|
* @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state
|
|
73
73
|
* @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function
|
|
74
|
+
* @returns Updated transaction metadata and approval transaction metadata if applicable.
|
|
74
75
|
*/
|
|
75
76
|
export declare function updatePostTransactionBalance(transactionMeta: TransactionMeta, { ethQuery, getTransaction, updateTransaction, }: {
|
|
76
77
|
ethQuery: EthQuery;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swaps.d.cts","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,4BAA4B;
|
|
1
|
+
{"version":3,"file":"swaps.d.cts","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,4BAA4B;AAMhD,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EAAE,eAAe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;IACxC,uBAAuB,CAAC,EAAE,eAAe,CAAC;CAC3C,CAAC,CA4DD"}
|
package/dist/utils/swaps.d.mts
CHANGED
|
@@ -71,6 +71,7 @@ export declare function updateSwapsTransaction(transactionMeta: TransactionMeta,
|
|
|
71
71
|
* @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object
|
|
72
72
|
* @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state
|
|
73
73
|
* @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function
|
|
74
|
+
* @returns Updated transaction metadata and approval transaction metadata if applicable.
|
|
74
75
|
*/
|
|
75
76
|
export declare function updatePostTransactionBalance(transactionMeta: TransactionMeta, { ethQuery, getTransaction, updateTransaction, }: {
|
|
76
77
|
ethQuery: EthQuery;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swaps.d.mts","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,4BAA4B;
|
|
1
|
+
{"version":3,"file":"swaps.d.mts","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,QAAQ,4BAA4B;AAMhD,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EAAE,eAAe,EAAE,qBAAiB;AAChD,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAI3C;;GAEG;AACH,eAAO,MAAM,8BAA8B,OAAO,CAAC;AAEnD;;GAEG;AACH,eAAO,MAAM,+BAA+B,IAAI,CAAC;AAIjD;;GAEG;AACH,eAAO,MAAM,qBAAqB,+CACY,CAAC;AAI/C,UAAU,gBAAgB;IACxB;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IACb;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;IAChB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;CAClB;AAkDD,eAAO,MAAM,+BAA+B;;;;;;;;;;CAUlC,CAAC;AAEX,eAAO,MAAM,sBAAsB,mBAIlC,CAAC;AAEF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,sBAAsB,CACpC,eAAe,EAAE,eAAe,EAChC,eAAe,EAAE,eAAe,EAChC,KAAK,EAAE;IACL,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,IAAI,CAAC,EAAE,OAAO,CAAC,eAAe,CAAC,CAAC;CACjC,EACD,EACE,eAAe,EACf,iBAAiB,EACjB,SAAS,GACV,EAAE;IACD,eAAe,EAAE,OAAO,CAAC;IACzB,iBAAiB,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,IAAI,CAAC;IACnD,SAAS,EAAE,8BAA8B,CAAC;CAC3C,GACA,eAAe,CA0DjB;AAED;;;;;;;;;GASG;AACH,wBAAsB,4BAA4B,CAChD,eAAe,EAAE,eAAe,EAChC,EACE,QAAQ,EACR,cAAc,EACd,iBAAiB,GAClB,EAAE;IACD,QAAQ,EAAE,QAAQ,CAAC;IACnB,cAAc,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,eAAe,GAAG,SAAS,CAAC;IACvE,iBAAiB,EAAE,CAAC,eAAe,EAAE,eAAe,EAAE,IAAI,EAAE,MAAM,KAAK,IAAI,CAAC;CAC7E,GACA,OAAO,CAAC;IACT,sBAAsB,EAAE,eAAe,CAAC;IACxC,uBAAuB,CAAC,EAAE,eAAe,CAAC;CAC3C,CAAC,CA4DD"}
|
package/dist/utils/swaps.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { query } from "@metamask/controller-utils";
|
|
2
2
|
import $lodash from "lodash";
|
|
3
3
|
const { merge, pickBy } = $lodash;
|
|
4
|
+
import { validateIfTransactionUnapproved } from "./utils.mjs";
|
|
4
5
|
import { CHAIN_IDS } from "../constants.mjs";
|
|
5
6
|
import { createModuleLogger, projectLogger } from "../logger.mjs";
|
|
6
7
|
import { TransactionType } from "../types.mjs";
|
|
7
|
-
import { validateIfTransactionUnapproved } from "./utils.mjs";
|
|
8
8
|
const log = createModuleLogger(projectLogger, 'swaps');
|
|
9
9
|
/**
|
|
10
10
|
* Interval in milliseconds between checks of post transaction balance
|
|
@@ -140,6 +140,7 @@ export function updateSwapsTransaction(transactionMeta, transactionType, swaps,
|
|
|
140
140
|
* @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object
|
|
141
141
|
* @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state
|
|
142
142
|
* @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function
|
|
143
|
+
* @returns Updated transaction metadata and approval transaction metadata if applicable.
|
|
143
144
|
*/
|
|
144
145
|
export async function updatePostTransactionBalance(transactionMeta, { ethQuery, getTransaction, updateTransaction, }) {
|
|
145
146
|
log('Updating post transaction balance', transactionMeta.id);
|
package/dist/utils/swaps.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swaps.mjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;;;AAInD,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAG9D,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAC3C,OAAO,EAAE,+BAA+B,EAAE,oBAAgB;AAE1D,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EA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+BAA+B,CAC7B,OAAuD,CACxD,EAAE,OAAO,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\nimport { validateIfTransactionUnapproved } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\n\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return merge({}, transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
|
1
|
+
{"version":3,"file":"swaps.mjs","sourceRoot":"","sources":["../../src/utils/swaps.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;;;AAInD,OAAO,EAAE,+BAA+B,EAAE,oBAAgB;AAC1D,OAAO,EAAE,SAAS,EAAE,yBAAqB;AACzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAG9D,OAAO,EAAE,eAAe,EAAE,qBAAiB;AAE3C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,OAAO,CAAC,CAAC;AAEvD;;GAEG;AACH,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAEnD;;GAEG;AACH,MAAM,CAAC,MAAM,+BAA+B,GAAG,CAAC,CAAC;AAEjD,MAAM,sBAAsB,GAAG,OAAO,CAAC;AAEvC;;GAEG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAChC,4CAA4C,CAAC;AAmB/C,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACb,CAAC;AAEF,MAAM,sBAAsB,GAAqB;IAC/C,IAAI,EAAE,cAAc;IACpB,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,wBAAwB,GAAqB;IACjD,IAAI,EAAE,OAAO;IACb,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,uBAAuB,GAAqB;IAChD,IAAI,EAAE,WAAW;IACjB,OAAO,EAAE,qBAAqB;IAC9B,QAAQ,EAAE,EAAE;CACJ,CAAC;AAEX,MAAM,2BAA2B,G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gB;QAChB,kBAAkB;QAClB,iBAAiB;QACjB,mBAAmB;QACnB,iBAAiB;QACjB,oBAAoB;QACpB,YAAY;QACZ,cAAc;QACd,IAAI;KACL,CAAC;IACF,gCAAgC;IAChC,8DAA8D;IAC9D,eAAe,GAAG,MAAM,CAAC,eAAe,CAAQ,CAAC;IAEjD,OAAO,KAAK,CAAC,EAAE,EAAE,eAAe,EAAE,eAAe,CAAC,CAAC;AACrD,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,6BAA6B,CACpC,eAAgC,EAChC,EAAE,IAAI,EAAE,iBAAiB,EAA4B;IAErD,+BAA+B,CAC7B,eAAe,EACf,+BAA+B,CAChC,CAAC;IAEF,gCAAgC;IAChC,8DAA8D;IAC9D,IAAI,uBAAuB,GAAG,EAAE,IAAI,EAAE,iBAAiB,EAAS,CAAC;IACjE,uBAAuB,GAAG,MAAM,CAAC;QAC/B,IAAI;QACJ,iBAAiB;KAClB,CAA6B,CAAC;IAE/B,OAAO,KAAK,CAAC,EAAE,EAAE,eAAe,EAAE,uBAAuB,CAAC,CAAC;AAC7D,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,0BAA0B,CAAC,OAAe,EAAE,OAAe;IAClE,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,EAAE;QACxB,OAAO,KAAK,CAAC;KACd;IAED,OAAO,CACL,OAAO;QACP,+BAA+B,CAC7B,OAAuD,CACxD,EAAE,OAAO,CACX,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,KAAK,CAAC,EAAU;IACvB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,CAAC;AAC3D,CAAC","sourcesContent":["import { query } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { merge, pickBy } from 'lodash';\n\nimport { validateIfTransactionUnapproved } from './utils';\nimport { CHAIN_IDS } from '../constants';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type { TransactionMeta } from '../types';\nimport { TransactionType } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'swaps');\n\n/**\n * Interval in milliseconds between checks of post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_TIMEOUT = 5000;\n\n/**\n * Retry attempts for checking post transaction balance\n */\nexport const UPDATE_POST_TX_BALANCE_ATTEMPTS = 6;\n\nconst SWAPS_TESTNET_CHAIN_ID = '0x539';\n\n/**\n * An address that the metaswap-api recognizes as the default token for the current network, in place of the token address that ERC-20 tokens have\n */\nexport const DEFAULT_TOKEN_ADDRESS =\n '0x0000000000000000000000000000000000000000';\n\n// Convert to a `type` in a future major version.\n// eslint-disable-next-line @typescript-eslint/consistent-type-definitions\ninterface SwapsTokenObject {\n /**\n * The name for the network\n */\n name: string;\n /**\n * An address that the metaswap-api recognizes as the default token\n */\n address: string;\n /**\n * Number of digits after decimal point\n */\n decimals: number;\n}\n\nconst ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n};\n\nconst BNB_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Binance Coin',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst MATIC_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Matic',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst AVAX_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Avalanche',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst TEST_ETH_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Test Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst GOERLI_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n name: 'Ether',\n address: DEFAULT_TOKEN_ADDRESS,\n decimals: 18,\n} as const;\n\nconst ARBITRUM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst OPTIMISM_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nconst ZKSYNC_ERA_SWAPS_TOKEN_OBJECT: SwapsTokenObject = {\n ...ETH_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAPS_CHAINID_DEFAULT_TOKEN_MAP = {\n [CHAIN_IDS.MAINNET]: ETH_SWAPS_TOKEN_OBJECT,\n [SWAPS_TESTNET_CHAIN_ID]: TEST_ETH_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.BSC]: BNB_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.POLYGON]: MATIC_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.GOERLI]: GOERLI_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.AVALANCHE]: AVAX_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.OPTIMISM]: OPTIMISM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ARBITRUM]: ARBITRUM_SWAPS_TOKEN_OBJECT,\n [CHAIN_IDS.ZKSYNC_ERA]: ZKSYNC_ERA_SWAPS_TOKEN_OBJECT,\n} as const;\n\nexport const SWAP_TRANSACTION_TYPES = [\n TransactionType.swap,\n TransactionType.swapAndSend,\n TransactionType.swapApproval,\n];\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - The transaction meta object to update\n * @param transactionType - The type of the transaction\n * @param swaps - The swaps object\n * @param swaps.hasApproveTx - Whether the swap has an approval transaction\n * @param swaps.meta - The swap meta object\n * @param updateSwapsTransactionRequest - Dependency bag\n * @param updateSwapsTransactionRequest.isSwapsDisabled - Whether swaps are disabled\n * @param updateSwapsTransactionRequest.cancelTransaction - Function to cancel a transaction\n * @param updateSwapsTransactionRequest.messenger - TransactionController messenger\n * @returns A copy of the transaction meta object with updates, or the same\n * transaction meta object if no updates were made.\n */\nexport function updateSwapsTransaction(\n transactionMeta: TransactionMeta,\n transactionType: TransactionType,\n swaps: {\n hasApproveTx?: boolean;\n meta?: Partial<TransactionMeta>;\n },\n {\n isSwapsDisabled,\n cancelTransaction,\n messenger,\n }: {\n isSwapsDisabled: boolean;\n cancelTransaction: (transactionId: string) => void;\n messenger: TransactionControllerMessenger;\n },\n): TransactionMeta {\n if (isSwapsDisabled || !SWAP_TRANSACTION_TYPES.includes(transactionType)) {\n return transactionMeta;\n }\n\n // The simulationFails property is added if the estimateGas call fails. In cases\n // when no swaps approval tx is required, this indicates that the swap will likely\n // fail. There was an earlier estimateGas call made by the swaps controller,\n // but it is possible that external conditions have change since then, and\n // a previously succeeding estimate gas call could now fail. By checking for\n // the `simulationFails` property here, we can reduce the number of swap\n // transactions that get published to the blockchain only to fail and thereby\n // waste the user's funds on gas.\n if (\n transactionType === TransactionType.swap &&\n swaps?.hasApproveTx === false &&\n transactionMeta.simulationFails\n ) {\n cancelTransaction(transactionMeta.id);\n throw new Error('Simulation failed');\n }\n\n const swapsMeta = swaps?.meta as Partial<TransactionMeta>;\n\n if (!swapsMeta) {\n return transactionMeta;\n }\n\n let updatedTransactionMeta = transactionMeta;\n\n if (transactionType === TransactionType.swapApproval) {\n updatedTransactionMeta = updateSwapApprovalTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapApproval', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swapAndSend) {\n updatedTransactionMeta = updateSwapAndSendTransaction(\n transactionMeta,\n swapsMeta,\n );\n messenger.publish('TransactionController:transactionNewSwapAndSend', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n if (transactionType === TransactionType.swap) {\n updatedTransactionMeta = updateSwapTransaction(transactionMeta, swapsMeta);\n messenger.publish('TransactionController:transactionNewSwap', {\n transactionMeta: updatedTransactionMeta,\n });\n }\n\n return updatedTransactionMeta;\n}\n\n/**\n * Attempts to update the post transaction balance of the provided transaction\n *\n * @param transactionMeta - Transaction meta object to update\n * @param updatePostTransactionBalanceRequest - Dependency bag\n * @param updatePostTransactionBalanceRequest.ethQuery - EthQuery object\n * @param updatePostTransactionBalanceRequest.getTransaction - Reading function for the latest transaction state\n * @param updatePostTransactionBalanceRequest.updateTransaction - Updating transaction function\n * @returns Updated transaction metadata and approval transaction metadata if applicable.\n */\nexport async function updatePostTransactionBalance(\n transactionMeta: TransactionMeta,\n {\n ethQuery,\n getTransaction,\n updateTransaction,\n }: {\n ethQuery: EthQuery;\n getTransaction: (transactionId: string) => TransactionMeta | undefined;\n updateTransaction: (transactionMeta: TransactionMeta, note: string) => void;\n },\n): Promise<{\n updatedTransactionMeta: TransactionMeta;\n approvalTransactionMeta?: TransactionMeta;\n}> {\n log('Updating post transaction balance', transactionMeta.id);\n\n const transactionId = transactionMeta.id;\n let latestTransactionMeta: TransactionMeta | undefined;\n let approvalTransactionMeta;\n\n for (let i = 0; i < UPDATE_POST_TX_BALANCE_ATTEMPTS; i++) {\n log('Querying balance', { attempt: i });\n\n const postTransactionBalance = await query(ethQuery, 'getBalance', [\n transactionMeta.txParams.from,\n ]);\n\n latestTransactionMeta = {\n ...(getTransaction(transactionId) ?? ({} as TransactionMeta)),\n };\n\n approvalTransactionMeta = latestTransactionMeta.approvalTxId\n ? getTransaction(latestTransactionMeta.approvalTxId)\n : undefined;\n\n latestTransactionMeta.postTxBalance = postTransactionBalance.toString(16);\n\n const isDefaultTokenAddress = isSwapsDefaultTokenAddress(\n transactionMeta.destinationTokenAddress as string,\n transactionMeta.chainId,\n );\n\n if (\n !isDefaultTokenAddress ||\n transactionMeta.preTxBalance !== latestTransactionMeta.postTxBalance\n ) {\n log('Finishing post balance update', {\n isDefaultTokenAddress,\n preTxBalance: transactionMeta.preTxBalance,\n postTxBalance: latestTransactionMeta.postTxBalance,\n });\n\n break;\n }\n\n log('Waiting for balance to update', {\n delay: UPDATE_POST_TX_BALANCE_TIMEOUT,\n });\n\n await sleep(UPDATE_POST_TX_BALANCE_TIMEOUT);\n }\n\n updateTransaction(\n latestTransactionMeta as TransactionMeta,\n 'TransactionController#updatePostTransactionBalance - Add post transaction balance',\n );\n\n log('Completed post balance update', latestTransactionMeta?.postTxBalance);\n\n return {\n updatedTransactionMeta: latestTransactionMeta as TransactionMeta,\n approvalTransactionMeta,\n };\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapTransaction(\n transactionMeta: TransactionMeta,\n {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n sourceTokenSymbol,\n destinationTokenSymbol,\n type,\n destinationTokenDecimals,\n destinationTokenAddress,\n swapMetaData,\n swapTokenValue,\n estimatedBaseFee,\n approvalTxId,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.approvalTxId - Transaction id of the approval transaction\n * @param propsToUpdate.destinationTokenAddress - Address of the token to be received\n * @param propsToUpdate.destinationTokenAmount - The raw amount of the destination token\n * @param propsToUpdate.destinationTokenDecimals - Decimals of the token to be received\n * @param propsToUpdate.destinationTokenSymbol - Symbol of the token to be received\n * @param propsToUpdate.estimatedBaseFee - Estimated base fee of the transaction\n * @param propsToUpdate.sourceTokenAddress - The address of the source token\n * @param propsToUpdate.sourceTokenAmount - The raw amount of the source token\n * @param propsToUpdate.sourceTokenDecimals - The decimals of the source token\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @param propsToUpdate.swapAndSendRecipient - The recipient of the swap and send transaction\n * @param propsToUpdate.swapMetaData - Metadata of the swap\n * @param propsToUpdate.swapTokenValue - Value of the token to be swapped – possibly the same as sourceTokenAmount; included for consistency\n * @param propsToUpdate.type - Type of the transaction\n * @returns The updated transaction meta object.\n */\nfunction updateSwapAndSendTransaction(\n transactionMeta: TransactionMeta,\n {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(transactionMeta, 'updateSwapTransaction');\n\n let swapTransaction = {\n approvalTxId,\n destinationTokenAddress,\n destinationTokenAmount,\n destinationTokenDecimals,\n destinationTokenSymbol,\n estimatedBaseFee,\n sourceTokenAddress,\n sourceTokenAmount,\n sourceTokenDecimals,\n sourceTokenSymbol,\n swapAndSendRecipient,\n swapMetaData,\n swapTokenValue,\n type,\n };\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n swapTransaction = pickBy(swapTransaction) as any;\n\n return merge({}, transactionMeta, swapTransaction);\n}\n\n/**\n * Updates the transaction meta object with the swap approval information\n *\n * @param transactionMeta - Transaction meta object to update\n * @param propsToUpdate - Properties to update\n * @param propsToUpdate.type - Type of the transaction\n * @param propsToUpdate.sourceTokenSymbol - Symbol of the token to be swapped\n * @returns The updated transaction meta object.\n */\nfunction updateSwapApprovalTransaction(\n transactionMeta: TransactionMeta,\n { type, sourceTokenSymbol }: Partial<TransactionMeta>,\n): TransactionMeta {\n validateIfTransactionUnapproved(\n transactionMeta,\n 'updateSwapApprovalTransaction',\n );\n\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let swapApprovalTransaction = { type, sourceTokenSymbol } as any;\n swapApprovalTransaction = pickBy({\n type,\n sourceTokenSymbol,\n }) as Partial<TransactionMeta>;\n\n return merge({}, transactionMeta, swapApprovalTransaction);\n}\n\n/**\n * Checks whether the provided address is strictly equal to the address for\n * the default swaps token of the provided chain.\n *\n * @param address - The string to compare to the default token address\n * @param chainId - The hex encoded chain ID of the default swaps token to check\n * @returns Whether the address is the provided chain's default token address\n */\nfunction isSwapsDefaultTokenAddress(address: string, chainId: string) {\n if (!address || !chainId) {\n return false;\n }\n\n return (\n address ===\n SWAPS_CHAINID_DEFAULT_TOKEN_MAP[\n chainId as keyof typeof SWAPS_CHAINID_DEFAULT_TOKEN_MAP\n ]?.address\n );\n}\n\n/**\n * Sleeps for the provided number of milliseconds\n *\n * @param ms - Number of milliseconds to sleep\n * @returns Promise that resolves after the provided number of milliseconds\n */\nfunction sleep(ms: number) {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n"]}
|
|
@@ -103,8 +103,10 @@ async function readAddressAsContract(ethQuery, address) {
|
|
|
103
103
|
let contractCode;
|
|
104
104
|
try {
|
|
105
105
|
contractCode = await (0, controller_utils_1.query)(ethQuery, 'getCode', [address]);
|
|
106
|
+
// Not used
|
|
107
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
106
108
|
}
|
|
107
|
-
catch (
|
|
109
|
+
catch (error) {
|
|
108
110
|
contractCode = null;
|
|
109
111
|
}
|
|
110
112
|
const isContractAddress = contractCode
|