@metamask-previews/transaction-controller 61.0.0-preview-14bbab23 → 61.1.0-preview-79b6f72

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 CHANGED
@@ -9,10 +9,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Added
11
11
 
12
+ - Calculate operator fee for OP stack networks and include it in `layer1GasFee` ([#6979](https://github.com/MetaMask/core/pull/6979))
13
+
14
+ ## [61.1.0]
15
+
16
+ ### Added
17
+
12
18
  - Add optional `isIntentComplete` property to `TransactionMeta` to indicate transaction outcome was achieved via an alternate chain or mechanism ([#6950](https://github.com/MetaMask/core/pull/6950))
13
19
 
14
20
  ### Changed
15
21
 
22
+ - Bump `@metamask/controller-utils` from `^11.14.1` to `^11.15.0` ([#7003](https://github.com/MetaMask/core/pull/7003))
16
23
  - Identify OP stack chains using gas API ([#6899](https://github.com/MetaMask/core/pull/6899))
17
24
 
18
25
  ## [61.0.0]
@@ -1913,7 +1920,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1913
1920
 
1914
1921
  All changes listed after this point were applied to this package following the monorepo conversion.
1915
1922
 
1916
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/transaction-controller@61.0.0...HEAD
1923
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/transaction-controller@61.1.0...HEAD
1924
+ [61.1.0]: https://github.com/MetaMask/core/compare/@metamask/transaction-controller@61.0.0...@metamask/transaction-controller@61.1.0
1917
1925
  [61.0.0]: https://github.com/MetaMask/core/compare/@metamask/transaction-controller@60.10.0...@metamask/transaction-controller@61.0.0
1918
1926
  [60.10.0]: https://github.com/MetaMask/core/compare/@metamask/transaction-controller@60.9.0...@metamask/transaction-controller@60.10.0
1919
1927
  [60.9.0]: https://github.com/MetaMask/core/compare/@metamask/transaction-controller@60.8.0...@metamask/transaction-controller@60.9.0
@@ -4,21 +4,59 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
4
4
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
5
5
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
6
6
  };
7
- var _OracleLayer1GasFeeFlow_instances, _OracleLayer1GasFeeFlow_getOracleLayer1GasFee, _OracleLayer1GasFeeFlow_buildUnserializedTransaction, _OracleLayer1GasFeeFlow_buildTransactionParams;
7
+ var __importDefault = (this && this.__importDefault) || function (mod) {
8
+ return (mod && mod.__esModule) ? mod : { "default": mod };
9
+ };
10
+ var _OracleLayer1GasFeeFlow_instances, _OracleLayer1GasFeeFlow_getOracleLayer1GasFee, _OracleLayer1GasFeeFlow_getOperatorLayer1GasFee, _OracleLayer1GasFeeFlow_buildUnserializedTransaction, _OracleLayer1GasFeeFlow_buildTransactionParams, _OracleLayer1GasFeeFlow_getGasPriceOracleContract;
8
11
  Object.defineProperty(exports, "__esModule", { value: true });
9
12
  exports.OracleLayer1GasFeeFlow = void 0;
10
13
  const contracts_1 = require("@ethersproject/contracts");
11
14
  const providers_1 = require("@ethersproject/providers");
12
15
  const utils_1 = require("@metamask/utils");
16
+ const bn_js_1 = __importDefault(require("bn.js"));
13
17
  const logger_1 = require("../logger.cjs");
14
18
  const prepare_1 = require("../utils/prepare.cjs");
19
+ const utils_2 = require("../utils/utils.cjs");
15
20
  const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'oracle-layer1-gas-fee-flow');
21
+ const ZERO = new bn_js_1.default(0);
16
22
  const DUMMY_KEY = 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';
17
23
  const GAS_PRICE_ORACLE_ABI = [
18
24
  {
19
- inputs: [{ internalType: 'bytes', name: '_data', type: 'bytes' }],
25
+ inputs: [
26
+ {
27
+ internalType: 'bytes',
28
+ name: '_data',
29
+ type: 'bytes',
30
+ },
31
+ ],
20
32
  name: 'getL1Fee',
21
- outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
33
+ outputs: [
34
+ {
35
+ internalType: 'uint256',
36
+ name: '',
37
+ type: 'uint256',
38
+ },
39
+ ],
40
+ stateMutability: 'view',
41
+ type: 'function',
42
+ },
43
+ // only available post Isthmus
44
+ {
45
+ inputs: [
46
+ {
47
+ internalType: 'uint256',
48
+ name: '_gasUsed',
49
+ type: 'uint256',
50
+ },
51
+ ],
52
+ name: 'getOperatorFee',
53
+ outputs: [
54
+ {
55
+ internalType: 'uint256',
56
+ name: '',
57
+ type: 'uint256',
58
+ },
59
+ ],
22
60
  stateMutability: 'view',
23
61
  type: 'function',
24
62
  },
@@ -57,7 +95,13 @@ class OracleLayer1GasFeeFlow {
57
95
  }
58
96
  async getLayer1Fee(request) {
59
97
  try {
60
- return await __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_getOracleLayer1GasFee).call(this, request);
98
+ const { provider, transactionMeta } = request;
99
+ const contract = __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_getGasPriceOracleContract).call(this, provider, transactionMeta.chainId);
100
+ const oracleFee = await __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_getOracleLayer1GasFee).call(this, contract, transactionMeta);
101
+ const operatorFee = await __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_getOperatorLayer1GasFee).call(this, contract, transactionMeta);
102
+ return {
103
+ layer1Fee: (0, utils_1.add0x)((0, utils_2.padHexToEvenLength)(oracleFee.add(operatorFee).toString(16))),
104
+ };
61
105
  }
62
106
  catch (error) {
63
107
  log('Failed to get oracle layer 1 gas fee', error);
@@ -66,19 +110,29 @@ class OracleLayer1GasFeeFlow {
66
110
  }
67
111
  }
68
112
  exports.OracleLayer1GasFeeFlow = OracleLayer1GasFeeFlow;
69
- _OracleLayer1GasFeeFlow_instances = new WeakSet(), _OracleLayer1GasFeeFlow_getOracleLayer1GasFee = async function _OracleLayer1GasFeeFlow_getOracleLayer1GasFee(request) {
70
- const { provider, transactionMeta } = request;
71
- const contract = new contracts_1.Contract(this.getOracleAddressForChain(transactionMeta.chainId), GAS_PRICE_ORACLE_ABI,
72
- // Network controller provider type is incompatible with ethers provider
73
- new providers_1.Web3Provider(provider));
113
+ _OracleLayer1GasFeeFlow_instances = new WeakSet(), _OracleLayer1GasFeeFlow_getOracleLayer1GasFee = async function _OracleLayer1GasFeeFlow_getOracleLayer1GasFee(contract, transactionMeta) {
74
114
  const serializedTransaction = __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_buildUnserializedTransaction).call(this, transactionMeta, this.shouldSignTransaction()).serialize();
75
115
  const result = await contract.getL1Fee(serializedTransaction);
76
116
  if (result === undefined) {
77
117
  throw new Error('No value returned from oracle contract');
78
118
  }
79
- return {
80
- layer1Fee: result.toHexString(),
81
- };
119
+ return (0, utils_2.toBN)(result);
120
+ }, _OracleLayer1GasFeeFlow_getOperatorLayer1GasFee = async function _OracleLayer1GasFeeFlow_getOperatorLayer1GasFee(contract, transactionMeta) {
121
+ const { gasUsed } = transactionMeta;
122
+ if (!gasUsed) {
123
+ return ZERO;
124
+ }
125
+ try {
126
+ const result = await contract.getOperatorFee(gasUsed);
127
+ if (result === undefined) {
128
+ return ZERO;
129
+ }
130
+ return (0, utils_2.toBN)(result);
131
+ }
132
+ catch (error) {
133
+ log('Failed to get operator layer 1 gas fee', error);
134
+ return ZERO;
135
+ }
82
136
  }, _OracleLayer1GasFeeFlow_buildUnserializedTransaction = function _OracleLayer1GasFeeFlow_buildUnserializedTransaction(transactionMeta, sign) {
83
137
  const txParams = __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_buildTransactionParams).call(this, transactionMeta);
84
138
  const { chainId } = transactionMeta;
@@ -94,5 +148,9 @@ _OracleLayer1GasFeeFlow_instances = new WeakSet(), _OracleLayer1GasFeeFlow_getOr
94
148
  ...transactionMeta.txParams,
95
149
  gasLimit: transactionMeta.txParams.gas,
96
150
  };
151
+ }, _OracleLayer1GasFeeFlow_getGasPriceOracleContract = function _OracleLayer1GasFeeFlow_getGasPriceOracleContract(provider, chainId) {
152
+ return new contracts_1.Contract(this.getOracleAddressForChain(chainId), GAS_PRICE_ORACLE_ABI,
153
+ // Network controller provider type is incompatible with ethers provider
154
+ new providers_1.Web3Provider(provider));
97
155
  };
98
156
  //# sourceMappingURL=OracleLayer1GasFeeFlow.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"OracleLayer1GasFeeFlow.cjs","sourceRoot":"","sources":["../../src/gas-flows/OracleLayer1GasFeeFlow.ts"],"names":[],"mappings":";;;;;;;;;AAAA,wDAAoD;AACpD,wDAA+E;AAE/E,2CAAqD;AAErD,0CAA0C;AAQ1C,kDAAsD;AAEtD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,4BAA4B,CAAC,CAAC;AAE5E,MAAM,SAAS,GACb,kEAAkE,CAAC;AAErE,MAAM,oBAAoB,GAAG;IAC3B;QACE,MAAM,EAAE,CAAC,EAAE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QACjE,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE,CAAC,EAAE,YAAY,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;QACjE,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KACjB;CACF,CAAC;AAEF,2EAA2E;AAC3E,MAAM,gCAAgC,GACpC,4CAAmD,CAAC;AAEtD;;GAEG;AACH,MAAsB,sBAAsB;IAA5C;;IAmGA,CAAC;IAlGC;;;;;;;OAOG;IACO,wBAAwB,CAAC,QAAa;QAC9C,OAAO,gCAAgC,CAAC;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kB,EAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAEpE,IAAI,IAAI,EAAE;QACR,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QAChD,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC5C,uBAAuB,GAAG,uBAAuB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;KAClE;IAED,OAAO,uBAAuB,CAAC;AACjC,CAAC,2GAGC,eAAgC;IAEhC,OAAO;QACL,GAAG,eAAe,CAAC,QAAQ;QAC3B,QAAQ,EAAE,eAAe,CAAC,QAAQ,CAAC,GAAG;KACvC,CAAC;AACJ,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider, type ExternalProvider } from '@ethersproject/providers';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n Layer1GasFeeFlow,\n Layer1GasFeeFlowRequest,\n Layer1GasFeeFlowResponse,\n TransactionMeta,\n} from '../types';\nimport { prepareTransaction } from '../utils/prepare';\n\nconst log = createModuleLogger(projectLogger, 'oracle-layer1-gas-fee-flow');\n\nconst DUMMY_KEY =\n 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';\n\nconst GAS_PRICE_ORACLE_ABI = [\n {\n inputs: [{ internalType: 'bytes', name: '_data', type: 'bytes' }],\n name: 'getL1Fee',\n outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n];\n\n// Default OP Stack gas price oracle address used across supported networks\nconst DEFAULT_GAS_PRICE_ORACLE_ADDRESS =\n '0x420000000000000000000000000000000000000F' as Hex;\n\n/**\n * Layer 1 gas fee flow that obtains gas fee estimate using an oracle smart contract.\n */\nexport abstract class OracleLayer1GasFeeFlow implements Layer1GasFeeFlow {\n /**\n * Resolves the oracle address for the given chain. Subclasses can override\n * this method to provide chain-specific oracle addresses. By default, this\n * returns the standard OP Stack gas price oracle address.\n *\n * @param _chainId - The chain ID to resolve the oracle address for.\n * @returns The oracle address for the given chain.\n */\n protected getOracleAddressForChain(_chainId: Hex): Hex {\n return DEFAULT_GAS_PRICE_ORACLE_ADDRESS;\n }\n\n /**\n * Whether to sign the transaction with a dummy key prior to calling the\n * oracle contract. Some oracle contracts require a signed payload even for\n * read-only methods.\n *\n * Subclasses can override to enable signing when needed. Defaults to false.\n *\n * @returns Whether the transaction should be signed prior to the oracle call.\n */\n protected shouldSignTransaction(): boolean {\n return false;\n }\n\n abstract matchesTransaction({\n transactionMeta,\n messenger,\n }: {\n transactionMeta: TransactionMeta;\n messenger: TransactionControllerMessenger;\n }): Promise<boolean>;\n\n async getLayer1Fee(\n request: Layer1GasFeeFlowRequest,\n ): Promise<Layer1GasFeeFlowResponse> {\n try {\n return await this.#getOracleLayer1GasFee(request);\n } catch (error) {\n log('Failed to get oracle layer 1 gas fee', error);\n throw new Error(`Failed to get oracle layer 1 gas fee`);\n }\n }\n\n async #getOracleLayer1GasFee(\n request: Layer1GasFeeFlowRequest,\n ): Promise<Layer1GasFeeFlowResponse> {\n const { provider, transactionMeta } = request;\n\n const contract = new Contract(\n this.getOracleAddressForChain(transactionMeta.chainId),\n GAS_PRICE_ORACLE_ABI,\n // Network controller provider type is incompatible with ethers provider\n new Web3Provider(provider as unknown as ExternalProvider),\n );\n\n const serializedTransaction = this.#buildUnserializedTransaction(\n transactionMeta,\n this.shouldSignTransaction(),\n ).serialize();\n\n const result = await contract.getL1Fee(serializedTransaction);\n\n if (result === undefined) {\n throw new Error('No value returned from oracle contract');\n }\n\n return {\n layer1Fee: result.toHexString(),\n };\n }\n\n #buildUnserializedTransaction(\n transactionMeta: TransactionMeta,\n sign: boolean,\n ) {\n const txParams = this.#buildTransactionParams(transactionMeta);\n const { chainId } = transactionMeta;\n\n let unserializedTransaction = prepareTransaction(chainId, txParams);\n\n if (sign) {\n const keyBuffer = Buffer.from(DUMMY_KEY, 'hex');\n const keyBytes = Uint8Array.from(keyBuffer);\n unserializedTransaction = unserializedTransaction.sign(keyBytes);\n }\n\n return unserializedTransaction;\n }\n\n #buildTransactionParams(\n transactionMeta: TransactionMeta,\n ): TransactionMeta['txParams'] {\n return {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"OracleLayer1GasFeeFlow.cjs","sourceRoot":"","sources":["../../src/gas-flows/OracleLayer1GasFeeFlow.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,wDAAoD;AACpD,wDAA+E;AAE/E,2CAA4D;AAC5D,kDAAuB;AAEvB,0CAA0C;AAQ1C,kDAAsD;AACtD,8CAA0D;AAE1D,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,4BAA4B,CAAC,CAAC;AAE5E,MAAM,IAAI,GAAG,IAAI,eAAE,CAAC,CAAC,CAAC,CAAC;AAEvB,MAAM,SAAS,GACb,kEAAkE,CAAC;AAErE,MAAM,oBAAoB,GAAG;IAC3B;QACE,MAAM,EAAE;YACN;gBACE,YAAY,EAAE,OAAO;gBACrB,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,OAAO;aACd;SACF;QACD,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE;YACP;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,EAAE;gBACR,IAAI,EAAE,SAAS;aAChB;SACF;QACD,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KACjB;IACD,8BAA8B;IAC9B;QACE,MAAM,EAAE;YACN;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,UAAU;gBAChB,IAAI,EAAE,SAAS;aAChB;SACF;QACD,IAAI,EAAE,gBAAgB;QACtB,OAAO,EAAE;YACP;gBACE,YAAY,EAAE,SAAS;gBACvB,IAAI,EAAE,EAAE;gBACR,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E;IAED,OAAO,uBAAuB,CAAC;AACjC,CAAC,2GAGC,eAAgC;IAEhC,OAAO;QACL,GAAG,eAAe,CAAC,QAAQ;QAC3B,QAAQ,EAAE,eAAe,CAAC,QAAQ,CAAC,GAAG;KACvC,CAAC;AACJ,CAAC,iHAGC,QAA6C,EAC7C,OAAY;IAEZ,OAAO,IAAI,oBAAQ,CACjB,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAAC,EACtC,oBAAoB;IACpB,wEAAwE;IACxE,IAAI,wBAAY,CAAC,QAAuC,CAAC,CAC1D,CAAC;AACJ,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider, type ExternalProvider } from '@ethersproject/providers';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n Layer1GasFeeFlow,\n Layer1GasFeeFlowRequest,\n Layer1GasFeeFlowResponse,\n TransactionMeta,\n} from '../types';\nimport { prepareTransaction } from '../utils/prepare';\nimport { padHexToEvenLength, toBN } from '../utils/utils';\n\nconst log = createModuleLogger(projectLogger, 'oracle-layer1-gas-fee-flow');\n\nconst ZERO = new BN(0);\n\nconst DUMMY_KEY =\n 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';\n\nconst GAS_PRICE_ORACLE_ABI = [\n {\n inputs: [\n {\n internalType: 'bytes',\n name: '_data',\n type: 'bytes',\n },\n ],\n name: 'getL1Fee',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n // only available post Isthmus\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '_gasUsed',\n type: 'uint256',\n },\n ],\n name: 'getOperatorFee',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n];\n\n// Default OP Stack gas price oracle address used across supported networks\nconst DEFAULT_GAS_PRICE_ORACLE_ADDRESS =\n '0x420000000000000000000000000000000000000F' as Hex;\n\n/**\n * Layer 1 gas fee flow that obtains gas fee estimate using an oracle smart contract.\n */\nexport abstract class OracleLayer1GasFeeFlow implements Layer1GasFeeFlow {\n /**\n * Resolves the oracle address for the given chain. Subclasses can override\n * this method to provide chain-specific oracle addresses. By default, this\n * returns the standard OP Stack gas price oracle address.\n *\n * @param _chainId - The chain ID to resolve the oracle address for.\n * @returns The oracle address for the given chain.\n */\n protected getOracleAddressForChain(_chainId: Hex): Hex {\n return DEFAULT_GAS_PRICE_ORACLE_ADDRESS;\n }\n\n /**\n * Whether to sign the transaction with a dummy key prior to calling the\n * oracle contract. Some oracle contracts require a signed payload even for\n * read-only methods.\n *\n * Subclasses can override to enable signing when needed. Defaults to false.\n *\n * @returns Whether the transaction should be signed prior to the oracle call.\n */\n protected shouldSignTransaction(): boolean {\n return false;\n }\n\n abstract matchesTransaction({\n transactionMeta,\n messenger,\n }: {\n transactionMeta: TransactionMeta;\n messenger: TransactionControllerMessenger;\n }): Promise<boolean>;\n\n async getLayer1Fee(\n request: Layer1GasFeeFlowRequest,\n ): Promise<Layer1GasFeeFlowResponse> {\n try {\n const { provider, transactionMeta } = request;\n\n const contract = this.#getGasPriceOracleContract(\n provider,\n transactionMeta.chainId,\n );\n\n const oracleFee = await this.#getOracleLayer1GasFee(\n contract,\n transactionMeta,\n );\n const operatorFee = await this.#getOperatorLayer1GasFee(\n contract,\n transactionMeta,\n );\n\n return {\n layer1Fee: add0x(\n padHexToEvenLength(oracleFee.add(operatorFee).toString(16)),\n ) as Hex,\n };\n } catch (error) {\n log('Failed to get oracle layer 1 gas fee', error);\n throw new Error(`Failed to get oracle layer 1 gas fee`);\n }\n }\n\n async #getOracleLayer1GasFee(\n contract: Contract,\n transactionMeta: TransactionMeta,\n ): Promise<BN> {\n const serializedTransaction = this.#buildUnserializedTransaction(\n transactionMeta,\n this.shouldSignTransaction(),\n ).serialize();\n\n const result = await contract.getL1Fee(serializedTransaction);\n\n if (result === undefined) {\n throw new Error('No value returned from oracle contract');\n }\n\n return toBN(result);\n }\n\n async #getOperatorLayer1GasFee(\n contract: Contract,\n transactionMeta: TransactionMeta,\n ): Promise<BN> {\n const { gasUsed } = transactionMeta;\n\n if (!gasUsed) {\n return ZERO;\n }\n\n try {\n const result = await contract.getOperatorFee(gasUsed);\n\n if (result === undefined) {\n return ZERO;\n }\n\n return toBN(result);\n } catch (error) {\n log('Failed to get operator layer 1 gas fee', error);\n return ZERO;\n }\n }\n\n #buildUnserializedTransaction(\n transactionMeta: TransactionMeta,\n sign: boolean,\n ) {\n const txParams = this.#buildTransactionParams(transactionMeta);\n const { chainId } = transactionMeta;\n\n let unserializedTransaction = prepareTransaction(chainId, txParams);\n\n if (sign) {\n const keyBuffer = Buffer.from(DUMMY_KEY, 'hex');\n const keyBytes = Uint8Array.from(keyBuffer);\n unserializedTransaction = unserializedTransaction.sign(keyBytes);\n }\n\n return unserializedTransaction;\n }\n\n #buildTransactionParams(\n transactionMeta: TransactionMeta,\n ): TransactionMeta['txParams'] {\n return {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n };\n }\n\n #getGasPriceOracleContract(\n provider: Layer1GasFeeFlowRequest['provider'],\n chainId: Hex,\n ) {\n return new Contract(\n this.getOracleAddressForChain(chainId),\n GAS_PRICE_ORACLE_ABI,\n // Network controller provider type is incompatible with ethers provider\n new Web3Provider(provider as unknown as ExternalProvider),\n );\n }\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"OracleLayer1GasFeeFlow.d.cts","sourceRoot":"","sources":["../../src/gas-flows/OracleLayer1GasFeeFlow.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EACV,gBAAgB,EAChB,uBAAuB,EACvB,wBAAwB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"OracleLayer1GasFeeFlow.d.mts","sourceRoot":"","sources":["../../src/gas-flows/OracleLayer1GasFeeFlow.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EACV,gBAAgB,EAChB,uBAAuB,EACvB,wBAAwB,EACxB,eAAe,EAChB,qBAAiB;AAsBlB;;GAEG;AACH,8BAAsB,sBAAuB,YAAW,gBAAgB;;IACtE;;;;;;;OAOG;IACH,SAAS,CAAC,wBAAwB,CAAC,QAAQ,EAAE,GAAG,GAAG,GAAG;IAItD;;;;;;;;OAQG;IACH,SAAS,CAAC,qBAAqB,IAAI,OAAO;IAI1C,QAAQ,CAAC,kBAAkB,CAAC,EAC1B,eAAe,EACf,SAAS,GACV,EAAE;QACD,eAAe,EAAE,eAAe,CAAC;QACjC,SAAS,EAAE,8BAA8B,CAAC;KAC3C,GAAG,OAAO,CAAC,OAAO,CAAC;IAEd,YAAY,CAChB,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,wBAAwB,CAAC;CA+DrC"}
1
+ {"version":3,"file":"OracleLayer1GasFeeFlow.d.mts","sourceRoot":"","sources":["../../src/gas-flows/OracleLayer1GasFeeFlow.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAK3C,OAAO,KAAK,EAAE,8BAA8B,EAAE,qCAAiC;AAC/E,OAAO,KAAK,EACV,gBAAgB,EAChB,uBAAuB,EACvB,wBAAwB,EACxB,eAAe,EAChB,qBAAiB;AAyDlB;;GAEG;AACH,8BAAsB,sBAAuB,YAAW,gBAAgB;;IACtE;;;;;;;OAOG;IACH,SAAS,CAAC,wBAAwB,CAAC,QAAQ,EAAE,GAAG,GAAG,GAAG;IAItD;;;;;;;;OAQG;IACH,SAAS,CAAC,qBAAqB,IAAI,OAAO;IAI1C,QAAQ,CAAC,kBAAkB,CAAC,EAC1B,eAAe,EACf,SAAS,GACV,EAAE;QACD,eAAe,EAAE,eAAe,CAAC;QACjC,SAAS,EAAE,8BAA8B,CAAC;KAC3C,GAAG,OAAO,CAAC,OAAO,CAAC;IAEd,YAAY,CAChB,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,wBAAwB,CAAC;CA6GrC"}
@@ -3,19 +3,61 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
3
3
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
4
4
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
5
5
  };
6
- var _OracleLayer1GasFeeFlow_instances, _OracleLayer1GasFeeFlow_getOracleLayer1GasFee, _OracleLayer1GasFeeFlow_buildUnserializedTransaction, _OracleLayer1GasFeeFlow_buildTransactionParams;
6
+ var _OracleLayer1GasFeeFlow_instances, _OracleLayer1GasFeeFlow_getOracleLayer1GasFee, _OracleLayer1GasFeeFlow_getOperatorLayer1GasFee, _OracleLayer1GasFeeFlow_buildUnserializedTransaction, _OracleLayer1GasFeeFlow_buildTransactionParams, _OracleLayer1GasFeeFlow_getGasPriceOracleContract;
7
+ function $importDefault(module) {
8
+ if (module?.__esModule) {
9
+ return module.default;
10
+ }
11
+ return module;
12
+ }
7
13
  import { Contract } from "@ethersproject/contracts";
8
14
  import { Web3Provider } from "@ethersproject/providers";
9
- import { createModuleLogger } from "@metamask/utils";
15
+ import { add0x, createModuleLogger } from "@metamask/utils";
16
+ import $BN from "bn.js";
17
+ const BN = $importDefault($BN);
10
18
  import { projectLogger } from "../logger.mjs";
11
19
  import { prepareTransaction } from "../utils/prepare.mjs";
20
+ import { padHexToEvenLength, toBN } from "../utils/utils.mjs";
12
21
  const log = createModuleLogger(projectLogger, 'oracle-layer1-gas-fee-flow');
22
+ const ZERO = new BN(0);
13
23
  const DUMMY_KEY = 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';
14
24
  const GAS_PRICE_ORACLE_ABI = [
15
25
  {
16
- inputs: [{ internalType: 'bytes', name: '_data', type: 'bytes' }],
26
+ inputs: [
27
+ {
28
+ internalType: 'bytes',
29
+ name: '_data',
30
+ type: 'bytes',
31
+ },
32
+ ],
17
33
  name: 'getL1Fee',
18
- outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],
34
+ outputs: [
35
+ {
36
+ internalType: 'uint256',
37
+ name: '',
38
+ type: 'uint256',
39
+ },
40
+ ],
41
+ stateMutability: 'view',
42
+ type: 'function',
43
+ },
44
+ // only available post Isthmus
45
+ {
46
+ inputs: [
47
+ {
48
+ internalType: 'uint256',
49
+ name: '_gasUsed',
50
+ type: 'uint256',
51
+ },
52
+ ],
53
+ name: 'getOperatorFee',
54
+ outputs: [
55
+ {
56
+ internalType: 'uint256',
57
+ name: '',
58
+ type: 'uint256',
59
+ },
60
+ ],
19
61
  stateMutability: 'view',
20
62
  type: 'function',
21
63
  },
@@ -54,7 +96,13 @@ export class OracleLayer1GasFeeFlow {
54
96
  }
55
97
  async getLayer1Fee(request) {
56
98
  try {
57
- return await __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_getOracleLayer1GasFee).call(this, request);
99
+ const { provider, transactionMeta } = request;
100
+ const contract = __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_getGasPriceOracleContract).call(this, provider, transactionMeta.chainId);
101
+ const oracleFee = await __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_getOracleLayer1GasFee).call(this, contract, transactionMeta);
102
+ const operatorFee = await __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_getOperatorLayer1GasFee).call(this, contract, transactionMeta);
103
+ return {
104
+ layer1Fee: add0x(padHexToEvenLength(oracleFee.add(operatorFee).toString(16))),
105
+ };
58
106
  }
