@metamask/transaction-controller 38.0.0 → 38.1.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 +18 -1
- package/dist/TransactionController.cjs +27 -29
- package/dist/TransactionController.cjs.map +1 -1
- package/dist/TransactionController.d.cts.map +1 -1
- package/dist/TransactionController.d.mts.map +1 -1
- package/dist/TransactionController.mjs +28 -30
- package/dist/TransactionController.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +2 -0
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +2 -0
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/resimulate.cjs +172 -0
- package/dist/utils/resimulate.cjs.map +1 -0
- package/dist/utils/resimulate.d.cts +27 -0
- package/dist/utils/resimulate.d.cts.map +1 -0
- package/dist/utils/resimulate.d.mts +27 -0
- package/dist/utils/resimulate.d.mts.map +1 -0
- package/dist/utils/resimulate.mjs +168 -0
- package/dist/utils/resimulate.mjs.map +1 -0
- package/dist/utils/simulation-api.cjs.map +1 -1
- package/dist/utils/simulation-api.d.cts +3 -0
- package/dist/utils/simulation-api.d.cts.map +1 -1
- package/dist/utils/simulation-api.d.mts +3 -0
- package/dist/utils/simulation-api.d.mts.map +1 -1
- package/dist/utils/simulation-api.mjs.map +1 -1
- package/dist/utils/simulation.cjs +19 -3
- package/dist/utils/simulation.cjs.map +1 -1
- package/dist/utils/simulation.d.cts +7 -2
- package/dist/utils/simulation.d.cts.map +1 -1
- package/dist/utils/simulation.d.mts +7 -2
- package/dist/utils/simulation.d.mts.map +1 -1
- package/dist/utils/simulation.mjs +19 -3
- package/dist/utils/simulation.mjs.map +1 -1
- package/dist/utils/utils.cjs +27 -1
- package/dist/utils/utils.cjs.map +1 -1
- package/dist/utils/utils.d.cts +10 -0
- package/dist/utils/utils.d.cts.map +1 -1
- package/dist/utils/utils.d.mts +10 -0
- package/dist/utils/utils.d.mts.map +1 -1
- package/dist/utils/utils.mjs +29 -0
- package/dist/utils/utils.mjs.map +1 -1
- package/package.json +5 -5
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.hasSimulationDataChanged = exports.shouldResimulate = exports.BLOCK_TIME_ADDITIONAL_SECONDS = exports.VALUE_COMPARISON_PERCENT_THRESHOLD = exports.BLOCKAID_RESULT_TYPE_MALICIOUS = exports.RESIMULATE_PARAMS = void 0;
|
|
4
|
+
const utils_1 = require("@metamask/utils");
|
|
5
|
+
const bn_js_1 = require("bn.js");
|
|
6
|
+
const lodash_1 = require("lodash");
|
|
7
|
+
const logger_1 = require("../logger.cjs");
|
|
8
|
+
const utils_2 = require("./utils.cjs");
|
|
9
|
+
const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'resimulate');
|
|
10
|
+
exports.RESIMULATE_PARAMS = ['to', 'value', 'data'];
|
|
11
|
+
exports.BLOCKAID_RESULT_TYPE_MALICIOUS = 'Malicious';
|
|
12
|
+
exports.VALUE_COMPARISON_PERCENT_THRESHOLD = 5;
|
|
13
|
+
exports.BLOCK_TIME_ADDITIONAL_SECONDS = 60;
|
|
14
|
+
/**
|
|
15
|
+
* Determine if a transaction should be resimulated.
|
|
16
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
17
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
18
|
+
* @returns Whether the transaction should be resimulated.
|
|
19
|
+
*/
|
|
20
|
+
function shouldResimulate(originalTransactionMeta, newTransactionMeta) {
|
|
21
|
+
const { id: transactionId } = newTransactionMeta;
|
|
22
|
+
const parametersUpdated = isParametersUpdated(originalTransactionMeta, newTransactionMeta);
|
|
23
|
+
const securityAlert = hasNewSecurityAlert(originalTransactionMeta, newTransactionMeta);
|
|
24
|
+
const valueAndNativeBalanceMismatch = hasValueAndNativeBalanceMismatch(originalTransactionMeta, newTransactionMeta);
|
|
25
|
+
const resimulate = parametersUpdated || securityAlert || valueAndNativeBalanceMismatch;
|
|
26
|
+
let blockTime;
|
|
27
|
+
if (securityAlert || valueAndNativeBalanceMismatch) {
|
|
28
|
+
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
29
|
+
blockTime = nowSeconds + exports.BLOCK_TIME_ADDITIONAL_SECONDS;
|
|
30
|
+
}
|
|
31
|
+
if (resimulate) {
|
|
32
|
+
log('Transaction should be resimulated', {
|
|
33
|
+
transactionId,
|
|
34
|
+
blockTime,
|
|
35
|
+
parametersUpdated,
|
|
36
|
+
securityAlert,
|
|
37
|
+
valueAndNativeBalanceMismatch,
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
return {
|
|
41
|
+
blockTime,
|
|
42
|
+
resimulate,
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
exports.shouldResimulate = shouldResimulate;
|
|
46
|
+
/**
|
|
47
|
+
* Determine if the simulation data has changed.
|
|
48
|
+
* @param originalSimulationData - The original simulation data.
|
|
49
|
+
* @param newSimulationData - The new simulation data.
|
|
50
|
+
* @returns Whether the simulation data has changed.
|
|
51
|
+
*/
|
|
52
|
+
function hasSimulationDataChanged(originalSimulationData, newSimulationData) {
|
|
53
|
+
if ((0, lodash_1.isEqual)(originalSimulationData, newSimulationData)) {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
if (isBalanceChangeUpdated(originalSimulationData?.nativeBalanceChange, newSimulationData?.nativeBalanceChange)) {
|
|
57
|
+
log('Simulation data native balance changed');
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
if (originalSimulationData.tokenBalanceChanges.length !==
|
|
61
|
+
newSimulationData.tokenBalanceChanges.length) {
|
|
62
|
+
return true;
|
|
63
|
+
}
|
|
64
|
+
for (const originalTokenBalanceChange of originalSimulationData.tokenBalanceChanges) {
|
|
65
|
+
const newTokenBalanceChange = newSimulationData.tokenBalanceChanges.find(({ address, id }) => address === originalTokenBalanceChange.address &&
|
|
66
|
+
id === originalTokenBalanceChange.id);
|
|
67
|
+
if (!newTokenBalanceChange) {
|
|
68
|
+
log('Missing new token balance', {
|
|
69
|
+
address: originalTokenBalanceChange.address,
|
|
70
|
+
id: originalTokenBalanceChange.id,
|
|
71
|
+
});
|
|
72
|
+
return true;
|
|
73
|
+
}
|
|
74
|
+
if (isBalanceChangeUpdated(originalTokenBalanceChange, newTokenBalanceChange)) {
|
|
75
|
+
log('Simulation data token balance changed', {
|
|
76
|
+
originalTokenBalanceChange,
|
|
77
|
+
newTokenBalanceChange,
|
|
78
|
+
});
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return false;
|
|
83
|
+
}
|
|
84
|
+
exports.hasSimulationDataChanged = hasSimulationDataChanged;
|
|
85
|
+
/**
|
|
86
|
+
* Determine if the transaction parameters have been updated.
|
|
87
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
88
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
89
|
+
* @returns Whether the transaction parameters have been updated.
|
|
90
|
+
*/
|
|
91
|
+
function isParametersUpdated(originalTransactionMeta, newTransactionMeta) {
|
|
92
|
+
const { id: transactionId, txParams: newParams } = newTransactionMeta;
|
|
93
|
+
const { txParams: originalParams } = originalTransactionMeta;
|
|
94
|
+
if (!originalParams || (0, lodash_1.isEqual)(originalParams, newParams)) {
|
|
95
|
+
return false;
|
|
96
|
+
}
|
|
97
|
+
const params = Object.keys(newParams);
|
|
98
|
+
const updatedProperties = params.filter((param) => newParams[param] !== originalParams[param]);
|
|
99
|
+
log('Transaction parameters updated', {
|
|
100
|
+
transactionId,
|
|
101
|
+
updatedProperties,
|
|
102
|
+
originalParams,
|
|
103
|
+
newParams,
|
|
104
|
+
});
|
|
105
|
+
return exports.RESIMULATE_PARAMS.some((param) => updatedProperties.includes(param));
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Determine if a transaction has a new security alert.
|
|
109
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
110
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
111
|
+
* @returns Whether the transaction has a new security alert.
|
|
112
|
+
*/
|
|
113
|
+
function hasNewSecurityAlert(originalTransactionMeta, newTransactionMeta) {
|
|
114
|
+
const { securityAlertResponse: originalSecurityAlertResponse } = originalTransactionMeta;
|
|
115
|
+
const { id: transactionId, securityAlertResponse: newSecurityAlertResponse } = newTransactionMeta;
|
|
116
|
+
if ((0, lodash_1.isEqual)(originalSecurityAlertResponse, newSecurityAlertResponse)) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
log('Security alert updated', {
|
|
120
|
+
transactionId,
|
|
121
|
+
originalSecurityAlertResponse,
|
|
122
|
+
newSecurityAlertResponse,
|
|
123
|
+
});
|
|
124
|
+
return (newSecurityAlertResponse?.result_type === exports.BLOCKAID_RESULT_TYPE_MALICIOUS);
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Determine if a transaction has a value and simulation native balance mismatch.
|
|
128
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
129
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
130
|
+
* @returns Whether the transaction has a value and simulation native balance mismatch.
|
|
131
|
+
*/
|
|
132
|
+
function hasValueAndNativeBalanceMismatch(originalTransactionMeta, newTransactionMeta) {
|
|
133
|
+
const { simulationData: originalSimulationData } = originalTransactionMeta;
|
|
134
|
+
const { simulationData: newSimulationData, txParams: newTxParams } = newTransactionMeta;
|
|
135
|
+
if (!newSimulationData ||
|
|
136
|
+
(0, lodash_1.isEqual)(originalSimulationData, newSimulationData)) {
|
|
137
|
+
return false;
|
|
138
|
+
}
|
|
139
|
+
const newValue = newTxParams?.value ?? '0x0';
|
|
140
|
+
const newNativeBalanceDifference = newSimulationData?.nativeBalanceChange?.difference ?? '0x0';
|
|
141
|
+
return !percentageChangeWithinThreshold(newValue, newNativeBalanceDifference, false, newSimulationData?.nativeBalanceChange?.isDecrease === false);
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Determine if a balance change has been updated.
|
|
145
|
+
* @param originalBalanceChange - The original balance change.
|
|
146
|
+
* @param newBalanceChange - The new balance change.
|
|
147
|
+
* @returns Whether the balance change has been updated.
|
|
148
|
+
*/
|
|
149
|
+
function isBalanceChangeUpdated(originalBalanceChange, newBalanceChange) {
|
|
150
|
+
return !percentageChangeWithinThreshold(originalBalanceChange?.difference ?? '0x0', newBalanceChange?.difference ?? '0x0', originalBalanceChange?.isDecrease === false, newBalanceChange?.isDecrease === false);
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Determine if the percentage change between two values is within a threshold.
|
|
154
|
+
* @param originalValue - The original value.
|
|
155
|
+
* @param newValue - The new value.
|
|
156
|
+
* @param originalNegative - Whether the original value is negative.
|
|
157
|
+
* @param newNegative - Whether the new value is negative.
|
|
158
|
+
* @returns Whether the percentage change between the two values is within a threshold.
|
|
159
|
+
*/
|
|
160
|
+
function percentageChangeWithinThreshold(originalValue, newValue, originalNegative, newNegative) {
|
|
161
|
+
let originalValueBN = new bn_js_1.BN((0, utils_1.remove0x)(originalValue), 'hex');
|
|
162
|
+
let newValueBN = new bn_js_1.BN((0, utils_1.remove0x)(newValue), 'hex');
|
|
163
|
+
if (originalNegative) {
|
|
164
|
+
originalValueBN = originalValueBN.neg();
|
|
165
|
+
}
|
|
166
|
+
if (newNegative) {
|
|
167
|
+
newValueBN = newValueBN.neg();
|
|
168
|
+
}
|
|
169
|
+
return ((0, utils_2.getPercentageChange)(originalValueBN, newValueBN) <=
|
|
170
|
+
exports.VALUE_COMPARISON_PERCENT_THRESHOLD);
|
|
171
|
+
}
|
|
172
|
+
//# sourceMappingURL=resimulate.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resimulate.cjs","sourceRoot":"","sources":["../../src/utils/resimulate.ts"],"names":[],"mappings":";;;AACA,2CAA+D;AAC/D,iCAA2B;AAC3B,mCAAiC;AAEjC,0C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ChD,0CAAkC,CACnC,CAAC;AACJ,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\nimport { createModuleLogger, remove0x } from '@metamask/utils';\nimport { BN } from 'bn.js';\nimport { isEqual } from 'lodash';\n\nimport { projectLogger } from '../logger';\nimport type {\n SimulationBalanceChange,\n SimulationData,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { getPercentageChange } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'resimulate');\n\nexport const RESIMULATE_PARAMS = ['to', 'value', 'data'] as const;\nexport const BLOCKAID_RESULT_TYPE_MALICIOUS = 'Malicious';\nexport const VALUE_COMPARISON_PERCENT_THRESHOLD = 5;\nexport const BLOCK_TIME_ADDITIONAL_SECONDS = 60;\n\nexport type ResimulateResponse = {\n blockTime?: number;\n resimulate: boolean;\n};\n\n/**\n * Determine if a transaction should be resimulated.\n * @param originalTransactionMeta - The original transaction metadata.\n * @param newTransactionMeta - The new transaction metadata.\n * @returns Whether the transaction should be resimulated.\n */\nexport function shouldResimulate(\n originalTransactionMeta: TransactionMeta,\n newTransactionMeta: TransactionMeta,\n) {\n const { id: transactionId } = newTransactionMeta;\n\n const parametersUpdated = isParametersUpdated(\n originalTransactionMeta,\n newTransactionMeta,\n );\n\n const securityAlert = hasNewSecurityAlert(\n originalTransactionMeta,\n newTransactionMeta,\n );\n\n const valueAndNativeBalanceMismatch = hasValueAndNativeBalanceMismatch(\n originalTransactionMeta,\n newTransactionMeta,\n );\n\n const resimulate =\n parametersUpdated || securityAlert || valueAndNativeBalanceMismatch;\n\n let blockTime: number | undefined;\n\n if (securityAlert || valueAndNativeBalanceMismatch) {\n const nowSeconds = Math.floor(Date.now() / 1000);\n blockTime = nowSeconds + BLOCK_TIME_ADDITIONAL_SECONDS;\n }\n\n if (resimulate) {\n log('Transaction should be resimulated', {\n transactionId,\n blockTime,\n parametersUpdated,\n securityAlert,\n valueAndNativeBalanceMismatch,\n });\n }\n\n return {\n blockTime,\n resimulate,\n };\n}\n\n/**\n * Determine if the simulation data has changed.\n * @param originalSimulationData - The original simulation data.\n * @param newSimulationData - The new simulation data.\n * @returns Whether the simulation data has changed.\n */\nexport function hasSimulationDataChanged(\n originalSimulationData: SimulationData,\n newSimulationData: SimulationData,\n): boolean {\n if (isEqual(originalSimulationData, newSimulationData)) {\n return false;\n }\n\n if (\n isBalanceChangeUpdated(\n originalSimulationData?.nativeBalanceChange,\n newSimulationData?.nativeBalanceChange,\n )\n ) {\n log('Simulation data native balance changed');\n return true;\n }\n\n if (\n originalSimulationData.tokenBalanceChanges.length !==\n newSimulationData.tokenBalanceChanges.length\n ) {\n return true;\n }\n\n for (const originalTokenBalanceChange of originalSimulationData.tokenBalanceChanges) {\n const newTokenBalanceChange = newSimulationData.tokenBalanceChanges.find(\n ({ address, id }) =>\n address === originalTokenBalanceChange.address &&\n id === originalTokenBalanceChange.id,\n );\n\n if (!newTokenBalanceChange) {\n log('Missing new token balance', {\n address: originalTokenBalanceChange.address,\n id: originalTokenBalanceChange.id,\n });\n\n return true;\n }\n\n if (\n isBalanceChangeUpdated(originalTokenBalanceChange, newTokenBalanceChange)\n ) {\n log('Simulation data token balance changed', {\n originalTokenBalanceChange,\n newTokenBalanceChange,\n });\n\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Determine if the transaction parameters have been updated.\n * @param originalTransactionMeta - The original transaction metadata.\n * @param newTransactionMeta - The new transaction metadata.\n * @returns Whether the transaction parameters have been updated.\n */\nfunction isParametersUpdated(\n originalTransactionMeta: TransactionMeta,\n newTransactionMeta: TransactionMeta,\n): boolean {\n const { id: transactionId, txParams: newParams } = newTransactionMeta;\n const { txParams: originalParams } = originalTransactionMeta;\n\n if (!originalParams || isEqual(originalParams, newParams)) {\n return false;\n }\n\n const params = Object.keys(newParams) as (keyof TransactionParams)[];\n\n const updatedProperties = params.filter(\n (param) => newParams[param] !== originalParams[param],\n );\n\n log('Transaction parameters updated', {\n transactionId,\n updatedProperties,\n originalParams,\n newParams,\n });\n\n return RESIMULATE_PARAMS.some((param) => updatedProperties.includes(param));\n}\n\n/**\n * Determine if a transaction has a new security alert.\n * @param originalTransactionMeta - The original transaction metadata.\n * @param newTransactionMeta - The new transaction metadata.\n * @returns Whether the transaction has a new security alert.\n */\nfunction hasNewSecurityAlert(\n originalTransactionMeta: TransactionMeta,\n newTransactionMeta: TransactionMeta,\n): boolean {\n const { securityAlertResponse: originalSecurityAlertResponse } =\n originalTransactionMeta;\n\n const { id: transactionId, securityAlertResponse: newSecurityAlertResponse } =\n newTransactionMeta;\n\n if (isEqual(originalSecurityAlertResponse, newSecurityAlertResponse)) {\n return false;\n }\n\n log('Security alert updated', {\n transactionId,\n originalSecurityAlertResponse,\n newSecurityAlertResponse,\n });\n\n return (\n newSecurityAlertResponse?.result_type === BLOCKAID_RESULT_TYPE_MALICIOUS\n );\n}\n\n/**\n * Determine if a transaction has a value and simulation native balance mismatch.\n * @param originalTransactionMeta - The original transaction metadata.\n * @param newTransactionMeta - The new transaction metadata.\n * @returns Whether the transaction has a value and simulation native balance mismatch.\n */\nfunction hasValueAndNativeBalanceMismatch(\n originalTransactionMeta: TransactionMeta,\n newTransactionMeta: TransactionMeta,\n): boolean {\n const { simulationData: originalSimulationData } = originalTransactionMeta;\n\n const { simulationData: newSimulationData, txParams: newTxParams } =\n newTransactionMeta;\n\n if (\n !newSimulationData ||\n isEqual(originalSimulationData, newSimulationData)\n ) {\n return false;\n }\n\n const newValue = newTxParams?.value ?? '0x0';\n\n const newNativeBalanceDifference =\n newSimulationData?.nativeBalanceChange?.difference ?? '0x0';\n\n return !percentageChangeWithinThreshold(\n newValue as Hex,\n newNativeBalanceDifference,\n false,\n newSimulationData?.nativeBalanceChange?.isDecrease === false,\n );\n}\n\n/**\n * Determine if a balance change has been updated.\n * @param originalBalanceChange - The original balance change.\n * @param newBalanceChange - The new balance change.\n * @returns Whether the balance change has been updated.\n */\nfunction isBalanceChangeUpdated(\n originalBalanceChange?: SimulationBalanceChange,\n newBalanceChange?: SimulationBalanceChange,\n): boolean {\n return !percentageChangeWithinThreshold(\n originalBalanceChange?.difference ?? '0x0',\n newBalanceChange?.difference ?? '0x0',\n originalBalanceChange?.isDecrease === false,\n newBalanceChange?.isDecrease === false,\n );\n}\n\n/**\n * Determine if the percentage change between two values is within a threshold.\n * @param originalValue - The original value.\n * @param newValue - The new value.\n * @param originalNegative - Whether the original value is negative.\n * @param newNegative - Whether the new value is negative.\n * @returns Whether the percentage change between the two values is within a threshold.\n */\nfunction percentageChangeWithinThreshold(\n originalValue: Hex,\n newValue: Hex,\n originalNegative?: boolean,\n newNegative?: boolean,\n): boolean {\n let originalValueBN = new BN(remove0x(originalValue), 'hex');\n let newValueBN = new BN(remove0x(newValue), 'hex');\n\n if (originalNegative) {\n originalValueBN = originalValueBN.neg();\n }\n\n if (newNegative) {\n newValueBN = newValueBN.neg();\n }\n\n return (\n getPercentageChange(originalValueBN, newValueBN) <=\n VALUE_COMPARISON_PERCENT_THRESHOLD\n );\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { SimulationData, TransactionMeta } from "../types.cjs";
|
|
2
|
+
export declare const RESIMULATE_PARAMS: readonly ["to", "value", "data"];
|
|
3
|
+
export declare const BLOCKAID_RESULT_TYPE_MALICIOUS = "Malicious";
|
|
4
|
+
export declare const VALUE_COMPARISON_PERCENT_THRESHOLD = 5;
|
|
5
|
+
export declare const BLOCK_TIME_ADDITIONAL_SECONDS = 60;
|
|
6
|
+
export type ResimulateResponse = {
|
|
7
|
+
blockTime?: number;
|
|
8
|
+
resimulate: boolean;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Determine if a transaction should be resimulated.
|
|
12
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
13
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
14
|
+
* @returns Whether the transaction should be resimulated.
|
|
15
|
+
*/
|
|
16
|
+
export declare function shouldResimulate(originalTransactionMeta: TransactionMeta, newTransactionMeta: TransactionMeta): {
|
|
17
|
+
blockTime: number | undefined;
|
|
18
|
+
resimulate: boolean;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Determine if the simulation data has changed.
|
|
22
|
+
* @param originalSimulationData - The original simulation data.
|
|
23
|
+
* @param newSimulationData - The new simulation data.
|
|
24
|
+
* @returns Whether the simulation data has changed.
|
|
25
|
+
*/
|
|
26
|
+
export declare function hasSimulationDataChanged(originalSimulationData: SimulationData, newSimulationData: SimulationData): boolean;
|
|
27
|
+
//# sourceMappingURL=resimulate.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resimulate.d.cts","sourceRoot":"","sources":["../../src/utils/resimulate.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAEV,cAAc,EACd,eAAe,EAEhB,qBAAiB;AAKlB,eAAO,MAAM,iBAAiB,kCAAmC,CAAC;AAClE,eAAO,MAAM,8BAA8B,cAAc,CAAC;AAC1D,eAAO,MAAM,kCAAkC,IAAI,CAAC;AACpD,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAEhD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,OAAO,CAAC;CACrB,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,uBAAuB,EAAE,eAAe,EACxC,kBAAkB,EAAE,eAAe;;;EA2CpC;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,sBAAsB,EAAE,cAAc,EACtC,iBAAiB,EAAE,cAAc,GAChC,OAAO,CAmDT"}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { SimulationData, TransactionMeta } from "../types.mjs";
|
|
2
|
+
export declare const RESIMULATE_PARAMS: readonly ["to", "value", "data"];
|
|
3
|
+
export declare const BLOCKAID_RESULT_TYPE_MALICIOUS = "Malicious";
|
|
4
|
+
export declare const VALUE_COMPARISON_PERCENT_THRESHOLD = 5;
|
|
5
|
+
export declare const BLOCK_TIME_ADDITIONAL_SECONDS = 60;
|
|
6
|
+
export type ResimulateResponse = {
|
|
7
|
+
blockTime?: number;
|
|
8
|
+
resimulate: boolean;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Determine if a transaction should be resimulated.
|
|
12
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
13
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
14
|
+
* @returns Whether the transaction should be resimulated.
|
|
15
|
+
*/
|
|
16
|
+
export declare function shouldResimulate(originalTransactionMeta: TransactionMeta, newTransactionMeta: TransactionMeta): {
|
|
17
|
+
blockTime: number | undefined;
|
|
18
|
+
resimulate: boolean;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Determine if the simulation data has changed.
|
|
22
|
+
* @param originalSimulationData - The original simulation data.
|
|
23
|
+
* @param newSimulationData - The new simulation data.
|
|
24
|
+
* @returns Whether the simulation data has changed.
|
|
25
|
+
*/
|
|
26
|
+
export declare function hasSimulationDataChanged(originalSimulationData: SimulationData, newSimulationData: SimulationData): boolean;
|
|
27
|
+
//# sourceMappingURL=resimulate.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resimulate.d.mts","sourceRoot":"","sources":["../../src/utils/resimulate.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAEV,cAAc,EACd,eAAe,EAEhB,qBAAiB;AAKlB,eAAO,MAAM,iBAAiB,kCAAmC,CAAC;AAClE,eAAO,MAAM,8BAA8B,cAAc,CAAC;AAC1D,eAAO,MAAM,kCAAkC,IAAI,CAAC;AACpD,eAAO,MAAM,6BAA6B,KAAK,CAAC;AAEhD,MAAM,MAAM,kBAAkB,GAAG;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,OAAO,CAAC;CACrB,CAAC;AAEF;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,uBAAuB,EAAE,eAAe,EACxC,kBAAkB,EAAE,eAAe;;;EA2CpC;AAED;;;;;GAKG;AACH,wBAAgB,wBAAwB,CACtC,sBAAsB,EAAE,cAAc,EACtC,iBAAiB,EAAE,cAAc,GAChC,OAAO,CAmDT"}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { createModuleLogger, remove0x } from "@metamask/utils";
|
|
2
|
+
import { BN } from "bn.js";
|
|
3
|
+
import $lodash from "lodash";
|
|
4
|
+
const { isEqual } = $lodash;
|
|
5
|
+
import { projectLogger } from "../logger.mjs";
|
|
6
|
+
import { getPercentageChange } from "./utils.mjs";
|
|
7
|
+
const log = createModuleLogger(projectLogger, 'resimulate');
|
|
8
|
+
export const RESIMULATE_PARAMS = ['to', 'value', 'data'];
|
|
9
|
+
export const BLOCKAID_RESULT_TYPE_MALICIOUS = 'Malicious';
|
|
10
|
+
export const VALUE_COMPARISON_PERCENT_THRESHOLD = 5;
|
|
11
|
+
export const BLOCK_TIME_ADDITIONAL_SECONDS = 60;
|
|
12
|
+
/**
|
|
13
|
+
* Determine if a transaction should be resimulated.
|
|
14
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
15
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
16
|
+
* @returns Whether the transaction should be resimulated.
|
|
17
|
+
*/
|
|
18
|
+
export function shouldResimulate(originalTransactionMeta, newTransactionMeta) {
|
|
19
|
+
const { id: transactionId } = newTransactionMeta;
|
|
20
|
+
const parametersUpdated = isParametersUpdated(originalTransactionMeta, newTransactionMeta);
|
|
21
|
+
const securityAlert = hasNewSecurityAlert(originalTransactionMeta, newTransactionMeta);
|
|
22
|
+
const valueAndNativeBalanceMismatch = hasValueAndNativeBalanceMismatch(originalTransactionMeta, newTransactionMeta);
|
|
23
|
+
const resimulate = parametersUpdated || securityAlert || valueAndNativeBalanceMismatch;
|
|
24
|
+
let blockTime;
|
|
25
|
+
if (securityAlert || valueAndNativeBalanceMismatch) {
|
|
26
|
+
const nowSeconds = Math.floor(Date.now() / 1000);
|
|
27
|
+
blockTime = nowSeconds + BLOCK_TIME_ADDITIONAL_SECONDS;
|
|
28
|
+
}
|
|
29
|
+
if (resimulate) {
|
|
30
|
+
log('Transaction should be resimulated', {
|
|
31
|
+
transactionId,
|
|
32
|
+
blockTime,
|
|
33
|
+
parametersUpdated,
|
|
34
|
+
securityAlert,
|
|
35
|
+
valueAndNativeBalanceMismatch,
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
blockTime,
|
|
40
|
+
resimulate,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Determine if the simulation data has changed.
|
|
45
|
+
* @param originalSimulationData - The original simulation data.
|
|
46
|
+
* @param newSimulationData - The new simulation data.
|
|
47
|
+
* @returns Whether the simulation data has changed.
|
|
48
|
+
*/
|
|
49
|
+
export function hasSimulationDataChanged(originalSimulationData, newSimulationData) {
|
|
50
|
+
if (isEqual(originalSimulationData, newSimulationData)) {
|
|
51
|
+
return false;
|
|
52
|
+
}
|
|
53
|
+
if (isBalanceChangeUpdated(originalSimulationData?.nativeBalanceChange, newSimulationData?.nativeBalanceChange)) {
|
|
54
|
+
log('Simulation data native balance changed');
|
|
55
|
+
return true;
|
|
56
|
+
}
|
|
57
|
+
if (originalSimulationData.tokenBalanceChanges.length !==
|
|
58
|
+
newSimulationData.tokenBalanceChanges.length) {
|
|
59
|
+
return true;
|
|
60
|
+
}
|
|
61
|
+
for (const originalTokenBalanceChange of originalSimulationData.tokenBalanceChanges) {
|
|
62
|
+
const newTokenBalanceChange = newSimulationData.tokenBalanceChanges.find(({ address, id }) => address === originalTokenBalanceChange.address &&
|
|
63
|
+
id === originalTokenBalanceChange.id);
|
|
64
|
+
if (!newTokenBalanceChange) {
|
|
65
|
+
log('Missing new token balance', {
|
|
66
|
+
address: originalTokenBalanceChange.address,
|
|
67
|
+
id: originalTokenBalanceChange.id,
|
|
68
|
+
});
|
|
69
|
+
return true;
|
|
70
|
+
}
|
|
71
|
+
if (isBalanceChangeUpdated(originalTokenBalanceChange, newTokenBalanceChange)) {
|
|
72
|
+
log('Simulation data token balance changed', {
|
|
73
|
+
originalTokenBalanceChange,
|
|
74
|
+
newTokenBalanceChange,
|
|
75
|
+
});
|
|
76
|
+
return true;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* Determine if the transaction parameters have been updated.
|
|
83
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
84
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
85
|
+
* @returns Whether the transaction parameters have been updated.
|
|
86
|
+
*/
|
|
87
|
+
function isParametersUpdated(originalTransactionMeta, newTransactionMeta) {
|
|
88
|
+
const { id: transactionId, txParams: newParams } = newTransactionMeta;
|
|
89
|
+
const { txParams: originalParams } = originalTransactionMeta;
|
|
90
|
+
if (!originalParams || isEqual(originalParams, newParams)) {
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
const params = Object.keys(newParams);
|
|
94
|
+
const updatedProperties = params.filter((param) => newParams[param] !== originalParams[param]);
|
|
95
|
+
log('Transaction parameters updated', {
|
|
96
|
+
transactionId,
|
|
97
|
+
updatedProperties,
|
|
98
|
+
originalParams,
|
|
99
|
+
newParams,
|
|
100
|
+
});
|
|
101
|
+
return RESIMULATE_PARAMS.some((param) => updatedProperties.includes(param));
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Determine if a transaction has a new security alert.
|
|
105
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
106
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
107
|
+
* @returns Whether the transaction has a new security alert.
|
|
108
|
+
*/
|
|
109
|
+
function hasNewSecurityAlert(originalTransactionMeta, newTransactionMeta) {
|
|
110
|
+
const { securityAlertResponse: originalSecurityAlertResponse } = originalTransactionMeta;
|
|
111
|
+
const { id: transactionId, securityAlertResponse: newSecurityAlertResponse } = newTransactionMeta;
|
|
112
|
+
if (isEqual(originalSecurityAlertResponse, newSecurityAlertResponse)) {
|
|
113
|
+
return false;
|
|
114
|
+
}
|
|
115
|
+
log('Security alert updated', {
|
|
116
|
+
transactionId,
|
|
117
|
+
originalSecurityAlertResponse,
|
|
118
|
+
newSecurityAlertResponse,
|
|
119
|
+
});
|
|
120
|
+
return (newSecurityAlertResponse?.result_type === BLOCKAID_RESULT_TYPE_MALICIOUS);
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Determine if a transaction has a value and simulation native balance mismatch.
|
|
124
|
+
* @param originalTransactionMeta - The original transaction metadata.
|
|
125
|
+
* @param newTransactionMeta - The new transaction metadata.
|
|
126
|
+
* @returns Whether the transaction has a value and simulation native balance mismatch.
|
|
127
|
+
*/
|
|
128
|
+
function hasValueAndNativeBalanceMismatch(originalTransactionMeta, newTransactionMeta) {
|
|
129
|
+
const { simulationData: originalSimulationData } = originalTransactionMeta;
|
|
130
|
+
const { simulationData: newSimulationData, txParams: newTxParams } = newTransactionMeta;
|
|
131
|
+
if (!newSimulationData ||
|
|
132
|
+
isEqual(originalSimulationData, newSimulationData)) {
|
|
133
|
+
return false;
|
|
134
|
+
}
|
|
135
|
+
const newValue = newTxParams?.value ?? '0x0';
|
|
136
|
+
const newNativeBalanceDifference = newSimulationData?.nativeBalanceChange?.difference ?? '0x0';
|
|
137
|
+
return !percentageChangeWithinThreshold(newValue, newNativeBalanceDifference, false, newSimulationData?.nativeBalanceChange?.isDecrease === false);
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Determine if a balance change has been updated.
|
|
141
|
+
* @param originalBalanceChange - The original balance change.
|
|
142
|
+
* @param newBalanceChange - The new balance change.
|
|
143
|
+
* @returns Whether the balance change has been updated.
|
|
144
|
+
*/
|
|
145
|
+
function isBalanceChangeUpdated(originalBalanceChange, newBalanceChange) {
|
|
146
|
+
return !percentageChangeWithinThreshold(originalBalanceChange?.difference ?? '0x0', newBalanceChange?.difference ?? '0x0', originalBalanceChange?.isDecrease === false, newBalanceChange?.isDecrease === false);
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Determine if the percentage change between two values is within a threshold.
|
|
150
|
+
* @param originalValue - The original value.
|
|
151
|
+
* @param newValue - The new value.
|
|
152
|
+
* @param originalNegative - Whether the original value is negative.
|
|
153
|
+
* @param newNegative - Whether the new value is negative.
|
|
154
|
+
* @returns Whether the percentage change between the two values is within a threshold.
|
|
155
|
+
*/
|
|
156
|
+
function percentageChangeWithinThreshold(originalValue, newValue, originalNegative, newNegative) {
|
|
157
|
+
let originalValueBN = new BN(remove0x(originalValue), 'hex');
|
|
158
|
+
let newValueBN = new BN(remove0x(newValue), 'hex');
|
|
159
|
+
if (originalNegative) {
|
|
160
|
+
originalValueBN = originalValueBN.neg();
|
|
161
|
+
}
|
|
162
|
+
if (newNegative) {
|
|
163
|
+
newValueBN = newValueBN.neg();
|
|
164
|
+
}
|
|
165
|
+
return (getPercentageChange(originalValueBN, newValueBN) <=
|
|
166
|
+
VALUE_COMPARISON_PERCENT_THRESHOLD);
|
|
167
|
+
}
|
|
168
|
+
//# sourceMappingURL=resimulate.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resimulate.mjs","sourceRoot":"","sources":["../../src/utils/resimulate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,kBAAkB,EAAE,QAAQ,EAAE,wBAAwB;AAC/D,OAAO,EAAE,EAAE,EAAE,cAAc;;;AAG3B,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAO1C,OAAO,EAAE,mBAAmB,EAAE,oBAAgB;AAE9C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;AAE5D,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,IAAI,EAAE,OAAO,EAAE,MAAM,CAAU,CAAC;AAClE,MAAM,CAAC,MAAM,8BAA8B,GAAG,WAAW,CAAC;AAC1D,MAAM,CAAC,MAAM,kCAAkC,GAAG,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UAAU,IAAI,KAAK,CAAC;IAE9D,OAAO,CAAC,+BAA+B,CACrC,QAAe,EACf,0BAA0B,EAC1B,KAAK,EACL,iBAAiB,EAAE,mBAAmB,EAAE,UAAU,KAAK,KAAK,CAC7D,CAAC;AACJ,CAAC;AAED;;;;;GAKG;AACH,SAAS,sBAAsB,CAC7B,qBAA+C,EAC/C,gBAA0C;IAE1C,OAAO,CAAC,+BAA+B,CACrC,qBAAqB,EAAE,UAAU,IAAI,KAAK,EAC1C,gBAAgB,EAAE,UAAU,IAAI,KAAK,EACrC,qBAAqB,EAAE,UAAU,KAAK,KAAK,EAC3C,gBAAgB,EAAE,UAAU,KAAK,KAAK,CACvC,CAAC;AACJ,CAAC;AAED;;;;;;;GAOG;AACH,SAAS,+BAA+B,CACtC,aAAkB,EAClB,QAAa,EACb,gBAA0B,EAC1B,WAAqB;IAErB,IAAI,eAAe,GAAG,IAAI,EAAE,CAAC,QAAQ,CAAC,aAAa,CAAC,EAAE,KAAK,CAAC,CAAC;IAC7D,IAAI,UAAU,GAAG,IAAI,EAAE,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,KAAK,CAAC,CAAC;IAEnD,IAAI,gBAAgB,EAAE;QACpB,eAAe,GAAG,eAAe,CAAC,GAAG,EAAE,CAAC;KACzC;IAED,IAAI,WAAW,EAAE;QACf,UAAU,GAAG,UAAU,CAAC,GAAG,EAAE,CAAC;KAC/B;IAED,OAAO,CACL,mBAAmB,CAAC,eAAe,EAAE,UAAU,CAAC;QAChD,kCAAkC,CACnC,CAAC;AACJ,CAAC","sourcesContent":["import type { Hex } from '@metamask/utils';\nimport { createModuleLogger, remove0x } from '@metamask/utils';\nimport { BN } from 'bn.js';\nimport { isEqual } from 'lodash';\n\nimport { projectLogger } from '../logger';\nimport type {\n SimulationBalanceChange,\n SimulationData,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { getPercentageChange } from './utils';\n\nconst log = createModuleLogger(projectLogger, 'resimulate');\n\nexport const RESIMULATE_PARAMS = ['to', 'value', 'data'] as const;\nexport const BLOCKAID_RESULT_TYPE_MALICIOUS = 'Malicious';\nexport const VALUE_COMPARISON_PERCENT_THRESHOLD = 5;\nexport const BLOCK_TIME_ADDITIONAL_SECONDS = 60;\n\nexport type ResimulateResponse = {\n blockTime?: number;\n resimulate: boolean;\n};\n\n/**\n * Determine if a transaction should be resimulated.\n * @param originalTransactionMeta - The original transaction metadata.\n * @param newTransactionMeta - The new transaction metadata.\n * @returns Whether the transaction should be resimulated.\n */\nexport function shouldResimulate(\n originalTransactionMeta: TransactionMeta,\n newTransactionMeta: TransactionMeta,\n) {\n const { id: transactionId } = newTransactionMeta;\n\n const parametersUpdated = isParametersUpdated(\n originalTransactionMeta,\n newTransactionMeta,\n );\n\n const securityAlert = hasNewSecurityAlert(\n originalTransactionMeta,\n newTransactionMeta,\n );\n\n const valueAndNativeBalanceMismatch = hasValueAndNativeBalanceMismatch(\n originalTransactionMeta,\n newTransactionMeta,\n );\n\n const resimulate =\n parametersUpdated || securityAlert || valueAndNativeBalanceMismatch;\n\n let blockTime: number | undefined;\n\n if (securityAlert || valueAndNativeBalanceMismatch) {\n const nowSeconds = Math.floor(Date.now() / 1000);\n blockTime = nowSeconds + BLOCK_TIME_ADDITIONAL_SECONDS;\n }\n\n if (resimulate) {\n log('Transaction should be resimulated', {\n transactionId,\n blockTime,\n parametersUpdated,\n securityAlert,\n valueAndNativeBalanceMismatch,\n });\n }\n\n return {\n blockTime,\n resimulate,\n };\n}\n\n/**\n * Determine if the simulation data has changed.\n * @param originalSimulationData - The original simulation data.\n * @param newSimulationData - The new simulation data.\n * @returns Whether the simulation data has changed.\n */\nexport function hasSimulationDataChanged(\n originalSimulationData: SimulationData,\n newSimulationData: SimulationData,\n): boolean {\n if (isEqual(originalSimulationData, newSimulationData)) {\n return false;\n }\n\n if (\n isBalanceChangeUpdated(\n originalSimulationData?.nativeBalanceChange,\n newSimulationData?.nativeBalanceChange,\n )\n ) {\n log('Simulation data native balance changed');\n return true;\n }\n\n if (\n originalSimulationData.tokenBalanceChanges.length !==\n newSimulationData.tokenBalanceChanges.length\n ) {\n return true;\n }\n\n for (const originalTokenBalanceChange of originalSimulationData.tokenBalanceChanges) {\n const newTokenBalanceChange = newSimulationData.tokenBalanceChanges.find(\n ({ address, id }) =>\n address === originalTokenBalanceChange.address &&\n id === originalTokenBalanceChange.id,\n );\n\n if (!newTokenBalanceChange) {\n log('Missing new token balance', {\n address: originalTokenBalanceChange.address,\n id: originalTokenBalanceChange.id,\n });\n\n return true;\n }\n\n if (\n isBalanceChangeUpdated(originalTokenBalanceChange, newTokenBalanceChange)\n ) {\n log('Simulation data token balance changed', {\n originalTokenBalanceChange,\n newTokenBalanceChange,\n });\n\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Determine if the transaction parameters have been updated.\n * @param originalTransactionMeta - The original transaction metadata.\n * @param newTransactionMeta - The new transaction metadata.\n * @returns Whether the transaction parameters have been updated.\n */\nfunction isParametersUpdated(\n originalTransactionMeta: TransactionMeta,\n newTransactionMeta: TransactionMeta,\n): boolean {\n const { id: transactionId, txParams: newParams } = newTransactionMeta;\n const { txParams: originalParams } = originalTransactionMeta;\n\n if (!originalParams || isEqual(originalParams, newParams)) {\n return false;\n }\n\n const params = Object.keys(newParams) as (keyof TransactionParams)[];\n\n const updatedProperties = params.filter(\n (param) => newParams[param] !== originalParams[param],\n );\n\n log('Transaction parameters updated', {\n transactionId,\n updatedProperties,\n originalParams,\n newParams,\n });\n\n return RESIMULATE_PARAMS.some((param) => updatedProperties.includes(param));\n}\n\n/**\n * Determine if a transaction has a new security alert.\n * @param originalTransactionMeta - The original transaction metadata.\n * @param newTransactionMeta - The new transaction metadata.\n * @returns Whether the transaction has a new security alert.\n */\nfunction hasNewSecurityAlert(\n originalTransactionMeta: TransactionMeta,\n newTransactionMeta: TransactionMeta,\n): boolean {\n const { securityAlertResponse: originalSecurityAlertResponse } =\n originalTransactionMeta;\n\n const { id: transactionId, securityAlertResponse: newSecurityAlertResponse } =\n newTransactionMeta;\n\n if (isEqual(originalSecurityAlertResponse, newSecurityAlertResponse)) {\n return false;\n }\n\n log('Security alert updated', {\n transactionId,\n originalSecurityAlertResponse,\n newSecurityAlertResponse,\n });\n\n return (\n newSecurityAlertResponse?.result_type === BLOCKAID_RESULT_TYPE_MALICIOUS\n );\n}\n\n/**\n * Determine if a transaction has a value and simulation native balance mismatch.\n * @param originalTransactionMeta - The original transaction metadata.\n * @param newTransactionMeta - The new transaction metadata.\n * @returns Whether the transaction has a value and simulation native balance mismatch.\n */\nfunction hasValueAndNativeBalanceMismatch(\n originalTransactionMeta: TransactionMeta,\n newTransactionMeta: TransactionMeta,\n): boolean {\n const { simulationData: originalSimulationData } = originalTransactionMeta;\n\n const { simulationData: newSimulationData, txParams: newTxParams } =\n newTransactionMeta;\n\n if (\n !newSimulationData ||\n isEqual(originalSimulationData, newSimulationData)\n ) {\n return false;\n }\n\n const newValue = newTxParams?.value ?? '0x0';\n\n const newNativeBalanceDifference =\n newSimulationData?.nativeBalanceChange?.difference ?? '0x0';\n\n return !percentageChangeWithinThreshold(\n newValue as Hex,\n newNativeBalanceDifference,\n false,\n newSimulationData?.nativeBalanceChange?.isDecrease === false,\n );\n}\n\n/**\n * Determine if a balance change has been updated.\n * @param originalBalanceChange - The original balance change.\n * @param newBalanceChange - The new balance change.\n * @returns Whether the balance change has been updated.\n */\nfunction isBalanceChangeUpdated(\n originalBalanceChange?: SimulationBalanceChange,\n newBalanceChange?: SimulationBalanceChange,\n): boolean {\n return !percentageChangeWithinThreshold(\n originalBalanceChange?.difference ?? '0x0',\n newBalanceChange?.difference ?? '0x0',\n originalBalanceChange?.isDecrease === false,\n newBalanceChange?.isDecrease === false,\n );\n}\n\n/**\n * Determine if the percentage change between two values is within a threshold.\n * @param originalValue - The original value.\n * @param newValue - The new value.\n * @param originalNegative - Whether the original value is negative.\n * @param newNegative - Whether the new value is negative.\n * @returns Whether the percentage change between the two values is within a threshold.\n */\nfunction percentageChangeWithinThreshold(\n originalValue: Hex,\n newValue: Hex,\n originalNegative?: boolean,\n newNegative?: boolean,\n): boolean {\n let originalValueBN = new BN(remove0x(originalValue), 'hex');\n let newValueBN = new BN(remove0x(newValue), 'hex');\n\n if (originalNegative) {\n originalValueBN = originalValueBN.neg();\n }\n\n if (newNegative) {\n newValueBN = newValueBN.neg();\n }\n\n return (\n getPercentageChange(originalValueBN, newValueBN) <=\n VALUE_COMPARISON_PERCENT_THRESHOLD\n );\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation-api.cjs","sourceRoot":"","sources":["../../src/utils/simulation-api.ts"],"names":[],"mappings":";;;AAAA,iEAAiE;AACjE,2CAA+D;AAE/D,0CAA8E;AAC9E,0CAA0C;AAE1C,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE,MAAM,UAAU,GAAG,6BAA6B,CAAC;AACjD,MAAM,QAAQ,GAAG,6CAA6C,CAAC;AAC/D,MAAM,iBAAiB,GAAG,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"simulation-api.cjs","sourceRoot":"","sources":["../../src/utils/simulation-api.ts"],"names":[],"mappings":";;;AAAA,iEAAiE;AACjE,2CAA+D;AAE/D,0CAA8E;AAC9E,0CAA0C;AAE1C,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE,MAAM,UAAU,GAAG,6BAA6B,CAAC;AACjD,MAAM,QAAQ,GAAG,6CAA6C,CAAC;AAC/D,MAAM,iBAAiB,GAAG,UAAU,CAAC;AAgJrC,IAAI,gBAAgB,GAAG,CAAC,CAAC;AAEzB;;;;GAIG;AACI,KAAK,UAAU,oBAAoB,CACxC,OAAY,EACZ,OAA0B;IAE1B,MAAM,GAAG,GAAG,MAAM,gBAAgB,CAAC,OAAO,CAAC,CAAC;IAE5C,GAAG,CAAC,iBAAiB,EAAE,GAAG,E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,CAAC,kBAAkB,CAAC,GAAG,iBAAiB,EAAE,CAAC;IAChE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC;AAED;;;;GAIG;AACH,SAAS,MAAM,CAAC,SAAiB;IAC/B,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { SimulationChainNotSupportedError, SimulationError } from '../errors';\nimport { projectLogger } from '../logger';\n\nconst log = createModuleLogger(projectLogger, 'simulation-api');\n\nconst RPC_METHOD = 'infura_simulateTransactions';\nconst BASE_URL = 'https://tx-sentinel-{0}.api.cx.metamask.io/';\nconst ENDPOINT_NETWORKS = 'networks';\n\n/** Single transaction to simulate in a simulation API request. */\nexport type SimulationRequestTransaction = {\n /** Data to send with the transaction. */\n data?: Hex;\n\n /** Sender of the transaction. */\n from: Hex;\n\n /** Gas limit for the transaction. */\n gas?: Hex;\n\n /** Maximum fee per gas for the transaction. */\n maxFeePerGas?: Hex;\n\n /** Maximum priority fee per gas for the transaction. */\n maxPriorityFeePerGas?: Hex;\n\n /** Recipient of the transaction. */\n to?: Hex;\n\n /** Value to send with the transaction. */\n value?: Hex;\n};\n\n/** Request to the simulation API to simulate transactions. */\nexport type SimulationRequest = {\n /**\n * Transactions to be sequentially simulated.\n * State changes impact subsequent transactions in the list.\n */\n transactions: SimulationRequestTransaction[];\n\n blockOverrides?: {\n time?: Hex;\n };\n\n /**\n * Overrides to the state of the blockchain, keyed by smart contract address.\n */\n overrides?: {\n [address: Hex]: {\n /** Overrides to the storage slots for a smart contract account. */\n stateDiff: {\n [slot: Hex]: Hex;\n };\n };\n };\n\n /**\n * Whether to include call traces in the response.\n * Defaults to false.\n */\n withCallTrace?: boolean;\n\n /**\n * Whether to include event logs in the response.\n * Defaults to false.\n */\n withLogs?: boolean;\n};\n\n/** Raw event log emitted by a simulated transaction. */\nexport type SimulationResponseLog = {\n /** Address of the account that created the event. */\n address: Hex;\n\n /** Raw data in the event that is not indexed. */\n data: Hex;\n\n /** Raw indexed data from the event. */\n topics: Hex[];\n};\n\n/** Call trace of a single simulated transaction. */\nexport type SimulationResponseCallTrace = {\n /** Nested calls. */\n calls: SimulationResponseCallTrace[];\n\n /** Raw event logs created by the call. */\n logs: SimulationResponseLog[];\n};\n\n/**\n * Changes to the blockchain state.\n * Keyed by account address.\n */\nexport type SimulationResponseStateDiff = {\n [address: Hex]: {\n /** Native balance of the account. */\n balance?: Hex;\n\n /** Nonce of the account. */\n nonce?: Hex;\n\n /** Storage values per slot. */\n storage?: {\n [slot: Hex]: Hex;\n };\n };\n};\n\n/** Response from the simulation API for a single transaction. */\nexport type SimulationResponseTransaction = {\n /** An error message indicating the transaction could not be simulated. */\n error?: string;\n\n /** Return value of the transaction, such as the balance if calling balanceOf. */\n return: Hex;\n\n /** Hierarchy of call data including nested calls and logs. */\n callTrace?: SimulationResponseCallTrace;\n\n /** Changes to the blockchain state. */\n stateDiff?: {\n /** Initial blockchain state before the transaction. */\n pre?: SimulationResponseStateDiff;\n\n /** Updated blockchain state after the transaction. */\n post?: SimulationResponseStateDiff;\n };\n};\n\n/** Response from the simulation API. */\nexport type SimulationResponse = {\n /** Simulation data for each transaction in the request. */\n transactions: SimulationResponseTransaction[];\n};\n\n/** Data for a network supported by the Simulation API. */\ntype SimulationNetwork = {\n /** Subdomain of the API for the network. */\n network: string;\n\n /** Whether the network supports confirmation simulations. */\n confirmations: boolean;\n};\n\n/** Response from the simulation API containing supported networks. */\ntype SimulationNetworkResponse = {\n [chainIdDecimal: string]: SimulationNetwork;\n};\n\nlet requestIdCounter = 0;\n\n/**\n * Simulate transactions using the transaction simulation API.\n * @param chainId - The chain ID to simulate transactions on.\n * @param request - The request to simulate transactions.\n */\nexport async function simulateTransactions(\n chainId: Hex,\n request: SimulationRequest,\n): Promise<SimulationResponse> {\n const url = await getSimulationUrl(chainId);\n\n log('Sending request', url, request);\n\n const requestId = requestIdCounter;\n requestIdCounter += 1;\n\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify({\n id: String(requestId),\n jsonrpc: '2.0',\n method: RPC_METHOD,\n params: [request],\n }),\n });\n\n const responseJson = await response.json();\n\n log('Received response', responseJson);\n\n if (responseJson.error) {\n const { code, message } = responseJson.error;\n throw new SimulationError(message, code);\n }\n\n return responseJson?.result;\n}\n\n/**\n * Get the URL for the transaction simulation API.\n * @param chainId - The chain ID to get the URL for.\n * @returns The URL for the transaction simulation API.\n */\nasync function getSimulationUrl(chainId: Hex): Promise<string> {\n const networkData = await getNetworkData();\n const chainIdDecimal = convertHexToDecimal(chainId);\n const network = networkData[chainIdDecimal];\n\n if (!network?.confirmations) {\n log('Chain is not supported', chainId);\n throw new SimulationChainNotSupportedError(chainId);\n }\n\n return getUrl(network.network);\n}\n\n/**\n * Retrieve the supported network data from the simulation API.\n */\nasync function getNetworkData(): Promise<SimulationNetworkResponse> {\n const url = `${getUrl('ethereum-mainnet')}${ENDPOINT_NETWORKS}`;\n const response = await fetch(url);\n return response.json();\n}\n\n/**\n * Generate the URL for the specified subdomain in the simulation API.\n * @param subdomain - The subdomain to generate the URL for.\n * @returns The URL for the transaction simulation API.\n */\nfunction getUrl(subdomain: string): string {\n return BASE_URL.replace('{0}', subdomain);\n}\n"]}
|
|
@@ -23,6 +23,9 @@ export type SimulationRequest = {
|
|
|
23
23
|
* State changes impact subsequent transactions in the list.
|
|
24
24
|
*/
|
|
25
25
|
transactions: SimulationRequestTransaction[];
|
|
26
|
+
blockOverrides?: {
|
|
27
|
+
time?: Hex;
|
|
28
|
+
};
|
|
26
29
|
/**
|
|
27
30
|
* Overrides to the state of the blockchain, keyed by smart contract address.
|
|
28
31
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation-api.d.cts","sour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Ed,4BAA4B;QAC5B,KAAK,CAAC,EAAE,GAAG,CAAC;QAEZ,+BAA+B;QAC/B,OAAO,CAAC,EAAE;YACR,CAAC,IAAI,EAAE,GAAG,GAAG,GAAG,CAAC;SAClB,CAAC;KACH,CAAC;CACH,CAAC;AAEF,iEAAiE;AACjE,MAAM,MAAM,6BAA6B,GAAG;IAC1C,0EAA0E;IAC1E,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,iFAAiF;IACjF,MAAM,EAAE,GAAG,CAAC;IAEZ,8DAA8D;IAC9D,SAAS,CAAC,EAAE,2BAA2B,CAAC;IAExC,uCAAuC;IACvC,SAAS,CAAC,EAAE;QACV,uDAAuD;QACvD,GAAG,CAAC,EAAE,2BAA2B,CAAC;QAElC,sDAAsD;QACtD,IAAI,CAAC,EAAE,2BAA2B,CAAC;KACpC,CAAC;CACH,CAAC;AAEF,wCAAwC;AACxC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,2DAA2D;IAC3D,YAAY,EAAE,6BAA6B,EAAE,CAAC;CAC/C,CAAC;AAkBF;;;;GAIG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,GAAG,EACZ,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,kBAAkB,CAAC,CA4B7B"}
|
|
@@ -23,6 +23,9 @@ export type SimulationRequest = {
|
|
|
23
23
|
* State changes impact subsequent transactions in the list.
|
|
24
24
|
*/
|
|
25
25
|
transactions: SimulationRequestTransaction[];
|
|
26
|
+
blockOverrides?: {
|
|
27
|
+
time?: Hex;
|
|
28
|
+
};
|
|
26
29
|
/**
|
|
27
30
|
* Overrides to the state of the blockchain, keyed by smart contract address.
|
|
28
31
|
*/
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation-api.d.mts","sourceRoot":"","sources":["../../src/utils/simulation-api.ts"],"names":[],"mappings":"AACA,OAAO,EAAsB,KAAK,GAAG,EAAE,wBAAwB;AAW/D,mEAAmE;AACnE,MAAM,MAAM,4B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AG,CAAC;SAClB,CAAC;KACH,CAAC;CACH,CAAC;AAEF,iEAAiE;AACjE,MAAM,MAAM,6BAA6B,GAAG;IAC1C,0EAA0E;IAC1E,KAAK,CAAC,EAAE,MAAM,CAAC;IAEf,iFAAiF;IACjF,MAAM,EAAE,GAAG,CAAC;IAEZ,8DAA8D;IAC9D,SAAS,CAAC,EAAE,2BAA2B,CAAC;IAExC,uCAAuC;IACvC,SAAS,CAAC,EAAE;QACV,uDAAuD;QACvD,GAAG,CAAC,EAAE,2BAA2B,CAAC;QAElC,sDAAsD;QACtD,IAAI,CAAC,EAAE,2BAA2B,CAAC;KACpC,CAAC;CACH,CAAC;AAEF,wCAAwC;AACxC,MAAM,MAAM,kBAAkB,GAAG;IAC/B,2DAA2D;IAC3D,YAAY,EAAE,6BAA6B,EAAE,CAAC;CAC/C,CAAC;AAkBF;;;;GAIG;AACH,wBAAsB,oBAAoB,CACxC,OAAO,EAAE,GAAG,EACZ,OAAO,EAAE,iBAAiB,GACzB,OAAO,CAAC,kBAAkB,CAAC,CA4B7B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"simulation-api.mjs","sourceRoot":"","sources":["../../src/utils/simulation-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,mBAAmB,EAAE,mCAAmC;AACjE,OAAO,EAAE,kBAAkB,EAAY,wBAAwB;AAE/D,OAAO,EAAE,gCAAgC,EAAE,eAAe,EAAE,sBAAkB;AAC9E,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAE1C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE,MAAM,UAAU,GAAG,6BAA6B,CAAC;AACjD,MAAM,QAAQ,GAAG,6CAA6C,CAAC;AAC/D,MAAM,iBAAiB,GAAG,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"simulation-api.mjs","sourceRoot":"","sources":["../../src/utils/simulation-api.ts"],"names":[],"mappings":"AAAA,OAAO,EA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AC1C;IAED,OAAO,YAAY,EAAE,MAAM,CAAC;AAC9B,CAAC;AAED;;;;GAIG;AACH,KAAK,UAAU,gBAAgB,CAAC,OAAY;IAC1C,MAAM,WAAW,GAAG,MAAM,cAAc,EAAE,CAAC;IAC3C,MAAM,cAAc,GAAG,mBAAmB,CAAC,OAAO,CAAC,CAAC;IACpD,MAAM,OAAO,GAAG,WAAW,CAAC,cAAc,CAAC,CAAC;IAE5C,IAAI,CAAC,OAAO,EAAE,aAAa,EAAE;QAC3B,GAAG,CAAC,wBAAwB,EAAE,OAAO,CAAC,CAAC;QACvC,MAAM,IAAI,gCAAgC,CAAC,OAAO,CAAC,CAAC;KACrD;IAED,OAAO,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;AACjC,CAAC;AAED;;GAEG;AACH,KAAK,UAAU,cAAc;IAC3B,MAAM,GAAG,GAAG,GAAG,MAAM,CAAC,kBAAkB,CAAC,GAAG,iBAAiB,EAAE,CAAC;IAChE,MAAM,QAAQ,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,CAAC;IAClC,OAAO,QAAQ,CAAC,IAAI,EAAE,CAAC;AACzB,CAAC;AAED;;;;GAIG;AACH,SAAS,MAAM,CAAC,SAAiB;IAC/B,OAAO,QAAQ,CAAC,OAAO,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC;AAC5C,CAAC","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\n\nimport { SimulationChainNotSupportedError, SimulationError } from '../errors';\nimport { projectLogger } from '../logger';\n\nconst log = createModuleLogger(projectLogger, 'simulation-api');\n\nconst RPC_METHOD = 'infura_simulateTransactions';\nconst BASE_URL = 'https://tx-sentinel-{0}.api.cx.metamask.io/';\nconst ENDPOINT_NETWORKS = 'networks';\n\n/** Single transaction to simulate in a simulation API request. */\nexport type SimulationRequestTransaction = {\n /** Data to send with the transaction. */\n data?: Hex;\n\n /** Sender of the transaction. */\n from: Hex;\n\n /** Gas limit for the transaction. */\n gas?: Hex;\n\n /** Maximum fee per gas for the transaction. */\n maxFeePerGas?: Hex;\n\n /** Maximum priority fee per gas for the transaction. */\n maxPriorityFeePerGas?: Hex;\n\n /** Recipient of the transaction. */\n to?: Hex;\n\n /** Value to send with the transaction. */\n value?: Hex;\n};\n\n/** Request to the simulation API to simulate transactions. */\nexport type SimulationRequest = {\n /**\n * Transactions to be sequentially simulated.\n * State changes impact subsequent transactions in the list.\n */\n transactions: SimulationRequestTransaction[];\n\n blockOverrides?: {\n time?: Hex;\n };\n\n /**\n * Overrides to the state of the blockchain, keyed by smart contract address.\n */\n overrides?: {\n [address: Hex]: {\n /** Overrides to the storage slots for a smart contract account. */\n stateDiff: {\n [slot: Hex]: Hex;\n };\n };\n };\n\n /**\n * Whether to include call traces in the response.\n * Defaults to false.\n */\n withCallTrace?: boolean;\n\n /**\n * Whether to include event logs in the response.\n * Defaults to false.\n */\n withLogs?: boolean;\n};\n\n/** Raw event log emitted by a simulated transaction. */\nexport type SimulationResponseLog = {\n /** Address of the account that created the event. */\n address: Hex;\n\n /** Raw data in the event that is not indexed. */\n data: Hex;\n\n /** Raw indexed data from the event. */\n topics: Hex[];\n};\n\n/** Call trace of a single simulated transaction. */\nexport type SimulationResponseCallTrace = {\n /** Nested calls. */\n calls: SimulationResponseCallTrace[];\n\n /** Raw event logs created by the call. */\n logs: SimulationResponseLog[];\n};\n\n/**\n * Changes to the blockchain state.\n * Keyed by account address.\n */\nexport type SimulationResponseStateDiff = {\n [address: Hex]: {\n /** Native balance of the account. */\n balance?: Hex;\n\n /** Nonce of the account. */\n nonce?: Hex;\n\n /** Storage values per slot. */\n storage?: {\n [slot: Hex]: Hex;\n };\n };\n};\n\n/** Response from the simulation API for a single transaction. */\nexport type SimulationResponseTransaction = {\n /** An error message indicating the transaction could not be simulated. */\n error?: string;\n\n /** Return value of the transaction, such as the balance if calling balanceOf. */\n return: Hex;\n\n /** Hierarchy of call data including nested calls and logs. */\n callTrace?: SimulationResponseCallTrace;\n\n /** Changes to the blockchain state. */\n stateDiff?: {\n /** Initial blockchain state before the transaction. */\n pre?: SimulationResponseStateDiff;\n\n /** Updated blockchain state after the transaction. */\n post?: SimulationResponseStateDiff;\n };\n};\n\n/** Response from the simulation API. */\nexport type SimulationResponse = {\n /** Simulation data for each transaction in the request. */\n transactions: SimulationResponseTransaction[];\n};\n\n/** Data for a network supported by the Simulation API. */\ntype SimulationNetwork = {\n /** Subdomain of the API for the network. */\n network: string;\n\n /** Whether the network supports confirmation simulations. */\n confirmations: boolean;\n};\n\n/** Response from the simulation API containing supported networks. */\ntype SimulationNetworkResponse = {\n [chainIdDecimal: string]: SimulationNetwork;\n};\n\nlet requestIdCounter = 0;\n\n/**\n * Simulate transactions using the transaction simulation API.\n * @param chainId - The chain ID to simulate transactions on.\n * @param request - The request to simulate transactions.\n */\nexport async function simulateTransactions(\n chainId: Hex,\n request: SimulationRequest,\n): Promise<SimulationResponse> {\n const url = await getSimulationUrl(chainId);\n\n log('Sending request', url, request);\n\n const requestId = requestIdCounter;\n requestIdCounter += 1;\n\n const response = await fetch(url, {\n method: 'POST',\n body: JSON.stringify({\n id: String(requestId),\n jsonrpc: '2.0',\n method: RPC_METHOD,\n params: [request],\n }),\n });\n\n const responseJson = await response.json();\n\n log('Received response', responseJson);\n\n if (responseJson.error) {\n const { code, message } = responseJson.error;\n throw new SimulationError(message, code);\n }\n\n return responseJson?.result;\n}\n\n/**\n * Get the URL for the transaction simulation API.\n * @param chainId - The chain ID to get the URL for.\n * @returns The URL for the transaction simulation API.\n */\nasync function getSimulationUrl(chainId: Hex): Promise<string> {\n const networkData = await getNetworkData();\n const chainIdDecimal = convertHexToDecimal(chainId);\n const network = networkData[chainIdDecimal];\n\n if (!network?.confirmations) {\n log('Chain is not supported', chainId);\n throw new SimulationChainNotSupportedError(chainId);\n }\n\n return getUrl(network.network);\n}\n\n/**\n * Retrieve the supported network data from the simulation API.\n */\nasync function getNetworkData(): Promise<SimulationNetworkResponse> {\n const url = `${getUrl('ethereum-mainnet')}${ENDPOINT_NETWORKS}`;\n const response = await fetch(url);\n return response.json();\n}\n\n/**\n * Generate the URL for the specified subdomain in the simulation API.\n * @param subdomain - The subdomain to generate the URL for.\n * @returns The URL for the transaction simulation API.\n */\nfunction getUrl(subdomain: string): string {\n return BASE_URL.replace('{0}', subdomain);\n}\n"]}
|