@toruslabs/ethereum-controllers 5.3.3 → 5.3.5

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.
@@ -115,7 +115,15 @@ __webpack_require__.d(__webpack_exports__, {
115
115
  TransactionStateManager: () => (/* reexport */ TransactionStateManager),
116
116
  TypedMessageController: () => (/* reexport */ TypedMessageController),
117
117
  XDAI_CHAIN_ID: () => (/* reexport */ XDAI_CHAIN_ID),
118
+ addCurrencies: () => (/* reexport */ addCurrencies),
119
+ addEtherscanTransactions: () => (/* reexport */ addEtherscanTransactions),
118
120
  bnLessThan: () => (/* reexport */ bnLessThan),
121
+ conversionGTE: () => (/* reexport */ conversionGTE),
122
+ conversionGreaterThan: () => (/* reexport */ conversionGreaterThan),
123
+ conversionLTE: () => (/* reexport */ conversionLTE),
124
+ conversionLessThan: () => (/* reexport */ conversionLessThan),
125
+ conversionMax: () => (/* reexport */ conversionMax),
126
+ conversionUtil: () => (/* reexport */ conversionUtil),
119
127
  createChainIdMiddleware: () => (/* reexport */ createChainIdMiddleware),
120
128
  createEthereumMiddleware: () => (/* reexport */ createEthereumMiddleware),
121
129
  createGetAccountsMiddleware: () => (/* reexport */ createGetAccountsMiddleware),
@@ -134,6 +142,7 @@ __webpack_require__.d(__webpack_exports__, {
134
142
  createProcessTypedMessageV4: () => (/* reexport */ createProcessTypedMessageV4),
135
143
  createProviderConfigMiddleware: () => (/* reexport */ createProviderConfigMiddleware),
136
144
  createRequestAccountsMiddleware: () => (/* reexport */ createRequestAccountsMiddleware),
145
+ decGWEIToHexWEI: () => (/* reexport */ decGWEIToHexWEI),
137
146
  determineTransactionType: () => (/* reexport */ determineTransactionType),
138
147
  ensureFieldIsString: () => (/* reexport */ ensureFieldIsString),
139
148
  ensureMutuallyExclusiveFieldsNotProvided: () => (/* reexport */ ensureMutuallyExclusiveFieldsNotProvided),
@@ -145,15 +154,18 @@ __webpack_require__.d(__webpack_exports__, {
145
154
  formatTime: () => (/* reexport */ formatTime),
146
155
  formatTxMetaForRpcResult: () => (/* reexport */ formatTxMetaForRpcResult),
147
156
  generateHistoryEntry: () => (/* reexport */ generateHistoryEntry),
157
+ getBigNumber: () => (/* reexport */ getBigNumber),
148
158
  getChainType: () => (/* reexport */ getChainType),
149
159
  getEthTxStatus: () => (/* reexport */ getEthTxStatus),
150
160
  getEtherScanHashLink: () => (/* reexport */ getEtherScanHashLink),
151
161
  getFinalStates: () => (/* reexport */ getFinalStates),
152
162
  getIpfsEndpoint: () => (/* reexport */ getIpfsEndpoint),
163
+ hexWEIToDecGWEI: () => (/* reexport */ hexWEIToDecGWEI),
153
164
  idleTimeTracker: () => (/* reexport */ idleTimeTracker),
154
165
  isAddressByChainId: () => (/* reexport */ isAddressByChainId),
155
166
  isEIP1559Transaction: () => (/* reexport */ isEIP1559Transaction),
156
167
  isLegacyTransaction: () => (/* reexport */ isLegacyTransaction),
168
+ multiplyCurrencies: () => (/* reexport */ multiplyCurrencies),
157
169
  normalizeAndValidateTxParams: () => (/* reexport */ normalizeAndValidateTxParams),
158
170
  normalizeMessageData: () => (/* reexport */ normalizeMessageData),
159
171
  normalizeTxParameters: () => (/* reexport */ normalizeTxParameters),
@@ -164,7 +176,9 @@ __webpack_require__.d(__webpack_exports__, {
164
176
  sanitizeNftMetdataUrl: () => (/* reexport */ sanitizeNftMetdataUrl),
165
177
  singleBalanceCheckerAbi: () => (/* reexport */ singleBalanceCheckerAbi),
166
178
  snapshotFromTxMeta: () => (/* reexport */ snapshotFromTxMeta),
179
+ subtractCurrencies: () => (/* reexport */ subtractCurrencies),
167
180
  toChecksumAddressByChainId: () => (/* reexport */ toChecksumAddressByChainId),
181
+ toNegative: () => (/* reexport */ toNegative),
168
182
  transactionMatchesNetwork: () => (/* reexport */ transactionMatchesNetwork),
169
183
  validateAddChainData: () => (/* reexport */ validateAddChainData),
170
184
  validateAddress: () => (/* reexport */ validateAddress),
@@ -755,7 +769,7 @@ const SUPPORTED_NETWORKS = {
755
769
  blockExplorerUrl: "https://bscscan.com",
756
770
  chainId: BSC_MAINNET_CHAIN_ID,
757
771
  displayName: "Binance Smart Chain (BSC)",
758
- logo: "bnb_logo.png",
772
+ logo: "bnb_logo.svg",
759
773
  rpcTarget: `https://bsc-dataseed.binance.org`,
760
774
  ticker: "BNB",
761
775
  tickerName: "Binance Coin"
@@ -810,7 +824,7 @@ const SUPPORTED_NETWORKS = {
810
824
  blockExplorerUrl: "https://gnosis.blockscout.com",
811
825
  chainId: XDAI_CHAIN_ID,
812
826
  displayName: "xDai",
813
- logo: "xdai.svg",
827
+ logo: "xDai.svg",
814
828
  rpcTarget: `https://rpc.gnosischain.com`,
815
829
  ticker: "DAI",
816
830
  tickerName: "xDai Token"
@@ -856,7 +870,7 @@ const SUPPORTED_NETWORKS = {
856
870
  blockExplorerUrl: "https://testnet.bscscan.com",
857
871
  chainId: BSC_TESTNET_CHAIN_ID,
858
872
  displayName: "Binance Smart Chain Testnet",
859
- logo: "bnb_logo.png",
873
+ logo: "bnb_logo.svg",
860
874
  rpcTarget: `https://data-seed-prebsc-1-s1.binance.org:8545`,
861
875
  ticker: "BNB",
862
876
  tickerName: "Binance Coin",
@@ -1206,12 +1220,351 @@ const util_namespaceObject = require("@ethereumjs/util");
1206
1220
  ;// CONCATENATED MODULE: external "bignumber.js"
1207
1221
  const external_bignumber_js_namespaceObject = require("bignumber.js");
1208
1222
  var external_bignumber_js_default = /*#__PURE__*/__webpack_require__.n(external_bignumber_js_namespaceObject);
1223
+ ;// CONCATENATED MODULE: external "@metamask/rpc-errors"
1224
+ const rpc_errors_namespaceObject = require("@metamask/rpc-errors");
1225
+ ;// CONCATENATED MODULE: ./src/Transaction/TransactionUtils.ts
1226
+
1227
+
1228
+
1229
+
1230
+
1231
+
1232
+
1233
+ const erc20Interface = new external_ethers_namespaceObject.Interface(erc20Abi);
1234
+ const erc721Interface = new external_ethers_namespaceObject.Interface(erc721Abi);
1235
+ const erc1155Interface = new external_ethers_namespaceObject.Interface(erc1155Abi);
1236
+
1237
+ // functions that handle normalizing of that key in txParams
1238
+
1239
+ const normalizers = {
1240
+ from: function (from) {
1241
+ let LowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1242
+ return LowerCase ? (0,util_namespaceObject.addHexPrefix)(from).toLowerCase() : (0,util_namespaceObject.addHexPrefix)(from);
1243
+ },
1244
+ to: function (to) {
1245
+ let LowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1246
+ return LowerCase ? (0,util_namespaceObject.addHexPrefix)(to).toLowerCase() : (0,util_namespaceObject.addHexPrefix)(to);
1247
+ },
1248
+ nonce: nonce => (0,util_namespaceObject.addHexPrefix)(nonce),
1249
+ customNonceValue: nonce => (0,util_namespaceObject.addHexPrefix)(nonce),
1250
+ value: value => (0,util_namespaceObject.addHexPrefix)(value),
1251
+ data: data => (0,util_namespaceObject.addHexPrefix)(data),
1252
+ gas: gas => (0,util_namespaceObject.addHexPrefix)(gas),
1253
+ gasPrice: gasPrice => (0,util_namespaceObject.addHexPrefix)(gasPrice),
1254
+ type: util_namespaceObject.addHexPrefix,
1255
+ maxFeePerGas: util_namespaceObject.addHexPrefix,
1256
+ maxPriorityFeePerGas: util_namespaceObject.addHexPrefix
1257
+ };
1258
+
1259
+ /**
1260
+ * normalizes txParams
1261
+ */
1262
+ function normalizeTxParameters(txParameters) {
1263
+ let lowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1264
+ // apply only keys in the normalizers
1265
+ const normalizedTxParameters = {
1266
+ id: txParameters.id || (0,base_controllers_namespaceObject.randomId)(),
1267
+ from: txParameters.from
1268
+ };
1269
+ for (const key in normalizers) {
1270
+ const currentKey = key;
1271
+ if (txParameters[currentKey])
1272
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1273
+ normalizedTxParameters[currentKey] = normalizers[currentKey](txParameters[currentKey], lowerCase);
1274
+ }
1275
+ return normalizedTxParameters;
1276
+ }
1277
+ function transactionMatchesNetwork(transaction, chainId) {
1278
+ if (typeof transaction.chainId !== "undefined") {
1279
+ return transaction.chainId === chainId;
1280
+ }
1281
+ return false;
1282
+ }
1283
+
1284
+ /**
1285
+ * Determines if the maxFeePerGas and maxPriorityFeePerGas fields are supplied
1286
+ * and valid inputs. This will return false for non hex string inputs.
1287
+ * the transaction to check
1288
+ * @returns true if transaction uses valid EIP1559 fields
1289
+ */
1290
+ function isEIP1559Transaction(transaction) {
1291
+ var _transaction$transact, _transaction$transact2;
1292
+ return (0,util_namespaceObject.isHexString)((0,util_namespaceObject.addHexPrefix)(transaction === null || transaction === void 0 || (_transaction$transact = transaction.transaction) === null || _transaction$transact === void 0 ? void 0 : _transaction$transact.maxFeePerGas)) && (0,util_namespaceObject.isHexString)((0,util_namespaceObject.addHexPrefix)(transaction === null || transaction === void 0 || (_transaction$transact2 = transaction.transaction) === null || _transaction$transact2 === void 0 ? void 0 : _transaction$transact2.maxPriorityFeePerGas));
1293
+ }
1294
+
1295
+ /**
1296
+ * Determine if the maxFeePerGas and maxPriorityFeePerGas fields are not
1297
+ * supplied and that the gasPrice field is valid if it is provided. This will
1298
+ * return false if gasPrice is a non hex string.
1299
+ * transaction -
1300
+ * the transaction to check
1301
+ * @returns true if transaction uses valid Legacy fields OR lacks
1302
+ * EIP1559 fields
1303
+ */
1304
+ function isLegacyTransaction(transaction) {
1305
+ return typeof transaction.transaction.maxFeePerGas === "undefined" && typeof transaction.transaction.maxPriorityFeePerGas === "undefined" && (typeof transaction.transaction.gasPrice === "undefined" || (0,util_namespaceObject.isHexString)((0,util_namespaceObject.addHexPrefix)(transaction.transaction.gasPrice)));
1306
+ }
1307
+
1308
+ /**
1309
+ * Given two fields, ensure that the second field is not included in txParams,
1310
+ * and if it is throw an invalidParams error.
1311
+ */
1312
+ function ensureMutuallyExclusiveFieldsNotProvided(txParams, fieldBeingValidated, mutuallyExclusiveField) {
1313
+ if (typeof txParams[mutuallyExclusiveField] !== "undefined") {
1314
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`);
1315
+ }
1316
+ }
1317
+
1318
+ /**
1319
+ * Ensures that the provided value for field is a string, throws an
1320
+ * invalidParams error if field is not a string.
1321
+ */
1322
+ function ensureFieldIsString(txParams, field) {
1323
+ if (typeof txParams[field] !== "string") {
1324
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction params: ${field} is not a string. got: (${txParams[field]})`);
1325
+ }
1326
+ }
1327
+
1328
+ /**
1329
+ * Ensures that the provided txParams has the proper 'type' specified for the
1330
+ * given field, if it is provided. If types do not match throws an
1331
+ * invalidParams error.
1332
+ */
1333
+ function ensureProperTransactionEnvelopeTypeProvided(txParams, field) {
1334
+ switch (field) {
1335
+ case "maxFeePerGas":
1336
+ case "maxPriorityFeePerGas":
1337
+ if (txParams.type && txParams.type !== TRANSACTION_ENVELOPE_TYPES.FEE_MARKET) {
1338
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${txParams.type}" but ` + `including maxFeePerGas and maxPriorityFeePerGas requires type: "${TRANSACTION_ENVELOPE_TYPES.FEE_MARKET}"`);
1339
+ }
1340
+ break;
1341
+ case "gasPrice":
1342
+ default:
1343
+ if (txParams.type && txParams.type === TRANSACTION_ENVELOPE_TYPES.FEE_MARKET) {
1344
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${txParams.type}" but ` + "included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas");
1345
+ }
1346
+ }
1347
+ }
1348
+
1349
+ /**
1350
+ * validates the from field in txParams
1351
+ */
1352
+ function validateFrom(txParams) {
1353
+ if (!(typeof txParams.from === "string")) {
1354
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid "from" address "${txParams.from}": not a string.`);
1355
+ }
1356
+ if (!(0,util_namespaceObject.isValidAddress)(txParams.from)) {
1357
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams('Invalid "from" address.');
1358
+ }
1359
+ }
1360
+
1361
+ /**
1362
+ * validates the to field in txParams
1363
+ */
1364
+ function validateRecipient(txParameters) {
1365
+ if (txParameters.to === "0x" || txParameters.to === null) {
1366
+ if (txParameters.data) {
1367
+ delete txParameters.to;
1368
+ } else {
1369
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams('Invalid "to" address.');
1370
+ }
1371
+ } else if (txParameters.to !== undefined && !(0,util_namespaceObject.isValidAddress)(txParameters.to)) {
1372
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams('Invalid "to" address.');
1373
+ }
1374
+ return txParameters;
1375
+ }
1376
+
1377
+ /**
1378
+ * Validates the given tx parameters
1379
+ * @throws if the tx params contains invalid fields
1380
+ */
1381
+ function validateTxParameters(txParams) {
1382
+ let eip1559Compatibility = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1383
+ if (!txParams || typeof txParams !== "object" || Array.isArray(txParams)) {
1384
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams("Invalid transaction params: must be an object.");
1385
+ }
1386
+ if (!txParams.to && !txParams.data) {
1387
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams('Invalid transaction params: must specify "data" for contract deployments, or "to" (and optionally "data") for all other types of transactions.');
1388
+ }
1389
+ if (isEIP1559Transaction({
1390
+ transaction: txParams
1391
+ }) && !eip1559Compatibility) {
1392
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams("Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559");
1393
+ }
1394
+ Object.entries(txParams).forEach(_ref => {
1395
+ let [key, value] = _ref;
1396
+ // validate types
1397
+ switch (key) {
1398
+ case "from":
1399
+ validateFrom(txParams);
1400
+ break;
1401
+ case "to":
1402
+ validateRecipient(txParams);
1403
+ break;
1404
+ case "gasPrice":
1405
+ ensureProperTransactionEnvelopeTypeProvided(txParams, "gasPrice");
1406
+ ensureMutuallyExclusiveFieldsNotProvided(txParams, "gasPrice", "maxFeePerGas");
1407
+ ensureMutuallyExclusiveFieldsNotProvided(txParams, "gasPrice", "maxPriorityFeePerGas");
1408
+ ensureFieldIsString(txParams, "gasPrice");
1409
+ break;
1410
+ case "maxFeePerGas":
1411
+ ensureProperTransactionEnvelopeTypeProvided(txParams, "maxFeePerGas");
1412
+ ensureMutuallyExclusiveFieldsNotProvided(txParams, "maxFeePerGas", "gasPrice");
1413
+ ensureFieldIsString(txParams, "maxFeePerGas");
1414
+ break;
1415
+ case "maxPriorityFeePerGas":
1416
+ ensureProperTransactionEnvelopeTypeProvided(txParams, "maxPriorityFeePerGas");
1417
+ ensureMutuallyExclusiveFieldsNotProvided(txParams, "maxPriorityFeePerGas", "gasPrice");
1418
+ ensureFieldIsString(txParams, "maxPriorityFeePerGas");
1419
+ break;
1420
+ case "value":
1421
+ ensureFieldIsString(txParams, "value");
1422
+ if (value.toString().includes("-")) {
1423
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction value "${value}": not a positive number.`);
1424
+ }
1425
+ if (value.toString().includes(".")) {
1426
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction value of "${value}": number must be in wei.`);
1427
+ }
1428
+ break;
1429
+ case "chainId":
1430
+ if (typeof value !== "number" && typeof value !== "string") {
1431
+ throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction params: ${key} is not a Number or hex string. got: (${value})`);
1432
+ }
1433
+ break;
1434
+ default:
1435
+ ensureFieldIsString(txParams, key);
1436
+ }
1437
+ });
1438
+ }
1439
+ function normalizeAndValidateTxParams(txParams) {
1440
+ let lowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
1441
+ const normalizedTxParams = normalizeTxParameters(txParams, lowerCase);
1442
+ validateTxParameters(normalizedTxParams);
1443
+ return normalizedTxParams;
1444
+ }
1445
+
1446
+ /**
1447
+ * @returns an array of states that can be considered final
1448
+ */
1449
+ function getFinalStates() {
1450
+ return [base_controllers_namespaceObject.TransactionStatus.rejected,
1451
+ // the user has responded no!
1452
+ base_controllers_namespaceObject.TransactionStatus.confirmed,
1453
+ // the tx has been included in a block.
1454
+ base_controllers_namespaceObject.TransactionStatus.failed,
1455
+ // the tx failed for some reason, included on tx data.
1456
+ base_controllers_namespaceObject.TransactionStatus.dropped // the tx nonce was already used
1457
+ ];
1458
+ }
1459
+ function parseStandardTokenTransactionData(data) {
1460
+ try {
1461
+ const txDesc = erc20Interface.parseTransaction({
1462
+ data
1463
+ });
1464
+ if (txDesc) return {
1465
+ name: txDesc.name,
1466
+ methodParams: txDesc.args.toArray(),
1467
+ type: CONTRACT_TYPE_ERC20
1468
+ };
1469
+ } catch {
1470
+ // ignore and next try to parse with erc721 ABI
1471
+ }
1472
+ try {
1473
+ const txDesc = erc721Interface.parseTransaction({
1474
+ data
1475
+ });
1476
+ if (txDesc) return {
1477
+ name: txDesc.name,
1478
+ methodParams: txDesc.args.toArray(),
1479
+ type: CONTRACT_TYPE_ERC721
1480
+ };
1481
+ } catch {
1482
+ // ignore and next try to parse with erc1155 ABI
1483
+ }
1484
+ try {
1485
+ const txDesc = erc1155Interface.parseTransaction({
1486
+ data
1487
+ });
1488
+ if (txDesc) return {
1489
+ name: txDesc.name,
1490
+ methodParams: txDesc.args.toArray(),
1491
+ type: CONTRACT_TYPE_ERC1155
1492
+ };
1493
+ } catch {
1494
+ // ignore and return undefined
1495
+ }
1496
+ return undefined;
1497
+ }
1498
+ const readAddressAsContract = async (provider, address) => {
1499
+ let contractCode;
1500
+ try {
1501
+ contractCode = await provider.request({
1502
+ method: METHOD_TYPES.ETH_GET_CODE,
1503
+ params: [address, "latest"]
1504
+ });
1505
+ } catch (e) {
1506
+ contractCode = null;
1507
+ }
1508
+ const isContractAddress = contractCode ? contractCode !== "0x" && contractCode !== "0x0" : false;
1509
+ return {
1510
+ contractCode,
1511
+ isContractAddress
1512
+ };
1513
+ };
1514
+ async function determineTransactionType(txParams, provider) {
1515
+ const {
1516
+ data,
1517
+ to
1518
+ } = txParams;
1519
+ let name = "";
1520
+ let methodParams = [];
1521
+ let type = "";
1522
+ try {
1523
+ ({
1524
+ name,
1525
+ methodParams,
1526
+ type
1527
+ } = data && parseStandardTokenTransactionData(data) || {});
1528
+ } catch (error) {
1529
+ external_loglevel_default().debug("Failed to parse transaction data", error);
1530
+ }
1531
+ let result;
1532
+ let contractCode = "";
1533
+ if (data && !to) {
1534
+ result = base_controllers_namespaceObject.TRANSACTION_TYPES.DEPLOY_CONTRACT;
1535
+ } else {
1536
+ const {
1537
+ contractCode: resultCode,
1538
+ isContractAddress
1539
+ } = await readAddressAsContract(provider, to);
1540
+ contractCode = resultCode;
1541
+ if (isContractAddress) {
1542
+ const valueExists = txParams.value && Number(txParams.value) !== 0;
1543
+ const tokenMethodName = [base_controllers_namespaceObject.TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, base_controllers_namespaceObject.TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, base_controllers_namespaceObject.TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, base_controllers_namespaceObject.TRANSACTION_TYPES.COLLECTIBLE_METHOD_SAFE_TRANSFER_FROM, base_controllers_namespaceObject.TRANSACTION_TYPES.SET_APPROVAL_FOR_ALL].find(x => {
1544
+ var _name;
1545
+ return x.toLowerCase() === ((_name = name) === null || _name === void 0 ? void 0 : _name.toLowerCase());
1546
+ });
1547
+ result = data && tokenMethodName && !valueExists ? tokenMethodName : base_controllers_namespaceObject.TRANSACTION_TYPES.CONTRACT_INTERACTION;
1548
+ } else {
1549
+ result = base_controllers_namespaceObject.TRANSACTION_TYPES.SENT_ETHER;
1550
+ }
1551
+ }
1552
+ return {
1553
+ type: type || CONTRACT_TYPE_ETH,
1554
+ category: result,
1555
+ methodParams,
1556
+ getCodeResponse: contractCode
1557
+ };
1558
+ }
1209
1559
  ;// CONCATENATED MODULE: ./src/utils/helpers.ts
1210
1560
 
1211
1561
 
1212
1562
 
1213
1563
 
1214
1564
 
1565
+
1566
+
1567
+
1215
1568
  function getEtherScanHashLink(txHash, chainId) {
1216
1569
  if (!SUPPORTED_NETWORKS[chainId]) return "";
1217
1570
  return `${SUPPORTED_NETWORKS[chainId].blockExplorerUrl}/tx/${txHash}`;
@@ -1246,9 +1599,9 @@ const formatPastTx = (x, lowerCaseSelectedAddress) => {
1246
1599
  transaction_hash: x.transaction_hash,
1247
1600
  transaction_category: x.transaction_category,
1248
1601
  // TODO: // figure out how to handle these values.
1249
- // isEtherscan: x.isEtherscan,
1250
- // input: x.input || "",
1251
- // token_id: x.token_id || "",
1602
+ isEtherscan: x.isEtherscan,
1603
+ input: x.input || "",
1604
+ token_id: x.token_id || "",
1252
1605
  contract_address: x.contract_address || "",
1253
1606
  nonce: x.nonce || "",
1254
1607
  is_cancel: !!x.is_cancel || false,
@@ -1349,6 +1702,55 @@ function getChainType(chainId) {
1349
1702
  }
1350
1703
  return "custom";
1351
1704
  }
1705
+ const addEtherscanTransactions = async (txn, lowerCaseSelectedAddress, provider, chainId) => {
1706
+ const transactionPromises = await Promise.all(txn.map(async tx => {
1707
+ var _SUPPORTED_NETWORKS$c, _SUPPORTED_NETWORKS$c2;
1708
+ const {
1709
+ category,
1710
+ type
1711
+ } = await determineTransactionType(objectSpread2_default()(objectSpread2_default()({}, tx), {}, {
1712
+ data: tx.input
1713
+ }), provider);
1714
+ tx.transaction_category = tx.transaction_category || category;
1715
+ tx.type_image_link = ((_SUPPORTED_NETWORKS$c = SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c === void 0 ? void 0 : _SUPPORTED_NETWORKS$c.logo) || "";
1716
+ tx.type_name = (_SUPPORTED_NETWORKS$c2 = SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c2 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c2.ticker;
1717
+ tx.type = type;
1718
+ return tx;
1719
+ }));
1720
+ const finalTxs = transactionPromises.reduce((accumulator, x) => {
1721
+ var _SUPPORTED_NETWORKS$c3, _SUPPORTED_NETWORKS$c4;
1722
+ const totalAmount = x.value ? (0,external_ethers_namespaceObject.formatEther)(x.value) : "";
1723
+ const etherscanTransaction = {
1724
+ etherscanLink: getEtherScanHashLink(x.hash, chainId),
1725
+ type: x.type || ((_SUPPORTED_NETWORKS$c3 = SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c3 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c3.ticker) || CONTRACT_TYPE_ETH,
1726
+ type_image_link: x.type_image_link || "n/a",
1727
+ type_name: x.type_name || "n/a",
1728
+ symbol: (_SUPPORTED_NETWORKS$c4 = SUPPORTED_NETWORKS[chainId]) === null || _SUPPORTED_NETWORKS$c4 === void 0 ? void 0 : _SUPPORTED_NETWORKS$c4.ticker,
1729
+ token_id: x.tokenID || "",
1730
+ total_amount: totalAmount,
1731
+ created_at: new Date(Number(x.timeStamp) * 1000),
1732
+ from: x.from,
1733
+ to: x.to,
1734
+ transaction_hash: x.hash,
1735
+ status: x.txreceipt_status && x.txreceipt_status === "0" ? base_controllers_namespaceObject.TransactionStatus.failed : base_controllers_namespaceObject.TransactionStatus.approved,
1736
+ isEtherscan: true,
1737
+ input: x.input,
1738
+ contract_address: x.contractAddress,
1739
+ transaction_category: x.transaction_category,
1740
+ gas: x.gas,
1741
+ gasPrice: x.gasPrice,
1742
+ chain_id: chainId,
1743
+ currency_amount: "",
1744
+ nonce: x.nonce,
1745
+ from_aa_address: "",
1746
+ is_cancel: false,
1747
+ selected_currency: ""
1748
+ };
1749
+ accumulator.push(formatPastTx(etherscanTransaction, lowerCaseSelectedAddress));
1750
+ return accumulator;
1751
+ }, []);
1752
+ return finalTxs;
1753
+ };
1352
1754
  ;// CONCATENATED MODULE: ./src/Block/PollingBlockTracker.ts
1353
1755
 
1354
1756
 
@@ -1547,6 +1949,7 @@ class CurrencyController extends base_controllers_namespaceObject.BaseCurrencyCo
1547
1949
  const external_lodash_namespaceObject = require("lodash");
1548
1950
  ;// CONCATENATED MODULE: external "@babel/runtime/helpers/objectDestructuringEmpty"
1549
1951
  const objectDestructuringEmpty_namespaceObject = require("@babel/runtime/helpers/objectDestructuringEmpty");
1952
+ var objectDestructuringEmpty_default = /*#__PURE__*/__webpack_require__.n(objectDestructuringEmpty_namespaceObject);
1550
1953
  ;// CONCATENATED MODULE: external "@babel/runtime/helpers/objectWithoutProperties"
1551
1954
  const objectWithoutProperties_namespaceObject = require("@babel/runtime/helpers/objectWithoutProperties");
1552
1955
  var objectWithoutProperties_default = /*#__PURE__*/__webpack_require__.n(objectWithoutProperties_namespaceObject);
@@ -1557,9 +1960,9 @@ var external_bn_js_default = /*#__PURE__*/__webpack_require__.n(external_bn_js_n
1557
1960
 
1558
1961
 
1559
1962
 
1560
- const _excluded = (/* unused pure expression or super */ null && (["aBase", "bBase"])),
1561
- _excluded2 = (/* unused pure expression or super */ null && (["aBase", "bBase"])),
1562
- _excluded3 = (/* unused pure expression or super */ null && (["multiplicandBase", "multiplierBase"]));
1963
+ const _excluded = ["aBase", "bBase"],
1964
+ _excluded2 = ["aBase", "bBase"],
1965
+ _excluded3 = ["multiplicandBase", "multiplierBase"];
1563
1966
  // eslint-disable-next-line @typescript-eslint/ban-ts-comment
1564
1967
  // @ts-nocheck
1565
1968
  /* Currency Conversion Utility
@@ -1698,10 +2101,10 @@ const getBigNumber = (value, base) => {
1698
2101
 
1699
2102
  // We don't include 'number' here, because BigNumber will throw if passed
1700
2103
  // a number primitive it considers unsafe.
1701
- if (typeof value === "string" || value instanceof BigNumber) {
1702
- return new BigNumber(value, base);
2104
+ if (typeof value === "string" || value instanceof (external_bignumber_js_default())) {
2105
+ return new (external_bignumber_js_default())(value, base);
1703
2106
  }
1704
- return new BigNumber(String(value), base);
2107
+ return new (external_bignumber_js_default())(String(value), base);
1705
2108
  };
1706
2109
  const addCurrencies = function (a, b) {
1707
2110
  let options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
@@ -1709,12 +2112,12 @@ const addCurrencies = function (a, b) {
1709
2112
  aBase,
1710
2113
  bBase
1711
2114
  } = options,
1712
- conversionOptions = _objectWithoutProperties(options, _excluded);
2115
+ conversionOptions = objectWithoutProperties_default()(options, _excluded);
1713
2116
  if (!isValidBase(aBase) || !isValidBase(bBase)) {
1714
2117
  throw new Error("Must specify valid aBase and bBase");
1715
2118
  }
1716
2119
  const value = getBigNumber(a, aBase).plus(getBigNumber(b, bBase));
1717
- return converter(_objectSpread({
2120
+ return converter(objectSpread2_default()({
1718
2121
  value
1719
2122
  }, conversionOptions));
1720
2123
  };
@@ -1724,12 +2127,12 @@ const subtractCurrencies = function (a, b) {
1724
2127
  aBase,
1725
2128
  bBase
1726
2129
  } = options,
1727
- conversionOptions = _objectWithoutProperties(options, _excluded2);
2130
+ conversionOptions = objectWithoutProperties_default()(options, _excluded2);
1728
2131
  if (!isValidBase(aBase) || !isValidBase(bBase)) {
1729
2132
  throw new Error("Must specify valid aBase and bBase");
1730
2133
  }
1731
2134
  const value = getBigNumber(a, aBase).minus(getBigNumber(b, bBase));
1732
- return converter(_objectSpread({
2135
+ return converter(objectSpread2_default()({
1733
2136
  value
1734
2137
  }, conversionOptions));
1735
2138
  };
@@ -1739,47 +2142,47 @@ const multiplyCurrencies = function (a, b) {
1739
2142
  multiplicandBase,
1740
2143
  multiplierBase
1741
2144
  } = options,
1742
- conversionOptions = _objectWithoutProperties(options, _excluded3);
2145
+ conversionOptions = objectWithoutProperties_default()(options, _excluded3);
1743
2146
  if (!isValidBase(multiplicandBase) || !isValidBase(multiplierBase)) {
1744
2147
  throw new Error("Must specify valid multiplicandBase and multiplierBase");
1745
2148
  }
1746
2149
  const value = getBigNumber(a, multiplicandBase).times(getBigNumber(b, multiplierBase));
1747
- return converter(_objectSpread({
2150
+ return converter(objectSpread2_default()({
1748
2151
  value
1749
2152
  }, conversionOptions));
1750
2153
  };
1751
2154
  const conversionGreaterThan = (_ref3, _ref4) => {
1752
- let secondProps = Object.assign({}, (_objectDestructuringEmpty(_ref4), _ref4));
1753
- let firstProps = Object.assign({}, (_objectDestructuringEmpty(_ref3), _ref3));
1754
- const firstValue = converter(_objectSpread({}, firstProps));
1755
- const secondValue = converter(_objectSpread({}, secondProps));
2155
+ let secondProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref4), _ref4));
2156
+ let firstProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref3), _ref3));
2157
+ const firstValue = converter(objectSpread2_default()({}, firstProps));
2158
+ const secondValue = converter(objectSpread2_default()({}, secondProps));
1756
2159
  return firstValue.gt(secondValue);
1757
2160
  };
1758
2161
  const conversionLessThan = (_ref5, _ref6) => {
1759
- let secondProps = Object.assign({}, (_objectDestructuringEmpty(_ref6), _ref6));
1760
- let firstProps = Object.assign({}, (_objectDestructuringEmpty(_ref5), _ref5));
1761
- const firstValue = converter(_objectSpread({}, firstProps));
1762
- const secondValue = converter(_objectSpread({}, secondProps));
2162
+ let secondProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref6), _ref6));
2163
+ let firstProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref5), _ref5));
2164
+ const firstValue = converter(objectSpread2_default()({}, firstProps));
2165
+ const secondValue = converter(objectSpread2_default()({}, secondProps));
1763
2166
  return firstValue.lt(secondValue);
1764
2167
  };
1765
2168
  const conversionMax = (_ref7, _ref8) => {
1766
- let secondProps = Object.assign({}, (_objectDestructuringEmpty(_ref8), _ref8));
1767
- let firstProps = Object.assign({}, (_objectDestructuringEmpty(_ref7), _ref7));
1768
- const firstIsGreater = conversionGreaterThan(_objectSpread({}, firstProps), _objectSpread({}, secondProps));
2169
+ let secondProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref8), _ref8));
2170
+ let firstProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref7), _ref7));
2171
+ const firstIsGreater = conversionGreaterThan(objectSpread2_default()({}, firstProps), objectSpread2_default()({}, secondProps));
1769
2172
  return firstIsGreater ? firstProps.value : secondProps.value;
1770
2173
  };
1771
2174
  const conversionGTE = (_ref9, _ref10) => {
1772
- let secondProps = Object.assign({}, (_objectDestructuringEmpty(_ref10), _ref10));
1773
- let firstProps = Object.assign({}, (_objectDestructuringEmpty(_ref9), _ref9));
1774
- const firstValue = converter(_objectSpread({}, firstProps));
1775
- const secondValue = converter(_objectSpread({}, secondProps));
2175
+ let secondProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref10), _ref10));
2176
+ let firstProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref9), _ref9));
2177
+ const firstValue = converter(objectSpread2_default()({}, firstProps));
2178
+ const secondValue = converter(objectSpread2_default()({}, secondProps));
1776
2179
  return firstValue.isGreaterThanOrEqualTo(secondValue);
1777
2180
  };
1778
2181
  const conversionLTE = (_ref11, _ref12) => {
1779
- let secondProps = Object.assign({}, (_objectDestructuringEmpty(_ref12), _ref12));
1780
- let firstProps = Object.assign({}, (_objectDestructuringEmpty(_ref11), _ref11));
1781
- const firstValue = converter(_objectSpread({}, firstProps));
1782
- const secondValue = converter(_objectSpread({}, secondProps));
2182
+ let secondProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref12), _ref12));
2183
+ let firstProps = Object.assign({}, (objectDestructuringEmpty_default()(_ref11), _ref11));
2184
+ const firstValue = converter(objectSpread2_default()({}, firstProps));
2185
+ const secondValue = converter(objectSpread2_default()({}, secondProps));
1783
2186
  return firstValue.isLessThanOrEqualTo(secondValue);
1784
2187
  };
1785
2188
  const toNegative = function (n) {
@@ -2267,8 +2670,6 @@ class KeyringController extends base_controllers_namespaceObject.BaseKeyringCont
2267
2670
  return wallet;
2268
2671
  }
2269
2672
  }
2270
- ;// CONCATENATED MODULE: external "@metamask/rpc-errors"
2271
- const rpc_errors_namespaceObject = require("@metamask/rpc-errors");
2272
2673
  ;// CONCATENATED MODULE: ./src/Message/AbstractMessageController.ts
2273
2674
 
2274
2675
 
@@ -4099,7 +4500,8 @@ class PreferencesController extends base_controllers_namespaceObject.BasePrefere
4099
4500
  defaultPreferences: {
4100
4501
  formattedPastTransactions: [],
4101
4502
  fetchedPastTx: [],
4102
- paymentTx: []
4503
+ paymentTx: [],
4504
+ etherscanTransactions: []
4103
4505
  },
4104
4506
  signAuthMessage
4105
4507
  });
@@ -4280,10 +4682,15 @@ class PreferencesController extends base_controllers_namespaceObject.BasePrefere
4280
4682
  chainId
4281
4683
  } = this.getProviderConfig();
4282
4684
  if (ETHERSCAN_SUPPORTED_CHAINS.includes(chainId)) {
4283
- return this.fetchEtherscanTx({
4685
+ const etherscanTxn = await this.fetchEtherscanTx({
4284
4686
  selectedAddress,
4285
4687
  chainId: this.getProviderConfig().chainId
4286
4688
  });
4689
+ const finalEthScanTxn = await addEtherscanTransactions(etherscanTxn, selectedAddress, this.provider, chainId);
4690
+ this.updateState({
4691
+ etherscanTransactions: finalEthScanTxn
4692
+ });
4693
+ return etherscanTxn;
4287
4694
  }
4288
4695
  }
4289
4696
  }
@@ -4292,6 +4699,7 @@ class PreferencesController extends base_controllers_namespaceObject.BasePrefere
4292
4699
  const url = new URL(`${this.config.api}/etherscan`);
4293
4700
  url.searchParams.append("chainId", parameters.chainId);
4294
4701
  const response = await (0,http_helpers_namespaceObject.get)(url.href, this.headers(parameters.selectedAddress));
4702
+ external_loglevel_default().info("Etherscan Response", response);
4295
4703
  return response.success ? response.data : [];
4296
4704
  } catch (error) {
4297
4705
  external_loglevel_default().error("unable to fetch etherscan tx", error);
@@ -5359,412 +5767,78 @@ class TransactionGasUtil {
5359
5767
  addGasBuffer(initialGasLimitHex, blockGasLimitHex) {
5360
5768
  let multiplier = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 1.5;
5361
5769
  const initialGasLimitBn = new external_bn_js_namespaceObject.BN((0,util_namespaceObject.stripHexPrefix)(initialGasLimitHex), 16);
5362
- const blockGasLimitBn = new external_bn_js_namespaceObject.BN((0,util_namespaceObject.stripHexPrefix)(blockGasLimitHex), 16);
5363
- const upperGasLimitBn = blockGasLimitBn.muln(0.9);
5364
- const bufferedGasLimitBn = initialGasLimitBn.muln(multiplier);
5365
-
5366
- // if initialGasLimit is above blockGasLimit, dont modify it
5367
- if (initialGasLimitBn.gt(upperGasLimitBn)) return (0,util_namespaceObject.addHexPrefix)(initialGasLimitBn.toString("hex"));
5368
- // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit
5369
- if (bufferedGasLimitBn.lt(upperGasLimitBn)) return (0,util_namespaceObject.addHexPrefix)(bufferedGasLimitBn.toString("hex"));
5370
- // otherwise use blockGasLimit
5371
- return (0,util_namespaceObject.addHexPrefix)(upperGasLimitBn.toString("hex"));
5372
- }
5373
-
5374
- /**
5375
- Estimates the tx's gas usage
5376
- */
5377
- async estimateTxGas(txMeta) {
5378
- const txParams = (0,external_lodash_namespaceObject.cloneDeep)(txMeta.transaction);
5379
-
5380
- // `eth_estimateGas` can fail if the user has insufficient balance for the
5381
- // value being sent, or for the gas cost. We don't want to check their
5382
- // balance here, we just want the gas estimate. The gas price is removed
5383
- // to skip those balance checks. We check balance elsewhere. We also delete
5384
- // maxFeePerGas and maxPriorityFeePerGas to support EIP-1559 txs.
5385
- delete txParams.gasPrice;
5386
- delete txParams.maxFeePerGas;
5387
- delete txParams.maxPriorityFeePerGas;
5388
- return this.provider.request({
5389
- method: "eth_estimateGas",
5390
- params: [txParams]
5391
- });
5392
- }
5393
- }
5394
- ;// CONCATENATED MODULE: external "fast-json-patch"
5395
- const external_fast_json_patch_namespaceObject = require("fast-json-patch");
5396
- var external_fast_json_patch_default = /*#__PURE__*/__webpack_require__.n(external_fast_json_patch_namespaceObject);
5397
- ;// CONCATENATED MODULE: ./src/Transaction/TransactionStateHistoryHelper.ts
5398
-
5399
-
5400
-
5401
- /**
5402
- Generates an array of history objects sense the previous state.
5403
- The object has the keys
5404
- op (the operation performed),
5405
- path (the key and if a nested object then each key will be seperated with a `/`)
5406
- value
5407
- with the first entry having the note and a timestamp when the change took place
5408
- */
5409
- function generateHistoryEntry(previousState, newState, note) {
5410
- const entry = external_fast_json_patch_default().compare(previousState, newState);
5411
- // Add a note to the first op, since it breaks if we append it to the entry
5412
- if (entry[0]) {
5413
- if (note) {
5414
- entry[0].note = note;
5415
- }
5416
- entry[0].timestamp = Date.now();
5417
- }
5418
- return entry;
5419
- }
5420
-
5421
- /**
5422
- Recovers previous txMeta state obj
5423
- */
5424
- function replayHistory(_shortHistory) {
5425
- const shortHistory = (0,external_lodash_namespaceObject.cloneDeep)(_shortHistory);
5426
- return shortHistory.reduce((val, entry) => external_fast_json_patch_default().applyPatch(val, entry).newDocument);
5427
- }
5428
- function snapshotFromTxMeta(txMeta) {
5429
- const shallow = objectSpread2_default()({}, txMeta);
5430
- delete shallow.history;
5431
- return (0,external_lodash_namespaceObject.cloneDeep)(shallow);
5432
- }
5433
-
5434
- ;// CONCATENATED MODULE: ./src/Transaction/TransactionUtils.ts
5435
-
5436
-
5437
-
5438
-
5439
-
5440
-
5441
-
5442
- const erc20Interface = new external_ethers_namespaceObject.Interface(erc20Abi);
5443
- const erc721Interface = new external_ethers_namespaceObject.Interface(erc721Abi);
5444
- const erc1155Interface = new external_ethers_namespaceObject.Interface(erc1155Abi);
5445
-
5446
- // functions that handle normalizing of that key in txParams
5447
-
5448
- const normalizers = {
5449
- from: function (from) {
5450
- let LowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
5451
- return LowerCase ? (0,util_namespaceObject.addHexPrefix)(from).toLowerCase() : (0,util_namespaceObject.addHexPrefix)(from);
5452
- },
5453
- to: function (to) {
5454
- let LowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
5455
- return LowerCase ? (0,util_namespaceObject.addHexPrefix)(to).toLowerCase() : (0,util_namespaceObject.addHexPrefix)(to);
5456
- },
5457
- nonce: nonce => (0,util_namespaceObject.addHexPrefix)(nonce),
5458
- customNonceValue: nonce => (0,util_namespaceObject.addHexPrefix)(nonce),
5459
- value: value => (0,util_namespaceObject.addHexPrefix)(value),
5460
- data: data => (0,util_namespaceObject.addHexPrefix)(data),
5461
- gas: gas => (0,util_namespaceObject.addHexPrefix)(gas),
5462
- gasPrice: gasPrice => (0,util_namespaceObject.addHexPrefix)(gasPrice),
5463
- type: util_namespaceObject.addHexPrefix,
5464
- maxFeePerGas: util_namespaceObject.addHexPrefix,
5465
- maxPriorityFeePerGas: util_namespaceObject.addHexPrefix
5466
- };
5467
-
5468
- /**
5469
- * normalizes txParams
5470
- */
5471
- function normalizeTxParameters(txParameters) {
5472
- let lowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
5473
- // apply only keys in the normalizers
5474
- const normalizedTxParameters = {
5475
- id: txParameters.id || (0,base_controllers_namespaceObject.randomId)(),
5476
- from: txParameters.from
5477
- };
5478
- for (const key in normalizers) {
5479
- const currentKey = key;
5480
- if (txParameters[currentKey])
5481
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
5482
- normalizedTxParameters[currentKey] = normalizers[currentKey](txParameters[currentKey], lowerCase);
5483
- }
5484
- return normalizedTxParameters;
5485
- }
5486
- function transactionMatchesNetwork(transaction, chainId) {
5487
- if (typeof transaction.chainId !== "undefined") {
5488
- return transaction.chainId === chainId;
5489
- }
5490
- return false;
5491
- }
5492
-
5493
- /**
5494
- * Determines if the maxFeePerGas and maxPriorityFeePerGas fields are supplied
5495
- * and valid inputs. This will return false for non hex string inputs.
5496
- * the transaction to check
5497
- * @returns true if transaction uses valid EIP1559 fields
5498
- */
5499
- function isEIP1559Transaction(transaction) {
5500
- var _transaction$transact, _transaction$transact2;
5501
- return (0,util_namespaceObject.isHexString)((0,util_namespaceObject.addHexPrefix)(transaction === null || transaction === void 0 || (_transaction$transact = transaction.transaction) === null || _transaction$transact === void 0 ? void 0 : _transaction$transact.maxFeePerGas)) && (0,util_namespaceObject.isHexString)((0,util_namespaceObject.addHexPrefix)(transaction === null || transaction === void 0 || (_transaction$transact2 = transaction.transaction) === null || _transaction$transact2 === void 0 ? void 0 : _transaction$transact2.maxPriorityFeePerGas));
5502
- }
5503
-
5504
- /**
5505
- * Determine if the maxFeePerGas and maxPriorityFeePerGas fields are not
5506
- * supplied and that the gasPrice field is valid if it is provided. This will
5507
- * return false if gasPrice is a non hex string.
5508
- * transaction -
5509
- * the transaction to check
5510
- * @returns true if transaction uses valid Legacy fields OR lacks
5511
- * EIP1559 fields
5512
- */
5513
- function isLegacyTransaction(transaction) {
5514
- return typeof transaction.transaction.maxFeePerGas === "undefined" && typeof transaction.transaction.maxPriorityFeePerGas === "undefined" && (typeof transaction.transaction.gasPrice === "undefined" || (0,util_namespaceObject.isHexString)((0,util_namespaceObject.addHexPrefix)(transaction.transaction.gasPrice)));
5515
- }
5516
-
5517
- /**
5518
- * Given two fields, ensure that the second field is not included in txParams,
5519
- * and if it is throw an invalidParams error.
5520
- */
5521
- function ensureMutuallyExclusiveFieldsNotProvided(txParams, fieldBeingValidated, mutuallyExclusiveField) {
5522
- if (typeof txParams[mutuallyExclusiveField] !== "undefined") {
5523
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`);
5524
- }
5525
- }
5526
-
5527
- /**
5528
- * Ensures that the provided value for field is a string, throws an
5529
- * invalidParams error if field is not a string.
5530
- */
5531
- function ensureFieldIsString(txParams, field) {
5532
- if (typeof txParams[field] !== "string") {
5533
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction params: ${field} is not a string. got: (${txParams[field]})`);
5534
- }
5535
- }
5536
-
5537
- /**
5538
- * Ensures that the provided txParams has the proper 'type' specified for the
5539
- * given field, if it is provided. If types do not match throws an
5540
- * invalidParams error.
5541
- */
5542
- function ensureProperTransactionEnvelopeTypeProvided(txParams, field) {
5543
- switch (field) {
5544
- case "maxFeePerGas":
5545
- case "maxPriorityFeePerGas":
5546
- if (txParams.type && txParams.type !== TRANSACTION_ENVELOPE_TYPES.FEE_MARKET) {
5547
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${txParams.type}" but ` + `including maxFeePerGas and maxPriorityFeePerGas requires type: "${TRANSACTION_ENVELOPE_TYPES.FEE_MARKET}"`);
5548
- }
5549
- break;
5550
- case "gasPrice":
5551
- default:
5552
- if (txParams.type && txParams.type === TRANSACTION_ENVELOPE_TYPES.FEE_MARKET) {
5553
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction envelope type: specified type "${txParams.type}" but ` + "included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas");
5554
- }
5555
- }
5556
- }
5770
+ const blockGasLimitBn = new external_bn_js_namespaceObject.BN((0,util_namespaceObject.stripHexPrefix)(blockGasLimitHex), 16);
5771
+ const upperGasLimitBn = blockGasLimitBn.muln(0.9);
5772
+ const bufferedGasLimitBn = initialGasLimitBn.muln(multiplier);
5557
5773
 
5558
- /**
5559
- * validates the from field in txParams
5560
- */
5561
- function validateFrom(txParams) {
5562
- if (!(typeof txParams.from === "string")) {
5563
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid "from" address "${txParams.from}": not a string.`);
5774
+ // if initialGasLimit is above blockGasLimit, dont modify it
5775
+ if (initialGasLimitBn.gt(upperGasLimitBn)) return (0,util_namespaceObject.addHexPrefix)(initialGasLimitBn.toString("hex"));
5776
+ // if bufferedGasLimit is below blockGasLimit, use bufferedGasLimit
5777
+ if (bufferedGasLimitBn.lt(upperGasLimitBn)) return (0,util_namespaceObject.addHexPrefix)(bufferedGasLimitBn.toString("hex"));
5778
+ // otherwise use blockGasLimit
5779
+ return (0,util_namespaceObject.addHexPrefix)(upperGasLimitBn.toString("hex"));
5564
5780
  }
5565
- if (!(0,util_namespaceObject.isValidAddress)(txParams.from)) {
5566
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams('Invalid "from" address.');
5781
+
5782
+ /**
5783
+ Estimates the tx's gas usage
5784
+ */
5785
+ async estimateTxGas(txMeta) {
5786
+ const txParams = (0,external_lodash_namespaceObject.cloneDeep)(txMeta.transaction);
5787
+
5788
+ // `eth_estimateGas` can fail if the user has insufficient balance for the
5789
+ // value being sent, or for the gas cost. We don't want to check their
5790
+ // balance here, we just want the gas estimate. The gas price is removed
5791
+ // to skip those balance checks. We check balance elsewhere. We also delete
5792
+ // maxFeePerGas and maxPriorityFeePerGas to support EIP-1559 txs.
5793
+ delete txParams.gasPrice;
5794
+ delete txParams.maxFeePerGas;
5795
+ delete txParams.maxPriorityFeePerGas;
5796
+ return this.provider.request({
5797
+ method: "eth_estimateGas",
5798
+ params: [txParams]
5799
+ });
5567
5800
  }
5568
5801
  }
5802
+ ;// CONCATENATED MODULE: external "fast-json-patch"
5803
+ const external_fast_json_patch_namespaceObject = require("fast-json-patch");
5804
+ var external_fast_json_patch_default = /*#__PURE__*/__webpack_require__.n(external_fast_json_patch_namespaceObject);
5805
+ ;// CONCATENATED MODULE: ./src/Transaction/TransactionStateHistoryHelper.ts
5806
+
5807
+
5569
5808
 
5570
5809
  /**
5571
- * validates the to field in txParams
5572
- */
5573
- function validateRecipient(txParameters) {
5574
- if (txParameters.to === "0x" || txParameters.to === null) {
5575
- if (txParameters.data) {
5576
- delete txParameters.to;
5577
- } else {
5578
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams('Invalid "to" address.');
5810
+ Generates an array of history objects sense the previous state.
5811
+ The object has the keys
5812
+ op (the operation performed),
5813
+ path (the key and if a nested object then each key will be seperated with a `/`)
5814
+ value
5815
+ with the first entry having the note and a timestamp when the change took place
5816
+ */
5817
+ function generateHistoryEntry(previousState, newState, note) {
5818
+ const entry = external_fast_json_patch_default().compare(previousState, newState);
5819
+ // Add a note to the first op, since it breaks if we append it to the entry
5820
+ if (entry[0]) {
5821
+ if (note) {
5822
+ entry[0].note = note;
5579
5823
  }
5580
- } else if (txParameters.to !== undefined && !(0,util_namespaceObject.isValidAddress)(txParameters.to)) {
5581
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams('Invalid "to" address.');
5824
+ entry[0].timestamp = Date.now();
5582
5825
  }
5583
- return txParameters;
5826
+ return entry;
5584
5827
  }
5585
5828
 
5586
5829
  /**
5587
- * Validates the given tx parameters
5588
- * @throws if the tx params contains invalid fields
5589
- */
5590
- function validateTxParameters(txParams) {
5591
- let eip1559Compatibility = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
5592
- if (!txParams || typeof txParams !== "object" || Array.isArray(txParams)) {
5593
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams("Invalid transaction params: must be an object.");
5594
- }
5595
- if (!txParams.to && !txParams.data) {
5596
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams('Invalid transaction params: must specify "data" for contract deployments, or "to" (and optionally "data") for all other types of transactions.');
5597
- }
5598
- if (isEIP1559Transaction({
5599
- transaction: txParams
5600
- }) && !eip1559Compatibility) {
5601
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams("Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559");
5602
- }
5603
- Object.entries(txParams).forEach(_ref => {
5604
- let [key, value] = _ref;
5605
- // validate types
5606
- switch (key) {
5607
- case "from":
5608
- validateFrom(txParams);
5609
- break;
5610
- case "to":
5611
- validateRecipient(txParams);
5612
- break;
5613
- case "gasPrice":
5614
- ensureProperTransactionEnvelopeTypeProvided(txParams, "gasPrice");
5615
- ensureMutuallyExclusiveFieldsNotProvided(txParams, "gasPrice", "maxFeePerGas");
5616
- ensureMutuallyExclusiveFieldsNotProvided(txParams, "gasPrice", "maxPriorityFeePerGas");
5617
- ensureFieldIsString(txParams, "gasPrice");
5618
- break;
5619
- case "maxFeePerGas":
5620
- ensureProperTransactionEnvelopeTypeProvided(txParams, "maxFeePerGas");
5621
- ensureMutuallyExclusiveFieldsNotProvided(txParams, "maxFeePerGas", "gasPrice");
5622
- ensureFieldIsString(txParams, "maxFeePerGas");
5623
- break;
5624
- case "maxPriorityFeePerGas":
5625
- ensureProperTransactionEnvelopeTypeProvided(txParams, "maxPriorityFeePerGas");
5626
- ensureMutuallyExclusiveFieldsNotProvided(txParams, "maxPriorityFeePerGas", "gasPrice");
5627
- ensureFieldIsString(txParams, "maxPriorityFeePerGas");
5628
- break;
5629
- case "value":
5630
- ensureFieldIsString(txParams, "value");
5631
- if (value.toString().includes("-")) {
5632
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction value "${value}": not a positive number.`);
5633
- }
5634
- if (value.toString().includes(".")) {
5635
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction value of "${value}": number must be in wei.`);
5636
- }
5637
- break;
5638
- case "chainId":
5639
- if (typeof value !== "number" && typeof value !== "string") {
5640
- throw rpc_errors_namespaceObject.rpcErrors.invalidParams(`Invalid transaction params: ${key} is not a Number or hex string. got: (${value})`);
5641
- }
5642
- break;
5643
- default:
5644
- ensureFieldIsString(txParams, key);
5645
- }
5646
- });
5830
+ Recovers previous txMeta state obj
5831
+ */
5832
+ function replayHistory(_shortHistory) {
5833
+ const shortHistory = (0,external_lodash_namespaceObject.cloneDeep)(_shortHistory);
5834
+ return shortHistory.reduce((val, entry) => external_fast_json_patch_default().applyPatch(val, entry).newDocument);
5647
5835
  }
5648
- function normalizeAndValidateTxParams(txParams) {
5649
- let lowerCase = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
5650
- const normalizedTxParams = normalizeTxParameters(txParams, lowerCase);
5651
- validateTxParameters(normalizedTxParams);
5652
- return normalizedTxParams;
5836
+ function snapshotFromTxMeta(txMeta) {
5837
+ const shallow = objectSpread2_default()({}, txMeta);
5838
+ delete shallow.history;
5839
+ return (0,external_lodash_namespaceObject.cloneDeep)(shallow);
5653
5840
  }
5654
5841
 
5655
- /**
5656
- * @returns an array of states that can be considered final
5657
- */
5658
- function getFinalStates() {
5659
- return [base_controllers_namespaceObject.TransactionStatus.rejected,
5660
- // the user has responded no!
5661
- base_controllers_namespaceObject.TransactionStatus.confirmed,
5662
- // the tx has been included in a block.
5663
- base_controllers_namespaceObject.TransactionStatus.failed,
5664
- // the tx failed for some reason, included on tx data.
5665
- base_controllers_namespaceObject.TransactionStatus.dropped // the tx nonce was already used
5666
- ];
5667
- }
5668
- function parseStandardTokenTransactionData(data) {
5669
- try {
5670
- const txDesc = erc20Interface.parseTransaction({
5671
- data
5672
- });
5673
- if (txDesc) return {
5674
- name: txDesc.name,
5675
- methodParams: txDesc.args.toArray(),
5676
- type: CONTRACT_TYPE_ERC20
5677
- };
5678
- } catch {
5679
- // ignore and next try to parse with erc721 ABI
5680
- }
5681
- try {
5682
- const txDesc = erc721Interface.parseTransaction({
5683
- data
5684
- });
5685
- if (txDesc) return {
5686
- name: txDesc.name,
5687
- methodParams: txDesc.args.toArray(),
5688
- type: CONTRACT_TYPE_ERC721
5689
- };
5690
- } catch {
5691
- // ignore and next try to parse with erc1155 ABI
5692
- }
5693
- try {
5694
- const txDesc = erc1155Interface.parseTransaction({
5695
- data
5696
- });
5697
- if (txDesc) return {
5698
- name: txDesc.name,
5699
- methodParams: txDesc.args.toArray(),
5700
- type: CONTRACT_TYPE_ERC1155
5701
- };
5702
- } catch {
5703
- // ignore and return undefined
5704
- }
5705
- return undefined;
5706
- }
5707
- const readAddressAsContract = async (provider, address) => {
5708
- let contractCode;
5709
- try {
5710
- contractCode = await provider.request({
5711
- method: METHOD_TYPES.ETH_GET_CODE,
5712
- params: [address, "latest"]
5713
- });
5714
- } catch (e) {
5715
- contractCode = null;
5716
- }
5717
- const isContractAddress = contractCode ? contractCode !== "0x" && contractCode !== "0x0" : false;
5718
- return {
5719
- contractCode,
5720
- isContractAddress
5721
- };
5722
- };
5723
- async function determineTransactionType(txParams, provider) {
5724
- const {
5725
- data,
5726
- to
5727
- } = txParams;
5728
- let name = "";
5729
- let methodParams = [];
5730
- let type = "";
5731
- try {
5732
- ({
5733
- name,
5734
- methodParams,
5735
- type
5736
- } = data && parseStandardTokenTransactionData(data) || {});
5737
- } catch (error) {
5738
- external_loglevel_default().debug("Failed to parse transaction data", error);
5739
- }
5740
- let result;
5741
- let contractCode = "";
5742
- if (data && !to) {
5743
- result = base_controllers_namespaceObject.TRANSACTION_TYPES.DEPLOY_CONTRACT;
5744
- } else {
5745
- const {
5746
- contractCode: resultCode,
5747
- isContractAddress
5748
- } = await readAddressAsContract(provider, to);
5749
- contractCode = resultCode;
5750
- if (isContractAddress) {
5751
- const valueExists = txParams.value && Number(txParams.value) !== 0;
5752
- const tokenMethodName = [base_controllers_namespaceObject.TRANSACTION_TYPES.TOKEN_METHOD_APPROVE, base_controllers_namespaceObject.TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER, base_controllers_namespaceObject.TRANSACTION_TYPES.TOKEN_METHOD_TRANSFER_FROM, base_controllers_namespaceObject.TRANSACTION_TYPES.COLLECTIBLE_METHOD_SAFE_TRANSFER_FROM, base_controllers_namespaceObject.TRANSACTION_TYPES.SET_APPROVAL_FOR_ALL].find(x => {
5753
- var _name;
5754
- return x.toLowerCase() === ((_name = name) === null || _name === void 0 ? void 0 : _name.toLowerCase());
5755
- });
5756
- result = data && tokenMethodName && !valueExists ? tokenMethodName : base_controllers_namespaceObject.TRANSACTION_TYPES.CONTRACT_INTERACTION;
5757
- } else {
5758
- result = base_controllers_namespaceObject.TRANSACTION_TYPES.SENT_ETHER;
5759
- }
5760
- }
5761
- return {
5762
- type: type || CONTRACT_TYPE_ETH,
5763
- category: result,
5764
- methodParams,
5765
- getCodeResponse: contractCode
5766
- };
5767
- }
5768
5842
  ;// CONCATENATED MODULE: ./src/Transaction/TransactionStateManager.ts
5769
5843
 
5770
5844
 
@@ -6603,6 +6677,7 @@ class TransactionController extends TransactionStateManager {
6603
6677
 
6604
6678
 
6605
6679
 
6680
+
6606
6681
 
6607
6682
 
6608
6683
  /**