59
107
  catch (error) {
60
108
  log('Failed to get oracle layer 1 gas fee', error);
@@ -62,19 +110,29 @@ export class OracleLayer1GasFeeFlow {
62
110
  }
63
111
  }
64
112
  }
65
- _OracleLayer1GasFeeFlow_instances = new WeakSet(), _OracleLayer1GasFeeFlow_getOracleLayer1GasFee = async function _OracleLayer1GasFeeFlow_getOracleLayer1GasFee(request) {
66
- const { provider, transactionMeta } = request;
67
- const contract = new Contract(this.getOracleAddressForChain(transactionMeta.chainId), GAS_PRICE_ORACLE_ABI,
68
- // Network controller provider type is incompatible with ethers provider
69
- new Web3Provider(provider));
113
+ _OracleLayer1GasFeeFlow_instances = new WeakSet(), _OracleLayer1GasFeeFlow_getOracleLayer1GasFee = async function _OracleLayer1GasFeeFlow_getOracleLayer1GasFee(contract, transactionMeta) {
70
114
  const serializedTransaction = __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_buildUnserializedTransaction).call(this, transactionMeta, this.shouldSignTransaction()).serialize();
71
115
  const result = await contract.getL1Fee(serializedTransaction);
72
116
  if (result === undefined) {
73
117
  throw new Error('No value returned from oracle contract');
74
118
  }
75
- return {
76
- layer1Fee: result.toHexString(),
77
- };
119
+ return toBN(result);
120
+ }, _OracleLayer1GasFeeFlow_getOperatorLayer1GasFee = async function _OracleLayer1GasFeeFlow_getOperatorLayer1GasFee(contract, transactionMeta) {
121
+ const { gasUsed } = transactionMeta;
122
+ if (!gasUsed) {
123
+ return ZERO;
124
+ }
125
+ try {
126
+ const result = await contract.getOperatorFee(gasUsed);
127
+ if (result === undefined) {
128
+ return ZERO;
129
+ }
130
+ return toBN(result);
131
+ }
132
+ catch (error) {
133
+ log('Failed to get operator layer 1 gas fee', error);
134
+ return ZERO;
135
+ }
78
136
  }, _OracleLayer1GasFeeFlow_buildUnserializedTransaction = function _OracleLayer1GasFeeFlow_buildUnserializedTransaction(transactionMeta, sign) {
79
137
  const txParams = __classPrivateFieldGet(this, _OracleLayer1GasFeeFlow_instances, "m", _OracleLayer1GasFeeFlow_buildTransactionParams).call(this, transactionMeta);
80
138
  const { chainId } = transactionMeta;
@@ -90,5 +148,9 @@ _OracleLayer1GasFeeFlow_instances = new WeakSet(), _OracleLayer1GasFeeFlow_getOr
90
148
  ...transactionMeta.txParams,
91
149
  gasLimit: transactionMeta.txParams.gas,
92
150
  };
