@metamask/transaction-pay-controller 22.3.0 → 22.4.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 +32 -1
- package/dist/TransactionPayController.cjs +2 -1
- package/dist/TransactionPayController.cjs.map +1 -1
- package/dist/TransactionPayController.d.cts.map +1 -1
- package/dist/TransactionPayController.d.mts.map +1 -1
- package/dist/TransactionPayController.mjs +2 -1
- package/dist/TransactionPayController.mjs.map +1 -1
- package/dist/strategy/across/AcrossStrategy.cjs +12 -1
- package/dist/strategy/across/AcrossStrategy.cjs.map +1 -1
- package/dist/strategy/across/AcrossStrategy.d.cts.map +1 -1
- package/dist/strategy/across/AcrossStrategy.d.mts.map +1 -1
- package/dist/strategy/across/AcrossStrategy.mjs +12 -1
- package/dist/strategy/across/AcrossStrategy.mjs.map +1 -1
- package/dist/strategy/across/across-quotes.cjs +160 -37
- package/dist/strategy/across/across-quotes.cjs.map +1 -1
- package/dist/strategy/across/across-quotes.d.cts.map +1 -1
- package/dist/strategy/across/across-quotes.d.mts.map +1 -1
- package/dist/strategy/across/across-quotes.mjs +160 -37
- package/dist/strategy/across/across-quotes.mjs.map +1 -1
- package/dist/strategy/across/types.cjs.map +1 -1
- package/dist/strategy/across/types.d.cts +1 -0
- package/dist/strategy/across/types.d.cts.map +1 -1
- package/dist/strategy/across/types.d.mts +1 -0
- package/dist/strategy/across/types.d.mts.map +1 -1
- package/dist/strategy/across/types.mjs.map +1 -1
- package/dist/strategy/fiat/fiat-submit.cjs +15 -29
- package/dist/strategy/fiat/fiat-submit.cjs.map +1 -1
- package/dist/strategy/fiat/fiat-submit.d.cts.map +1 -1
- package/dist/strategy/fiat/fiat-submit.d.mts.map +1 -1
- package/dist/strategy/fiat/fiat-submit.mjs +17 -31
- package/dist/strategy/fiat/fiat-submit.mjs.map +1 -1
- package/dist/strategy/fiat/utils.cjs +76 -1
- package/dist/strategy/fiat/utils.cjs.map +1 -1
- package/dist/strategy/fiat/utils.d.cts +34 -0
- package/dist/strategy/fiat/utils.d.cts.map +1 -1
- package/dist/strategy/fiat/utils.d.mts +34 -0
- package/dist/strategy/fiat/utils.d.mts.map +1 -1
- package/dist/strategy/fiat/utils.mjs +73 -0
- package/dist/strategy/fiat/utils.mjs.map +1 -1
- package/dist/utils/transaction.cjs +137 -1
- package/dist/utils/transaction.cjs.map +1 -1
- package/dist/utils/transaction.d.cts +24 -0
- package/dist/utils/transaction.d.cts.map +1 -1
- package/dist/utils/transaction.d.mts +24 -0
- package/dist/utils/transaction.d.mts.map +1 -1
- package/dist/utils/transaction.mjs +135 -0
- package/dist/utils/transaction.mjs.map +1 -1
- package/package.json +8 -8
|
@@ -1,6 +1,12 @@
|
|
|
1
1
|
import { TransactionType } from "@metamask/transaction-controller";
|
|
2
|
+
import { createModuleLogger } from "@metamask/utils";
|
|
3
|
+
import { BigNumber } from "bignumber.js";
|
|
4
|
+
import { projectLogger } from "../../logger.mjs";
|
|
2
5
|
import { getFiatAssetPerTransactionType } from "../../utils/feature-flags.mjs";
|
|
6
|
+
import { getTokenInfo } from "../../utils/token.mjs";
|
|
7
|
+
import { getTransferredAmountFromTxHash } from "../../utils/transaction.mjs";
|
|
3
8
|
import { FIAT_ASSET_ID_BY_TX_TYPE } from "./constants.mjs";
|
|
9
|
+
const log = createModuleLogger(projectLogger, 'fiat-utils');
|
|
4
10
|
export function deriveFiatAssetForFiatPayment(transaction, messenger) {
|
|
5
11
|
const txType = resolveTransactionType(transaction);
|
|
6
12
|
return getFiatAssetPerTransactionType(messenger, txType);
|
|
@@ -11,4 +17,71 @@ function resolveTransactionType(transaction) {
|
|
|
11
17
|
}
|
|
12
18
|
return transaction.nestedTransactions?.find((tx) => tx.type && FIAT_ASSET_ID_BY_TX_TYPE[tx.type] !== undefined)?.type;
|
|
13
19
|
}
|
|
20
|
+
/**
|
|
21
|
+
* Resolves the raw source amount for a completed fiat order.
|
|
22
|
+
*
|
|
23
|
+
* Attempts to read the actual transferred amount from the on-chain transaction
|
|
24
|
+
* identified by `order.txHash`. If the on-chain read fails or returns
|
|
25
|
+
* no amount, falls back to computing the amount from `order.cryptoAmount`.
|
|
26
|
+
*
|
|
27
|
+
* @param options - The resolution options.
|
|
28
|
+
* @param options.messenger - Controller messenger for network access.
|
|
29
|
+
* @param options.order - The completed on-ramp order.
|
|
30
|
+
* @param options.fiatAsset - The fiat asset describing the expected token.
|
|
31
|
+
* @param options.walletAddress - Recipient wallet address for on-chain lookup.
|
|
32
|
+
* @returns The raw (atomic) source amount as a decimal string.
|
|
33
|
+
*/
|
|
34
|
+
export async function resolveSourceAmountRaw({ messenger, order, fiatAsset, walletAddress, }) {
|
|
35
|
+
if (order.txHash) {
|
|
36
|
+
try {
|
|
37
|
+
const onChainAmount = await getTransferredAmountFromTxHash({
|
|
38
|
+
messenger,
|
|
39
|
+
txHash: order.txHash,
|
|
40
|
+
chainId: fiatAsset.chainId,
|
|
41
|
+
tokenAddress: fiatAsset.address,
|
|
42
|
+
walletAddress,
|
|
43
|
+
});
|
|
44
|
+
if (onChainAmount) {
|
|
45
|
+
log('Resolved source amount from on-chain transaction', {
|
|
46
|
+
txHash: order.txHash,
|
|
47
|
+
onChainAmount,
|
|
48
|
+
});
|
|
49
|
+
return onChainAmount;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
catch (error) {
|
|
53
|
+
log('Failed to read on-chain amount, falling back to order.cryptoAmount', { txHash: order.txHash, error });
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
const tokenInfo = getTokenInfo(messenger, fiatAsset.address, fiatAsset.chainId);
|
|
57
|
+
if (!tokenInfo) {
|
|
58
|
+
throw new Error(`Unable to resolve token info for fiat asset ${fiatAsset.address} on chain ${fiatAsset.chainId}`);
|
|
59
|
+
}
|
|
60
|
+
return getRawSourceAmountFromOrderCryptoAmount({
|
|
61
|
+
cryptoAmount: order.cryptoAmount,
|
|
62
|
+
decimals: tokenInfo.decimals,
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Converts the order's human-readable crypto amount to a raw token amount.
|
|
67
|
+
*
|
|
68
|
+
* @param options - The conversion options.
|
|
69
|
+
* @param options.cryptoAmount - Human-readable crypto amount from the completed order.
|
|
70
|
+
* @param options.decimals - Token decimals for the fiat asset.
|
|
71
|
+
* @returns The raw token amount as a string.
|
|
72
|
+
*/
|
|
73
|
+
export function getRawSourceAmountFromOrderCryptoAmount({ cryptoAmount, decimals, }) {
|
|
74
|
+
const normalizedAmount = new BigNumber(String(cryptoAmount));
|
|
75
|
+
if (!normalizedAmount.isFinite() || normalizedAmount.lte(0)) {
|
|
76
|
+
throw new Error(`Invalid fiat order crypto amount: ${String(cryptoAmount)}`);
|
|
77
|
+
}
|
|
78
|
+
const rawAmount = normalizedAmount
|
|
79
|
+
.shiftedBy(decimals)
|
|
80
|
+
.decimalPlaces(0, BigNumber.ROUND_DOWN)
|
|
81
|
+
.toFixed(0);
|
|
82
|
+
if (!new BigNumber(rawAmount).gt(0)) {
|
|
83
|
+
throw new Error('Computed fiat order source amount is not positive');
|
|
84
|
+
}
|
|
85
|
+
return rawAmount;
|
|
86
|
+
}
|
|
14
87
|
//# sourceMappingURL=utils.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../../src/strategy/fiat/utils.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../../src/strategy/fiat/utils.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,eAAe,EAAE,yCAAyC;AAEnE,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AACrD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EAAE,aAAa,EAAE,yBAAqB;AAE7C,OAAO,EAAE,8BAA8B,EAAE,sCAAkC;AAC3E,OAAO,EAAE,YAAY,EAAE,8BAA0B;AACjD,OAAO,EAAE,8BAA8B,EAAE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-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger';\nimport type { TransactionPayControllerMessenger } from '../../types';\nimport { getFiatAssetPerTransactionType } from '../../utils/feature-flags';\nimport { getTokenInfo } from '../../utils/token';\nimport { getTransferredAmountFromTxHash } from '../../utils/transaction';\nimport type { TransactionPayFiatAsset } from './constants';\nimport { FIAT_ASSET_ID_BY_TX_TYPE } from './constants';\n\nconst log = createModuleLogger(projectLogger, 'fiat-utils');\n\nexport function deriveFiatAssetForFiatPayment(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayFiatAsset {\n const txType = resolveTransactionType(transaction);\n\n return getFiatAssetPerTransactionType(messenger, txType);\n}\n\nfunction resolveTransactionType(\n transaction: TransactionMeta,\n): TransactionType | undefined {\n if (transaction.type !== TransactionType.batch) {\n return transaction.type;\n }\n\n return transaction.nestedTransactions?.find(\n (tx) => tx.type && FIAT_ASSET_ID_BY_TX_TYPE[tx.type] !== undefined,\n )?.type;\n}\n\n/**\n * Resolves the raw source amount for a completed fiat order.\n *\n * Attempts to read the actual transferred amount from the on-chain transaction\n * identified by `order.txHash`. If the on-chain read fails or returns\n * no amount, falls back to computing the amount from `order.cryptoAmount`.\n *\n * @param options - The resolution options.\n * @param options.messenger - Controller messenger for network access.\n * @param options.order - The completed on-ramp order.\n * @param options.fiatAsset - The fiat asset describing the expected token.\n * @param options.walletAddress - Recipient wallet address for on-chain lookup.\n * @returns The raw (atomic) source amount as a decimal string.\n */\nexport async function resolveSourceAmountRaw({\n messenger,\n order,\n fiatAsset,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n order: RampsOrder;\n fiatAsset: TransactionPayFiatAsset;\n walletAddress: Hex;\n}): Promise<string> {\n if (order.txHash) {\n try {\n const onChainAmount = await getTransferredAmountFromTxHash({\n messenger,\n txHash: order.txHash,\n chainId: fiatAsset.chainId,\n tokenAddress: fiatAsset.address,\n walletAddress,\n });\n\n if (onChainAmount) {\n log('Resolved source amount from on-chain transaction', {\n txHash: order.txHash,\n onChainAmount,\n });\n return onChainAmount;\n }\n } catch (error) {\n log(\n 'Failed to read on-chain amount, falling back to order.cryptoAmount',\n { txHash: order.txHash, error },\n );\n }\n }\n\n const tokenInfo = getTokenInfo(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error(\n `Unable to resolve token info for fiat asset ${fiatAsset.address} on chain ${fiatAsset.chainId}`,\n );\n }\n\n return getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount: order.cryptoAmount,\n decimals: tokenInfo.decimals,\n });\n}\n\n/**\n * Converts the order's human-readable crypto amount to a raw token amount.\n *\n * @param options - The conversion options.\n * @param options.cryptoAmount - Human-readable crypto amount from the completed order.\n * @param options.decimals - Token decimals for the fiat asset.\n * @returns The raw token amount as a string.\n */\nexport function getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount,\n decimals,\n}: {\n cryptoAmount: RampsOrder['cryptoAmount'];\n decimals: number;\n}): string {\n const normalizedAmount = new BigNumber(String(cryptoAmount));\n\n if (!normalizedAmount.isFinite() || normalizedAmount.lte(0)) {\n throw new Error(\n `Invalid fiat order crypto amount: ${String(cryptoAmount)}`,\n );\n }\n\n const rawAmount = normalizedAmount\n .shiftedBy(decimals)\n .decimalPlaces(0, BigNumber.ROUND_DOWN)\n .toFixed(0);\n\n if (!new BigNumber(rawAmount).gt(0)) {\n throw new Error('Computed fiat order source amount is not positive');\n }\n\n return rawAmount;\n}\n"]}
|
|
@@ -1,12 +1,17 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.isPredictWithdrawTransaction = exports.collectTransactionIds = exports.updateTransaction = exports.waitForTransactionConfirmed = exports.subscribeAssetChanges = exports.subscribeTransactionChanges = exports.getTransaction = exports.FINALIZED_STATUSES = void 0;
|
|
3
|
+
exports.getTransferredAmountFromTxHash = exports.isPredictWithdrawTransaction = exports.collectTransactionIds = exports.updateTransaction = exports.waitForTransactionConfirmed = exports.subscribeAssetChanges = exports.subscribeTransactionChanges = exports.getTransaction = exports.FINALIZED_STATUSES = void 0;
|
|
4
|
+
const abi_1 = require("@ethersproject/abi");
|
|
5
|
+
const providers_1 = require("@ethersproject/providers");
|
|
6
|
+
const metamask_eth_abis_1 = require("@metamask/metamask-eth-abis");
|
|
4
7
|
const transaction_controller_1 = require("@metamask/transaction-controller");
|
|
5
8
|
const utils_1 = require("@metamask/utils");
|
|
9
|
+
const bignumber_js_1 = require("bignumber.js");
|
|
6
10
|
const lodash_1 = require("lodash");
|
|
7
11
|
const logger_1 = require("../logger.cjs");
|
|
8
12
|
const feature_flags_1 = require("./feature-flags.cjs");
|
|
9
13
|
const required_tokens_1 = require("./required-tokens.cjs");
|
|
14
|
+
const token_1 = require("./token.cjs");
|
|
10
15
|
const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'transaction');
|
|
11
16
|
exports.FINALIZED_STATUSES = [
|
|
12
17
|
transaction_controller_1.TransactionStatus.confirmed,
|
|
@@ -202,4 +207,135 @@ function onTransactionFinalized(transaction, removeTransactionData) {
|
|
|
202
207
|
log('Transaction finalized', { transaction });
|
|
203
208
|
removeTransactionData(transaction.id);
|
|
204
209
|
}
|
|
210
|
+
const erc20Interface = new abi_1.Interface(metamask_eth_abis_1.abiERC20);
|
|
211
|
+
const ERC20_TRANSFER_EVENT_TOPIC = erc20Interface.getEventTopic('Transfer');
|
|
212
|
+
/**
|
|
213
|
+
* Reads the transferred token amount from a completed on-chain transaction.
|
|
214
|
+
*
|
|
215
|
+
* For native tokens the amount is resolved via `debug_traceTransaction`
|
|
216
|
+
* (internal-call aware), falling back to the top-level `tx.value`.
|
|
217
|
+
* For ERC-20 tokens the amount is decoded from `Transfer` event logs
|
|
218
|
+
* in the transaction receipt.
|
|
219
|
+
*
|
|
220
|
+
* @param options - The options.
|
|
221
|
+
* @param options.messenger - Controller messenger for network access.
|
|
222
|
+
* @param options.txHash - Transaction hash of the completed on-chain transaction.
|
|
223
|
+
* @param options.chainId - Chain ID where the transaction was executed.
|
|
224
|
+
* @param options.tokenAddress - Address of the transferred token.
|
|
225
|
+
* @param options.walletAddress - Recipient wallet address to filter transfers to.
|
|
226
|
+
* @returns The raw (atomic) transferred amount as a decimal string,
|
|
227
|
+
* or `undefined` if the amount cannot be determined.
|
|
228
|
+
*/
|
|
229
|
+
async function getTransferredAmountFromTxHash({ messenger, txHash, chainId, tokenAddress, walletAddress, }) {
|
|
230
|
+
const provider = getEthersProvider(messenger, chainId);
|
|
231
|
+
const isNative = tokenAddress.toLowerCase() === (0, token_1.getNativeToken)(chainId).toLowerCase();
|
|
232
|
+
if (isNative) {
|
|
233
|
+
return await getNativeTransferAmount(provider, txHash, walletAddress);
|
|
234
|
+
}
|
|
235
|
+
return await getErc20TransferAmount(provider, txHash, tokenAddress, walletAddress);
|
|
236
|
+
}
|
|
237
|
+
exports.getTransferredAmountFromTxHash = getTransferredAmountFromTxHash;
|
|
238
|
+
/**
|
|
239
|
+
* Resolves the native token amount received by a wallet from a transaction.
|
|
240
|
+
*
|
|
241
|
+
* 1. Attempts `debug_traceTransaction` with `callTracer` to walk internal
|
|
242
|
+
* calls and sum all native value transfers targeting `walletAddress`.
|
|
243
|
+
* 2. Falls back to the top-level `tx.value` when the wallet is the direct
|
|
244
|
+
* recipient and the trace RPC is unavailable or errors.
|
|
245
|
+
*
|
|
246
|
+
* @param provider - Ethers Web3Provider.
|
|
247
|
+
* @param txHash - Transaction hash.
|
|
248
|
+
* @param walletAddress - Recipient wallet address.
|
|
249
|
+
* @returns Raw amount as a decimal string, or `undefined`.
|
|
250
|
+
*/
|
|
251
|
+
async function getNativeTransferAmount(provider, txHash, walletAddress) {
|
|
252
|
+
try {
|
|
253
|
+
const trace = await provider.send('debug_traceTransaction', [
|
|
254
|
+
txHash,
|
|
255
|
+
{ tracer: 'callTracer' },
|
|
256
|
+
]);
|
|
257
|
+
const amount = sumNativeValueFromTrace(trace, walletAddress);
|
|
258
|
+
if (amount.gt(0)) {
|
|
259
|
+
return amount.toFixed(0);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
catch {
|
|
263
|
+
// debug_traceTransaction not supported — fall through to tx.value
|
|
264
|
+
}
|
|
265
|
+
const tx = await provider.getTransaction(txHash);
|
|
266
|
+
if (!tx) {
|
|
267
|
+
return undefined;
|
|
268
|
+
}
|
|
269
|
+
if (tx.to?.toLowerCase() !== walletAddress.toLowerCase()) {
|
|
270
|
+
return undefined;
|
|
271
|
+
}
|
|
272
|
+
return positiveOrUndefined(tx.value.toString());
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* Resolves the ERC-20 token amount received by a wallet from a transaction
|
|
276
|
+
* by decoding `Transfer` event logs from the transaction receipt.
|
|
277
|
+
*
|
|
278
|
+
* @param provider - Ethers Web3Provider.
|
|
279
|
+
* @param txHash - Transaction hash.
|
|
280
|
+
* @param tokenAddress - ERC-20 token contract address.
|
|
281
|
+
* @param walletAddress - Recipient wallet address.
|
|
282
|
+
* @returns Raw amount as a decimal string, or `undefined`.
|
|
283
|
+
*/
|
|
284
|
+
async function getErc20TransferAmount(provider, txHash, tokenAddress, walletAddress) {
|
|
285
|
+
const receipt = await provider.getTransactionReceipt(txHash);
|
|
286
|
+
if (!receipt) {
|
|
287
|
+
return undefined;
|
|
288
|
+
}
|
|
289
|
+
let total = new bignumber_js_1.BigNumber(0);
|
|
290
|
+
for (const txLog of receipt.logs) {
|
|
291
|
+
if (txLog.address.toLowerCase() !== tokenAddress.toLowerCase()) {
|
|
292
|
+
continue;
|
|
293
|
+
}
|
|
294
|
+
if (!txLog.topics[0] || txLog.topics[0] !== ERC20_TRANSFER_EVENT_TOPIC) {
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
try {
|
|
298
|
+
const parsed = erc20Interface.parseLog(txLog);
|
|
299
|
+
const to = parsed.args[1].toLowerCase();
|
|
300
|
+
if (to !== walletAddress.toLowerCase()) {
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
total = total.plus(parsed.args[2].toString());
|
|
304
|
+
}
|
|
305
|
+
catch {
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
return positiveOrUndefined(total.toFixed(0));
|
|
310
|
+
}
|
|
311
|
+
/**
|
|
312
|
+
* Recursively walks a `callTracer` result and sums native value
|
|
313
|
+
* transferred to a specific address.
|
|
314
|
+
*
|
|
315
|
+
* @param trace - Call trace node.
|
|
316
|
+
* @param walletAddress - Target address to accumulate value for.
|
|
317
|
+
* @returns Accumulated native value as BigNumber.
|
|
318
|
+
*/
|
|
319
|
+
function sumNativeValueFromTrace(trace, walletAddress) {
|
|
320
|
+
let total = new bignumber_js_1.BigNumber(0);
|
|
321
|
+
if (trace.to?.toLowerCase() === walletAddress.toLowerCase() &&
|
|
322
|
+
trace.value &&
|
|
323
|
+
trace.value !== '0x0') {
|
|
324
|
+
total = total.plus(new bignumber_js_1.BigNumber(trace.value));
|
|
325
|
+
}
|
|
326
|
+
if (trace.calls) {
|
|
327
|
+
for (const child of trace.calls) {
|
|
328
|
+
total = total.plus(sumNativeValueFromTrace(child, walletAddress));
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return total;
|
|
332
|
+
}
|
|
333
|
+
function getEthersProvider(messenger, chainId) {
|
|
334
|
+
const networkClientId = messenger.call('NetworkController:findNetworkClientIdByChainId', chainId);
|
|
335
|
+
const { provider } = messenger.call('NetworkController:getNetworkClientById', networkClientId);
|
|
336
|
+
return new providers_1.Web3Provider(provider);
|
|
337
|
+
}
|
|
338
|
+
function positiveOrUndefined(amount) {
|
|
339
|
+
return new bignumber_js_1.BigNumber(amount).gt(0) ? amount : undefined;
|
|
340
|
+
}
|
|
205
341
|
//# sourceMappingURL=transaction.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.cjs","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":";;;AAAA,6EAG0C;AAG1C,2CAAqD;AAErD,mCAAmC;AAEnC,0CAA0C;AAM1C,uDAA6D;AAC7D,2DAAwD;AAExD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,aAAa,CAAC,CAAC;AAEhD,QAAA,kBAAkB,GAAG;IAChC,0CAAiB,CAAC,SAAS;IAC3B,0CAAiB,CAAC,OAAO;IACzB,0CAAiB,CAAC,MAAM;CACzB,CAAC;AAEF;;;;;;GAMG;AACH,SAAgB,cAAc,CAC5B,aAAqB,EACrB,SAA4C;IAE5C,MAAM,0BAA0B,GAAG,SAAS,CAAC,IAAI,CAC/C,gCAAgC,CACjC,CAAC;IAEF,OAAO,0BAA0B,CAAC,YAAY,CAAC,IAAI,CACjD,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,KAAK,aAAa,CAChC,CAAC;AACJ,CAAC;AAXD,wCAWC;AAED;;;;;;GAMG;AACH,SAAgB,2BAA2B,CACzC,SAA4C,EAC5C,qBAAoD,EACpD,qBAAsD;IAEtD,SAAS,CAAC,SAAS,CACjB,mCAAmC,EACnC,CACE,YAA+B,EAC/B,oBAAmD,EACnD,EAAE;QACF,MAAM,eAAe,GAAG,YAAY,CAAC,MAAM,CACzC,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,oBAAoB,EAAE,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,CAAC,EAAE,KAAK,EAAE,CAAC,EAAE,CAAC,CACrE,CAAC;QAEF,MAAM,mBAAmB,GAAG,YAAY,CAAC,MAAM,CAAC,CAAC,EAAE,EAAE,EAAE;YACrD,MAAM,mBAAmB,GAAG,oBAAoB,EAAE,IAAI,CACpD,CAAC,MAAM,EAAE,EAAE,CAAC,MAAM,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;IAEF,MAAM,GAAG,GAAG,GAAS,EAAE;QACrB,SAAS,CAAC,WAAW,CACnB,kDAAkD,EAClD,QAAQ,CACT,CAAC;IACJ,CAAC,CAAC;IAEF,OAAO,EAAE,GAAG,EAAE,CAAC;AACjB,CAAC;AA9BD,sDA8BC;AAED;;;;;;;;GAQG;AACH,SAAgB,4BAA4B,CAC1C,WAA4B;IAE5B,OAAO,CACL,WAAW,CAAC,IAAI,KAAK,wCAAe,CAAC,eAAe;QACpD,CAAC,WAAW,CAAC,kBAAkB,EAAE,IAAI,CACnC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,IAAI,KAAK,wCAAe,CAAC,eAAe,CACpD;YACC,KAAK,CAAC,CACT,CAAC;AACJ,CAAC;AAVD,oEAUC;AAED;;;;;;GAMG;AACH,SAAS,mBAAmB,CAC1B,WAA4B,EAC5B,SAA4C,EAC5C,qBAAoD;IAEpD,MAAM,MAAM,GAAG,IAAA,qCAAmB,EAAC,WAAW,EAAE,SAAS,CAAC,CAAC;IAE3D,GAAG,CAAC,qBAAqB,EAAE,EAAE,WAAW,EAAE,MAAM,EAAE,CAAC,CAAC;IAEpD,qBAAqB,CAAC,WAAW,CAAC,EAAE,EAAE,CAAC,IAAI,EAAE,EAAE;QAC7C,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC,CAAC,CAAC;AACL,CAAC;AAED;;;;;GAKG;AACH,SAAS,sBAAsB,CAC7B,WAA4B,EAC5B,qBAAsD;IAEtD,GAAG,CAAC,uBAAuB,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;IAC9C,qBAAqB,CAAC,WAAW,CAAC,EAAE,CAAC,CAAC;AACxC,CAAC","sourcesContent":["import {\n TransactionStatus,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport type { Patch } from 'immer';\nimport { cloneDeep } from 'lodash';\n\nimport { projectLogger } from '../logger';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayControllerState,\n UpdateTransactionDataCallback,\n} from '../types';\nimport { getAssetsUnifyStateFeature } from './feature-flags';\nimport { parseRequiredTokens } from './required-tokens';\n\nconst log = createModuleLogger(projectLogger, 'transaction');\n\nexport const FINALIZED_STATUSES = [\n TransactionStatus.confirmed,\n TransactionStatus.dropped,\n TransactionStatus.failed,\n];\n\n/**\n * Retrieve transaction metadata by ID.\n *\n * @param transactionId - ID of the transaction to retrieve.\n * @param messenger - Controller messenger.\n * @returns The transaction metadata or undefined if not found.\n */\nexport function getTransaction(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): TransactionMeta | undefined {\n const transactionControllerState = messenger.call(\n 'TransactionController:getState',\n );\n\n return transactionControllerState.transactions.find(\n (tx) => tx.id === transactionId,\n );\n}\n\n/**\n * Subscribe to transaction changes and update the transaction data accordingly.\n *\n * @param messenger - Controller messenger.\n * @param updateTransactionData - Callback to update transaction data.\n * @param removeTransactionData - Callback to remove transaction data.\n */\nexport function subscribeTransactionChanges(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n removeTransactionData: (transactionId: string) => void,\n): void {\n messenger.subscribe(\n 'TransactionController:stateChange',\n (\n transactions: TransactionMeta[],\n previousTransactions: TransactionMeta[] | undefined,\n ) => {\n const newTransactions = transactions.filter(\n (tx) => !previousTransactions?.find((prevTx) => prevTx.id === tx.id),\n );\n\n const updatedTransactions = transactions.filter((tx) => {\n const previousTransaction = previousTransactions?.find(\n (prevTx) => prevTx.id === tx.id,\n );\n\n return (\n previousTransaction &&\n previousTransaction?.txParams.data !== tx.txParams.data\n );\n });\n\n const finalizedTransactions = transactions.filter((tx) => {\n const previousTransaction = previousTransactions?.find(\n (prevTx) => prevTx.id === tx.id,\n );\n\n return (\n previousTransaction &&\n !FINALIZED_STATUSES.includes(previousTransaction.status) &&\n FINALIZED_STATUSES.includes(tx.status)\n );\n });\n\n const deletedTransactions = (previousTransactions ?? []).filter(\n (prevTx) => !transactions.find((tx) => tx.id === prevTx.id),\n );\n\n [...finalizedTransactions, ...deletedTransactions].forEach((tx) =>\n onTransactionFinalized(tx, removeTransactionData),\n );\n\n [...newTransactions, ...updatedTransactions].forEach((tx) =>\n onTransactionChange(tx, messenger, updateTransactionData),\n );\n },\n (state) => state.transactions,\n );\n}\n\n/**\n * Subscribe to asset state changes and re-parse required tokens for\n * in-flight transactions whose tokens have not yet resolved.\n *\n * @param messenger - Controller messenger.\n * @param getControllerState - Callback returning the current controller state.\n * @param updateTransactionData - Callback to update transaction data.\n */\nexport function subscribeAssetChanges(\n messenger: TransactionPayControllerMessenger,\n getControllerState: () => TransactionPayControllerState,\n updateTransactionData: UpdateTransactionDataCallback,\n): void {\n const buildHandler =\n (source: string) =>\n (_state: unknown, patches: Patch[] | undefined): void => {\n const { transactionData } = getControllerState();\n\n for (const [transactionId, data] of Object.entries(transactionData)) {\n if (data.tokens.length > 0) {\n continue;\n }\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || FINALIZED_STATUSES.includes(transaction.status)) {\n continue;\n }\n\n log('Asset data changed', { transactionId, source, patches });\n\n onTransactionChange(transaction, messenger, updateTransactionData);\n }\n };\n\n if (getAssetsUnifyStateFeature(messenger)) {\n messenger.subscribe(\n 'AssetsController:stateChange',\n buildHandler('AssetsController'),\n );\n return;\n }\n\n messenger.subscribe(\n 'TokensController:stateChange',\n buildHandler('TokensController'),\n );\n messenger.subscribe(\n 'TokenRatesController:stateChange',\n buildHandler('TokenRatesController'),\n );\n messenger.subscribe(\n 'CurrencyRateController:stateChange',\n buildHandler('CurrencyRateController'),\n );\n}\n\n/**\n * Wait for a transaction to be confirmed or fail.\n *\n * @param transactionId - ID of the transaction to wait for.\n * @param messenger - Controller messenger.\n * @returns A promise that resolves when the transaction is confirmed or rejects if it fails.\n */\nexport function waitForTransactionConfirmed(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const isConfirmed = (tx?: TransactionMeta, fn?: () => void): boolean => {\n log('Checking transaction status', tx?.status, tx?.type);\n\n if (tx?.status === TransactionStatus.confirmed) {\n fn?.();\n resolve();\n return true;\n }\n\n if (\n [TransactionStatus.dropped, TransactionStatus.failed].includes(\n tx?.status as TransactionStatus,\n )\n ) {\n fn?.();\n reject(\n new Error(`Transaction failed - ${tx?.type} - ${tx?.error?.message}`),\n );\n return true;\n }\n\n return false;\n };\n\n const initialState = messenger.call('TransactionController:getState');\n\n const initialTx = initialState.transactions.find(\n (singleTransaction) => singleTransaction.id === transactionId,\n );\n\n if (isConfirmed(initialTx)) {\n return;\n }\n\n const handler = (tx?: TransactionMeta): void => {\n const unsubscribe = (): void =>\n messenger.unsubscribe('TransactionController:stateChange', handler);\n\n isConfirmed(tx, unsubscribe);\n };\n\n messenger.subscribe('TransactionController:stateChange', handler, (state) =>\n state.transactions.find((tx) => tx.id === transactionId),\n );\n });\n}\n\n/**\n * Update a transaction by applying a function to its draft.\n *\n * @param request - Request object.\n * @param request.transactionId - ID of the transaction to update.\n * @param request.messenger - Controller messenger.\n * @param request.note - Note describing the update.\n * @param fn - Function that applies updates to the transaction draft.\n */\nexport function updateTransaction(\n {\n transactionId,\n messenger,\n note,\n }: {\n transactionId: string;\n messenger: TransactionPayControllerMessenger;\n note: string;\n },\n fn: (draft: TransactionMeta) => void,\n): void {\n const transaction = getTransaction(transactionId, messenger as never);\n\n if (!transaction) {\n throw new Error(`Transaction not found: ${transactionId}`);\n }\n\n const newTransaction = cloneDeep(transaction);\n\n fn(newTransaction);\n\n messenger.call(\n 'TransactionController:updateTransaction',\n newTransaction,\n note,\n );\n}\n\n/**\n * Collect all new transactions until `end` is called.\n *\n * @param chainId - The chain ID to filter transactions by.\n * @param from - The address to filter transactions by.\n * @param messenger - The controller messenger.\n * @param onTransaction - Callback called with each matching transaction ID.\n * @returns An object with an `end` method to stop collecting transactions.\n */\nexport function collectTransactionIds(\n chainId: Hex,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n onTransaction: (transactionId: string) => void,\n): { end: () => void } {\n const listener = (tx: TransactionMeta): void => {\n if (\n tx.chainId !== chainId ||\n tx.txParams.from.toLowerCase() !== from.toLowerCase()\n ) {\n return;\n }\n\n onTransaction(tx.id);\n };\n\n messenger.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n listener,\n );\n\n const end = (): void => {\n messenger.unsubscribe(\n 'TransactionController:unapprovedTransactionAdded',\n listener,\n );\n };\n\n return { end };\n}\n\n/**\n * Check whether a transaction is a Predict withdrawal.\n *\n * Returns `true` when the transaction's own type is `predictWithdraw`, or\n * when any of its nested transactions has that type.\n *\n * @param transaction - Transaction metadata.\n * @returns `true` when the transaction is a Predict withdrawal.\n */\nexport function isPredictWithdrawTransaction(\n transaction: TransactionMeta,\n): boolean {\n return (\n transaction.type === TransactionType.predictWithdraw ||\n (transaction.nestedTransactions?.some(\n (nt) => nt.type === TransactionType.predictWithdraw,\n ) ??\n false)\n );\n}\n\n/**\n * Handle a transaction change by updating its associated data.\n *\n * @param transaction - Transaction metadata.\n * @param messenger - Controller messenger.\n * @param updateTransactionData - Callback to update transaction data.\n */\nfunction onTransactionChange(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n): void {\n const tokens = parseRequiredTokens(transaction, messenger);\n\n log('Transaction changed', { transaction, tokens });\n\n updateTransactionData(transaction.id, (data) => {\n data.tokens = tokens;\n });\n}\n\n/**\n * Handle a finalized transaction by removing its associated data.\n *\n * @param transaction - Transaction metadata.\n * @param removeTransactionData - Callback to remove transaction data.\n */\nfunction onTransactionFinalized(\n transaction: TransactionMeta,\n removeTransactionData: (transactionId: string) => void,\n): void {\n log('Transaction finalized', { transaction });\n removeTransactionData(transaction.id);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"transaction.cjs","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":";;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AgB,EAChB,aAAkB;IAElB,IAAI,KAAK,GAAG,IAAI,wBAAS,CAAC,CAAC,CAAC,CAAC;IAE7B,IACE,KAAK,CAAC,EAAE,EAAE,WAAW,EAAE,KAAK,aAAa,CAAC,WAAW,EAAE;QACvD,KAAK,CAAC,KAAK;QACX,KAAK,CAAC,KAAK,KAAK,KAAK,EACrB,CAAC;QACD,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,wBAAS,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,CAAC;IACjD,CAAC;IAED,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;QAChB,KAAK,MAAM,KAAK,IAAI,KAAK,CAAC,KAAK,EAAE,CAAC;YAChC,KAAK,GAAG,KAAK,CAAC,IAAI,CAAC,uBAAuB,CAAC,KAAK,EAAE,aAAa,CAAC,CAAC,CAAC;QACpE,CAAC;IACH,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,iBAAiB,CACxB,SAA4C,EAC5C,OAAY;IAEZ,MAAM,eAAe,GAAG,SAAS,CAAC,IAAI,CACpC,gDAAgD,EAChD,OAAO,CACR,CAAC;IAEF,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAC,IAAI,CACjC,wCAAwC,EACxC,eAAe,CAChB,CAAC;IAEF,OAAO,IAAI,wBAAY,CAAC,QAAQ,CAAC,CAAC;AACpC,CAAC;AAED,SAAS,mBAAmB,CAAC,MAAc;IACzC,OAAO,IAAI,wBAAS,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { Web3Provider } from '@ethersproject/providers';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport {\n TransactionStatus,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\nimport type { Patch } from 'immer';\nimport { cloneDeep } from 'lodash';\n\nimport { projectLogger } from '../logger';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayControllerState,\n UpdateTransactionDataCallback,\n} from '../types';\nimport { getAssetsUnifyStateFeature } from './feature-flags';\nimport { parseRequiredTokens } from './required-tokens';\nimport { getNativeToken } from './token';\n\nconst log = createModuleLogger(projectLogger, 'transaction');\n\nexport const FINALIZED_STATUSES = [\n TransactionStatus.confirmed,\n TransactionStatus.dropped,\n TransactionStatus.failed,\n];\n\n/**\n * Retrieve transaction metadata by ID.\n *\n * @param transactionId - ID of the transaction to retrieve.\n * @param messenger - Controller messenger.\n * @returns The transaction metadata or undefined if not found.\n */\nexport function getTransaction(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): TransactionMeta | undefined {\n const transactionControllerState = messenger.call(\n 'TransactionController:getState',\n );\n\n return transactionControllerState.transactions.find(\n (tx) => tx.id === transactionId,\n );\n}\n\n/**\n * Subscribe to transaction changes and update the transaction data accordingly.\n *\n * @param messenger - Controller messenger.\n * @param updateTransactionData - Callback to update transaction data.\n * @param removeTransactionData - Callback to remove transaction data.\n */\nexport function subscribeTransactionChanges(\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n removeTransactionData: (transactionId: string) => void,\n): void {\n messenger.subscribe(\n 'TransactionController:stateChange',\n (\n transactions: TransactionMeta[],\n previousTransactions: TransactionMeta[] | undefined,\n ) => {\n const newTransactions = transactions.filter(\n (tx) => !previousTransactions?.find((prevTx) => prevTx.id === tx.id),\n );\n\n const updatedTransactions = transactions.filter((tx) => {\n const previousTransaction = previousTransactions?.find(\n (prevTx) => prevTx.id === tx.id,\n );\n\n return (\n previousTransaction &&\n previousTransaction?.txParams.data !== tx.txParams.data\n );\n });\n\n const finalizedTransactions = transactions.filter((tx) => {\n const previousTransaction = previousTransactions?.find(\n (prevTx) => prevTx.id === tx.id,\n );\n\n return (\n previousTransaction &&\n !FINALIZED_STATUSES.includes(previousTransaction.status) &&\n FINALIZED_STATUSES.includes(tx.status)\n );\n });\n\n const deletedTransactions = (previousTransactions ?? []).filter(\n (prevTx) => !transactions.find((tx) => tx.id === prevTx.id),\n );\n\n [...finalizedTransactions, ...deletedTransactions].forEach((tx) =>\n onTransactionFinalized(tx, removeTransactionData),\n );\n\n [...newTransactions, ...updatedTransactions].forEach((tx) =>\n onTransactionChange(tx, messenger, updateTransactionData),\n );\n },\n (state) => state.transactions,\n );\n}\n\n/**\n * Subscribe to asset state changes and re-parse required tokens for\n * in-flight transactions whose tokens have not yet resolved.\n *\n * @param messenger - Controller messenger.\n * @param getControllerState - Callback returning the current controller state.\n * @param updateTransactionData - Callback to update transaction data.\n */\nexport function subscribeAssetChanges(\n messenger: TransactionPayControllerMessenger,\n getControllerState: () => TransactionPayControllerState,\n updateTransactionData: UpdateTransactionDataCallback,\n): void {\n const buildHandler =\n (source: string) =>\n (_state: unknown, patches: Patch[] | undefined): void => {\n const { transactionData } = getControllerState();\n\n for (const [transactionId, data] of Object.entries(transactionData)) {\n if (data.tokens.length > 0) {\n continue;\n }\n\n const transaction = getTransaction(transactionId, messenger);\n\n if (!transaction || FINALIZED_STATUSES.includes(transaction.status)) {\n continue;\n }\n\n log('Asset data changed', { transactionId, source, patches });\n\n onTransactionChange(transaction, messenger, updateTransactionData);\n }\n };\n\n if (getAssetsUnifyStateFeature(messenger)) {\n messenger.subscribe(\n 'AssetsController:stateChange',\n buildHandler('AssetsController'),\n );\n return;\n }\n\n messenger.subscribe(\n 'TokensController:stateChange',\n buildHandler('TokensController'),\n );\n messenger.subscribe(\n 'TokenRatesController:stateChange',\n buildHandler('TokenRatesController'),\n );\n messenger.subscribe(\n 'CurrencyRateController:stateChange',\n buildHandler('CurrencyRateController'),\n );\n}\n\n/**\n * Wait for a transaction to be confirmed or fail.\n *\n * @param transactionId - ID of the transaction to wait for.\n * @param messenger - Controller messenger.\n * @returns A promise that resolves when the transaction is confirmed or rejects if it fails.\n */\nexport function waitForTransactionConfirmed(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n const isConfirmed = (tx?: TransactionMeta, fn?: () => void): boolean => {\n log('Checking transaction status', tx?.status, tx?.type);\n\n if (tx?.status === TransactionStatus.confirmed) {\n fn?.();\n resolve();\n return true;\n }\n\n if (\n [TransactionStatus.dropped, TransactionStatus.failed].includes(\n tx?.status as TransactionStatus,\n )\n ) {\n fn?.();\n reject(\n new Error(`Transaction failed - ${tx?.type} - ${tx?.error?.message}`),\n );\n return true;\n }\n\n return false;\n };\n\n const initialState = messenger.call('TransactionController:getState');\n\n const initialTx = initialState.transactions.find(\n (singleTransaction) => singleTransaction.id === transactionId,\n );\n\n if (isConfirmed(initialTx)) {\n return;\n }\n\n const handler = (tx?: TransactionMeta): void => {\n const unsubscribe = (): void =>\n messenger.unsubscribe('TransactionController:stateChange', handler);\n\n isConfirmed(tx, unsubscribe);\n };\n\n messenger.subscribe('TransactionController:stateChange', handler, (state) =>\n state.transactions.find((tx) => tx.id === transactionId),\n );\n });\n}\n\n/**\n * Update a transaction by applying a function to its draft.\n *\n * @param request - Request object.\n * @param request.transactionId - ID of the transaction to update.\n * @param request.messenger - Controller messenger.\n * @param request.note - Note describing the update.\n * @param fn - Function that applies updates to the transaction draft.\n */\nexport function updateTransaction(\n {\n transactionId,\n messenger,\n note,\n }: {\n transactionId: string;\n messenger: TransactionPayControllerMessenger;\n note: string;\n },\n fn: (draft: TransactionMeta) => void,\n): void {\n const transaction = getTransaction(transactionId, messenger as never);\n\n if (!transaction) {\n throw new Error(`Transaction not found: ${transactionId}`);\n }\n\n const newTransaction = cloneDeep(transaction);\n\n fn(newTransaction);\n\n messenger.call(\n 'TransactionController:updateTransaction',\n newTransaction,\n note,\n );\n}\n\n/**\n * Collect all new transactions until `end` is called.\n *\n * @param chainId - The chain ID to filter transactions by.\n * @param from - The address to filter transactions by.\n * @param messenger - The controller messenger.\n * @param onTransaction - Callback called with each matching transaction ID.\n * @returns An object with an `end` method to stop collecting transactions.\n */\nexport function collectTransactionIds(\n chainId: Hex,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n onTransaction: (transactionId: string) => void,\n): { end: () => void } {\n const listener = (tx: TransactionMeta): void => {\n if (\n tx.chainId !== chainId ||\n tx.txParams.from.toLowerCase() !== from.toLowerCase()\n ) {\n return;\n }\n\n onTransaction(tx.id);\n };\n\n messenger.subscribe(\n 'TransactionController:unapprovedTransactionAdded',\n listener,\n );\n\n const end = (): void => {\n messenger.unsubscribe(\n 'TransactionController:unapprovedTransactionAdded',\n listener,\n );\n };\n\n return { end };\n}\n\n/**\n * Check whether a transaction is a Predict withdrawal.\n *\n * Returns `true` when the transaction's own type is `predictWithdraw`, or\n * when any of its nested transactions has that type.\n *\n * @param transaction - Transaction metadata.\n * @returns `true` when the transaction is a Predict withdrawal.\n */\nexport function isPredictWithdrawTransaction(\n transaction: TransactionMeta,\n): boolean {\n return (\n transaction.type === TransactionType.predictWithdraw ||\n (transaction.nestedTransactions?.some(\n (nt) => nt.type === TransactionType.predictWithdraw,\n ) ??\n false)\n );\n}\n\n/**\n * Handle a transaction change by updating its associated data.\n *\n * @param transaction - Transaction metadata.\n * @param messenger - Controller messenger.\n * @param updateTransactionData - Callback to update transaction data.\n */\nfunction onTransactionChange(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n updateTransactionData: UpdateTransactionDataCallback,\n): void {\n const tokens = parseRequiredTokens(transaction, messenger);\n\n log('Transaction changed', { transaction, tokens });\n\n updateTransactionData(transaction.id, (data) => {\n data.tokens = tokens;\n });\n}\n\n/**\n * Handle a finalized transaction by removing its associated data.\n *\n * @param transaction - Transaction metadata.\n * @param removeTransactionData - Callback to remove transaction data.\n */\nfunction onTransactionFinalized(\n transaction: TransactionMeta,\n removeTransactionData: (transactionId: string) => void,\n): void {\n log('Transaction finalized', { transaction });\n removeTransactionData(transaction.id);\n}\n\nconst erc20Interface = new Interface(abiERC20);\n\nconst ERC20_TRANSFER_EVENT_TOPIC = erc20Interface.getEventTopic('Transfer');\n\n/**\n * Reads the transferred token amount from a completed on-chain transaction.\n *\n * For native tokens the amount is resolved via `debug_traceTransaction`\n * (internal-call aware), falling back to the top-level `tx.value`.\n * For ERC-20 tokens the amount is decoded from `Transfer` event logs\n * in the transaction receipt.\n *\n * @param options - The options.\n * @param options.messenger - Controller messenger for network access.\n * @param options.txHash - Transaction hash of the completed on-chain transaction.\n * @param options.chainId - Chain ID where the transaction was executed.\n * @param options.tokenAddress - Address of the transferred token.\n * @param options.walletAddress - Recipient wallet address to filter transfers to.\n * @returns The raw (atomic) transferred amount as a decimal string,\n * or `undefined` if the amount cannot be determined.\n */\nexport async function getTransferredAmountFromTxHash({\n messenger,\n txHash,\n chainId,\n tokenAddress,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n txHash: string;\n chainId: Hex;\n tokenAddress: Hex;\n walletAddress: Hex;\n}): Promise<string | undefined> {\n const provider = getEthersProvider(messenger, chainId);\n\n const isNative =\n tokenAddress.toLowerCase() === getNativeToken(chainId).toLowerCase();\n\n if (isNative) {\n return await getNativeTransferAmount(provider, txHash, walletAddress);\n }\n\n return await getErc20TransferAmount(\n provider,\n txHash,\n tokenAddress,\n walletAddress,\n );\n}\n\n/**\n * Resolves the native token amount received by a wallet from a transaction.\n *\n * 1. Attempts `debug_traceTransaction` with `callTracer` to walk internal\n * calls and sum all native value transfers targeting `walletAddress`.\n * 2. Falls back to the top-level `tx.value` when the wallet is the direct\n * recipient and the trace RPC is unavailable or errors.\n *\n * @param provider - Ethers Web3Provider.\n * @param txHash - Transaction hash.\n * @param walletAddress - Recipient wallet address.\n * @returns Raw amount as a decimal string, or `undefined`.\n */\nasync function getNativeTransferAmount(\n provider: Web3Provider,\n txHash: string,\n walletAddress: Hex,\n): Promise<string | undefined> {\n try {\n const trace = await provider.send('debug_traceTransaction', [\n txHash,\n { tracer: 'callTracer' },\n ]);\n\n const amount = sumNativeValueFromTrace(trace, walletAddress);\n if (amount.gt(0)) {\n return amount.toFixed(0);\n }\n } catch {\n // debug_traceTransaction not supported — fall through to tx.value\n }\n\n const tx = await provider.getTransaction(txHash);\n if (!tx) {\n return undefined;\n }\n\n if (tx.to?.toLowerCase() !== walletAddress.toLowerCase()) {\n return undefined;\n }\n\n return positiveOrUndefined(tx.value.toString());\n}\n\n/**\n * Resolves the ERC-20 token amount received by a wallet from a transaction\n * by decoding `Transfer` event logs from the transaction receipt.\n *\n * @param provider - Ethers Web3Provider.\n * @param txHash - Transaction hash.\n * @param tokenAddress - ERC-20 token contract address.\n * @param walletAddress - Recipient wallet address.\n * @returns Raw amount as a decimal string, or `undefined`.\n */\nasync function getErc20TransferAmount(\n provider: Web3Provider,\n txHash: string,\n tokenAddress: Hex,\n walletAddress: Hex,\n): Promise<string | undefined> {\n const receipt = await provider.getTransactionReceipt(txHash);\n\n if (!receipt) {\n return undefined;\n }\n\n let total = new BigNumber(0);\n\n for (const txLog of receipt.logs) {\n if (txLog.address.toLowerCase() !== tokenAddress.toLowerCase()) {\n continue;\n }\n\n if (!txLog.topics[0] || txLog.topics[0] !== ERC20_TRANSFER_EVENT_TOPIC) {\n continue;\n }\n\n try {\n const parsed = erc20Interface.parseLog(txLog);\n const to = (parsed.args[1] as string).toLowerCase();\n\n if (to !== walletAddress.toLowerCase()) {\n continue;\n }\n\n total = total.plus(parsed.args[2].toString());\n } catch {\n continue;\n }\n }\n\n return positiveOrUndefined(total.toFixed(0));\n}\n\ntype CallTrace = {\n to?: string;\n value?: string;\n calls?: CallTrace[];\n};\n\n/**\n * Recursively walks a `callTracer` result and sums native value\n * transferred to a specific address.\n *\n * @param trace - Call trace node.\n * @param walletAddress - Target address to accumulate value for.\n * @returns Accumulated native value as BigNumber.\n */\nfunction sumNativeValueFromTrace(\n trace: CallTrace,\n walletAddress: Hex,\n): BigNumber {\n let total = new BigNumber(0);\n\n if (\n trace.to?.toLowerCase() === walletAddress.toLowerCase() &&\n trace.value &&\n trace.value !== '0x0'\n ) {\n total = total.plus(new BigNumber(trace.value));\n }\n\n if (trace.calls) {\n for (const child of trace.calls) {\n total = total.plus(sumNativeValueFromTrace(child, walletAddress));\n }\n }\n\n return total;\n}\n\nfunction getEthersProvider(\n messenger: TransactionPayControllerMessenger,\n chainId: Hex,\n): Web3Provider {\n const networkClientId = messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n\n const { provider } = messenger.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n\n return new Web3Provider(provider);\n}\n\nfunction positiveOrUndefined(amount: string): string | undefined {\n return new BigNumber(amount).gt(0) ? amount : undefined;\n}\n"]}
|
|
@@ -72,4 +72,28 @@ export declare function collectTransactionIds(chainId: Hex, from: Hex, messenger
|
|
|
72
72
|
* @returns `true` when the transaction is a Predict withdrawal.
|
|
73
73
|
*/
|
|
74
74
|
export declare function isPredictWithdrawTransaction(transaction: TransactionMeta): boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Reads the transferred token amount from a completed on-chain transaction.
|
|
77
|
+
*
|
|
78
|
+
* For native tokens the amount is resolved via `debug_traceTransaction`
|
|
79
|
+
* (internal-call aware), falling back to the top-level `tx.value`.
|
|
80
|
+
* For ERC-20 tokens the amount is decoded from `Transfer` event logs
|
|
81
|
+
* in the transaction receipt.
|
|
82
|
+
*
|
|
83
|
+
* @param options - The options.
|
|
84
|
+
* @param options.messenger - Controller messenger for network access.
|
|
85
|
+
* @param options.txHash - Transaction hash of the completed on-chain transaction.
|
|
86
|
+
* @param options.chainId - Chain ID where the transaction was executed.
|
|
87
|
+
* @param options.tokenAddress - Address of the transferred token.
|
|
88
|
+
* @param options.walletAddress - Recipient wallet address to filter transfers to.
|
|
89
|
+
* @returns The raw (atomic) transferred amount as a decimal string,
|
|
90
|
+
* or `undefined` if the amount cannot be determined.
|
|
91
|
+
*/
|
|
92
|
+
export declare function getTransferredAmountFromTxHash({ messenger, txHash, chainId, tokenAddress, walletAddress, }: {
|
|
93
|
+
messenger: TransactionPayControllerMessenger;
|
|
94
|
+
txHash: string;
|
|
95
|
+
chainId: Hex;
|
|
96
|
+
tokenAddress: Hex;
|
|
97
|
+
walletAddress: Hex;
|
|
98
|
+
}): Promise<string | undefined>;
|
|
75
99
|
//# sourceMappingURL=transaction.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.d.cts","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"transaction.d.cts","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iBAAiB,EAElB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAO3C,OAAO,KAAK,EACV,iCAAiC,EACjC,6BAA6B,EAC7B,6BAA6B,EAC9B,qBAAiB;AAOlB,eAAO,MAAM,kBAAkB,qBAI9B,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,aAAa,EAAE,MAAM,EACrB,SAAS,EAAE,iCAAiC,GAC3C,eAAe,GAAG,SAAS,CAQ7B;AAED;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CACzC,SAAS,EAAE,iCAAiC,EAC5C,qBAAqB,EAAE,6BAA6B,EACpD,qBAAqB,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,IAAI,GACrD,IAAI,CAgDN;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,iCAAiC,EAC5C,kBAAkB,EAAE,MAAM,6BAA6B,EACvD,qBAAqB,EAAE,6BAA6B,GACnD,IAAI,CA2CN;AAED;;;;;;GAMG;AACH,wBAAgB,2BAA2B,CACzC,aAAa,EAAE,MAAM,EACrB,SAAS,EAAE,iCAAiC,GAC3C,OAAO,CAAC,IAAI,CAAC,CA+Cf;AAED;;;;;;;;GAQG;AACH,wBAAgB,iBAAiB,CAC/B,EACE,aAAa,EACb,SAAS,EACT,IAAI,GACL,EAAE;IACD,aAAa,EAAE,MAAM,CAAC;IACtB,SAAS,EAAE,iCAAiC,CAAC;IAC7C,IAAI,EAAE,MAAM,CAAC;CACd,EACD,EAAE,EAAE,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,GACnC,IAAI,CAgBN;AAED;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,GAAG,EACZ,IAAI,EAAE,GAAG,EACT,SAAS,EAAE,iCAAiC,EAC5C,aAAa,EAAE,CAAC,aAAa,EAAE,MAAM,KAAK,IAAI,GAC7C;IAAE,GAAG,EAAE,MAAM,IAAI,CAAA;CAAE,CAyBrB;AAED;;;;;;;;GAQG;AACH,wBAAgB,4BAA4B,CAC1C,WAAW,EAAE,eAAe,GAC3B,OAAO,CAQT;AAyCD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAsB,8BAA8B,CAAC,EACnD,SAAS,EACT,MAAM,EACN,OAAO,EACP,YAAY,EACZ,aAAa,GACd,EAAE;IACD,SAAS,EAAE,iCAAiC,CAAC;IAC7C,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,GAAG,CAAC;IACb,YAAY,EAAE,GAAG,CAAC;IAClB,aAAa,EAAE,GAAG,CAAC;CACpB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAgB9B"}
|
|
@@ -72,4 +72,28 @@ export declare function collectTransactionIds(chainId: Hex, from: Hex, messenger
|
|
|
72
72
|
* @returns `true` when the transaction is a Predict withdrawal.
|
|
73
73
|
*/
|
|
74
74
|
export declare function isPredictWithdrawTransaction(transaction: TransactionMeta): boolean;
|
|
75
|
+
/**
|
|
76
|
+
* Reads the transferred token amount from a completed on-chain transaction.
|
|
77
|
+
*
|
|
78
|
+
* For native tokens the amount is resolved via `debug_traceTransaction`
|
|
79
|
+
* (internal-call aware), falling back to the top-level `tx.value`.
|
|
80
|
+
* For ERC-20 tokens the amount is decoded from `Transfer` event logs
|
|
81
|
+
* in the transaction receipt.
|
|
82
|
+
*
|
|
83
|
+
* @param options - The options.
|
|
84
|
+
* @param options.messenger - Controller messenger for network access.
|
|
85
|
+
* @param options.txHash - Transaction hash of the completed on-chain transaction.
|
|
86
|
+
* @param options.chainId - Chain ID where the transaction was executed.
|
|
87
|
+
* @param options.tokenAddress - Address of the transferred token.
|
|
88
|
+
* @param options.walletAddress - Recipient wallet address to filter transfers to.
|
|
89
|
+
* @returns The raw (atomic) transferred amount as a decimal string,
|
|
90
|
+
* or `undefined` if the amount cannot be determined.
|
|
91
|
+
*/
|
|
92
|
+
export declare function getTransferredAmountFromTxHash({ messenger, txHash, chainId, tokenAddress, walletAddress, }: {
|
|
93
|
+
messenger: TransactionPayControllerMessenger;
|
|
94
|
+
txHash: string;
|
|
95
|
+
chainId: Hex;
|
|
96
|
+
tokenAddress: Hex;
|
|
97
|
+
walletAddress: Hex;
|
|
98
|
+
}): Promise<string | undefined>;
|
|
75
99
|
//# sourceMappingURL=transaction.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transaction.d.mts","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"transaction.d.mts","sourceRoot":"","sources":["../../src/utils/transaction.ts"],"names":[],"mappings":"AAGA,OAAO,EACL,iBAAiB,EAElB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAO3C,OAAO,KAAK,EACV,iCAAiC,EACjC,6BAA6B,EAC7B,6BAA6B,EAC9B,qBAAiB;AAOlB,eAAO,MAAM,kBAAkB,qBAI9B,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,cAAc,CAC5B,aAAa,EAAE,MAAM,EACrB,SAAS,E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C7C,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,GAAG,CAAC;IACb,YAAY,EAAE,GAAG,CAAC;IAClB,aAAa,EAAE,GAAG,CAAC;CACpB,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAgB9B"}
|
|
@@ -1,10 +1,15 @@
|
|
|
1
|
+
import { Interface } from "@ethersproject/abi";
|
|
2
|
+
import { Web3Provider } from "@ethersproject/providers";
|
|
3
|
+
import { abiERC20 } from "@metamask/metamask-eth-abis";
|
|
1
4
|
import { TransactionStatus, TransactionType } from "@metamask/transaction-controller";
|
|
2
5
|
import { createModuleLogger } from "@metamask/utils";
|
|
6
|
+
import { BigNumber } from "bignumber.js";
|
|
3
7
|
import $lodash from "lodash";
|
|
4
8
|
const { cloneDeep } = $lodash;
|
|
5
9
|
import { projectLogger } from "../logger.mjs";
|
|
6
10
|
import { getAssetsUnifyStateFeature } from "./feature-flags.mjs";
|
|
7
11
|
import { parseRequiredTokens } from "./required-tokens.mjs";
|
|
12
|
+
import { getNativeToken } from "./token.mjs";
|
|
8
13
|
const log = createModuleLogger(projectLogger, 'transaction');
|
|
9
14
|
export const FINALIZED_STATUSES = [
|
|
10
15
|
TransactionStatus.confirmed,
|
|
@@ -193,4 +198,134 @@ function onTransactionFinalized(transaction, removeTransactionData) {
|
|
|
193
198
|
log('Transaction finalized', { transaction });
|
|
194
199
|
removeTransactionData(transaction.id);
|
|
195
200
|
}
|
|
201
|
+
const erc20Interface = new Interface(abiERC20);
|
|
202
|
+
const ERC20_TRANSFER_EVENT_TOPIC = erc20Interface.getEventTopic('Transfer');
|
|
203
|
+
/**
|
|
204
|
+
* Reads the transferred token amount from a completed on-chain transaction.
|
|
205
|
+
*
|
|
206
|
+
* For native tokens the amount is resolved via `debug_traceTransaction`
|
|
207
|
+
* (internal-call aware), falling back to the top-level `tx.value`.
|
|
208
|
+
* For ERC-20 tokens the amount is decoded from `Transfer` event logs
|
|
209
|
+
* in the transaction receipt.
|
|
210
|
+
*
|
|
211
|
+
* @param options - The options.
|
|
212
|
+
* @param options.messenger - Controller messenger for network access.
|
|
213
|
+
* @param options.txHash - Transaction hash of the completed on-chain transaction.
|
|
214
|
+
* @param options.chainId - Chain ID where the transaction was executed.
|
|
215
|
+
* @param options.tokenAddress - Address of the transferred token.
|
|
216
|
+
* @param options.walletAddress - Recipient wallet address to filter transfers to.
|
|
217
|
+
* @returns The raw (atomic) transferred amount as a decimal string,
|
|
218
|
+
* or `undefined` if the amount cannot be determined.
|
|
219
|
+
*/
|
|
220
|
+
export async function getTransferredAmountFromTxHash({ messenger, txHash, chainId, tokenAddress, walletAddress, }) {
|
|
221
|
+
const provider = getEthersProvider(messenger, chainId);
|
|
222
|
+
const isNative = tokenAddress.toLowerCase() === getNativeToken(chainId).toLowerCase();
|
|
223
|
+
if (isNative) {
|
|
224
|
+
return await getNativeTransferAmount(provider, txHash, walletAddress);
|
|
225
|
+
}
|
|
226
|
+
return await getErc20TransferAmount(provider, txHash, tokenAddress, walletAddress);
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Resolves the native token amount received by a wallet from a transaction.
|
|
230
|
+
*
|
|
231
|
+
* 1. Attempts `debug_traceTransaction` with `callTracer` to walk internal
|
|
232
|
+
* calls and sum all native value transfers targeting `walletAddress`.
|
|
233
|
+
* 2. Falls back to the top-level `tx.value` when the wallet is the direct
|
|
234
|
+
* recipient and the trace RPC is unavailable or errors.
|
|
235
|
+
*
|
|
236
|
+
* @param provider - Ethers Web3Provider.
|
|
237
|
+
* @param txHash - Transaction hash.
|
|
238
|
+
* @param walletAddress - Recipient wallet address.
|
|
239
|
+
* @returns Raw amount as a decimal string, or `undefined`.
|
|
240
|
+
*/
|
|
241
|
+
async function getNativeTransferAmount(provider, txHash, walletAddress) {
|
|
242
|
+
try {
|
|
243
|
+
const trace = await provider.send('debug_traceTransaction', [
|
|
244
|
+
txHash,
|
|
245
|
+
{ tracer: 'callTracer' },
|
|
246
|
+
]);
|
|
247
|
+
const amount = sumNativeValueFromTrace(trace, walletAddress);
|
|
248
|
+
if (amount.gt(0)) {
|
|
249
|
+
return amount.toFixed(0);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
catch {
|
|
253
|
+
// debug_traceTransaction not supported — fall through to tx.value
|
|
254
|
+
}
|
|
255
|
+
const tx = await provider.getTransaction(txHash);
|
|
256
|
+
if (!tx) {
|
|
257
|
+
return undefined;
|
|
258
|
+
}
|
|
259
|
+
if (tx.to?.toLowerCase() !== walletAddress.toLowerCase()) {
|
|
260
|
+
return undefined;
|
|
261
|
+
}
|
|
262
|
+
return positiveOrUndefined(tx.value.toString());
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Resolves the ERC-20 token amount received by a wallet from a transaction
|
|
266
|
+
* by decoding `Transfer` event logs from the transaction receipt.
|
|
267
|
+
*
|
|
268
|
+
* @param provider - Ethers Web3Provider.
|
|
269
|
+
* @param txHash - Transaction hash.
|
|
270
|
+
* @param tokenAddress - ERC-20 token contract address.
|
|
271
|
+
* @param walletAddress - Recipient wallet address.
|
|
272
|
+
* @returns Raw amount as a decimal string, or `undefined`.
|
|
273
|
+
*/
|
|
274
|
+
async function getErc20TransferAmount(provider, txHash, tokenAddress, walletAddress) {
|
|
275
|
+
const receipt = await provider.getTransactionReceipt(txHash);
|
|
276
|
+
if (!receipt) {
|
|
277
|
+
return undefined;
|
|
278
|
+
}
|
|
279
|
+
let total = new BigNumber(0);
|
|
280
|
+
for (const txLog of receipt.logs) {
|
|
281
|
+
if (txLog.address.toLowerCase() !== tokenAddress.toLowerCase()) {
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
if (!txLog.topics[0] || txLog.topics[0] !== ERC20_TRANSFER_EVENT_TOPIC) {
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
try {
|
|
288
|
+
const parsed = erc20Interface.parseLog(txLog);
|
|
289
|
+
const to = parsed.args[1].toLowerCase();
|
|
290
|
+
if (to !== walletAddress.toLowerCase()) {
|
|
291
|
+
continue;
|
|
292
|
+
}
|
|
293
|
+
total = total.plus(parsed.args[2].toString());
|
|
294
|
+
}
|
|
295
|
+
catch {
|
|
296
|
+
continue;
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
return positiveOrUndefined(total.toFixed(0));
|
|
300
|
+
}
|
|
301
|
+
/**
|
|
302
|
+
* Recursively walks a `callTracer` result and sums native value
|
|
303
|
+
* transferred to a specific address.
|
|
304
|
+
*
|
|
305
|
+
* @param trace - Call trace node.
|
|
306
|
+
* @param walletAddress - Target address to accumulate value for.
|
|
307
|
+
* @returns Accumulated native value as BigNumber.
|
|
308
|
+
*/
|
|
309
|
+
function sumNativeValueFromTrace(trace, walletAddress) {
|
|
310
|
+
let total = new BigNumber(0);
|
|
311
|
+
if (trace.to?.toLowerCase() === walletAddress.toLowerCase() &&
|
|
312
|
+
trace.value &&
|
|
313
|
+
trace.value !== '0x0') {
|
|
314
|
+
total = total.plus(new BigNumber(trace.value));
|
|
315
|
+
}
|
|
316
|
+
if (trace.calls) {
|
|
317
|
+
for (const child of trace.calls) {
|
|
318
|
+
total = total.plus(sumNativeValueFromTrace(child, walletAddress));
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return total;
|
|
322
|
+
}
|
|
323
|
+
function getEthersProvider(messenger, chainId) {
|
|
324
|
+
const networkClientId = messenger.call('NetworkController:findNetworkClientIdByChainId', chainId);
|
|
325
|
+
const { provider } = messenger.call('NetworkController:getNetworkClientById', networkClientId);
|
|
326
|
+
return new Web3Provider(provider);
|
|
327
|
+
}
|
|
328
|
+
function positiveOrUndefined(amount) {
|
|
329
|
+
return new BigNumber(amount).gt(0) ? amount : undefined;
|
|
330
|
+
}
|
|
196
331
|
//# sourceMappingURL=transaction.mjs.map
|