@metamask/transaction-controller 23.1.0 → 25.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +134 -1
- package/dist/TransactionController.js +38 -1816
- package/dist/TransactionController.js.map +1 -1
- package/dist/TransactionController.mjs +39 -0
- package/dist/TransactionController.mjs.map +1 -0
- package/dist/chunk-2K7J3EY3.mjs +170 -0
- package/dist/chunk-2K7J3EY3.mjs.map +1 -0
- package/dist/chunk-5XBULBP2.js +399 -0
- package/dist/chunk-5XBULBP2.js.map +1 -0
- package/dist/chunk-6MYNWYJK.mjs +158 -0
- package/dist/chunk-6MYNWYJK.mjs.map +1 -0
- package/dist/chunk-7APMBUKB.js +158 -0
- package/dist/chunk-7APMBUKB.js.map +1 -0
- package/dist/chunk-7LXE4KHV.js +40 -0
- package/dist/chunk-7LXE4KHV.js.map +1 -0
- package/dist/chunk-7MZ57ILQ.mjs +62 -0
- package/dist/chunk-7MZ57ILQ.mjs.map +1 -0
- package/dist/chunk-BJEESIBE.js +2313 -0
- package/dist/chunk-BJEESIBE.js.map +1 -0
- package/dist/chunk-C67QD5PV.mjs +320 -0
- package/dist/chunk-C67QD5PV.mjs.map +1 -0
- package/dist/chunk-DE3MZYVY.mjs +2313 -0
- package/dist/chunk-DE3MZYVY.mjs.map +1 -0
- package/dist/chunk-DEKM6PVG.mjs +46 -0
- package/dist/chunk-DEKM6PVG.mjs.map +1 -0
- package/dist/chunk-DQP6X25N.mjs +208 -0
- package/dist/chunk-DQP6X25N.mjs.map +1 -0
- package/dist/chunk-DTDTOMTB.js +238 -0
- package/dist/chunk-DTDTOMTB.js.map +1 -0
- package/dist/chunk-DTEDYRTL.js +242 -0
- package/dist/chunk-DTEDYRTL.js.map +1 -0
- package/dist/chunk-EQ3RRHB7.mjs +211 -0
- package/dist/chunk-EQ3RRHB7.mjs.map +1 -0
- package/dist/chunk-FDJPXQTF.js +46 -0
- package/dist/chunk-FDJPXQTF.js.map +1 -0
- package/dist/chunk-FRKQ3Z2L.mjs +40 -0
- package/dist/chunk-FRKQ3Z2L.mjs.map +1 -0
- package/dist/chunk-FS7FRO7B.mjs +90 -0
- package/dist/chunk-FS7FRO7B.mjs.map +1 -0
- package/dist/chunk-GKTIFXPN.js +170 -0
- package/dist/chunk-GKTIFXPN.js.map +1 -0
- package/dist/chunk-H4M66BA3.js +62 -0
- package/dist/chunk-H4M66BA3.js.map +1 -0
- package/dist/chunk-HPNXIKFY.js +76 -0
- package/dist/chunk-HPNXIKFY.js.map +1 -0
- package/dist/chunk-HS277C77.js +75 -0
- package/dist/chunk-HS277C77.js.map +1 -0
- package/dist/chunk-I5YZ7QUK.js +121 -0
- package/dist/chunk-I5YZ7QUK.js.map +1 -0
- package/dist/chunk-IC233ZQS.js +211 -0
- package/dist/chunk-IC233ZQS.js.map +1 -0
- package/dist/chunk-IUBAETUH.js +137 -0
- package/dist/chunk-IUBAETUH.js.map +1 -0
- package/dist/chunk-J56A7UCK.mjs +123 -0
- package/dist/chunk-J56A7UCK.mjs.map +1 -0
- package/dist/chunk-JR6HDRNV.mjs +242 -0
- package/dist/chunk-JR6HDRNV.mjs.map +1 -0
- package/dist/chunk-JRBREX22.mjs +75 -0
- package/dist/chunk-JRBREX22.mjs.map +1 -0
- package/dist/chunk-JRQHIBG5.mjs +399 -0
- package/dist/chunk-JRQHIBG5.mjs.map +1 -0
- package/dist/chunk-LM4NUNMT.mjs +76 -0
- package/dist/chunk-LM4NUNMT.mjs.map +1 -0
- package/dist/chunk-M7455RU7.js +320 -0
- package/dist/chunk-M7455RU7.js.map +1 -0
- package/dist/chunk-MHM5LRRF.mjs +122 -0
- package/dist/chunk-MHM5LRRF.mjs.map +1 -0
- package/dist/chunk-NHRBO3LU.mjs +50 -0
- package/dist/chunk-NHRBO3LU.mjs.map +1 -0
- package/dist/chunk-NM6OYEPP.mjs +182 -0
- package/dist/chunk-NM6OYEPP.mjs.map +1 -0
- package/dist/chunk-NUOBUW7C.js +85 -0
- package/dist/chunk-NUOBUW7C.js.map +1 -0
- package/dist/chunk-QP75SWIQ.js +53 -0
- package/dist/chunk-QP75SWIQ.js.map +1 -0
- package/dist/chunk-RI6MVJJN.js +122 -0
- package/dist/chunk-RI6MVJJN.js.map +1 -0
- package/dist/chunk-S6VGOPUY.js +14 -0
- package/dist/chunk-S6VGOPUY.js.map +1 -0
- package/dist/chunk-UGFBA4GV.js +123 -0
- package/dist/chunk-UGFBA4GV.js.map +1 -0
- package/dist/chunk-UKYY2RVS.mjs +137 -0
- package/dist/chunk-UKYY2RVS.mjs.map +1 -0
- package/dist/chunk-UM4ORJ5B.mjs +121 -0
- package/dist/chunk-UM4ORJ5B.mjs.map +1 -0
- package/dist/chunk-UQQWZT6C.mjs +14 -0
- package/dist/chunk-UQQWZT6C.mjs.map +1 -0
- package/dist/chunk-VH47Q6TS.js +182 -0
- package/dist/chunk-VH47Q6TS.js.map +1 -0
- package/dist/chunk-XGRAHX6T.mjs +53 -0
- package/dist/chunk-XGRAHX6T.mjs.map +1 -0
- package/dist/chunk-XUI43LEZ.mjs +30 -0
- package/dist/chunk-XUI43LEZ.mjs.map +1 -0
- package/dist/chunk-Y734U4V6.mjs +85 -0
- package/dist/chunk-Y734U4V6.mjs.map +1 -0
- package/dist/chunk-Y7ENNK7L.mjs +238 -0
- package/dist/chunk-Y7ENNK7L.mjs.map +1 -0
- package/dist/chunk-Z4BLTVTB.js +30 -0
- package/dist/chunk-Z4BLTVTB.js.map +1 -0
- package/dist/chunk-ZCQRDZ36.js +208 -0
- package/dist/chunk-ZCQRDZ36.js.map +1 -0
- package/dist/chunk-ZJLZSFOZ.js +90 -0
- package/dist/chunk-ZJLZSFOZ.js.map +1 -0
- package/dist/chunk-ZNZEJDOE.js +50 -0
- package/dist/chunk-ZNZEJDOE.js.map +1 -0
- package/dist/constants.js +15 -110
- package/dist/constants.js.map +1 -1
- package/dist/constants.mjs +16 -0
- package/dist/constants.mjs.map +1 -0
- package/dist/gas-flows/DefaultGasFeeFlow.js +14 -77
- package/dist/gas-flows/DefaultGasFeeFlow.js.map +1 -1
- package/dist/gas-flows/DefaultGasFeeFlow.mjs +15 -0
- package/dist/gas-flows/DefaultGasFeeFlow.mjs.map +1 -0
- package/dist/gas-flows/LineaGasFeeFlow.js +15 -110
- package/dist/gas-flows/LineaGasFeeFlow.js.map +1 -1
- package/dist/gas-flows/LineaGasFeeFlow.mjs +16 -0
- package/dist/gas-flows/LineaGasFeeFlow.mjs.map +1 -0
- package/dist/helpers/EtherscanRemoteTransactionSource.js +11 -145
- package/dist/helpers/EtherscanRemoteTransactionSource.js.map +1 -1
- package/dist/helpers/EtherscanRemoteTransactionSource.mjs +12 -0
- package/dist/helpers/EtherscanRemoteTransactionSource.mjs.map +1 -0
- package/dist/helpers/GasFeePoller.js +10 -143
- package/dist/helpers/GasFeePoller.js.map +1 -1
- package/dist/helpers/GasFeePoller.mjs +11 -0
- package/dist/helpers/GasFeePoller.mjs.map +1 -0
- package/dist/helpers/IncomingTransactionHelper.js +8 -205
- package/dist/helpers/IncomingTransactionHelper.js.map +1 -1
- package/dist/helpers/IncomingTransactionHelper.mjs +9 -0
- package/dist/helpers/IncomingTransactionHelper.mjs.map +1 -0
- package/dist/helpers/MultichainTrackingHelper.js +12 -291
- package/dist/helpers/MultichainTrackingHelper.js.map +1 -1
- package/dist/helpers/MultichainTrackingHelper.mjs +13 -0
- package/dist/helpers/MultichainTrackingHelper.mjs.map +1 -0
- package/dist/helpers/PendingTransactionTracker.js +9 -360
- package/dist/helpers/PendingTransactionTracker.js.map +1 -1
- package/dist/helpers/PendingTransactionTracker.mjs +10 -0
- package/dist/helpers/PendingTransactionTracker.mjs.map +1 -0
- package/dist/index.js +56 -25
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +57 -0
- package/dist/index.mjs.map +1 -0
- package/dist/logger.js +11 -8
- package/dist/logger.js.map +1 -1
- package/dist/logger.mjs +12 -0
- package/dist/logger.mjs.map +1 -0
- package/dist/tsconfig.build.tsbuildinfo +1 -0
- package/dist/{TransactionController.d.ts → types/TransactionController.d.ts} +235 -46
- package/dist/types/TransactionController.d.ts.map +1 -0
- package/dist/{constants.d.ts → types/constants.d.ts} +8 -3
- package/dist/types/constants.d.ts.map +1 -0
- package/dist/types/gas-flows/DefaultGasFeeFlow.d.ts.map +1 -0
- package/dist/types/gas-flows/LineaGasFeeFlow.d.ts.map +1 -0
- package/dist/types/helpers/EtherscanRemoteTransactionSource.d.ts.map +1 -0
- package/dist/types/helpers/GasFeePoller.d.ts.map +1 -0
- package/dist/types/helpers/IncomingTransactionHelper.d.ts.map +1 -0
- package/dist/types/helpers/MultichainTrackingHelper.d.ts.map +1 -0
- package/dist/types/helpers/PendingTransactionTracker.d.ts.map +1 -0
- package/dist/types/index.d.ts +9 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/logger.d.ts.map +1 -0
- package/dist/{types.d.ts → types/types.d.ts} +63 -65
- package/dist/types/types.d.ts.map +1 -0
- package/dist/types/utils/etherscan.d.ts.map +1 -0
- package/dist/types/utils/external-transactions.d.ts.map +1 -0
- package/dist/types/utils/gas-fees.d.ts.map +1 -0
- package/dist/types/utils/gas-flow.d.ts.map +1 -0
- package/dist/types/utils/gas.d.ts.map +1 -0
- package/dist/types/utils/history.d.ts +20 -0
- package/dist/types/utils/history.d.ts.map +1 -0
- package/dist/types/utils/nonce.d.ts.map +1 -0
- package/dist/types/utils/simulation-api.d.ts +99 -0
- package/dist/types/utils/simulation-api.d.ts.map +1 -0
- package/dist/types/utils/simulation.d.ts +21 -0
- package/dist/types/utils/simulation.d.ts.map +1 -0
- package/dist/{utils → types/utils}/swaps.d.ts +8 -5
- package/dist/types/utils/swaps.d.ts.map +1 -0
- package/dist/types/utils/transaction-type.d.ts.map +1 -0
- package/dist/{utils → types/utils}/utils.d.ts +9 -1
- package/dist/types/utils/utils.d.ts.map +1 -0
- package/dist/types/utils/validation.d.ts.map +1 -0
- package/dist/types.js +19 -170
- package/dist/types.js.map +1 -1
- package/dist/types.mjs +20 -0
- package/dist/types.mjs.map +1 -0
- package/dist/utils/etherscan.js +13 -118
- package/dist/utils/etherscan.js.map +1 -1
- package/dist/utils/etherscan.mjs +14 -0
- package/dist/utils/etherscan.mjs.map +1 -0
- package/dist/utils/external-transactions.js +8 -35
- package/dist/utils/external-transactions.js.map +1 -1
- package/dist/utils/external-transactions.mjs +9 -0
- package/dist/utils/external-transactions.mjs.map +1 -0
- package/dist/utils/gas-fees.js +15 -200
- package/dist/utils/gas-fees.js.map +1 -1
- package/dist/utils/gas-fees.mjs +16 -0
- package/dist/utils/gas-fees.mjs.map +1 -0
- package/dist/utils/gas-flow.js +10 -52
- package/dist/utils/gas-flow.js.map +1 -1
- package/dist/utils/gas-flow.mjs +11 -0
- package/dist/utils/gas-flow.mjs.map +1 -0
- package/dist/utils/gas.js +19 -133
- package/dist/utils/gas.js.map +1 -1
- package/dist/utils/gas.mjs +20 -0
- package/dist/utils/gas.mjs.map +1 -0
- package/dist/utils/history.js +9 -83
- package/dist/utils/history.js.map +1 -1
- package/dist/utils/history.mjs +10 -0
- package/dist/utils/history.mjs.map +1 -0
- package/dist/utils/nonce.js +10 -76
- package/dist/utils/nonce.js.map +1 -1
- package/dist/utils/nonce.mjs +11 -0
- package/dist/utils/nonce.mjs.map +1 -0
- package/dist/utils/simulation-api.js +10 -0
- package/dist/utils/simulation-api.js.map +1 -0
- package/dist/utils/simulation-api.mjs +10 -0
- package/dist/utils/simulation-api.mjs.map +1 -0
- package/dist/utils/simulation.js +12 -0
- package/dist/utils/simulation.js.map +1 -0
- package/dist/utils/simulation.mjs +12 -0
- package/dist/utils/simulation.mjs.map +1 -0
- package/dist/utils/swaps.js +23 -256
- package/dist/utils/swaps.js.map +1 -1
- package/dist/utils/swaps.mjs +24 -0
- package/dist/utils/swaps.mjs.map +1 -0
- package/dist/utils/transaction-type.js +10 -120
- package/dist/utils/transaction-type.js.map +1 -1
- package/dist/utils/transaction-type.mjs +11 -0
- package/dist/utils/transaction-type.mjs.map +1 -0
- package/dist/utils/utils.js +32 -146
- package/dist/utils/utils.js.map +1 -1
- package/dist/utils/utils.mjs +33 -0
- package/dist/utils/utils.mjs.map +1 -0
- package/dist/utils/validation.js +11 -258
- package/dist/utils/validation.js.map +1 -1
- package/dist/utils/validation.mjs +12 -0
- package/dist/utils/validation.mjs.map +1 -0
- package/package.json +21 -9
- package/dist/TransactionController.d.ts.map +0 -1
- package/dist/constants.d.ts.map +0 -1
- package/dist/gas-flows/DefaultGasFeeFlow.d.ts.map +0 -1
- package/dist/gas-flows/LineaGasFeeFlow.d.ts.map +0 -1
- package/dist/helpers/EtherscanRemoteTransactionSource.d.ts.map +0 -1
- package/dist/helpers/GasFeePoller.d.ts.map +0 -1
- package/dist/helpers/IncomingTransactionHelper.d.ts.map +0 -1
- package/dist/helpers/MultichainTrackingHelper.d.ts.map +0 -1
- package/dist/helpers/PendingTransactionTracker.d.ts.map +0 -1
- package/dist/index.d.ts +0 -7
- package/dist/index.d.ts.map +0 -1
- package/dist/logger.d.ts.map +0 -1
- package/dist/types.d.ts.map +0 -1
- package/dist/utils/etherscan.d.ts.map +0 -1
- package/dist/utils/external-transactions.d.ts.map +0 -1
- package/dist/utils/gas-fees.d.ts.map +0 -1
- package/dist/utils/gas-flow.d.ts.map +0 -1
- package/dist/utils/gas.d.ts.map +0 -1
- package/dist/utils/history.d.ts +0 -15
- package/dist/utils/history.d.ts.map +0 -1
- package/dist/utils/nonce.d.ts.map +0 -1
- package/dist/utils/swaps.d.ts.map +0 -1
- package/dist/utils/transaction-type.d.ts.map +0 -1
- package/dist/utils/utils.d.ts.map +0 -1
- package/dist/utils/validation.d.ts.map +0 -1
- /package/dist/{gas-flows → types/gas-flows}/DefaultGasFeeFlow.d.ts +0 -0
- /package/dist/{gas-flows → types/gas-flows}/LineaGasFeeFlow.d.ts +0 -0
- /package/dist/{helpers → types/helpers}/EtherscanRemoteTransactionSource.d.ts +0 -0
- /package/dist/{helpers → types/helpers}/GasFeePoller.d.ts +0 -0
- /package/dist/{helpers → types/helpers}/IncomingTransactionHelper.d.ts +0 -0
- /package/dist/{helpers → types/helpers}/MultichainTrackingHelper.d.ts +0 -0
- /package/dist/{helpers → types/helpers}/PendingTransactionTracker.d.ts +0 -0
- /package/dist/{logger.d.ts → types/logger.d.ts} +0 -0
- /package/dist/{utils → types/utils}/etherscan.d.ts +0 -0
- /package/dist/{utils → types/utils}/external-transactions.d.ts +0 -0
- /package/dist/{utils → types/utils}/gas-fees.d.ts +0 -0
- /package/dist/{utils → types/utils}/gas-flow.d.ts +0 -0
- /package/dist/{utils → types/utils}/gas.d.ts +0 -0
- /package/dist/{utils → types/utils}/nonce.d.ts +0 -0
- /package/dist/{utils → types/utils}/transaction-type.d.ts +0 -0
- /package/dist/{utils → types/utils}/validation.d.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/utils.ts"],"names":[],"mappings":";AAAA,SAAS,2BAA2B;AACpC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAcA,IAAM,qBAAqB;AAIlC,IAAM,cAA2D;AAAA,EAC/D,MAAM,CAAC,SAAiB,MAAM,mBAAmB,IAAI,CAAC;AAAA,EACtD,MAAM,CAAC,SAAiB,MAAM,IAAI,EAAE,YAAY;AAAA,EAChD,KAAK,CAAC,QAAgB,MAAM,GAAG;AAAA,EAC/B,UAAU,CAAC,QAAgB,MAAM,GAAG;AAAA,EACpC,UAAU,CAAC,aAAqB,MAAM,QAAQ;AAAA,EAC9C,OAAO,CAAC,UAAkB,MAAM,KAAK;AAAA,EACrC,IAAI,CAAC,OAAe,MAAM,EAAE,EAAE,YAAY;AAAA,EAC1C,OAAO,CAAC,UAAkB,MAAM,KAAK;AAAA,EACrC,cAAc,CAAC,iBAAyB,MAAM,YAAY;AAAA,EAC1D,sBAAsB,CAAC,yBACrB,MAAM,oBAAoB;AAAA,EAC5B,kBAAkB,CAAC,yBACjB,MAAM,oBAAoB;AAAA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AI,mBAAmB,YAAY;AACjC,WAAO;AAAA,EACT;AACA,QAAM,WAAW,uBAAuB,eAAe,6CAA6C,UAAU;AAC9G,QAAM,IAAI,MAAM,QAAQ;AAC1B;AASO,SAAS,gCACd,iBACA,QACA;AACA,MAAI,iBAAiB,0CAAyC;AAC5D,UAAM,IAAI;AAAA,MACR,yCAAyC,MAAM;AAAA,2BAC1B,iBAAiB,MAAM;AAAA,IAC9C;AAAA,EACF;AACF;AAQO,SAAS,iBACd,OACkB;AAClB,SAAO;AAAA,IACL,MAAM,MAAM;AAAA,IACZ,SAAS,MAAM;AAAA,IACf,OAAO,MAAM;AAAA,IACb,MAAM,MAAM;AAAA,IACZ,KAAK,iBAAiB,MAAM,KAAK,IAAI,MAAM,QAAQ;AAAA,EACrD;AACF;AAQO,SAAS,sBACd,cACwC;AAGxC,QAAM,YAAY,CAAC,UACjB,OAAO,UAAU,WAAW,MAAM,KAAK,IAAI;AAE7C,MAAI,cAAc,cAAc;AAC9B,WAAO;AAAA,MACL,UAAU,UAAU,aAAa,QAAQ;AAAA,IAC3C;AAAA,EACF;AAEA,SAAO;AAAA,IACL,cAAc,UAAU,aAAa,YAAY;AAAA,IACjD,sBAAsB,UAAU,aAAa,oBAAoB;AAAA,EACnE;AACF;AAQA,SAAS,iBAAiB,OAA+B;AACvD,MAAI;AACF,SAAK,MAAM,KAAK,UAAU,KAAK,CAAC;AAChC,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AASO,SAAS,mBAAmB,KAAa;AAC9C,QAAM,SAAS,IAAI,YAAY,EAAE,WAAW,IAAI,IAAI,IAAI,MAAM,GAAG,CAAC,IAAI;AACtE,QAAM,OAAO,SAAS,IAAI,MAAM,CAAC,IAAI;AACrC,QAAM,WAAW,KAAK,SAAS,MAAM,IAAI,OAAO,IAAI,IAAI;AAExD,SAAO,SAAS;AAClB","sourcesContent":["import { convertHexToDecimal } from '@metamask/controller-utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\n\nimport type {\n GasPriceValue,\n FeeMarketEIP1559Values,\n} from '../TransactionController';\nimport { TransactionStatus } from '../types';\nimport type {\n TransactionParams,\n TransactionMeta,\n TransactionError,\n} from '../types';\n\nexport const ESTIMATE_GAS_ERROR = 'eth_estimateGas rpc method error';\n\n// TODO: Replace `any` with type\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst NORMALIZERS: { [param in keyof TransactionParams]: any } = {\n data: (data: string) => add0x(padHexToEvenLength(data)),\n from: (from: string) => add0x(from).toLowerCase(),\n gas: (gas: string) => add0x(gas),\n gasLimit: (gas: string) => add0x(gas),\n gasPrice: (gasPrice: string) => add0x(gasPrice),\n nonce: (nonce: string) => add0x(nonce),\n to: (to: string) => add0x(to).toLowerCase(),\n value: (value: string) => add0x(value),\n maxFeePerGas: (maxFeePerGas: string) => add0x(maxFeePerGas),\n maxPriorityFeePerGas: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n estimatedBaseFee: (maxPriorityFeePerGas: string) =>\n add0x(maxPriorityFeePerGas),\n type: (type: string) => add0x(type),\n};\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param txParams - The transaction params to normalize.\n * @returns Normalized transaction params.\n */\nexport function normalizeTransactionParams(txParams: TransactionParams) {\n const normalizedTxParams: TransactionParams = { from: '' };\n\n for (const key of getKnownPropertyNames(NORMALIZERS)) {\n if (txParams[key]) {\n normalizedTxParams[key] = NORMALIZERS[key](txParams[key]);\n }\n }\n\n if (!normalizedTxParams.value) {\n normalizedTxParams.value = '0x0';\n }\n\n return normalizedTxParams;\n}\n\n/**\n * Checks if a transaction is EIP-1559 by checking for the existence of\n * maxFeePerGas and maxPriorityFeePerGas within its parameters.\n *\n * @param txParams - Transaction params object to add.\n * @returns Boolean that is true if the transaction is EIP-1559 (has maxFeePerGas and maxPriorityFeePerGas), otherwise returns false.\n */\nexport function isEIP1559Transaction(txParams: TransactionParams): boolean {\n const hasOwnProp = (obj: TransactionParams, key: string) =>\n Object.prototype.hasOwnProperty.call(obj, key);\n return (\n hasOwnProp(txParams, 'maxFeePerGas') &&\n hasOwnProp(txParams, 'maxPriorityFeePerGas')\n );\n}\n\nexport const validateGasValues = (\n gasValues: GasPriceValue | FeeMarketEIP1559Values,\n) => {\n Object.keys(gasValues).forEach((key) => {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const value = (gasValues as any)[key];\n if (typeof value !== 'string' || !isStrictHexString(value)) {\n throw new TypeError(\n `expected hex string for ${key} but received: ${value}`,\n );\n }\n });\n};\n\nexport const isFeeMarketEIP1559Values = (\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): gasValues is FeeMarketEIP1559Values =>\n (gasValues as FeeMarketEIP1559Values)?.maxFeePerGas !== undefined ||\n (gasValues as FeeMarketEIP1559Values)?.maxPriorityFeePerGas !== undefined;\n\nexport const isGasPriceValue = (\n gasValues?: GasPriceValue | FeeMarketEIP1559Values,\n): gasValues is GasPriceValue =>\n (gasValues as GasPriceValue)?.gasPrice !== undefined;\n\nexport const getIncreasedPriceHex = (value: number, rate: number): string =>\n add0x(`${parseInt(`${value * rate}`, 10).toString(16)}`);\n\nexport const getIncreasedPriceFromExisting = (\n value: string | undefined,\n rate: number,\n): string => {\n return getIncreasedPriceHex(convertHexToDecimal(value), rate);\n};\n\n/**\n * Validates that the proposed value is greater than or equal to the minimum value.\n *\n * @param proposed - The proposed value.\n * @param min - The minimum value.\n * @returns The proposed value.\n * @throws Will throw if the proposed value is too low.\n */\nexport function validateMinimumIncrease(proposed: string, min: string) {\n const proposedDecimal = convertHexToDecimal(proposed);\n const minDecimal = convertHexToDecimal(min);\n if (proposedDecimal >= minDecimal) {\n return proposed;\n }\n const errorMsg = `The proposed value: ${proposedDecimal} should meet or exceed the minimum value: ${minDecimal}`;\n throw new Error(errorMsg);\n}\n\n/**\n * Validates that a transaction is unapproved.\n * Throws if the transaction is not unapproved.\n *\n * @param transactionMeta - The transaction metadata to check.\n * @param fnName - The name of the function calling this helper.\n */\nexport function validateIfTransactionUnapproved(\n transactionMeta: TransactionMeta | undefined,\n fnName: string,\n) {\n if (transactionMeta?.status !== TransactionStatus.unapproved) {\n throw new Error(\n `TransactionsController: Can only call ${fnName} on an unapproved transaction.\n Current tx status: ${transactionMeta?.status}`,\n );\n }\n}\n\n/**\n * Normalizes properties on transaction params.\n *\n * @param error - The error to be normalize.\n * @returns Normalized transaction error.\n */\nexport function normalizeTxError(\n error: Error & { code?: string; value?: unknown },\n): TransactionError {\n return {\n name: error.name,\n message: error.message,\n stack: error.stack,\n code: error.code,\n rpc: isJsonCompatible(error.value) ? error.value : undefined,\n };\n}\n\n/**\n * Normalize an object containing gas fee values.\n *\n * @param gasFeeValues - An object containing gas fee values.\n * @returns An object containing normalized gas fee values.\n */\nexport function normalizeGasFeeValues(\n gasFeeValues: GasPriceValue | FeeMarketEIP1559Values,\n): GasPriceValue | FeeMarketEIP1559Values {\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const normalize = (value: any) =>\n typeof value === 'string' ? add0x(value) : value;\n\n if ('gasPrice' in gasFeeValues) {\n return {\n gasPrice: normalize(gasFeeValues.gasPrice),\n };\n }\n\n return {\n maxFeePerGas: normalize(gasFeeValues.maxFeePerGas),\n maxPriorityFeePerGas: normalize(gasFeeValues.maxPriorityFeePerGas),\n };\n}\n\n/**\n * Determines whether the given value can be encoded as JSON.\n *\n * @param value - The value.\n * @returns True if the value is JSON-encodable, false if not.\n */\nfunction isJsonCompatible(value: unknown): value is Json {\n try {\n JSON.parse(JSON.stringify(value));\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Ensure a hex string is of even length by adding a leading 0 if necessary.\n * Any existing `0x` prefix is preserved but is not added if missing.\n *\n * @param hex - The hex string to ensure is even.\n * @returns The hex string with an even length.\n */\nexport function padHexToEvenLength(hex: string) {\n const prefix = hex.toLowerCase().startsWith('0x') ? hex.slice(0, 2) : '';\n const data = prefix ? hex.slice(2) : hex;\n const evenData = data.length % 2 === 0 ? data : `0${data}`;\n\n return prefix + evenData;\n}\n"]}
|
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
import {
|
|
2
|
+
GAS_BUFFER_CHAIN_OVERRIDES
|
|
3
|
+
} from "./chunk-MHM5LRRF.mjs";
|
|
4
|
+
import {
|
|
5
|
+
projectLogger
|
|
6
|
+
} from "./chunk-UQQWZT6C.mjs";
|
|
7
|
+
|
|
8
|
+
// src/utils/gas.ts
|
|
9
|
+
import {
|
|
10
|
+
BNToHex,
|
|
11
|
+
fractionBN,
|
|
12
|
+
hexToBN,
|
|
13
|
+
query
|
|
14
|
+
} from "@metamask/controller-utils";
|
|
15
|
+
import { add0x, createModuleLogger } from "@metamask/utils";
|
|
16
|
+
var log = createModuleLogger(projectLogger, "gas");
|
|
17
|
+
var FIXED_GAS = "0x5208";
|
|
18
|
+
var DEFAULT_GAS_MULTIPLIER = 1.5;
|
|
19
|
+
async function updateGas(request) {
|
|
20
|
+
const { txMeta } = request;
|
|
21
|
+
const initialParams = { ...txMeta.txParams };
|
|
22
|
+
const [gas, simulationFails] = await getGas(request);
|
|
23
|
+
txMeta.txParams.gas = gas;
|
|
24
|
+
txMeta.simulationFails = simulationFails;
|
|
25
|
+
if (!initialParams.gas) {
|
|
26
|
+
txMeta.originalGasEstimate = txMeta.txParams.gas;
|
|
27
|
+
}
|
|
28
|
+
if (!txMeta.defaultGasEstimates) {
|
|
29
|
+
txMeta.defaultGasEstimates = {};
|
|
30
|
+
}
|
|
31
|
+
txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;
|
|
32
|
+
}
|
|
33
|
+
async function estimateGas(txParams, ethQuery) {
|
|
34
|
+
const request = { ...txParams };
|
|
35
|
+
const { data, value } = request;
|
|
36
|
+
const { gasLimit: gasLimitHex, number: blockNumber } = await getLatestBlock(
|
|
37
|
+
ethQuery
|
|
38
|
+
);
|
|
39
|
+
const gasLimitBN = hexToBN(gasLimitHex);
|
|
40
|
+
request.data = data ? add0x(data) : data;
|
|
41
|
+
request.gas = BNToHex(fractionBN(gasLimitBN, 19, 20));
|
|
42
|
+
request.value = value || "0x0";
|
|
43
|
+
let estimatedGas = request.gas;
|
|
44
|
+
let simulationFails;
|
|
45
|
+
try {
|
|
46
|
+
estimatedGas = await query(ethQuery, "estimateGas", [request]);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
simulationFails = {
|
|
49
|
+
reason: error.message,
|
|
50
|
+
errorKey: error.errorKey,
|
|
51
|
+
debug: {
|
|
52
|
+
blockNumber,
|
|
53
|
+
blockGasLimit: gasLimitHex
|
|
54
|
+
}
|
|
55
|
+
};
|
|
56
|
+
log("Estimation failed", { ...simulationFails, fallback: estimateGas });
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
blockGasLimit: gasLimitHex,
|
|
60
|
+
estimatedGas,
|
|
61
|
+
simulationFails
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function addGasBuffer(estimatedGas, blockGasLimit, multiplier) {
|
|
65
|
+
const estimatedGasBN = hexToBN(estimatedGas);
|
|
66
|
+
const maxGasBN = hexToBN(blockGasLimit).muln(0.9);
|
|
67
|
+
const paddedGasBN = estimatedGasBN.muln(multiplier);
|
|
68
|
+
if (estimatedGasBN.gt(maxGasBN)) {
|
|
69
|
+
const estimatedGasHex = add0x(estimatedGas);
|
|
70
|
+
log("Using estimated value", estimatedGasHex);
|
|
71
|
+
return estimatedGasHex;
|
|
72
|
+
}
|
|
73
|
+
if (paddedGasBN.lt(maxGasBN)) {
|
|
74
|
+
const paddedHex = add0x(BNToHex(paddedGasBN));
|
|
75
|
+
log("Using padded estimate", paddedHex, multiplier);
|
|
76
|
+
return paddedHex;
|
|
77
|
+
}
|
|
78
|
+
const maxHex = add0x(BNToHex(maxGasBN));
|
|
79
|
+
log("Using 90% of block gas limit", maxHex);
|
|
80
|
+
return maxHex;
|
|
81
|
+
}
|
|
82
|
+
async function getGas(request) {
|
|
83
|
+
const { isCustomNetwork, chainId, txMeta } = request;
|
|
84
|
+
if (txMeta.txParams.gas) {
|
|
85
|
+
log("Using value from request", txMeta.txParams.gas);
|
|
86
|
+
return [txMeta.txParams.gas];
|
|
87
|
+
}
|
|
88
|
+
if (await requiresFixedGas(request)) {
|
|
89
|
+
log("Using fixed value", FIXED_GAS);
|
|
90
|
+
return [FIXED_GAS];
|
|
91
|
+
}
|
|
92
|
+
const { blockGasLimit, estimatedGas, simulationFails } = await estimateGas(
|
|
93
|
+
txMeta.txParams,
|
|
94
|
+
request.ethQuery
|
|
95
|
+
);
|
|
96
|
+
if (isCustomNetwork) {
|
|
97
|
+
log("Using original estimate as custom network");
|
|
98
|
+
return [estimatedGas, simulationFails];
|
|
99
|
+
}
|
|
100
|
+
const bufferMultiplier = GAS_BUFFER_CHAIN_OVERRIDES[chainId] ?? DEFAULT_GAS_MULTIPLIER;
|
|
101
|
+
const bufferedGas = addGasBuffer(
|
|
102
|
+
estimatedGas,
|
|
103
|
+
blockGasLimit,
|
|
104
|
+
bufferMultiplier
|
|
105
|
+
);
|
|
106
|
+
return [bufferedGas, simulationFails];
|
|
107
|
+
}
|
|
108
|
+
async function requiresFixedGas({
|
|
109
|
+
ethQuery,
|
|
110
|
+
txMeta,
|
|
111
|
+
isCustomNetwork
|
|
112
|
+
}) {
|
|
113
|
+
const {
|
|
114
|
+
txParams: { to, data }
|
|
115
|
+
} = txMeta;
|
|
116
|
+
if (isCustomNetwork || !to || data) {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
const code = await getCode(ethQuery, to);
|
|
120
|
+
return !code || code === "0x";
|
|
121
|
+
}
|
|
122
|
+
async function getCode(ethQuery, address) {
|
|
123
|
+
return await query(ethQuery, "getCode", [address]);
|
|
124
|
+
}
|
|
125
|
+
async function getLatestBlock(ethQuery) {
|
|
126
|
+
return await query(ethQuery, "getBlockByNumber", ["latest", false]);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export {
|
|
130
|
+
log,
|
|
131
|
+
FIXED_GAS,
|
|
132
|
+
DEFAULT_GAS_MULTIPLIER,
|
|
133
|
+
updateGas,
|
|
134
|
+
estimateGas,
|
|
135
|
+
addGasBuffer
|
|
136
|
+
};
|
|
137
|
+
//# sourceMappingURL=chunk-UKYY2RVS.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/gas.ts"],"sourcesContent":["/* eslint-disable jsdoc/require-jsdoc */\n\nimport {\n BNToHex,\n fractionBN,\n hexToBN,\n query,\n} from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\n\nimport { GAS_BUFFER_CHAIN_OVERRIDES } from '../constants';\nimport { projectLogger } from '../logger';\nimport type { TransactionMeta, TransactionParams } from '../types';\n\nexport type UpdateGasRequest = {\n ethQuery: EthQuery;\n isCustomNetwork: boolean;\n chainId: Hex;\n txMeta: TransactionMeta;\n};\n\nexport const log = createModuleLogger(projectLogger, 'gas');\n\nexport const FIXED_GAS = '0x5208';\nexport const DEFAULT_GAS_MULTIPLIER = 1.5;\n\nexport async function updateGas(request: UpdateGasRequest) {\n const { txMeta } = request;\n const initialParams = { ...txMeta.txParams };\n\n const [gas, simulationFails] = await getGas(request);\n\n txMeta.txParams.gas = gas;\n txMeta.simulationFails = simulationFails;\n\n if (!initialParams.gas) {\n txMeta.originalGasEstimate = txMeta.txParams.gas;\n }\n\n if (!txMeta.defaultGasEstimates) {\n txMeta.defaultGasEstimates = {};\n }\n\n txMeta.defaultGasEstimates.gas = txMeta.txParams.gas;\n}\n\nexport async function estimateGas(\n txParams: TransactionParams,\n ethQuery: EthQuery,\n) {\n const request = { ...txParams };\n const { data, value } = request;\n\n const { gasLimit: gasLimitHex, number: blockNumber } = await getLatestBlock(\n ethQuery,\n );\n\n const gasLimitBN = hexToBN(gasLimitHex);\n\n request.data = data ? add0x(data) : data;\n request.gas = BNToHex(fractionBN(gasLimitBN, 19, 20));\n request.value = value || '0x0';\n\n let estimatedGas = request.gas;\n let simulationFails;\n\n try {\n estimatedGas = await query(ethQuery, 'estimateGas', [request]);\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n simulationFails = {\n reason: error.message,\n errorKey: error.errorKey,\n debug: {\n blockNumber,\n blockGasLimit: gasLimitHex,\n },\n };\n\n log('Estimation failed', { ...simulationFails, fallback: estimateGas });\n }\n\n return {\n blockGasLimit: gasLimitHex,\n estimatedGas,\n simulationFails,\n };\n}\n\nexport function addGasBuffer(\n estimatedGas: string,\n blockGasLimit: string,\n multiplier: number,\n) {\n const estimatedGasBN = hexToBN(estimatedGas);\n const maxGasBN = hexToBN(blockGasLimit).muln(0.9);\n const paddedGasBN = estimatedGasBN.muln(multiplier);\n\n if (estimatedGasBN.gt(maxGasBN)) {\n const estimatedGasHex = add0x(estimatedGas);\n log('Using estimated value', estimatedGasHex);\n return estimatedGasHex;\n }\n\n if (paddedGasBN.lt(maxGasBN)) {\n const paddedHex = add0x(BNToHex(paddedGasBN));\n log('Using padded estimate', paddedHex, multiplier);\n return paddedHex;\n }\n\n const maxHex = add0x(BNToHex(maxGasBN));\n log('Using 90% of block gas limit', maxHex);\n return maxHex;\n}\n\nasync function getGas(\n request: UpdateGasRequest,\n): Promise<[string, TransactionMeta['simulationFails']?]> {\n const { isCustomNetwork, chainId, txMeta } = request;\n\n if (txMeta.txParams.gas) {\n log('Using value from request', txMeta.txParams.gas);\n return [txMeta.txParams.gas];\n }\n\n if (await requiresFixedGas(request)) {\n log('Using fixed value', FIXED_GAS);\n return [FIXED_GAS];\n }\n\n const { blockGasLimit, estimatedGas, simulationFails } = await estimateGas(\n txMeta.txParams,\n request.ethQuery,\n );\n\n if (isCustomNetwork) {\n log('Using original estimate as custom network');\n return [estimatedGas, simulationFails];\n }\n\n const bufferMultiplier =\n GAS_BUFFER_CHAIN_OVERRIDES[\n chainId as keyof typeof GAS_BUFFER_CHAIN_OVERRIDES\n ] ?? DEFAULT_GAS_MULTIPLIER;\n\n const bufferedGas = addGasBuffer(\n estimatedGas,\n blockGasLimit,\n bufferMultiplier,\n );\n\n return [bufferedGas, simulationFails];\n}\n\nasync function requiresFixedGas({\n ethQuery,\n txMeta,\n isCustomNetwork,\n}: UpdateGasRequest): Promise<boolean> {\n const {\n txParams: { to, data },\n } = txMeta;\n\n if (isCustomNetwork || !to || data) {\n return false;\n }\n\n const code = await getCode(ethQuery, to);\n\n return !code || code === '0x';\n}\n\nasync function getCode(\n ethQuery: EthQuery,\n address: string,\n): Promise<string | undefined> {\n return await query(ethQuery, 'getCode', [address]);\n}\n\nasync function getLatestBlock(\n ethQuery: EthQuery,\n): Promise<{ gasLimit: string; number: string }> {\n return await query(ethQuery, 'getBlockByNumber', ['latest', false]);\n}\n"],"mappings":";;;;;;;;AAEA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAGP,SAAS,OAAO,0BAA0B;AAanC,IAAM,MAAM,mBAAmB,eAAe,KAAK;AAEnD,IAAM,YAAY;AAClB,IAAM,yBAAyB;AAEtC,eAAsB,UAAU,SAA2B;AACzD,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,gBAAgB,EAAE,GAAG,OAAO,SAAS;AAE3C,QAAM,CAAC,KAAK,eAAe,IAAI,MAAM,OAAO,OAAO;AAEnD,SAAO,SAAS,MAAM;AACtB,SAAO,kBAAkB;AAEzB,MAAI,CAAC,cAAc,KAAK;AACtB,WAAO,sBAAsB,OAAO,SAAS;AAAA,EAC/C;AAEA,MAAI,CAAC,OAAO,qBAAqB;AAC/B,WAAO,sBAAsB,CAAC;AAAA,EAChC;AAEA,SAAO,oBAAoB,MAAM,OAAO,SAAS;AACnD;AAEA,eAAsB,YACpB,UACA,UACA;AACA,QAAM,UAAU,EAAE,GAAG,SAAS;AAC9B,QAAM,EAAE,MAAM,MAAM,I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unk-LM4NUNMT.mjs";
|
|
10
|
+
import {
|
|
11
|
+
__privateAdd,
|
|
12
|
+
__privateMethod
|
|
13
|
+
} from "./chunk-XUI43LEZ.mjs";
|
|
14
|
+
|
|
15
|
+
// src/gas-flows/LineaGasFeeFlow.ts
|
|
16
|
+
import { ChainId, hexToBN, query, toHex } from "@metamask/controller-utils";
|
|
17
|
+
import { createModuleLogger } from "@metamask/utils";
|
|
18
|
+
var log = createModuleLogger(projectLogger, "linea-gas-fee-flow");
|
|
19
|
+
var LINEA_CHAIN_IDS = [
|
|
20
|
+
ChainId["linea-mainnet"],
|
|
21
|
+
ChainId["linea-goerli"],
|
|
22
|
+
ChainId["linea-sepolia"]
|
|
23
|
+
];
|
|
24
|
+
var BASE_FEE_MULTIPLIERS = {
|
|
25
|
+
low: 1,
|
|
26
|
+
medium: 1.35,
|
|
27
|
+
high: 1.7
|
|
28
|
+
};
|
|
29
|
+
var PRIORITY_FEE_MULTIPLIERS = {
|
|
30
|
+
low: 1,
|
|
31
|
+
medium: 1.05,
|
|
32
|
+
high: 1.1
|
|
33
|
+
};
|
|
34
|
+
var _getLineaGasFees, getLineaGasFees_fn, _getLineaResponse, getLineaResponse_fn, _getValuesFromMultipliers, getValuesFromMultipliers_fn, _getMaxFees, getMaxFees_fn, _feesToString, feesToString_fn;
|
|
35
|
+
var LineaGasFeeFlow = class {
|
|
36
|
+
constructor() {
|
|
37
|
+
__privateAdd(this, _getLineaGasFees);
|
|
38
|
+
__privateAdd(this, _getLineaResponse);
|
|
39
|
+
__privateAdd(this, _getValuesFromMultipliers);
|
|
40
|
+
__privateAdd(this, _getMaxFees);
|
|
41
|
+
__privateAdd(this, _feesToString);
|
|
42
|
+
}
|
|
43
|
+
matchesTransaction(transactionMeta) {
|
|
44
|
+
return LINEA_CHAIN_IDS.includes(transactionMeta.chainId);
|
|
45
|
+
}
|
|
46
|
+
async getGasFees(request) {
|
|
47
|
+
try {
|
|
48
|
+
return await __privateMethod(this, _getLineaGasFees, getLineaGasFees_fn).call(this, request);
|
|
49
|
+
} catch (error) {
|
|
50
|
+
log("Using default flow as fallback due to error", error);
|
|
51
|
+
return new DefaultGasFeeFlow().getGasFees(request);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
_getLineaGasFees = new WeakSet();
|
|
56
|
+
getLineaGasFees_fn = async function(request) {
|
|
57
|
+
const { ethQuery, transactionMeta } = request;
|
|
58
|
+
const lineaResponse = await __privateMethod(this, _getLineaResponse, getLineaResponse_fn).call(this, transactionMeta, ethQuery);
|
|
59
|
+
log("Received Linea response", lineaResponse);
|
|
60
|
+
const baseFees = __privateMethod(this, _getValuesFromMultipliers, getValuesFromMultipliers_fn).call(this, lineaResponse.baseFeePerGas, BASE_FEE_MULTIPLIERS);
|
|
61
|
+
log("Generated base fees", __privateMethod(this, _feesToString, feesToString_fn).call(this, baseFees));
|
|
62
|
+
const priorityFees = __privateMethod(this, _getValuesFromMultipliers, getValuesFromMultipliers_fn).call(this, lineaResponse.priorityFeePerGas, PRIORITY_FEE_MULTIPLIERS);
|
|
63
|
+
log("Generated priority fees", __privateMethod(this, _feesToString, feesToString_fn).call(this, priorityFees));
|
|
64
|
+
const maxFees = __privateMethod(this, _getMaxFees, getMaxFees_fn).call(this, baseFees, priorityFees);
|
|
65
|
+
log("Generated max fees", __privateMethod(this, _feesToString, feesToString_fn).call(this, maxFees));
|
|
66
|
+
const estimates = Object.values(GasFeeEstimateLevel).reduce(
|
|
67
|
+
(result, level) => ({
|
|
68
|
+
...result,
|
|
69
|
+
[level]: {
|
|
70
|
+
maxFeePerGas: toHex(maxFees[level]),
|
|
71
|
+
maxPriorityFeePerGas: toHex(priorityFees[level])
|
|
72
|
+
}
|
|
73
|
+
}),
|
|
74
|
+
{}
|
|
75
|
+
);
|
|
76
|
+
return { estimates };
|
|
77
|
+
};
|
|
78
|
+
_getLineaResponse = new WeakSet();
|
|
79
|
+
getLineaResponse_fn = function(transactionMeta, ethQuery) {
|
|
80
|
+
return query(ethQuery, "linea_estimateGas", [
|
|
81
|
+
{
|
|
82
|
+
from: transactionMeta.txParams.from,
|
|
83
|
+
to: transactionMeta.txParams.to,
|
|
84
|
+
value: transactionMeta.txParams.value,
|
|
85
|
+
input: transactionMeta.txParams.data,
|
|
86
|
+
// Required in request but no impact on response.
|
|
87
|
+
gasPrice: "0x100000000"
|
|
88
|
+
}
|
|
89
|
+
]);
|
|
90
|
+
};
|
|
91
|
+
_getValuesFromMultipliers = new WeakSet();
|
|
92
|
+
getValuesFromMultipliers_fn = function(value, multipliers) {
|
|
93
|
+
const base = hexToBN(value);
|
|
94
|
+
const low = base.muln(multipliers.low);
|
|
95
|
+
const medium = base.muln(multipliers.medium);
|
|
96
|
+
const high = base.muln(multipliers.high);
|
|
97
|
+
return {
|
|
98
|
+
low,
|
|
99
|
+
medium,
|
|
100
|
+
high
|
|
101
|
+
};
|
|
102
|
+
};
|
|
103
|
+
_getMaxFees = new WeakSet();
|
|
104
|
+
getMaxFees_fn = function(baseFees, priorityFees) {
|
|
105
|
+
return {
|
|
106
|
+
low: baseFees.low.add(priorityFees.low),
|
|
107
|
+
medium: baseFees.medium.add(priorityFees.medium),
|
|
108
|
+
high: baseFees.high.add(priorityFees.high)
|
|
109
|
+
};
|
|
110
|
+
};
|
|
111
|
+
_feesToString = new WeakSet();
|
|
112
|
+
feesToString_fn = function(fees) {
|
|
113
|
+
return Object.values(GasFeeEstimateLevel).map(
|
|
114
|
+
(level) => fees[level].toString(10)
|
|
115
|
+
);
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
export {
|
|
119
|
+
LineaGasFeeFlow
|
|
120
|
+
};
|
|
121
|
+
//# sourceMappingURL=chunk-UM4ORJ5B.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/gas-flows/LineaGasFeeFlow.ts"],"sourcesContent":["import { ChainId, hexToBN, query, toHex } from '@metamask/controller-utils';\nimport type EthQuery from '@metamask/eth-query';\nimport { createModuleLogger, type Hex } from '@metamask/utils';\nimport type BN from 'bn.js';\n\nimport { projectLogger } from '../logger';\nimport type {\n GasFeeEstimates,\n GasFeeFlow,\n GasFeeFlowRequest,\n GasFeeFlowResponse,\n TransactionMeta,\n} from '../types';\nimport { GasFeeEstimateLevel } from '../types';\nimport { DefaultGasFeeFlow } from './DefaultGasFeeFlow';\n\ntype LineaEstimateGasResponse = {\n baseFeePerGas: Hex;\n priorityFeePerGas: Hex;\n};\n\ntype FeesByLevel = {\n [key in GasFeeEstimateLevel]: BN;\n};\n\nconst log = createModuleLogger(projectLogger, 'linea-gas-fee-flow');\n\nconst LINEA_CHAIN_IDS: Hex[] = [\n ChainId['linea-mainnet'],\n ChainId['linea-goerli'],\n ChainId['linea-sepolia'],\n];\n\nconst BASE_FEE_MULTIPLIERS = {\n low: 1,\n medium: 1.35,\n high: 1.7,\n};\n\nconst PRIORITY_FEE_MULTIPLIERS = {\n low: 1,\n medium: 1.05,\n high: 1.1,\n};\n\n/**\n * Implementation of a gas fee flow specific to Linea networks that obtains gas fee estimates using:\n * - The `linea_estimateGas` RPC method to obtain the base fee and lowest priority fee.\n * - Static multipliers to increase the base and priority fees.\n */\nexport class LineaGasFeeFlow implements GasFeeFlow {\n matchesTransaction(transactionMeta: TransactionMeta): boolean {\n return LINEA_CHAIN_IDS.includes(transactionMeta.chainId);\n }\n\n async getGasFees(request: GasFeeFlowRequest): Promise<GasFeeFlowResponse> {\n try {\n return await this.#getLineaGasFees(request);\n } catch (error) {\n log('Using default flow as fallback due to error', error);\n return new DefaultGasFeeFlow().getGasFees(request);\n }\n }\n\n async #getLineaGasFees(\n request: GasFeeFlowRequest,\n ): Promise<GasFeeFlowResponse> {\n const { ethQuery, transactionMeta } = request;\n\n const lineaResponse = await this.#getLineaResponse(\n transactionMeta,\n ethQuery,\n );\n\n log('Received Linea response', lineaResponse);\n\n const baseFees = this.#getValuesFromMultipliers(\n lineaResponse.baseFeePerGas,\n BASE_FEE_MULTIPLIERS,\n );\n\n log('Generated base fees', this.#feesToString(baseFees));\n\n const priorityFees = this.#getValuesFromMultipliers(\n lineaResponse.priorityFeePerGas,\n PRIORITY_FEE_MULTIPLIERS,\n );\n\n log('Generated priority fees', this.#feesToString(priorityFees));\n\n const maxFees = this.#getMaxFees(baseFees, priorityFees);\n\n log('Generated max fees', this.#feesToString(maxFees));\n\n const estimates = Object.values(GasFeeEstimateLevel).reduce(\n (result, level) => ({\n ...result,\n [level]: {\n maxFeePerGas: toHex(maxFees[level]),\n maxPriorityFeePerGas: toHex(priorityFees[level]),\n },\n }),\n {} as GasFeeEstimates,\n );\n\n return { estimates };\n }\n\n #getLineaResponse(\n transactionMeta: TransactionMeta,\n ethQuery: EthQuery,\n ): Promise<LineaEstimateGasResponse> {\n return query(ethQuery, 'linea_estimateGas', [\n {\n from: transactionMeta.txParams.from,\n to: transactionMeta.txParams.to,\n value: transactionMeta.txParams.value,\n input: transactionMeta.txParams.data,\n // Required in request but no impact on response.\n gasPrice: '0x100000000',\n },\n ]);\n }\n\n #getValuesFromMultipliers(\n value: Hex,\n multipliers: { low: number; medium: number; high: number },\n ): FeesByLevel {\n const base = hexToBN(value);\n const low = base.muln(multipliers.low);\n const medium = base.muln(multipliers.medium);\n const high = base.muln(multipliers.high);\n\n return {\n low,\n medium,\n high,\n };\n }\n\n #getMaxFees(\n baseFees: Record<GasFeeEstimateLevel, BN>,\n priorityFees: Record<GasFeeEstimateLevel, BN>,\n ): FeesByLevel {\n return {\n low: baseFees.low.add(priorityFees.low),\n medium: baseFees.medium.add(priorityFees.medium),\n high: baseFees.high.add(priorityFees.high),\n };\n }\n\n #feesToString(fees: FeesByLevel) {\n return Object.values(GasFeeEstimateLevel).map((level) =>\n fees[level].toString(10),\n );\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;AAAA,SAAS,SAAS,SAAS,OAAO,aAAa;AAE/C,SAAS,0BAAoC;AAuB7C,IAAM,MAAM,mBAAmB,eAAe,oBAAoB;AAElE,IAAM,kBAAyB;A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AK,CAAC;AAAA,QAClC,sBAAsB,MAAM,aAAa,KAAK,CAAC;AAAA,MACjD;AAAA,IACF;AAAA,IACA,CAAC;AAAA,EACH;AAEA,SAAO,EAAE,UAAU;AACrB;AAEA;AAAA,sBAAiB,SACf,iBACA,UACmC;AACnC,SAAO,MAAM,UAAU,qBAAqB;AAAA,IAC1C;AAAA,MACE,MAAM,gBAAgB,SAAS;AAAA,MAC/B,IAAI,gBAAgB,SAAS;AAAA,MAC7B,OAAO,gBAAgB,SAAS;AAAA,MAChC,OAAO,gBAAgB,SAAS;AAAA;AAAA,MAEhC,UAAU;AAAA,IACZ;AAAA,EACF,CAAC;AACH;AAEA;AAAA,8BAAyB,SACvB,OACA,aACa;AACb,QAAM,OAAO,QAAQ,KAAK;AAC1B,QAAM,MAAM,KAAK,KAAK,YAAY,GAAG;AACrC,QAAM,SAAS,KAAK,KAAK,YAAY,MAAM;AAC3C,QAAM,OAAO,KAAK,KAAK,YAAY,IAAI;AAEvC,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEA;AAAA,gBAAW,SACT,UACA,cACa;AACb,SAAO;AAAA,IACL,KAAK,SAAS,IAAI,IAAI,aAAa,GAAG;AAAA,IACtC,QAAQ,SAAS,OAAO,IAAI,aAAa,MAAM;AAAA,IAC/C,MAAM,SAAS,KAAK,IAAI,aAAa,IAAI;AAAA,EAC3C;AACF;AAEA;AAAA,kBAAa,SAAC,MAAmB;AAC/B,SAAO,OAAO,OAAO,mBAAmB,EAAE;AAAA,IAAI,CAAC,UAC7C,KAAK,KAAK,EAAE,SAAS,EAAE;AAAA,EACzB;AACF;","names":[]}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// src/logger.ts
|
|
2
|
+
import { createProjectLogger, createModuleLogger } from "@metamask/utils";
|
|
3
|
+
var projectLogger = createProjectLogger("transaction-controller");
|
|
4
|
+
var incomingTransactionsLogger = createModuleLogger(
|
|
5
|
+
projectLogger,
|
|
6
|
+
"incoming-transactions"
|
|
7
|
+
);
|
|
8
|
+
|
|
9
|
+
export {
|
|
10
|
+
createModuleLogger,
|
|
11
|
+
projectLogger,
|
|
12
|
+
incomingTransactionsLogger
|
|
13
|
+
};
|
|
14
|
+
//# sourceMappingURL=chunk-UQQWZT6C.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/logger.ts"],"sourcesContent":["/* istanbul ignore file */\n\nimport { createProjectLogger, createModuleLogger } from '@metamask/utils';\n\nexport const projectLogger = createProjectLogger('transaction-controller');\n\nexport const incomingTransactionsLogger = createModuleLogger(\n projectLogger,\n 'incoming-transactions',\n);\n\nexport { createModuleLogger };\n"],"mappings":";AAEA,SAAS,qBAAqB,0BAA0B;AAEjD,IAAM,gBAAgB,oBAAoB,wBAAwB;AAElE,IAAM,6BAA6B;AAAA,EACxC;AAAA,EACA;AACF;","names":[]}
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
|
|
2
|
+
|
|
3
|
+
var _chunkUGFBA4GVjs = require('./chunk-UGFBA4GV.js');
|
|
4
|
+
|
|
5
|
+
// src/utils/validation.ts
|
|
6
|
+
var _abi = require('@ethersproject/abi');
|
|
7
|
+
var _controllerutils = require('@metamask/controller-utils');
|
|
8
|
+
var _metamaskethabis = require('@metamask/metamask-eth-abis');
|
|
9
|
+
var _rpcerrors = require('@metamask/rpc-errors');
|
|
10
|
+
async function validateTransactionOrigin(permittedAddresses, selectedAddress, from, origin) {
|
|
11
|
+
if (origin === _controllerutils.ORIGIN_METAMASK) {
|
|
12
|
+
if (from !== selectedAddress) {
|
|
13
|
+
throw _rpcerrors.rpcErrors.internal({
|
|
14
|
+
message: `Internally initiated transaction is using invalid account.`,
|
|
15
|
+
data: {
|
|
16
|
+
origin,
|
|
17
|
+
fromAddress: from,
|
|
18
|
+
selectedAddress
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
if (!permittedAddresses.includes(from)) {
|
|
25
|
+
throw _rpcerrors.providerErrors.unauthorized({ data: { origin } });
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function validateTxParams(txParams, isEIP1559Compatible = true) {
|
|
29
|
+
validateEIP1559Compatibility(txParams, isEIP1559Compatible);
|
|
30
|
+
validateParamFrom(txParams.from);
|
|
31
|
+
validateParamRecipient(txParams);
|
|
32
|
+
validateParamValue(txParams.value);
|
|
33
|
+
validateParamData(txParams.data);
|
|
34
|
+
validateParamChainId(txParams.chainId);
|
|
35
|
+
validateGasFeeParams(txParams);
|
|
36
|
+
}
|
|
37
|
+
function validateEIP1559Compatibility(txParams, isEIP1559Compatible) {
|
|
38
|
+
if (_chunkUGFBA4GVjs.isEIP1559Transaction.call(void 0, txParams) && !isEIP1559Compatible) {
|
|
39
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
40
|
+
"Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559"
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
function validateParamValue(value) {
|
|
45
|
+
if (value !== void 0) {
|
|
46
|
+
if (value.includes("-")) {
|
|
47
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
48
|
+
`Invalid transaction value "${value}": not a positive number.`
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
if (value.includes(".")) {
|
|
52
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
53
|
+
`Invalid transaction value "${value}": number must be in wei.`
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
const intValue = parseInt(value, 10);
|
|
57
|
+
const isValid = Number.isFinite(intValue) && !Number.isNaN(intValue) && !isNaN(Number(value)) && Number.isSafeInteger(intValue);
|
|
58
|
+
if (!isValid) {
|
|
59
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
60
|
+
`Invalid transaction value ${value}: number must be a valid number.`
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
function validateParamRecipient(txParams) {
|
|
66
|
+
if (txParams.to === "0x" || txParams.to === void 0) {
|
|
67
|
+
if (txParams.data) {
|
|
68
|
+
delete txParams.to;
|
|
69
|
+
} else {
|
|
70
|
+
throw _rpcerrors.rpcErrors.invalidParams(`Invalid "to" address.`);
|
|
71
|
+
}
|
|
72
|
+
} else if (txParams.to !== void 0 && !_controllerutils.isValidHexAddress.call(void 0, txParams.to)) {
|
|
73
|
+
throw _rpcerrors.rpcErrors.invalidParams(`Invalid "to" address.`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
function validateParamFrom(from) {
|
|
77
|
+
if (!from || typeof from !== "string") {
|
|
78
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
79
|
+
`Invalid "from" address ${from}: not a string.`
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
if (!_controllerutils.isValidHexAddress.call(void 0, from)) {
|
|
83
|
+
throw _rpcerrors.rpcErrors.invalidParams('Invalid "from" address.');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function validateParamData(value) {
|
|
87
|
+
if (value) {
|
|
88
|
+
const ERC20Interface = new (0, _abi.Interface)(_metamaskethabis.abiERC20);
|
|
89
|
+
try {
|
|
90
|
+
ERC20Interface.parseTransaction({ data: value });
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (error.message.match(/BUFFER_OVERRUN/u)) {
|
|
93
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
94
|
+
"Invalid transaction params: data out-of-bounds, BUFFER_OVERRUN."
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function validateParamChainId(chainId) {
|
|
101
|
+
if (chainId !== void 0 && typeof chainId !== "number" && typeof chainId !== "string") {
|
|
102
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
103
|
+
`Invalid transaction params: chainId is not a Number or hex string. got: (${chainId})`
|
|
104
|
+
);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
function validateGasFeeParams(txParams) {
|
|
108
|
+
if (txParams.gasPrice) {
|
|
109
|
+
ensureProperTransactionEnvelopeTypeProvided(txParams, "gasPrice");
|
|
110
|
+
ensureMutuallyExclusiveFieldsNotProvided(
|
|
111
|
+
txParams,
|
|
112
|
+
"gasPrice",
|
|
113
|
+
"maxFeePerGas"
|
|
114
|
+
);
|
|
115
|
+
ensureMutuallyExclusiveFieldsNotProvided(
|
|
116
|
+
txParams,
|
|
117
|
+
"gasPrice",
|
|
118
|
+
"maxPriorityFeePerGas"
|
|
119
|
+
);
|
|
120
|
+
ensureFieldIsString(txParams, "gasPrice");
|
|
121
|
+
}
|
|
122
|
+
if (txParams.maxFeePerGas) {
|
|
123
|
+
ensureProperTransactionEnvelopeTypeProvided(txParams, "maxFeePerGas");
|
|
124
|
+
ensureMutuallyExclusiveFieldsNotProvided(
|
|
125
|
+
txParams,
|
|
126
|
+
"maxFeePerGas",
|
|
127
|
+
"gasPrice"
|
|
128
|
+
);
|
|
129
|
+
ensureFieldIsString(txParams, "maxFeePerGas");
|
|
130
|
+
}
|
|
131
|
+
if (txParams.maxPriorityFeePerGas) {
|
|
132
|
+
ensureProperTransactionEnvelopeTypeProvided(
|
|
133
|
+
txParams,
|
|
134
|
+
"maxPriorityFeePerGas"
|
|
135
|
+
);
|
|
136
|
+
ensureMutuallyExclusiveFieldsNotProvided(
|
|
137
|
+
txParams,
|
|
138
|
+
"maxPriorityFeePerGas",
|
|
139
|
+
"gasPrice"
|
|
140
|
+
);
|
|
141
|
+
ensureFieldIsString(txParams, "maxPriorityFeePerGas");
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function ensureProperTransactionEnvelopeTypeProvided(txParams, field) {
|
|
145
|
+
switch (field) {
|
|
146
|
+
case "maxFeePerGas":
|
|
147
|
+
case "maxPriorityFeePerGas":
|
|
148
|
+
if (txParams.type && txParams.type !== "0x2" /* feeMarket */) {
|
|
149
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
150
|
+
`Invalid transaction envelope type: specified type "${txParams.type}" but including maxFeePerGas and maxPriorityFeePerGas requires type: "${"0x2" /* feeMarket */}"`
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
break;
|
|
154
|
+
case "gasPrice":
|
|
155
|
+
default:
|
|
156
|
+
if (txParams.type && txParams.type === "0x2" /* feeMarket */) {
|
|
157
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
158
|
+
`Invalid transaction envelope type: specified type "${txParams.type}" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`
|
|
159
|
+
);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
function ensureMutuallyExclusiveFieldsNotProvided(txParams, fieldBeingValidated, mutuallyExclusiveField) {
|
|
164
|
+
if (typeof txParams[mutuallyExclusiveField] !== "undefined") {
|
|
165
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
166
|
+
`Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
function ensureFieldIsString(txParams, field) {
|
|
171
|
+
if (typeof txParams[field] !== "string") {
|
|
172
|
+
throw _rpcerrors.rpcErrors.invalidParams(
|
|
173
|
+
`Invalid transaction params: ${field} is not a string. got: (${txParams[field]})`
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
exports.validateTransactionOrigin = validateTransactionOrigin; exports.validateTxParams = validateTxParams;
|
|
182
|
+
//# sourceMappingURL=chunk-VH47Q6TS.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/validation.ts"],"names":[],"mappings":";;;;;AAAA,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;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,wBAAoB,UAAU,UAAU;AAAA,EAC1C;AAEA,MAAI,SAAS,cAAc;AACzB,gDAA4C,UAAU,cAAc;AACpE;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,wBAAoB,UAAU,cAAc;AAAA,EAC9C;AAEA,MAAI,SAAS,sBAAsB;AACjC;AAAA,MACE;AAAA,MACA;AAAA,IACF;AACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,IACF;AACA,wBAAoB,UAAU,sBAAsB;AAAA,EACtD;AACF;AAYA,SAAS,4CACP,UACA,OACA;AACA,UAAQ,OAAO;AAAA,IACb,KAAK;AAAA,IACL,KAAK;AACH,UACE,SAAS,QACT,SAAS,gCACT;AACA,cAAM,UAAU;AAAA,UACd,sDAAsD,SAAS,IAAI,8FAA0G;AAAA,QAC/K;AAAA,MACF;AACA;AAAA,IACF,KAAK;AAAA,IACL;AACE,UACE,SAAS,QACT,SAAS,gCACT;AACA,cAAM,UAAU;AAAA,UACd,sDAAsD,SAAS,IAAI;AAAA,QACrE;AAAA,MACF;AAAA,EACJ;AACF;AAYA,SAAS,yCACP,UACA,qBACA,wBACA;AACA,MAAI,OAAO,SAAS,sBAAsB,MAAM,aAAa;AAC3D,UAAM,UAAU;AAAA,MACd,yCAAyC,mBAAmB,sBAAsB,sBAAsB;AAAA,IAC1G;AAAA,EACF;AACF;AAUA,SAAS,oBACP,UACA,OACA;AACA,MAAI,OAAO,SAAS,KAAK,MAAM,UAAU;AACvC,UAAM,UAAU;AAAA,MACd,+BAA+B,KAAK,2BAA2B,SAAS,KAAK,CAAC;AAAA,IAChF;AAAA,EACF;AACF","sourcesContent":["import { Interface } from '@ethersproject/abi';\nimport { ORIGIN_METAMASK, isValidHexAddress } from '@metamask/controller-utils';\nimport { abiERC20 } from '@metamask/metamask-eth-abis';\nimport { providerErrors, rpcErrors } from '@metamask/rpc-errors';\n\nimport { TransactionEnvelopeType, type TransactionParams } from '../types';\nimport { isEIP1559Transaction } from './utils';\n\ntype GasFieldsToValidate = 'gasPrice' | 'maxFeePerGas' | 'maxPriorityFeePerGas';\n\n/**\n * Validates whether a transaction initiated by a specific 'from' address is permitted by the origin.\n *\n * @param permittedAddresses - The permitted accounts for the given origin.\n * @param selectedAddress - The currently selected Ethereum address in the wallet.\n * @param from - The address from which the transaction is initiated.\n * @param origin - The origin or source of the transaction.\n * @throws Throws an error if the transaction is not permitted.\n */\nexport async function validateTransactionOrigin(\n permittedAddresses: string[],\n selectedAddress: string,\n from: string,\n origin: string,\n) {\n if (origin === ORIGIN_METAMASK) {\n // Ensure the 'from' address matches the currently selected address\n if (from !== selectedAddress) {\n throw rpcErrors.internal({\n message: `Internally initiated transaction is using invalid account.`,\n data: {\n origin,\n fromAddress: from,\n selectedAddress,\n },\n });\n }\n return;\n }\n\n // Check if the origin has permissions to initiate transactions from the specified address\n if (!permittedAddresses.includes(from)) {\n throw providerErrors.unauthorized({ data: { origin } });\n }\n}\n\n/**\n * Validates the transaction params for required properties and throws in\n * the event of any validation error.\n *\n * @param txParams - Transaction params object to validate.\n * @param isEIP1559Compatible - whether or not the current network supports EIP-1559 transactions.\n */\nexport function validateTxParams(\n txParams: TransactionParams,\n isEIP1559Compatible = true,\n) {\n validateEIP1559Compatibility(txParams, isEIP1559Compatible);\n validateParamFrom(txParams.from);\n validateParamRecipient(txParams);\n validateParamValue(txParams.value);\n validateParamData(txParams.data);\n validateParamChainId(txParams.chainId);\n validateGasFeeParams(txParams);\n}\n\n/**\n * Validates EIP-1559 compatibility for transaction creation.\n *\n * @param txParams - The transaction parameters to validate.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n * @throws Throws invalid params if the transaction specifies EIP-1559 but the network does not support it.\n */\nfunction validateEIP1559Compatibility(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (isEIP1559Transaction(txParams) && !isEIP1559Compatible) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: params specify an EIP-1559 transaction but the current network does not support EIP-1559',\n );\n }\n}\n\n/**\n * Validates value property, ensuring it is a valid positive integer number\n * denominated in wei.\n *\n * @param value - The value to validate, expressed as a string.\n * @throws Throws an error if the value is not a valid positive integer\n * number denominated in wei.\n * - If the value contains a hyphen (-), it is considered invalid.\n * - If the value contains a decimal point (.), it is considered invalid.\n * - If the value is not a finite number, is NaN, or is not a safe integer, it is considered invalid.\n */\nfunction validateParamValue(value?: string) {\n if (value !== undefined) {\n if (value.includes('-')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": not a positive number.`,\n );\n }\n\n if (value.includes('.')) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value \"${value}\": number must be in wei.`,\n );\n }\n const intValue = parseInt(value, 10);\n const isValid =\n Number.isFinite(intValue) &&\n !Number.isNaN(intValue) &&\n !isNaN(Number(value)) &&\n Number.isSafeInteger(intValue);\n if (!isValid) {\n throw rpcErrors.invalidParams(\n `Invalid transaction value ${value}: number must be a valid number.`,\n );\n }\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param txParams - The transaction parameters object to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamRecipient(txParams: TransactionParams) {\n if (txParams.to === '0x' || txParams.to === undefined) {\n if (txParams.data) {\n delete txParams.to;\n } else {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n } else if (txParams.to !== undefined && !isValidHexAddress(txParams.to)) {\n throw rpcErrors.invalidParams(`Invalid \"to\" address.`);\n }\n}\n\n/**\n * Validates the recipient address in a transaction's parameters.\n *\n * @param from - The from property to validate.\n * @throws Throws an error if the recipient address is invalid:\n * - If the recipient address is an empty string ('0x') or undefined and the transaction contains data,\n * the \"to\" field is removed from the transaction parameters.\n * - If the recipient address is not a valid hexadecimal Ethereum address, an error is thrown.\n */\nfunction validateParamFrom(from: string) {\n if (!from || typeof from !== 'string') {\n throw rpcErrors.invalidParams(\n `Invalid \"from\" address ${from}: not a string.`,\n );\n }\n if (!isValidHexAddress(from)) {\n throw rpcErrors.invalidParams('Invalid \"from\" address.');\n }\n}\n\n/**\n * Validates input data for transactions.\n *\n * @param value - The input data to validate.\n * @throws Throws invalid params if the input data is invalid.\n */\nfunction validateParamData(value?: string) {\n if (value) {\n const ERC20Interface = new Interface(abiERC20);\n try {\n ERC20Interface.parseTransaction({ data: value });\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n } catch (error: any) {\n if (error.message.match(/BUFFER_OVERRUN/u)) {\n throw rpcErrors.invalidParams(\n 'Invalid transaction params: data out-of-bounds, BUFFER_OVERRUN.',\n );\n }\n }\n }\n}\n\n/**\n * Validates chainId type.\n *\n * @param chainId - The chainId to validate.\n */\nfunction validateParamChainId(chainId: number | string | undefined) {\n if (\n chainId !== undefined &&\n typeof chainId !== 'number' &&\n typeof chainId !== 'string'\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: chainId is not a Number or hex string. got: (${chainId})`,\n );\n }\n}\n\n/**\n * Validates gas values.\n *\n * @param txParams - The transaction parameters to validate.\n */\nfunction validateGasFeeParams(txParams: TransactionParams) {\n if (txParams.gasPrice) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'gasPrice');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'gasPrice',\n 'maxPriorityFeePerGas',\n );\n ensureFieldIsString(txParams, 'gasPrice');\n }\n\n if (txParams.maxFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(txParams, 'maxFeePerGas');\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsString(txParams, 'maxFeePerGas');\n }\n\n if (txParams.maxPriorityFeePerGas) {\n ensureProperTransactionEnvelopeTypeProvided(\n txParams,\n 'maxPriorityFeePerGas',\n );\n ensureMutuallyExclusiveFieldsNotProvided(\n txParams,\n 'maxPriorityFeePerGas',\n 'gasPrice',\n );\n ensureFieldIsString(txParams, 'maxPriorityFeePerGas');\n }\n}\n\n/**\n * Ensures that the provided txParams has the proper 'type' specified for the\n * given field, if it is provided. If types do not match throws an\n * invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {ethErrors.rpc.invalidParams} Throws if type does not match the\n * expectations for provided field.\n */\nfunction ensureProperTransactionEnvelopeTypeProvided(\n txParams: TransactionParams,\n field: GasFieldsToValidate,\n) {\n switch (field) {\n case 'maxFeePerGas':\n case 'maxPriorityFeePerGas':\n if (\n txParams.type &&\n txParams.type !== TransactionEnvelopeType.feeMarket\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${txParams.type}\" but including maxFeePerGas and maxPriorityFeePerGas requires type: \"${TransactionEnvelopeType.feeMarket}\"`,\n );\n }\n break;\n case 'gasPrice':\n default:\n if (\n txParams.type &&\n txParams.type === TransactionEnvelopeType.feeMarket\n ) {\n throw rpcErrors.invalidParams(\n `Invalid transaction envelope type: specified type \"${txParams.type}\" but included a gasPrice instead of maxFeePerGas and maxPriorityFeePerGas`,\n );\n }\n }\n}\n\n/**\n * Given two fields, ensure that the second field is not included in txParams,\n * and if it is throw an invalidParams error.\n *\n * @param txParams - The transaction parameters object\n * @param fieldBeingValidated - The current field being validated\n * @param mutuallyExclusiveField - The field to ensure is not provided\n * @throws {ethErrors.rpc.invalidParams} Throws if mutuallyExclusiveField is\n * present in txParams.\n */\nfunction ensureMutuallyExclusiveFieldsNotProvided(\n txParams: TransactionParams,\n fieldBeingValidated: GasFieldsToValidate,\n mutuallyExclusiveField: GasFieldsToValidate,\n) {\n if (typeof txParams[mutuallyExclusiveField] !== 'undefined') {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: specified ${fieldBeingValidated} but also included ${mutuallyExclusiveField}, these cannot be mixed`,\n );\n }\n}\n\n/**\n * Ensures that the provided value for field is a string, throws an\n * invalidParams error if field is not a string.\n *\n * @param txParams - The transaction parameters object\n * @param field - The current field being validated\n * @throws {rpcErrors.invalidParams} Throws if field is not a string\n */\nfunction ensureFieldIsString(\n txParams: TransactionParams,\n field: GasFieldsToValidate,\n) {\n if (typeof txParams[field] !== 'string') {\n throw rpcErrors.invalidParams(\n `Invalid transaction params: ${field} is not a string. got: (${txParams[field]})`,\n );\n }\n}\n"]}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
// src/utils/history.ts
|
|
2
|
+
import jsonDiffer from "fast-json-patch";
|
|
3
|
+
import { cloneDeep, merge } from "lodash";
|
|
4
|
+
function addInitialHistorySnapshot(transactionMeta) {
|
|
5
|
+
const snapshot = snapshotFromTransactionMeta(transactionMeta);
|
|
6
|
+
return merge({}, transactionMeta, { history: [snapshot] });
|
|
7
|
+
}
|
|
8
|
+
function updateTransactionHistory(transactionMeta, note) {
|
|
9
|
+
if (!transactionMeta.history) {
|
|
10
|
+
return transactionMeta;
|
|
11
|
+
}
|
|
12
|
+
const currentState = snapshotFromTransactionMeta(transactionMeta);
|
|
13
|
+
const previousState = replayHistory(transactionMeta.history);
|
|
14
|
+
const historyEntry = generateHistoryEntry(previousState, currentState, note);
|
|
15
|
+
if (historyEntry.length > 0) {
|
|
16
|
+
return merge({}, transactionMeta, {
|
|
17
|
+
history: [...transactionMeta.history, historyEntry]
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
return transactionMeta;
|
|
21
|
+
}
|
|
22
|
+
function generateHistoryEntry(previousState, currentState, note) {
|
|
23
|
+
const historyOperationsEntry = jsonDiffer.compare(
|
|
24
|
+
previousState,
|
|
25
|
+
currentState
|
|
26
|
+
);
|
|
27
|
+
if (historyOperationsEntry[0]) {
|
|
28
|
+
if (note) {
|
|
29
|
+
historyOperationsEntry[0].note = note;
|
|
30
|
+
}
|
|
31
|
+
historyOperationsEntry[0].timestamp = Date.now();
|
|
32
|
+
}
|
|
33
|
+
return historyOperationsEntry;
|
|
34
|
+
}
|
|
35
|
+
function replayHistory(transactionHistory) {
|
|
36
|
+
const shortHistory = cloneDeep(transactionHistory);
|
|
37
|
+
return shortHistory.reduce(
|
|
38
|
+
// TODO: Replace `any` with type
|
|
39
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
40
|
+
(val, entry) => jsonDiffer.applyPatch(val, entry).newDocument
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
function snapshotFromTransactionMeta(transactionMeta) {
|
|
44
|
+
const snapshot = { ...transactionMeta };
|
|
45
|
+
delete snapshot.history;
|
|
46
|
+
return cloneDeep(snapshot);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export {
|
|
50
|
+
addInitialHistorySnapshot,
|
|
51
|
+
updateTransactionHistory
|
|
52
|
+
};
|
|
53
|
+
//# sourceMappingURL=chunk-XGRAHX6T.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/utils/history.ts"],"sourcesContent":["import jsonDiffer from 'fast-json-patch';\nimport { cloneDeep, merge } from 'lodash';\n\nimport type {\n TransactionHistory,\n TransactionHistoryEntry,\n TransactionMeta,\n} from '../types';\n\n/**\n * Build a new version of the provided transaction with an initial history\n * entry, which is just a snapshot of the transaction.\n *\n * @param transactionMeta - TransactionMeta to add initial history snapshot to.\n * @returns A copy of `transactionMeta` with a new `history` property.\n */\nexport function addInitialHistorySnapshot(\n transactionMeta: TransactionMeta,\n): TransactionMeta {\n const snapshot = snapshotFromTransactionMeta(transactionMeta);\n return merge({}, transactionMeta, { history: [snapshot] });\n}\n\n/**\n * Builds a new version of the transaction with a new history entry if\n * it has a `history` property, or just returns the transaction.\n *\n * @param transactionMeta - TransactionMeta to add history entry to.\n * @param note - Note to add to history entry.\n * @returns A copy of `transactionMeta` with a new `history` entry if it has an\n * existing non-empty `history` array.\n */\nexport function updateTransactionHistory(\n transactionMeta: TransactionMeta,\n note: string,\n): TransactionMeta {\n if (!transactionMeta.history) {\n return transactionMeta;\n }\n\n const currentState = snapshotFromTransactionMeta(transactionMeta);\n const previousState = replayHistory(transactionMeta.history);\n const historyEntry = generateHistoryEntry(previousState, currentState, note);\n\n if (historyEntry.length > 0) {\n return merge({}, transactionMeta, {\n history: [...transactionMeta.history, historyEntry],\n });\n }\n return transactionMeta;\n}\n\n/**\n * Generates a history entry from the previous and new transaction metadata.\n *\n * @param previousState - The previous transaction metadata.\n * @param currentState - The new transaction metadata.\n * @param note - A note for the transaction metada update.\n * @returns An array of history operation.\n */\nfunction generateHistoryEntry(\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n previousState: any,\n currentState: TransactionMeta,\n note: string,\n): TransactionHistoryEntry {\n const historyOperationsEntry = jsonDiffer.compare(\n previousState,\n currentState,\n ) as TransactionHistoryEntry;\n // Add a note to the first operation, since it breaks if we append it to the entry\n if (historyOperationsEntry[0]) {\n if (note) {\n historyOperationsEntry[0].note = note;\n }\n historyOperationsEntry[0].timestamp = Date.now();\n }\n return historyOperationsEntry;\n}\n\n/**\n * Recovers previous transactionMeta from passed history array.\n *\n * @param transactionHistory - The transaction metadata to replay.\n * @returns The transaction metadata.\n */\nfunction replayHistory(\n transactionHistory: TransactionHistory,\n): TransactionMeta {\n const shortHistory = cloneDeep(transactionHistory);\n return shortHistory.reduce(\n // TODO: Replace `any` with type\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (val, entry: any) => jsonDiffer.applyPatch(val, entry).newDocument,\n ) as TransactionMeta;\n}\n\n/**\n * Clone the transaction meta data without the history property.\n *\n * @param transactionMeta - The transaction metadata to snapshot.\n * @returns A deep clone of transaction metadata without history property.\n */\nfunction snapshotFromTransactionMeta(\n transactionMeta: TransactionMeta,\n): TransactionMeta {\n const snapshot = { ...transactionMeta };\n delete snapshot.history;\n return cloneD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
throw TypeError("Cannot " + msg);
|
|
4
|
+
};
|
|
5
|
+
var __privateGet = (obj, member, getter) => {
|
|
6
|
+
__accessCheck(obj, member, "read from private field");
|
|
7
|
+
return getter ? getter.call(obj) : member.get(obj);
|
|
8
|
+
};
|
|
9
|
+
var __privateAdd = (obj, member, value) => {
|
|
10
|
+
if (member.has(obj))
|
|
11
|
+
throw TypeError("Cannot add the same private member more than once");
|
|
12
|
+
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
13
|
+
};
|
|
14
|
+
var __privateSet = (obj, member, value, setter) => {
|
|
15
|
+
__accessCheck(obj, member, "write to private field");
|
|
16
|
+
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
17
|
+
return value;
|
|
18
|
+
};
|
|
19
|
+
var __privateMethod = (obj, member, method) => {
|
|
20
|
+
__accessCheck(obj, member, "access private method");
|
|
21
|
+
return method;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export {
|
|
25
|
+
__privateGet,
|
|
26
|
+
__privateAdd,
|
|
27
|
+
__privateSet,
|
|
28
|
+
__privateMethod
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=chunk-XUI43LEZ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|