151
+ }, _OracleLayer1GasFeeFlow_getGasPriceOracleContract = function _OracleLayer1GasFeeFlow_getGasPriceOracleContract(provider, chainId) {
152
+ return new Contract(this.getOracleAddressForChain(chainId), GAS_PRICE_ORACLE_ABI,
153
+ // Network controller provider type is incompatible with ethers provider
154
+ new Web3Provider(provider));
93
155
  };
94
156
  //# sourceMappingURL=OracleLayer1GasFeeFlow.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"OracleLayer1GasFeeFlow.mjs","sourceRoot":"","sources":["../../src/gas-flows/OracleLayer1GasFeeFlow.ts"],"names":[],"mappings":";;;;;;AAAA,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,YAAY,EAAyB,iCAAiC;AAE/E,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAQ1C,OAAO,EAAE,kBAAkB,EAAE,6BAAyB;AAEtD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,4BAA4B,CAAC,CAAC;AAE5E,MAAM,SAAS,GACb,kEAAkE,CAAC;AAErE,MAAM,oBAAoB,GAAG;IAC3B;QACE,MAAM,EAAE,CAAC,EAAE,YAAY,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;QACjE,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE,CAAC,EAAE,YAAY,EAAE,SAAS,EAAE,IAAI,EAAE,EAAE,EAAE,IAAI,EAAE,SAAS,EAAE,CAAC;QACjE,eAAe,EAAE,MAAM;QACvB,IAAI,EAAE,UAAU;KACjB;C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AChC,IAAa;IAEb,MAAM,QAAQ,GAAG,uBAAA,IAAI,yFAAwB,MAA5B,IAAI,EAAyB,eAAe,CAAC,CAAC;IAC/D,MAAM,EAAE,OAAO,EAAE,GAAG,eAAe,CAAC;IAEpC,IAAI,uBAAuB,GAAG,kBAAkB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAEpE,IAAI,IAAI,EAAE;QACR,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QAChD,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC5C,uBAAuB,GAAG,uBAAuB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;KAClE;IAED,OAAO,uBAAuB,CAAC;AACjC,CAAC,2GAGC,eAAgC;IAEhC,OAAO;QACL,GAAG,eAAe,CAAC,QAAQ;QAC3B,QAAQ,EAAE,eAAe,CAAC,QAAQ,CAAC,GAAG;KACvC,CAAC;AACJ,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider, type ExternalProvider } from '@ethersproject/providers';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n Layer1GasFeeFlow,\n Layer1GasFeeFlowRequest,\n Layer1GasFeeFlowResponse,\n TransactionMeta,\n} from '../types';\nimport { prepareTransaction } from '../utils/prepare';\n\nconst log = createModuleLogger(projectLogger, 'oracle-layer1-gas-fee-flow');\n\nconst DUMMY_KEY =\n 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';\n\nconst GAS_PRICE_ORACLE_ABI = [\n {\n inputs: [{ internalType: 'bytes', name: '_data', type: 'bytes' }],\n name: 'getL1Fee',\n outputs: [{ internalType: 'uint256', name: '', type: 'uint256' }],\n stateMutability: 'view',\n type: 'function',\n },\n];\n\n// Default OP Stack gas price oracle address used across supported networks\nconst DEFAULT_GAS_PRICE_ORACLE_ADDRESS =\n '0x420000000000000000000000000000000000000F' as Hex;\n\n/**\n * Layer 1 gas fee flow that obtains gas fee estimate using an oracle smart contract.\n */\nexport abstract class OracleLayer1GasFeeFlow implements Layer1GasFeeFlow {\n /**\n * Resolves the oracle address for the given chain. Subclasses can override\n * this method to provide chain-specific oracle addresses. By default, this\n * returns the standard OP Stack gas price oracle address.\n *\n * @param _chainId - The chain ID to resolve the oracle address for.\n * @returns The oracle address for the given chain.\n */\n protected getOracleAddressForChain(_chainId: Hex): Hex {\n return DEFAULT_GAS_PRICE_ORACLE_ADDRESS;\n }\n\n /**\n * Whether to sign the transaction with a dummy key prior to calling the\n * oracle contract. Some oracle contracts require a signed payload even for\n * read-only methods.\n *\n * Subclasses can override to enable signing when needed. Defaults to false.\n *\n * @returns Whether the transaction should be signed prior to the oracle call.\n */\n protected shouldSignTransaction(): boolean {\n return false;\n }\n\n abstract matchesTransaction({\n transactionMeta,\n messenger,\n }: {\n transactionMeta: TransactionMeta;\n messenger: TransactionControllerMessenger;\n }): Promise<boolean>;\n\n async getLayer1Fee(\n request: Layer1GasFeeFlowRequest,\n ): Promise<Layer1GasFeeFlowResponse> {\n try {\n return await this.#getOracleLayer1GasFee(request);\n } catch (error) {\n log('Failed to get oracle layer 1 gas fee', error);\n throw new Error(`Failed to get oracle layer 1 gas fee`);\n }\n }\n\n async #getOracleLayer1GasFee(\n request: Layer1GasFeeFlowRequest,\n ): Promise<Layer1GasFeeFlowResponse> {\n const { provider, transactionMeta } = request;\n\n const contract = new Contract(\n this.getOracleAddressForChain(transactionMeta.chainId),\n GAS_PRICE_ORACLE_ABI,\n // Network controller provider type is incompatible with ethers provider\n new Web3Provider(provider as unknown as ExternalProvider),\n );\n\n const serializedTransaction = this.#buildUnserializedTransaction(\n transactionMeta,\n this.shouldSignTransaction(),\n ).serialize();\n\n const result = await contract.getL1Fee(serializedTransaction);\n\n if (result === undefined) {\n throw new Error('No value returned from oracle contract');\n }\n\n return {\n layer1Fee: result.toHexString(),\n };\n }\n\n #buildUnserializedTransaction(\n transactionMeta: TransactionMeta,\n sign: boolean,\n ) {\n const txParams = this.#buildTransactionParams(transactionMeta);\n const { chainId } = transactionMeta;\n\n let unserializedTransaction = prepareTransaction(chainId, txParams);\n\n if (sign) {\n const keyBuffer = Buffer.from(DUMMY_KEY, 'hex');\n const keyBytes = Uint8Array.from(keyBuffer);\n unserializedTransaction = unserializedTransaction.sign(keyBytes);\n }\n\n return unserializedTransaction;\n }\n\n #buildTransactionParams(\n transactionMeta: TransactionMeta,\n ): TransactionMeta['txParams'] {\n return {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n };\n }\n}\n"]}
1
+ {"version":3,"file":"OracleLayer1GasFeeFlow.mjs","sourceRoot":"","sources":["../../src/gas-flows/OracleLayer1GasFeeFlow.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,QAAQ,EAAE,iCAAiC;AACpD,OAAO,EAAE,YAAY,EAAyB,iCAAiC;AAE/E,OAAO,EAAE,KAAK,EAAE,kBAAkB,EAAE,wBAAwB;AAC5D,OAAO,GAAE,cAAc;;AAEvB,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAQ1C,OAAO,EAAE,kBAAkB,EAAE,6BAAyB;AACtD,OAAO,EAAE,kBAAkB,EAAE,IAAI,EAAE,2BAAuB;AAE1D,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,4BAA4B,CAAC,CAAC;AAE5E,MAAM,IAAI,GAAG,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;AAEvB,MAAM,SAAS,GACb,kEAAkE,CAAC;AAErE,MAAM,oBAAoB,GAAG;IAC3B;QACE,MAAM,EAAE;YACN;gBACE,YAAY,EAAE,OAAO;gBACrB,IAAI,EAAE,OAAO;gBACb,IAAI,EAAE,OAAO;aACd;SACF;QACD,IAAI,EAAE,UAAU;QAChB,OAAO,EAAE;YACP;gBACE,YA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CAAC;IAEpC,IAAI,uBAAuB,GAAG,kBAAkB,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;IAEpE,IAAI,IAAI,EAAE;QACR,MAAM,SAAS,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,EAAE,KAAK,CAAC,CAAC;QAChD,MAAM,QAAQ,GAAG,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC5C,uBAAuB,GAAG,uBAAuB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;KAClE;IAED,OAAO,uBAAuB,CAAC;AACjC,CAAC,2GAGC,eAAgC;IAEhC,OAAO;QACL,GAAG,eAAe,CAAC,QAAQ;QAC3B,QAAQ,EAAE,eAAe,CAAC,QAAQ,CAAC,GAAG;KACvC,CAAC;AACJ,CAAC,iHAGC,QAA6C,EAC7C,OAAY;IAEZ,OAAO,IAAI,QAAQ,CACjB,IAAI,CAAC,wBAAwB,CAAC,OAAO,CAAC,EACtC,oBAAoB;IACpB,wEAAwE;IACxE,IAAI,YAAY,CAAC,QAAuC,CAAC,CAC1D,CAAC;AACJ,CAAC","sourcesContent":["import { Contract } from '@ethersproject/contracts';\nimport { Web3Provider, type ExternalProvider } from '@ethersproject/providers';\nimport type { Hex } from '@metamask/utils';\nimport { add0x, createModuleLogger } from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionControllerMessenger } from '../TransactionController';\nimport type {\n Layer1GasFeeFlow,\n Layer1GasFeeFlowRequest,\n Layer1GasFeeFlowResponse,\n TransactionMeta,\n} from '../types';\nimport { prepareTransaction } from '../utils/prepare';\nimport { padHexToEvenLength, toBN } from '../utils/utils';\n\nconst log = createModuleLogger(projectLogger, 'oracle-layer1-gas-fee-flow');\n\nconst ZERO = new BN(0);\n\nconst DUMMY_KEY =\n 'abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789';\n\nconst GAS_PRICE_ORACLE_ABI = [\n {\n inputs: [\n {\n internalType: 'bytes',\n name: '_data',\n type: 'bytes',\n },\n ],\n name: 'getL1Fee',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n // only available post Isthmus\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '_gasUsed',\n type: 'uint256',\n },\n ],\n name: 'getOperatorFee',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n];\n\n// Default OP Stack gas price oracle address used across supported networks\nconst DEFAULT_GAS_PRICE_ORACLE_ADDRESS =\n '0x420000000000000000000000000000000000000F' as Hex;\n\n/**\n * Layer 1 gas fee flow that obtains gas fee estimate using an oracle smart contract.\n */\nexport abstract class OracleLayer1GasFeeFlow implements Layer1GasFeeFlow {\n /**\n * Resolves the oracle address for the given chain. Subclasses can override\n * this method to provide chain-specific oracle addresses. By default, this\n * returns the standard OP Stack gas price oracle address.\n *\n * @param _chainId - The chain ID to resolve the oracle address for.\n * @returns The oracle address for the given chain.\n */\n protected getOracleAddressForChain(_chainId: Hex): Hex {\n return DEFAULT_GAS_PRICE_ORACLE_ADDRESS;\n }\n\n /**\n * Whether to sign the transaction with a dummy key prior to calling the\n * oracle contract. Some oracle contracts require a signed payload even for\n * read-only methods.\n *\n * Subclasses can override to enable signing when needed. Defaults to false.\n *\n * @returns Whether the transaction should be signed prior to the oracle call.\n */\n protected shouldSignTransaction(): boolean {\n return false;\n }\n\n abstract matchesTransaction({\n transactionMeta,\n messenger,\n }: {\n transactionMeta: TransactionMeta;\n messenger: TransactionControllerMessenger;\n }): Promise<boolean>;\n\n async getLayer1Fee(\n request: Layer1GasFeeFlowRequest,\n ): Promise<Layer1GasFeeFlowResponse> {\n try {\n const { provider, transactionMeta } = request;\n\n const contract = this.#getGasPriceOracleContract(\n provider,\n transactionMeta.chainId,\n );\n\n const oracleFee = await this.#getOracleLayer1GasFee(\n contract,\n transactionMeta,\n );\n const operatorFee = await this.#getOperatorLayer1GasFee(\n contract,\n transactionMeta,\n );\n\n return {\n layer1Fee: add0x(\n padHexToEvenLength(oracleFee.add(operatorFee).toString(16)),\n ) as Hex,\n };\n } catch (error) {\n log('Failed to get oracle layer 1 gas fee', error);\n throw new Error(`Failed to get oracle layer 1 gas fee`);\n }\n }\n\n async #getOracleLayer1GasFee(\n contract: Contract,\n transactionMeta: TransactionMeta,\n ): Promise<BN> {\n const serializedTransaction = this.#buildUnserializedTransaction(\n transactionMeta,\n this.shouldSignTransaction(),\n ).serialize();\n\n const result = await contract.getL1Fee(serializedTransaction);\n\n if (result === undefined) {\n throw new Error('No value returned from oracle contract');\n }\n\n return toBN(result);\n }\n\n async #getOperatorLayer1GasFee(\n contract: Contract,\n transactionMeta: TransactionMeta,\n ): Promise<BN> {\n const { gasUsed } = transactionMeta;\n\n if (!gasUsed) {\n return ZERO;\n }\n\n try {\n const result = await contract.getOperatorFee(gasUsed);\n\n if (result === undefined) {\n return ZERO;\n }\n\n return toBN(result);\n } catch (error) {\n log('Failed to get operator layer 1 gas fee', error);\n return ZERO;\n }\n }\n\n #buildUnserializedTransaction(\n transactionMeta: TransactionMeta,\n sign: boolean,\n ) {\n const txParams = this.#buildTransactionParams(transactionMeta);\n const { chainId } = transactionMeta;\n\n let unserializedTransaction = prepareTransaction(chainId, txParams);\n\n if (sign) {\n const keyBuffer = Buffer.from(DUMMY_KEY, 'hex');\n const keyBytes = Uint8Array.from(keyBuffer);\n unserializedTransaction = unserializedTransaction.sign(keyBytes);\n }\n\n return unserializedTransaction;\n }\n\n #buildTransactionParams(\n transactionMeta: TransactionMeta,\n ): TransactionMeta['txParams'] {\n return {\n ...transactionMeta.txParams,\n gasLimit: transactionMeta.txParams.gas,\n };\n }\n\n #getGasPriceOracleContract(\n provider: Layer1GasFeeFlowRequest['provider'],\n chainId: Hex,\n ) {\n return new Contract(\n this.getOracleAddressForChain(chainId),\n GAS_PRICE_ORACLE_ABI,\n // Network controller provider type is incompatible with ethers provider\n new Web3Provider(provider as unknown as ExternalProvider),\n );\n }\n}\n"]}
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.setEnvelopeType = exports.getPercentageChange = exports.padHexToEvenLength = exports.normalizeGasFeeValues = exports.normalizeTxError = exports.validateIfTransactionUnapproved = exports.validateGasValues = exports.isEIP1559Transaction = exports.normalizeTransactionParams = exports.ESTIMATE_GAS_ERROR = void 0;
6
+ exports.setEnvelopeType = exports.getPercentageChange = exports.toBN = exports.bnFromHex = exports.padHexToEvenLength = exports.normalizeGasFeeValues = exports.normalizeTxError = exports.validateIfTransactionUnapproved = exports.validateGasValues = exports.isEIP1559Transaction = exports.normalizeTransactionParams = exports.ESTIMATE_GAS_ERROR = void 0;
7
7
  const utils_1 = require("@metamask/utils");
8
8
  const bn_js_1 = __importDefault(require("bn.js"));
9
9
  const types_1 = require("../types.cjs");
@@ -151,6 +151,59 @@ function padHexToEvenLength(hex) {
151
151
  return prefix + evenData;
152
152
  }
153
153
  exports.padHexToEvenLength = padHexToEvenLength;
154
+ /**
155
+ * Create a BN from a hex string, accepting an optional 0x prefix.
156
+ *
157
+ * @param hex - Hex string with or without 0x prefix.
158
+ * @returns BN parsed as base-16.
159
+ */
160
+ function bnFromHex(hex) {
161
+ const str = typeof hex === 'string' ? hex : hex;
162
+ const withoutPrefix = str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;
163
+ if (withoutPrefix.length === 0) {
164
+ return new bn_js_1.default(0);
165
+ }
166
+ return new bn_js_1.default(withoutPrefix, 16);
167
+ }
168
+ exports.bnFromHex = bnFromHex;
169
+ /**
170
+ * Convert various numeric-like values to a BN instance.
171
+ * Accepts BN, ethers BigNumber, hex string, bigint, or number.
172
+ *
173
+ * @param value - The value to convert.
174
+ * @returns BN representation of the input value.
175
+ */
176
+ function toBN(value) {
177
+ if (value instanceof bn_js_1.default) {
178
+ return value;
179
+ }
180
+ if (typeof bn_js_1.default.isBN ===
181
+ 'function' &&
182
+ bn_js_1.default.isBN(value)) {
183
+ return value;
184
+ }
185
+ if (value !== null &&
186
+ typeof value === 'object' &&
187
+ typeof value.toHexString === 'function') {
188
+ return bnFromHex(value.toHexString());
189
+ }
190
+ if (value !== null &&
191
+ typeof value === 'object' &&
192
+ typeof value._hex === 'string') {
193
+ return bnFromHex(value._hex);
194
+ }
195
+ if (typeof value === 'string') {
196
+ return bnFromHex(value);
197
+ }
198
+ if (typeof value === 'bigint') {
199
+ return new bn_js_1.default(value.toString());
200
+ }
201
+ if (typeof value === 'number') {
202
+ return new bn_js_1.default(value);
203
+ }
204
+ throw new Error('Unexpected value returned from oracle contract');
205
+ }
206
+ exports.toBN = toBN;
154
207
  /**
155
208
  * Calculate the absolute percentage change between two values.
156
209
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AACA,2CAIyB;AAEzB,kDAAuB;AAEvB,wCAAsE;AASzD,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAAE,EAAE,CAAC,UAAU;IACnD,iBAAiB,EAAE,CAAC,iBAAqC,EAAE,EAAE,CAC3D,iBAAiB;IACnB,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,IAAI,CAAC,CAAC,WAAW,EAAE;IACjD,GAAG,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,GAAG,CAAC;IAChC,QAAQ,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IAAA,aAAK,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iBAAiB,EAAE;QACrC,QAAQ,CAAC,IAAI,GAAG,+BAAuB,CAAC,OAAO,CAAC;KACjD;SAAM;QACL,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,+BAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,+BAAuB,CAAC,MAAM,CAAC;KACpC;AACH,CAAC;AAbD,0CAaC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport { TransactionEnvelopeType, TransactionStatus } from '../types';\nimport type {\n TransactionParams,\n TransactionMeta,\n TransactionError,\n GasPriceValue,\n FeeMarketEIP1559Values,\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 accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\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 if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\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\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\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
1
+ {"version":3,"file":"utils.cjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AAEA,2CAIyB;AACzB,kDAAuB;AASvB,wCAAsE;AAEzD,QAAA,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAAE,EAAE,CAAC,UAAU;IACnD,iBAAiB,EAAE,CAAC,iBAAqC,EAAE,EAAE,CAC3D,iBAAiB;IACnB,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,IAAI,CAAC,CAAC,WAAW,EAAE;IACjD,GAAG,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IAAA,aAAK,EAAC,GAAG,CAAC;IAChC,QAAQ,EAAE,CAAC,GAAW,EAAE,EAAE,CAAC,IA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CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC;AAC3E,CAAC;AAhBD,kDAgBC;AAED;;;;;;GAMG;AACH,SAAgB,eAAe,CAC7B,QAA2B,EAC3B,mBAA4B;IAE5B,IAAI,QAAQ,CAAC,UAAU,EAAE;QACvB,QAAQ,CAAC,IAAI,GAAG,+BAAuB,CAAC,UAAU,CAAC;KACpD;SAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE;QACrC,QAAQ,CAAC,IAAI,GAAG,+BAAuB,CAAC,OAAO,CAAC;KACjD;SAAM;QACL,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,+BAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,+BAAuB,CAAC,MAAM,CAAC;KACpC;AACH,CAAC;AAbD,0CAaC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionError,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { TransactionEnvelopeType, TransactionStatus } 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 accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\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 if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\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\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\n/**\n * Create a BN from a hex string, accepting an optional 0x prefix.\n *\n * @param hex - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hex: string | Hex): BN {\n const str = typeof hex === 'string' ? hex : (hex as string);\n const withoutPrefix =\n str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;\n if (withoutPrefix.length === 0) {\n return new BN(0);\n }\n return new BN(withoutPrefix, 16);\n}\n\n/**\n * Convert various numeric-like values to a BN instance.\n * Accepts BN, ethers BigNumber, hex string, bigint, or number.\n *\n * @param value - The value to convert.\n * @returns BN representation of the input value.\n */\nexport function toBN(value: unknown): BN {\n if (value instanceof BN) {\n return value as BN;\n }\n if (\n typeof (BN as unknown as { isBN?: (v: unknown) => boolean }).isBN ===\n 'function' &&\n (BN as unknown as { isBN: (v: unknown) => boolean }).isBN(value)\n ) {\n return value as BN;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { toHexString?: () => string }).toHexString === 'function'\n ) {\n return bnFromHex((value as { toHexString: () => string }).toHexString());\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { _hex?: string })._hex === 'string'\n ) {\n return bnFromHex((value as { _hex: string })._hex);\n }\n if (typeof value === 'string') {\n return bnFromHex(value);\n }\n if (typeof value === 'bigint') {\n return new BN(value.toString());\n }\n if (typeof value === 'number') {\n return new BN(value);\n }\n throw new Error('Unexpected value returned from oracle contract');\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
@@ -1,5 +1,6 @@
1
+ import type { Hex } from "@metamask/utils";
1
2
  import BN from "bn.js";
2
- import type { TransactionParams, TransactionMeta, TransactionError, GasPriceValue, FeeMarketEIP1559Values } from "../types.cjs";
3
+ import type { FeeMarketEIP1559Values, GasPriceValue, TransactionError, TransactionMeta, TransactionParams } from "../types.cjs";
3
4
  export declare const ESTIMATE_GAS_ERROR = "eth_estimateGas rpc method error";
4
5
  /**
5
6
  * Normalizes properties on transaction params.
@@ -50,6 +51,21 @@ export declare function normalizeGasFeeValues(gasFeeValues: GasPriceValue | FeeM
50
51
  * @returns The hex string with an even length.
51
52
  */
52
53
  export declare function padHexToEvenLength(hex: string): string;
54
+ /**
55
+ * Create a BN from a hex string, accepting an optional 0x prefix.
56
+ *
57
+ * @param hex - Hex string with or without 0x prefix.
58
+ * @returns BN parsed as base-16.
59
+ */
60
+ export declare function bnFromHex(hex: string | Hex): BN;
61
+ /**
62
+ * Convert various numeric-like values to a BN instance.
63
+ * Accepts BN, ethers BigNumber, hex string, bigint, or number.
64
+ *
65
+ * @param value - The value to convert.
66
+ * @returns BN representation of the input value.
67
+ */
68
+ export declare function toBN(value: unknown): BN;
53
69
  /**
54
70
  * Calculate the absolute percentage change between two values.
55
71
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,cAAc;AAGvB,OAAO,KAAK,EACV,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,sBAAsB,EACvB,qBAAiB;AAElB,eAAO,MAAM,kBAAkB,qCAAqC,CAAC;AAwBrE;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,iBAAiB,qBAkBrE;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,OAAO,CAOzE;AAED,eAAO,MAAM,iBAAiB,cACjB,aAAa,GAAG,sBAAsB,SAYlD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAC7C,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,QAOf;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,KAAK,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,GAChD,gBAAgB,CAQlB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,aAAa,GAAG,sBAAsB,GACnD,aAAa,GAAG,sBAAsB,CAgBxC;AAiBD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,UAM7C;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,GAAG,MAAM,CAgB3E;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,EAAE,OAAO,QAW7B"}
1
+ {"version":3,"file":"utils.d.cts","sourceRoot":"","sources":["../../src/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B,eAAe,CAC7B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,EAAE,OAAO,QAW7B"}
@@ -1,5 +1,6 @@
1
+ import type { Hex } from "@metamask/utils";
1
2
  import BN from "bn.js";
2
- import type { TransactionParams, TransactionMeta, TransactionError, GasPriceValue, FeeMarketEIP1559Values } from "../types.mjs";
3
+ import type { FeeMarketEIP1559Values, GasPriceValue, TransactionError, TransactionMeta, TransactionParams } from "../types.mjs";
3
4
  export declare const ESTIMATE_GAS_ERROR = "eth_estimateGas rpc method error";
4
5
  /**
5
6
  * Normalizes properties on transaction params.
@@ -50,6 +51,21 @@ export declare function normalizeGasFeeValues(gasFeeValues: GasPriceValue | FeeM
50
51
  * @returns The hex string with an even length.
51
52
  */
52
53
  export declare function padHexToEvenLength(hex: string): string;
54
+ /**
55
+ * Create a BN from a hex string, accepting an optional 0x prefix.
56
+ *
57
+ * @param hex - Hex string with or without 0x prefix.
58
+ * @returns BN parsed as base-16.
59
+ */
60
+ export declare function bnFromHex(hex: string | Hex): BN;
61
+ /**
62
+ * Convert various numeric-like values to a BN instance.
63
+ * Accepts BN, ethers BigNumber, hex string, bigint, or number.
64
+ *
65
+ * @param value - The value to convert.
66
+ * @returns BN representation of the input value.
67
+ */
68
+ export declare function toBN(value: unknown): BN;
53
69
  /**
54
70
  * Calculate the absolute percentage change between two values.
55
71
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,cAAc;AAGvB,OAAO,KAAK,EACV,iBAAiB,EACjB,eAAe,EACf,gBAAgB,EAChB,aAAa,EACb,sBAAsB,EACvB,qBAAiB;AAElB,eAAO,MAAM,kBAAkB,qCAAqC,CAAC;AAwBrE;;;;;GAKG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,iBAAiB,qBAkBrE;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAA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jB,aAAa,GAAG,sBAAsB,SAYlD,CAAC;AAEF;;;;;;GAMG;AACH,wBAAgB,+BAA+B,CAC7C,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,MAAM,EAAE,MAAM,QAOf;AAED;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,KAAK,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,OAAO,CAAA;CAAE,GAChD,gBAAgB,CAQlB;AAED;;;;;GAKG;AACH,wBAAgB,qBAAqB,CACnC,YAAY,EAAE,aAAa,GAAG,sBAAsB,GACnD,aAAa,GAAG,sBAAsB,CAgBxC;AAiBD;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAAC,GAAG,EAAE,MAAM,UAM7C;AAED;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,GAAG,GAAG,EAAE,CAQ/C;AAED;;;;;;GAMG;AACH,wBAAgB,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,EAAE,CAmCvC;AAED;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CAAC,aAAa,EAAE,EAAE,EAAE,QAAQ,EAAE,EAAE,GAAG,MAAM,CAgB3E;AAED;;;;;;GAMG;AACH,wBAAgB,eAAe,CAC7B,QAAQ,EAAE,iBAAiB,EAC3B,mBAAmB,EAAE,OAAO,QAW7B"}
@@ -145,6 +145,57 @@ export function padHexToEvenLength(hex) {
145
145
  const evenData = data.length % 2 === 0 ? data : `0${data}`;
146
146
  return prefix + evenData;
147
147
  }
148
+ /**
149
+ * Create a BN from a hex string, accepting an optional 0x prefix.
150
+ *
151
+ * @param hex - Hex string with or without 0x prefix.
152
+ * @returns BN parsed as base-16.
153
+ */
154
+ export function bnFromHex(hex) {
155
+ const str = typeof hex === 'string' ? hex : hex;
156
+ const withoutPrefix = str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;
157
+ if (withoutPrefix.length === 0) {
158
+ return new BN(0);
159
+ }
160
+ return new BN(withoutPrefix, 16);
161
+ }
162
+ /**
163
+ * Convert various numeric-like values to a BN instance.
164
+ * Accepts BN, ethers BigNumber, hex string, bigint, or number.
165
+ *
166
+ * @param value - The value to convert.
167
+ * @returns BN representation of the input value.
168
+ */
169
+ export function toBN(value) {
170
+ if (value instanceof BN) {
171
+ return value;
172
+ }
173
+ if (typeof BN.isBN ===
174
+ 'function' &&
175
+ BN.isBN(value)) {
176
+ return value;
177
+ }
178
+ if (value !== null &&
179
+ typeof value === 'object' &&
180
+ typeof value.toHexString === 'function') {
181
+ return bnFromHex(value.toHexString());
182
+ }
183
+ if (value !== null &&
184
+ typeof value === 'object' &&
185
+ typeof value._hex === 'string') {
186
+ return bnFromHex(value._hex);
187
+ }
188
+ if (typeof value === 'string') {
189
+ return bnFromHex(value);
190
+ }
191
+ if (typeof value === 'bigint') {
192
+ return new BN(value.toString());
193
+ }
194
+ if (typeof value === 'number') {
195
+ return new BN(value);
196
+ }
197
+ throw new Error('Unexpected value returned from oracle contract');
198
+ }
148
199
  /**
149
200
  * Calculate the absolute percentage change between two values.
150
201
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AACA,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,iBAAiB,EAClB,wBAAwB;AAEzB,OAAO,GAAE,cAAc;;AAEvB,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,qBAAiB;AAStE,MAAM,CAAC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAAE,EAAE,CAAC,UAAU;IACnD,iBAAiB,EAAE,CAAC,iBAAqC,EAAE,EAAE,CAC3D,iBAAiB;IACnB,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,k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CAAC,UAAU,EAAE;QACvB,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,UAAU,CAAC;KACpD;SAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE;QACrC,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,OAAO,CAAC;KACjD;SAAM;QACL,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,uBAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,uBAAuB,CAAC,MAAM,CAAC;KACpC;AACH,CAAC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport type { Json } from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport { TransactionEnvelopeType, TransactionStatus } from '../types';\nimport type {\n TransactionParams,\n TransactionMeta,\n TransactionError,\n GasPriceValue,\n FeeMarketEIP1559Values,\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 accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\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 if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\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\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\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
1
+ {"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../src/utils/utils.ts"],"names":[],"mappings":";;;;;;AAEA,OAAO,EACL,KAAK,EACL,qBAAqB,EACrB,iBAAiB,EAClB,wBAAwB;AACzB,OAAO,GAAE,cAAc;;AASvB,OAAO,EAAE,uBAAuB,EAAE,iBAAiB,EAAE,qBAAiB;AAEtE,MAAM,CAAC,MAAM,kBAAkB,GAAG,kCAAkC,CAAC;AAErE,gCAAgC;AAChC,8DAA8D;AAC9D,MAAM,WAAW,GAAgD;IAC/D,UAAU,EAAE,CAAC,UAAuB,EAAE,EAAE,CAAC,UAAU;IACnD,iBAAiB,EAAE,CAAC,iBAAqC,EAAE,EAAE,CAC3D,iBAAiB;IACnB,IAAI,EAAE,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,CAAC,kBAAkB,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,EAAE,CAAC,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G,CAAC,CAAC,GAAG,CAAC,sBAAsB,CAAC,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE,CAAC;AAC3E,CAAC;AAED;;;;;;GAMG;AACH,MAAM,UAAU,eAAe,CAC7B,QAA2B,EAC3B,mBAA4B;IAE5B,IAAI,QAAQ,CAAC,UAAU,EAAE;QACvB,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,UAAU,CAAC;KACpD;SAAM,IAAI,QAAQ,CAAC,iBAAiB,EAAE;QACrC,QAAQ,CAAC,IAAI,GAAG,uBAAuB,CAAC,OAAO,CAAC;KACjD;SAAM;QACL,QAAQ,CAAC,IAAI,GAAG,mBAAmB;YACjC,CAAC,CAAC,uBAAuB,CAAC,SAAS;YACnC,CAAC,CAAC,uBAAuB,CAAC,MAAM,CAAC;KACpC;AACH,CAAC","sourcesContent":["import type { AccessList, AuthorizationList } from '@ethereumjs/common';\nimport type { Hex, Json } from '@metamask/utils';\nimport {\n add0x,\n getKnownPropertyNames,\n isStrictHexString,\n} from '@metamask/utils';\nimport BN from 'bn.js';\n\nimport type {\n FeeMarketEIP1559Values,\n GasPriceValue,\n TransactionError,\n TransactionMeta,\n TransactionParams,\n} from '../types';\nimport { TransactionEnvelopeType, TransactionStatus } 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 accessList: (accessList?: AccessList) => accessList,\n authorizationList: (authorizationList?: AuthorizationList) =>\n authorizationList,\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 if (normalizedTxParams.gasLimit && !normalizedTxParams.gas) {\n normalizedTxParams.gas = normalizedTxParams.gasLimit;\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\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\n/**\n * Create a BN from a hex string, accepting an optional 0x prefix.\n *\n * @param hex - Hex string with or without 0x prefix.\n * @returns BN parsed as base-16.\n */\nexport function bnFromHex(hex: string | Hex): BN {\n const str = typeof hex === 'string' ? hex : (hex as string);\n const withoutPrefix =\n str.startsWith('0x') || str.startsWith('0X') ? str.slice(2) : str;\n if (withoutPrefix.length === 0) {\n return new BN(0);\n }\n return new BN(withoutPrefix, 16);\n}\n\n/**\n * Convert various numeric-like values to a BN instance.\n * Accepts BN, ethers BigNumber, hex string, bigint, or number.\n *\n * @param value - The value to convert.\n * @returns BN representation of the input value.\n */\nexport function toBN(value: unknown): BN {\n if (value instanceof BN) {\n return value as BN;\n }\n if (\n typeof (BN as unknown as { isBN?: (v: unknown) => boolean }).isBN ===\n 'function' &&\n (BN as unknown as { isBN: (v: unknown) => boolean }).isBN(value)\n ) {\n return value as BN;\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { toHexString?: () => string }).toHexString === 'function'\n ) {\n return bnFromHex((value as { toHexString: () => string }).toHexString());\n }\n if (\n value !== null &&\n typeof value === 'object' &&\n typeof (value as { _hex?: string })._hex === 'string'\n ) {\n return bnFromHex((value as { _hex: string })._hex);\n }\n if (typeof value === 'string') {\n return bnFromHex(value);\n }\n if (typeof value === 'bigint') {\n return new BN(value.toString());\n }\n if (typeof value === 'number') {\n return new BN(value);\n }\n throw new Error('Unexpected value returned from oracle contract');\n}\n\n/**\n * Calculate the absolute percentage change between two values.\n *\n * @param originalValue - The first value.\n * @param newValue - The second value.\n * @returns The percentage change from the first value to the second value.\n * If the original value is zero and the new value is not, returns 100.\n */\nexport function getPercentageChange(originalValue: BN, newValue: BN): number {\n const precisionFactor = new BN(10).pow(new BN(18));\n const originalValuePrecision = originalValue.mul(precisionFactor);\n const newValuePrecision = newValue.mul(precisionFactor);\n\n const difference = newValuePrecision.sub(originalValuePrecision);\n\n if (difference.isZero()) {\n return 0;\n }\n\n if (originalValuePrecision.isZero() && !newValuePrecision.isZero()) {\n return 100;\n }\n\n return difference.muln(100).div(originalValuePrecision).abs().toNumber();\n}\n\n/**\n * Sets the envelope type for the given transaction parameters based on the\n * current network's EIP-1559 compatibility and the transaction parameters.\n *\n * @param txParams - The transaction parameters to set the envelope type for.\n * @param isEIP1559Compatible - Indicates if the current network supports EIP-1559.\n */\nexport function setEnvelopeType(\n txParams: TransactionParams,\n isEIP1559Compatible: boolean,\n) {\n if (txParams.accessList) {\n txParams.type = TransactionEnvelopeType.accessList;\n } else if (txParams.authorizationList) {\n txParams.type = TransactionEnvelopeType.setCode;\n } else {\n txParams.type = isEIP1559Compatible\n ? TransactionEnvelopeType.feeMarket\n : TransactionEnvelopeType.legacy;\n }\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/transaction-controller",
3
- "version": "61.0.0-preview-14bbab23",
3
+ "version": "61.1.0-preview-79b6f72",
4
4
  "description": "Stores transactions alongside their periodically updated statuses and manages interactions such as approval and cancellation",
5
5
  "keywords": [
6
6
  "MetaMask",