@metamask-previews/transaction-pay-controller 22.8.0-preview-be0eea21e → 23.0.0-preview-e15374a5d
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 +7 -1
- package/dist/strategy/across/across-submit.cjs +2 -1
- package/dist/strategy/across/across-submit.cjs.map +1 -1
- package/dist/strategy/across/across-submit.d.cts.map +1 -1
- package/dist/strategy/across/across-submit.d.mts.map +1 -1
- package/dist/strategy/across/across-submit.mjs +2 -1
- package/dist/strategy/across/across-submit.mjs.map +1 -1
- package/dist/strategy/relay/relay-submit.cjs +3 -2
- package/dist/strategy/relay/relay-submit.cjs.map +1 -1
- package/dist/strategy/relay/relay-submit.d.cts.map +1 -1
- package/dist/strategy/relay/relay-submit.d.mts.map +1 -1
- package/dist/strategy/relay/relay-submit.mjs +3 -2
- package/dist/strategy/relay/relay-submit.mjs.map +1 -1
- package/dist/tests/messenger-mock.cjs +3 -0
- package/dist/tests/messenger-mock.cjs.map +1 -1
- package/dist/tests/messenger-mock.d.cts +1 -0
- package/dist/tests/messenger-mock.d.cts.map +1 -1
- package/dist/tests/messenger-mock.d.mts +1 -0
- package/dist/tests/messenger-mock.d.mts.map +1 -1
- package/dist/tests/messenger-mock.mjs +3 -0
- package/dist/tests/messenger-mock.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +2 -1
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +2 -1
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/gas.cjs +2 -1
- package/dist/utils/gas.cjs.map +1 -1
- package/dist/utils/gas.d.cts.map +1 -1
- package/dist/utils/gas.d.mts.map +1 -1
- package/dist/utils/gas.mjs +2 -1
- package/dist/utils/gas.mjs.map +1 -1
- package/dist/utils/provider.cjs +61 -0
- package/dist/utils/provider.cjs.map +1 -0
- package/dist/utils/provider.d.cts +59 -0
- package/dist/utils/provider.d.cts.map +1 -0
- package/dist/utils/provider.d.mts +59 -0
- package/dist/utils/provider.d.mts.map +1 -0
- package/dist/utils/provider.mjs +56 -0
- package/dist/utils/provider.mjs.map +1 -0
- package/dist/utils/token.cjs +28 -16
- package/dist/utils/token.cjs.map +1 -1
- package/dist/utils/token.d.cts +4 -0
- package/dist/utils/token.d.cts.map +1 -1
- package/dist/utils/token.d.mts +4 -0
- package/dist/utils/token.d.mts.map +1 -1
- package/dist/utils/token.mjs +28 -16
- package/dist/utils/token.mjs.map +1 -1
- package/dist/utils/transaction.cjs +28 -20
- package/dist/utils/transaction.cjs.map +1 -1
- package/dist/utils/transaction.d.cts.map +1 -1
- package/dist/utils/transaction.d.mts.map +1 -1
- package/dist/utils/transaction.mjs +28 -20
- package/dist/utils/transaction.mjs.map +1 -1
- package/package.json +2 -2
package/dist/utils/gas.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas.cjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAOnD,+CAAyC;AAGzC,0CAA8D;AAE9D,uDAA+D;AAC/D,uCAA4E;AAE5E,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,KAAK,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,SAAgB,2BAA2B,CACzC,WAA4B,EAC5B,SAA4C,EAC5C,EAAE,KAAK,KAA0B,EAAE;IAEnC,MAAM,EACJ,OAAO,EACP,OAAO,EAAE,eAAe,EACxB,gBAAgB,EAChB,QAAQ,GACT,GAAG,WAAW,CAAC;IAEhB,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,YAAY,EAAE,oBAAoB,EAAE,GAAG,QAAQ,CAAC;IACnE,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC;IACpD,MAAM,QAAQ,GAAG,OAAO,IAAI,gBAAgB,IAAI,GAAG,IAAI,K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;GAQG;AACH,SAAS,mCAAmC,CAAC,EAC3C,UAAU,EACV,SAAS,EACT,WAAW,GAKZ;IACC,MAAM,EACJ,OAAO,EACP,YAAY,EACZ,6BAA6B,EAC7B,mBAAmB,GACpB,GAAG,WAAW,CAAC;IAEhB,IACE,CAAC,YAAY;QACb,CAAC,mBAAmB;QACpB,CAAC,6BAA6B,IAAI,UAAU,CAAC,EAC7C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CAAC,gCAAgC,EAAE,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,CAAC;IAExE,MAAM,WAAW,GAAG,YAAY,EAAE,IAAI,CACpC,CAAC,iBAAiB,EAAE,EAAE,CACpB,iBAAiB,CAAC,YAAY,CAAC,WAAW,EAAE;QAC5C,mBAAmB,CAAC,WAAW,EAAE,CACpC,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,GAAG,CAAC,yBAAyB,EAAE;YAC7B,YAAY;YACZ,mBAAmB;SACpB,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,wBAAwB,CAAC;QAC9B,OAAO;QACP,WAAW;QACX,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type { GasFeeEstimates } from '@metamask/gas-fee-controller';\nimport type {\n GasFeeToken,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport type { TransactionPayControllerMessenger } from '..';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Amount } from '../types';\nimport { getFallbackGas, getGasBuffer } from './feature-flags';\nimport { getNativeToken, getTokenBalance, getTokenFiatRate } from './token';\n\nconst log = createModuleLogger(projectLogger, 'gas');\n\n/**\n *\n * Calculate the estimated gas cost for a given transaction in fiat.\n *\n * @param transaction - Transaction to calculate gas cost for\n * @param messenger - Controller messenger.\n * @param options - Calculation options.\n * @param options.isMax - Whether to calculate the maximum fee.\n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateTransactionGasCost(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n { isMax }: { isMax?: boolean } = {},\n): Amount & { isGasFeeToken?: boolean } {\n const {\n chainId,\n gasUsed: gasUsedOriginal,\n gasLimitNoBuffer,\n txParams,\n } = transaction;\n\n const { from, gas, maxFeePerGas, maxPriorityFeePerGas } = txParams;\n const gasUsed = isMax ? undefined : gasUsedOriginal;\n const finalGas = gasUsed ?? gasLimitNoBuffer ?? gas ?? '0x0';\n\n const result = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax: true,\n messenger,\n });\n\n const nativeBalance = getTokenBalance(\n messenger,\n from as Hex,\n chainId,\n getNativeToken(chainId),\n );\n\n const hasBalance = new BigNumber(nativeBalance).gte(max.raw);\n\n const gasFeeTokenCost = calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n });\n\n if (gasFeeTokenCost) {\n return gasFeeTokenCost;\n }\n\n return result;\n}\n\n/**\n * Calculate the gas cost for the specified parameters.\n *\n * @param request - Gas cost calculation parameters.\n * @param request.chainId - ID of the chain.\n * @param request.gas - Amount of gas the transaction will use.\n * @param request.isMax - Whether to calculate the maximum fee.\n * @param request.maxFeePerGas - Max fee to pay per gas.\n * @param request.maxPriorityFeePerGas - Max priority fee to pay per gas.\n * @param request.messenger - Controller messenger.\n \n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateGasCost(request: {\n chainId: number | Hex;\n gas: BigNumber.Value;\n isMax?: boolean;\n maxFeePerGas?: BigNumber.Value;\n maxPriorityFeePerGas?: BigNumber.Value;\n messenger: TransactionPayControllerMessenger;\n}): Amount {\n const {\n chainId: chainIdInput,\n gas,\n isMax,\n maxFeePerGas: maxFeePerGasInput,\n maxPriorityFeePerGas: maxPriorityFeePerGasInput,\n messenger,\n } = request;\n\n const chainId = toHex(chainIdInput);\n\n const {\n estimatedBaseFee,\n maxFeePerGas: maxFeePerGasEstimate,\n maxPriorityFeePerGas: maxPriorityFeePerGasEstimate,\n } = getGasFee(chainId, messenger);\n\n const maxFeePerGas = maxFeePerGasInput ?? maxFeePerGasEstimate;\n\n const maxPriorityFeePerGas =\n maxPriorityFeePerGasInput ?? maxPriorityFeePerGasEstimate;\n\n const feePerGas =\n estimatedBaseFee && maxPriorityFeePerGas && !isMax\n ? new BigNumber(estimatedBaseFee).plus(maxPriorityFeePerGas)\n : new BigNumber(maxFeePerGas ?? '0x0');\n\n const rawValue = new BigNumber(gas).multipliedBy(feePerGas);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-18);\n const human = humanValue.toString(10);\n\n const fiatRate = getTokenFiatRate(\n messenger,\n getNativeToken(chainId),\n chainId,\n );\n\n if (!fiatRate) {\n throw new Error('Could not fetch fiat rate for native token');\n }\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.chainId - Chain ID.\n * @param request.gasFeeToken - Gas fee token to calculate cost for.\n * @param request.messenger - Controller messenger.\n * @returns Cost of the gas fee token.\n */\nexport function calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n}: {\n chainId: Hex;\n gasFeeToken: GasFeeToken;\n messenger: TransactionPayControllerMessenger;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const { amount, decimals, tokenAddress } = gasFeeToken;\n\n const tokenFiatRate = getTokenFiatRate(messenger, tokenAddress, chainId);\n\n if (!tokenFiatRate) {\n log('Cannot get gas fee token info');\n return undefined;\n }\n\n const rawValue = new BigNumber(amount);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const fiat = humanValue.multipliedBy(tokenFiatRate.fiatRate).toString(10);\n const usd = humanValue.multipliedBy(tokenFiatRate.usdRate).toString(10);\n\n return {\n isGasFeeToken: true,\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nexport async function estimateGasLimit({\n chainId,\n data,\n fallbackGas,\n fallbackOnSimulationFailure = false,\n from,\n messenger,\n to,\n value,\n}: {\n chainId: Hex;\n data: Hex;\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure?: boolean;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n to: Hex;\n value?: Hex;\n}): Promise<{\n estimate: number;\n max: number;\n usedFallback: boolean;\n error?: unknown;\n}> {\n const gasBuffer = getGasBuffer(messenger, chainId);\n const networkClientId = messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n\n let estimateGasError: unknown;\n let simulationError: Error | undefined;\n\n try {\n const { gas: gasHex, simulationFails } = await messenger.call(\n 'TransactionController:estimateGas',\n { from, data, to, value: value ?? '0x0' },\n networkClientId,\n );\n\n if (simulationFails) {\n simulationError = new Error('Gas simulation failed');\n } else {\n const estimatedGas = parseEstimatedGas(gasHex);\n const bufferedGas = Math.ceil(estimatedGas * gasBuffer);\n\n return {\n estimate: bufferedGas,\n max: bufferedGas,\n usedFallback: false,\n };\n }\n } catch (caughtError) {\n estimateGasError = caughtError;\n }\n\n if (simulationError !== undefined && !fallbackOnSimulationFailure) {\n throw simulationError;\n }\n\n const fallbackGasConfig = fallbackGas ?? getFallbackGas(messenger);\n\n return {\n estimate: fallbackGasConfig.estimate,\n max: fallbackGasConfig.max,\n usedFallback: true,\n error: estimateGasError ?? simulationError,\n };\n}\n\n/**\n * Get gas fee estimates for a given chain.\n *\n * @param chainId - Chain ID.\n * @param messenger - Controller messenger.\n * @returns Gas fee estimates for the chain.\n */\nexport function getGasFee(\n chainId: Hex,\n messenger: TransactionPayControllerMessenger,\n): {\n estimatedBaseFee: string | undefined;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n} {\n const gasFeeControllerState = messenger.call('GasFeeController:getState');\n\n const chainState = gasFeeControllerState?.gasFeeEstimatesByChainId?.[chainId];\n\n const { estimatedBaseFee: estimatedBaseFeeGwei, medium } =\n (chainState?.gasFeeEstimates as GasFeeEstimates | undefined) ?? {};\n\n const maxFeePerGasGwei = medium?.suggestedMaxFeePerGas;\n const maxPriorityFeePerGasGwei = medium?.suggestedMaxPriorityFeePerGas;\n\n const estimatedBaseFee = estimatedBaseFeeGwei\n ? new BigNumber(estimatedBaseFeeGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxFeePerGas = maxFeePerGasGwei\n ? new BigNumber(maxFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxPriorityFeePerGas = maxPriorityFeePerGasGwei\n ? new BigNumber(maxPriorityFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n return { estimatedBaseFee, maxFeePerGas, maxPriorityFeePerGas };\n}\n\nfunction parseEstimatedGas(gasValue: string): number {\n const parsedGas = gasValue.startsWith('0x')\n ? new BigNumber(gasValue.slice(2), 16)\n : new BigNumber(gasValue);\n\n if (!parsedGas.isFinite() || parsedGas.isNaN()) {\n throw new Error(`Invalid gas estimate returned: ${gasValue}`);\n }\n\n return parsedGas.toNumber();\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.hasBalance - Whether the user has enough balance to cover the gas fee.\n * @param request.messenger - Controller messenger.\n * @param request.transaction - Transaction to calculate gas fee token cost for.\n * @returns Cost of the gas fee token.\n */\nfunction calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n}: {\n hasBalance: boolean;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const {\n chainId,\n gasFeeTokens,\n isGasFeeTokenIgnoredIfBalance,\n selectedGasFeeToken,\n } = transaction;\n\n if (\n !gasFeeTokens ||\n !selectedGasFeeToken ||\n (isGasFeeTokenIgnoredIfBalance && hasBalance)\n ) {\n return undefined;\n }\n\n log('Calculating gas fee token cost', { selectedGasFeeToken, chainId });\n\n const gasFeeToken = gasFeeTokens?.find(\n (singleGasFeeToken) =>\n singleGasFeeToken.tokenAddress.toLowerCase() ===\n selectedGasFeeToken.toLowerCase(),\n );\n\n if (!gasFeeToken) {\n log('Gas fee token not found', {\n gasFeeTokens,\n selectedGasFeeToken,\n });\n\n return undefined;\n }\n\n return calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas.cjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":";;;AAAA,iEAAmD;AAOnD,+CAAyC;AAGzC,0CAA8D;AAE9D,uDAA+D;AAC/D,6CAAgD;AAChD,uCAA4E;AAE5E,MAAM,GAAG,GAAG,IAAA,2BAAkB,EAAC,sBAAa,EAAE,KAAK,CAAC,CAAC;AAErD;;;;;;;;;GASG;AACH,SAAgB,2BAA2B,CACzC,WAA4B,EAC5B,SAA4C,EAC5C,EAAE,KAAK,KAA0B,EAAE;IAEnC,MAAM,EACJ,OAAO,EACP,OAAO,EAAE,eAAe,EACxB,gBAAgB,EAChB,QAAQ,GACT,GAAG,WAAW,CAAC;IAEhB,MAAM,EAAE,IAAI,EAAE,GAAG,EAAE,YAAY,EAAE,oBAAoB,EAAE,GAAG,QAAQ,CAAC;IACnE,MAAM,OAAO,GAAG,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC;IACpD,MAAM,QAAQ,GAAG,OAAO,IAAI,gBAAgB,IAAI,GAAG,IAAI,KAAK,CAAC;IAE7D,MAAM,MAAM,GAAG,gBAAgB,CAAC;QAC9B,OAAO;QACP,GAAG,EAAE,QAAQ;QACb,KAAK;QACL,YAAY;QACZ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6B,EAC7B,mBAAmB,GACpB,GAAG,WAAW,CAAC;IAEhB,IACE,CAAC,YAAY;QACb,CAAC,mBAAmB;QACpB,CAAC,6BAA6B,IAAI,UAAU,CAAC,EAC7C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CAAC,gCAAgC,EAAE,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,CAAC;IAExE,MAAM,WAAW,GAAG,YAAY,EAAE,IAAI,CACpC,CAAC,iBAAiB,EAAE,EAAE,CACpB,iBAAiB,CAAC,YAAY,CAAC,WAAW,EAAE;QAC5C,mBAAmB,CAAC,WAAW,EAAE,CACpC,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,GAAG,CAAC,yBAAyB,EAAE;YAC7B,YAAY;YACZ,mBAAmB;SACpB,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,wBAAwB,CAAC;QAC9B,OAAO;QACP,WAAW;QACX,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type { GasFeeEstimates } from '@metamask/gas-fee-controller';\nimport type {\n GasFeeToken,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport type { TransactionPayControllerMessenger } from '..';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Amount } from '../types';\nimport { getFallbackGas, getGasBuffer } from './feature-flags';\nimport { getNetworkClientId } from './provider';\nimport { getNativeToken, getTokenBalance, getTokenFiatRate } from './token';\n\nconst log = createModuleLogger(projectLogger, 'gas');\n\n/**\n *\n * Calculate the estimated gas cost for a given transaction in fiat.\n *\n * @param transaction - Transaction to calculate gas cost for\n * @param messenger - Controller messenger.\n * @param options - Calculation options.\n * @param options.isMax - Whether to calculate the maximum fee.\n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateTransactionGasCost(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n { isMax }: { isMax?: boolean } = {},\n): Amount & { isGasFeeToken?: boolean } {\n const {\n chainId,\n gasUsed: gasUsedOriginal,\n gasLimitNoBuffer,\n txParams,\n } = transaction;\n\n const { from, gas, maxFeePerGas, maxPriorityFeePerGas } = txParams;\n const gasUsed = isMax ? undefined : gasUsedOriginal;\n const finalGas = gasUsed ?? gasLimitNoBuffer ?? gas ?? '0x0';\n\n const result = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax: true,\n messenger,\n });\n\n const nativeBalance = getTokenBalance(\n messenger,\n from as Hex,\n chainId,\n getNativeToken(chainId),\n );\n\n const hasBalance = new BigNumber(nativeBalance).gte(max.raw);\n\n const gasFeeTokenCost = calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n });\n\n if (gasFeeTokenCost) {\n return gasFeeTokenCost;\n }\n\n return result;\n}\n\n/**\n * Calculate the gas cost for the specified parameters.\n *\n * @param request - Gas cost calculation parameters.\n * @param request.chainId - ID of the chain.\n * @param request.gas - Amount of gas the transaction will use.\n * @param request.isMax - Whether to calculate the maximum fee.\n * @param request.maxFeePerGas - Max fee to pay per gas.\n * @param request.maxPriorityFeePerGas - Max priority fee to pay per gas.\n * @param request.messenger - Controller messenger.\n \n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateGasCost(request: {\n chainId: number | Hex;\n gas: BigNumber.Value;\n isMax?: boolean;\n maxFeePerGas?: BigNumber.Value;\n maxPriorityFeePerGas?: BigNumber.Value;\n messenger: TransactionPayControllerMessenger;\n}): Amount {\n const {\n chainId: chainIdInput,\n gas,\n isMax,\n maxFeePerGas: maxFeePerGasInput,\n maxPriorityFeePerGas: maxPriorityFeePerGasInput,\n messenger,\n } = request;\n\n const chainId = toHex(chainIdInput);\n\n const {\n estimatedBaseFee,\n maxFeePerGas: maxFeePerGasEstimate,\n maxPriorityFeePerGas: maxPriorityFeePerGasEstimate,\n } = getGasFee(chainId, messenger);\n\n const maxFeePerGas = maxFeePerGasInput ?? maxFeePerGasEstimate;\n\n const maxPriorityFeePerGas =\n maxPriorityFeePerGasInput ?? maxPriorityFeePerGasEstimate;\n\n const feePerGas =\n estimatedBaseFee && maxPriorityFeePerGas && !isMax\n ? new BigNumber(estimatedBaseFee).plus(maxPriorityFeePerGas)\n : new BigNumber(maxFeePerGas ?? '0x0');\n\n const rawValue = new BigNumber(gas).multipliedBy(feePerGas);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-18);\n const human = humanValue.toString(10);\n\n const fiatRate = getTokenFiatRate(\n messenger,\n getNativeToken(chainId),\n chainId,\n );\n\n if (!fiatRate) {\n throw new Error('Could not fetch fiat rate for native token');\n }\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.chainId - Chain ID.\n * @param request.gasFeeToken - Gas fee token to calculate cost for.\n * @param request.messenger - Controller messenger.\n * @returns Cost of the gas fee token.\n */\nexport function calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n}: {\n chainId: Hex;\n gasFeeToken: GasFeeToken;\n messenger: TransactionPayControllerMessenger;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const { amount, decimals, tokenAddress } = gasFeeToken;\n\n const tokenFiatRate = getTokenFiatRate(messenger, tokenAddress, chainId);\n\n if (!tokenFiatRate) {\n log('Cannot get gas fee token info');\n return undefined;\n }\n\n const rawValue = new BigNumber(amount);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const fiat = humanValue.multipliedBy(tokenFiatRate.fiatRate).toString(10);\n const usd = humanValue.multipliedBy(tokenFiatRate.usdRate).toString(10);\n\n return {\n isGasFeeToken: true,\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nexport async function estimateGasLimit({\n chainId,\n data,\n fallbackGas,\n fallbackOnSimulationFailure = false,\n from,\n messenger,\n to,\n value,\n}: {\n chainId: Hex;\n data: Hex;\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure?: boolean;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n to: Hex;\n value?: Hex;\n}): Promise<{\n estimate: number;\n max: number;\n usedFallback: boolean;\n error?: unknown;\n}> {\n const gasBuffer = getGasBuffer(messenger, chainId);\n const networkClientId = getNetworkClientId(messenger, chainId);\n\n let estimateGasError: unknown;\n let simulationError: Error | undefined;\n\n try {\n const { gas: gasHex, simulationFails } = await messenger.call(\n 'TransactionController:estimateGas',\n { from, data, to, value: value ?? '0x0' },\n networkClientId,\n );\n\n if (simulationFails) {\n simulationError = new Error('Gas simulation failed');\n } else {\n const estimatedGas = parseEstimatedGas(gasHex);\n const bufferedGas = Math.ceil(estimatedGas * gasBuffer);\n\n return {\n estimate: bufferedGas,\n max: bufferedGas,\n usedFallback: false,\n };\n }\n } catch (caughtError) {\n estimateGasError = caughtError;\n }\n\n if (simulationError !== undefined && !fallbackOnSimulationFailure) {\n throw simulationError;\n }\n\n const fallbackGasConfig = fallbackGas ?? getFallbackGas(messenger);\n\n return {\n estimate: fallbackGasConfig.estimate,\n max: fallbackGasConfig.max,\n usedFallback: true,\n error: estimateGasError ?? simulationError,\n };\n}\n\n/**\n * Get gas fee estimates for a given chain.\n *\n * @param chainId - Chain ID.\n * @param messenger - Controller messenger.\n * @returns Gas fee estimates for the chain.\n */\nexport function getGasFee(\n chainId: Hex,\n messenger: TransactionPayControllerMessenger,\n): {\n estimatedBaseFee: string | undefined;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n} {\n const gasFeeControllerState = messenger.call('GasFeeController:getState');\n\n const chainState = gasFeeControllerState?.gasFeeEstimatesByChainId?.[chainId];\n\n const { estimatedBaseFee: estimatedBaseFeeGwei, medium } =\n (chainState?.gasFeeEstimates as GasFeeEstimates | undefined) ?? {};\n\n const maxFeePerGasGwei = medium?.suggestedMaxFeePerGas;\n const maxPriorityFeePerGasGwei = medium?.suggestedMaxPriorityFeePerGas;\n\n const estimatedBaseFee = estimatedBaseFeeGwei\n ? new BigNumber(estimatedBaseFeeGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxFeePerGas = maxFeePerGasGwei\n ? new BigNumber(maxFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxPriorityFeePerGas = maxPriorityFeePerGasGwei\n ? new BigNumber(maxPriorityFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n return { estimatedBaseFee, maxFeePerGas, maxPriorityFeePerGas };\n}\n\nfunction parseEstimatedGas(gasValue: string): number {\n const parsedGas = gasValue.startsWith('0x')\n ? new BigNumber(gasValue.slice(2), 16)\n : new BigNumber(gasValue);\n\n if (!parsedGas.isFinite() || parsedGas.isNaN()) {\n throw new Error(`Invalid gas estimate returned: ${gasValue}`);\n }\n\n return parsedGas.toNumber();\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.hasBalance - Whether the user has enough balance to cover the gas fee.\n * @param request.messenger - Controller messenger.\n * @param request.transaction - Transaction to calculate gas fee token cost for.\n * @returns Cost of the gas fee token.\n */\nfunction calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n}: {\n hasBalance: boolean;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const {\n chainId,\n gasFeeTokens,\n isGasFeeTokenIgnoredIfBalance,\n selectedGasFeeToken,\n } = transaction;\n\n if (\n !gasFeeTokens ||\n !selectedGasFeeToken ||\n (isGasFeeTokenIgnoredIfBalance && hasBalance)\n ) {\n return undefined;\n }\n\n log('Calculating gas fee token cost', { selectedGasFeeToken, chainId });\n\n const gasFeeToken = gasFeeTokens?.find(\n (singleGasFeeToken) =>\n singleGasFeeToken.tokenAddress.toLowerCase() ===\n selectedGasFeeToken.toLowerCase(),\n );\n\n if (!gasFeeToken) {\n log('Gas fee token not found', {\n gasFeeTokens,\n selectedGasFeeToken,\n });\n\n return undefined;\n }\n\n return calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n });\n}\n"]}
|
package/dist/utils/gas.d.cts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas.d.cts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,eAAe,EAChB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAC3C,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAW;AAE5D,OAAO,KAAK,EAAE,MAAM,EAAE,qBAAiB;
|
|
1
|
+
{"version":3,"file":"gas.d.cts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,eAAe,EAChB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAC3C,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAW;AAE5D,OAAO,KAAK,EAAE,MAAM,EAAE,qBAAiB;AAOvC;;;;;;;;;GASG;AACH,wBAAgB,2BAA2B,CACzC,WAAW,EAAE,eAAe,EAC5B,SAAS,EAAE,iCAAiC,EAC5C,EAAE,KAAK,EAAE,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GAClC,MAAM,GAAG;IAAE,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,CAgDtC;AAED;;;;;;;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AED;;;;;;GAMG;AACH,wBAAgB,SAAS,CACvB,OAAO,EAAE,GAAG,EACZ,SAAS,EAAE,iCAAiC,GAC3C;IACD,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,oBAAoB,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1C,CAwBA"}
|
package/dist/utils/gas.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas.d.mts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,eAAe,EAChB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAC3C,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAW;AAE5D,OAAO,KAAK,EAAE,MAAM,EAAE,qBAAiB;
|
|
1
|
+
{"version":3,"file":"gas.d.mts","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EACV,WAAW,EACX,eAAe,EAChB,yCAAyC;AAC1C,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAC3C,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAW;AAE5D,OAAO,KAAK,EAAE,MAAM,EAAE,qBAAiB;AAOvC;;;;;;;;;GASG;AACH,wBAAgB,2BAA2B,CACzC,WAAW,EAAE,eAAe,EAC5B,SAAS,EAAE,iCAAiC,EAC5C,EAAE,KAAK,EAAE,GAAE;IAAE,KAAK,CAAC,EAAE,OAAO,CAAA;CAAO,GAClC,MAAM,GAAG;IAAE,aAAa,CAAC,EAAE,OAAO,CAAA;CAAE,CAgDtC;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE;IACxC,OAAO,EAAE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S,EAAE,iCAAiC,GAC3C;IACD,gBAAgB,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,YAAY,EAAE,MAAM,GAAG,SAAS,CAAC;IACjC,oBAAoB,EAAE,MAAM,GAAG,SAAS,CAAC;CAC1C,CAwBA"}
|
package/dist/utils/gas.mjs
CHANGED
|
@@ -2,6 +2,7 @@ import { toHex } from "@metamask/controller-utils";
|
|
|
2
2
|
import { BigNumber } from "bignumber.js";
|
|
3
3
|
import { createModuleLogger, projectLogger } from "../logger.mjs";
|
|
4
4
|
import { getFallbackGas, getGasBuffer } from "./feature-flags.mjs";
|
|
5
|
+
import { getNetworkClientId } from "./provider.mjs";
|
|
5
6
|
import { getNativeToken, getTokenBalance, getTokenFiatRate } from "./token.mjs";
|
|
6
7
|
const log = createModuleLogger(projectLogger, 'gas');
|
|
7
8
|
/**
|
|
@@ -116,7 +117,7 @@ export function calculateGasFeeTokenCost({ chainId, gasFeeToken, messenger, }) {
|
|
|
116
117
|
}
|
|
117
118
|
export async function estimateGasLimit({ chainId, data, fallbackGas, fallbackOnSimulationFailure = false, from, messenger, to, value, }) {
|
|
118
119
|
const gasBuffer = getGasBuffer(messenger, chainId);
|
|
119
|
-
const networkClientId = messenger
|
|
120
|
+
const networkClientId = getNetworkClientId(messenger, chainId);
|
|
120
121
|
let estimateGasError;
|
|
121
122
|
let simulationError;
|
|
122
123
|
try {
|
package/dist/utils/gas.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"gas.mjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAOnD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAGzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAE9D,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,4BAAwB;AAC/D,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,gBAAgB,EAAE,oBA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as-fee-controller';\nimport type {\n GasFeeToken,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport type { TransactionPayControllerMessenger } from '..';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Amount } from '../types';\nimport { getFallbackGas, getGasBuffer } from './feature-flags';\nimport { getNativeToken, getTokenBalance, getTokenFiatRate } from './token';\n\nconst log = createModuleLogger(projectLogger, 'gas');\n\n/**\n *\n * Calculate the estimated gas cost for a given transaction in fiat.\n *\n * @param transaction - Transaction to calculate gas cost for\n * @param messenger - Controller messenger.\n * @param options - Calculation options.\n * @param options.isMax - Whether to calculate the maximum fee.\n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateTransactionGasCost(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n { isMax }: { isMax?: boolean } = {},\n): Amount & { isGasFeeToken?: boolean } {\n const {\n chainId,\n gasUsed: gasUsedOriginal,\n gasLimitNoBuffer,\n txParams,\n } = transaction;\n\n const { from, gas, maxFeePerGas, maxPriorityFeePerGas } = txParams;\n const gasUsed = isMax ? undefined : gasUsedOriginal;\n const finalGas = gasUsed ?? gasLimitNoBuffer ?? gas ?? '0x0';\n\n const result = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax: true,\n messenger,\n });\n\n const nativeBalance = getTokenBalance(\n messenger,\n from as Hex,\n chainId,\n getNativeToken(chainId),\n );\n\n const hasBalance = new BigNumber(nativeBalance).gte(max.raw);\n\n const gasFeeTokenCost = calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n });\n\n if (gasFeeTokenCost) {\n return gasFeeTokenCost;\n }\n\n return result;\n}\n\n/**\n * Calculate the gas cost for the specified parameters.\n *\n * @param request - Gas cost calculation parameters.\n * @param request.chainId - ID of the chain.\n * @param request.gas - Amount of gas the transaction will use.\n * @param request.isMax - Whether to calculate the maximum fee.\n * @param request.maxFeePerGas - Max fee to pay per gas.\n * @param request.maxPriorityFeePerGas - Max priority fee to pay per gas.\n * @param request.messenger - Controller messenger.\n \n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateGasCost(request: {\n chainId: number | Hex;\n gas: BigNumber.Value;\n isMax?: boolean;\n maxFeePerGas?: BigNumber.Value;\n maxPriorityFeePerGas?: BigNumber.Value;\n messenger: TransactionPayControllerMessenger;\n}): Amount {\n const {\n chainId: chainIdInput,\n gas,\n isMax,\n maxFeePerGas: maxFeePerGasInput,\n maxPriorityFeePerGas: maxPriorityFeePerGasInput,\n messenger,\n } = request;\n\n const chainId = toHex(chainIdInput);\n\n const {\n estimatedBaseFee,\n maxFeePerGas: maxFeePerGasEstimate,\n maxPriorityFeePerGas: maxPriorityFeePerGasEstimate,\n } = getGasFee(chainId, messenger);\n\n const maxFeePerGas = maxFeePerGasInput ?? maxFeePerGasEstimate;\n\n const maxPriorityFeePerGas =\n maxPriorityFeePerGasInput ?? maxPriorityFeePerGasEstimate;\n\n const feePerGas =\n estimatedBaseFee && maxPriorityFeePerGas && !isMax\n ? new BigNumber(estimatedBaseFee).plus(maxPriorityFeePerGas)\n : new BigNumber(maxFeePerGas ?? '0x0');\n\n const rawValue = new BigNumber(gas).multipliedBy(feePerGas);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-18);\n const human = humanValue.toString(10);\n\n const fiatRate = getTokenFiatRate(\n messenger,\n getNativeToken(chainId),\n chainId,\n );\n\n if (!fiatRate) {\n throw new Error('Could not fetch fiat rate for native token');\n }\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.chainId - Chain ID.\n * @param request.gasFeeToken - Gas fee token to calculate cost for.\n * @param request.messenger - Controller messenger.\n * @returns Cost of the gas fee token.\n */\nexport function calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n}: {\n chainId: Hex;\n gasFeeToken: GasFeeToken;\n messenger: TransactionPayControllerMessenger;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const { amount, decimals, tokenAddress } = gasFeeToken;\n\n const tokenFiatRate = getTokenFiatRate(messenger, tokenAddress, chainId);\n\n if (!tokenFiatRate) {\n log('Cannot get gas fee token info');\n return undefined;\n }\n\n const rawValue = new BigNumber(amount);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const fiat = humanValue.multipliedBy(tokenFiatRate.fiatRate).toString(10);\n const usd = humanValue.multipliedBy(tokenFiatRate.usdRate).toString(10);\n\n return {\n isGasFeeToken: true,\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nexport async function estimateGasLimit({\n chainId,\n data,\n fallbackGas,\n fallbackOnSimulationFailure = false,\n from,\n messenger,\n to,\n value,\n}: {\n chainId: Hex;\n data: Hex;\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure?: boolean;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n to: Hex;\n value?: Hex;\n}): Promise<{\n estimate: number;\n max: number;\n usedFallback: boolean;\n error?: unknown;\n}> {\n const gasBuffer = getGasBuffer(messenger, chainId);\n const networkClientId = messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n\n let estimateGasError: unknown;\n let simulationError: Error | undefined;\n\n try {\n const { gas: gasHex, simulationFails } = await messenger.call(\n 'TransactionController:estimateGas',\n { from, data, to, value: value ?? '0x0' },\n networkClientId,\n );\n\n if (simulationFails) {\n simulationError = new Error('Gas simulation failed');\n } else {\n const estimatedGas = parseEstimatedGas(gasHex);\n const bufferedGas = Math.ceil(estimatedGas * gasBuffer);\n\n return {\n estimate: bufferedGas,\n max: bufferedGas,\n usedFallback: false,\n };\n }\n } catch (caughtError) {\n estimateGasError = caughtError;\n }\n\n if (simulationError !== undefined && !fallbackOnSimulationFailure) {\n throw simulationError;\n }\n\n const fallbackGasConfig = fallbackGas ?? getFallbackGas(messenger);\n\n return {\n estimate: fallbackGasConfig.estimate,\n max: fallbackGasConfig.max,\n usedFallback: true,\n error: estimateGasError ?? simulationError,\n };\n}\n\n/**\n * Get gas fee estimates for a given chain.\n *\n * @param chainId - Chain ID.\n * @param messenger - Controller messenger.\n * @returns Gas fee estimates for the chain.\n */\nexport function getGasFee(\n chainId: Hex,\n messenger: TransactionPayControllerMessenger,\n): {\n estimatedBaseFee: string | undefined;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n} {\n const gasFeeControllerState = messenger.call('GasFeeController:getState');\n\n const chainState = gasFeeControllerState?.gasFeeEstimatesByChainId?.[chainId];\n\n const { estimatedBaseFee: estimatedBaseFeeGwei, medium } =\n (chainState?.gasFeeEstimates as GasFeeEstimates | undefined) ?? {};\n\n const maxFeePerGasGwei = medium?.suggestedMaxFeePerGas;\n const maxPriorityFeePerGasGwei = medium?.suggestedMaxPriorityFeePerGas;\n\n const estimatedBaseFee = estimatedBaseFeeGwei\n ? new BigNumber(estimatedBaseFeeGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxFeePerGas = maxFeePerGasGwei\n ? new BigNumber(maxFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxPriorityFeePerGas = maxPriorityFeePerGasGwei\n ? new BigNumber(maxPriorityFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n return { estimatedBaseFee, maxFeePerGas, maxPriorityFeePerGas };\n}\n\nfunction parseEstimatedGas(gasValue: string): number {\n const parsedGas = gasValue.startsWith('0x')\n ? new BigNumber(gasValue.slice(2), 16)\n : new BigNumber(gasValue);\n\n if (!parsedGas.isFinite() || parsedGas.isNaN()) {\n throw new Error(`Invalid gas estimate returned: ${gasValue}`);\n }\n\n return parsedGas.toNumber();\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.hasBalance - Whether the user has enough balance to cover the gas fee.\n * @param request.messenger - Controller messenger.\n * @param request.transaction - Transaction to calculate gas fee token cost for.\n * @returns Cost of the gas fee token.\n */\nfunction calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n}: {\n hasBalance: boolean;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const {\n chainId,\n gasFeeTokens,\n isGasFeeTokenIgnoredIfBalance,\n selectedGasFeeToken,\n } = transaction;\n\n if (\n !gasFeeTokens ||\n !selectedGasFeeToken ||\n (isGasFeeTokenIgnoredIfBalance && hasBalance)\n ) {\n return undefined;\n }\n\n log('Calculating gas fee token cost', { selectedGasFeeToken, chainId });\n\n const gasFeeToken = gasFeeTokens?.find(\n (singleGasFeeToken) =>\n singleGasFeeToken.tokenAddress.toLowerCase() ===\n selectedGasFeeToken.toLowerCase(),\n );\n\n if (!gasFeeToken) {\n log('Gas fee token not found', {\n gasFeeTokens,\n selectedGasFeeToken,\n });\n\n return undefined;\n }\n\n return calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"gas.mjs","sourceRoot":"","sources":["../../src/utils/gas.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,mCAAmC;AAOnD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAGzC,OAAO,EAAE,kBAAkB,EAAE,aAAa,EAAE,sBAAkB;AAE9D,OAAO,EAAE,cAAc,EAAE,YAAY,EAAE,4BAAwB;AAC/D,OAAO,EAAE,kBAAkB,EAAE,uBAAmB;AAChD,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,gBAAgB,EAAE,oBAAgB;AAE5E,MAAM,GAAG,GAAG,kBAAkB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AAS,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC;QACtC,CAAC,CAAC,IAAI,SAAS,CAAC,QAAQ,CAAC,CAAC;IAE5B,IAAI,CAAC,SAAS,CAAC,QAAQ,EAAE,IAAI,SAAS,CAAC,KAAK,EAAE,EAAE,CAAC;QAC/C,MAAM,IAAI,KAAK,CAAC,kCAAkC,QAAQ,EAAE,CAAC,CAAC;IAChE,CAAC;IAED,OAAO,SAAS,CAAC,QAAQ,EAAE,CAAC;AAC9B,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,mCAAmC,CAAC,EAC3C,UAAU,EACV,SAAS,EACT,WAAW,GAKZ;IACC,MAAM,EACJ,OAAO,EACP,YAAY,EACZ,6BAA6B,EAC7B,mBAAmB,GACpB,GAAG,WAAW,CAAC;IAEhB,IACE,CAAC,YAAY;QACb,CAAC,mBAAmB;QACpB,CAAC,6BAA6B,IAAI,UAAU,CAAC,EAC7C,CAAC;QACD,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,GAAG,CAAC,gCAAgC,EAAE,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,CAAC;IAExE,MAAM,WAAW,GAAG,YAAY,EAAE,IAAI,CACpC,CAAC,iBAAiB,EAAE,EAAE,CACpB,iBAAiB,CAAC,YAAY,CAAC,WAAW,EAAE;QAC5C,mBAAmB,CAAC,WAAW,EAAE,CACpC,CAAC;IAEF,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,GAAG,CAAC,yBAAyB,EAAE;YAC7B,YAAY;YACZ,mBAAmB;SACpB,CAAC,CAAC;QAEH,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,OAAO,wBAAwB,CAAC;QAC9B,OAAO;QACP,WAAW;QACX,SAAS;KACV,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { toHex } from '@metamask/controller-utils';\nimport type { GasFeeEstimates } from '@metamask/gas-fee-controller';\nimport type {\n GasFeeToken,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport type { TransactionPayControllerMessenger } from '..';\nimport { createModuleLogger, projectLogger } from '../logger';\nimport type { Amount } from '../types';\nimport { getFallbackGas, getGasBuffer } from './feature-flags';\nimport { getNetworkClientId } from './provider';\nimport { getNativeToken, getTokenBalance, getTokenFiatRate } from './token';\n\nconst log = createModuleLogger(projectLogger, 'gas');\n\n/**\n *\n * Calculate the estimated gas cost for a given transaction in fiat.\n *\n * @param transaction - Transaction to calculate gas cost for\n * @param messenger - Controller messenger.\n * @param options - Calculation options.\n * @param options.isMax - Whether to calculate the maximum fee.\n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateTransactionGasCost(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n { isMax }: { isMax?: boolean } = {},\n): Amount & { isGasFeeToken?: boolean } {\n const {\n chainId,\n gasUsed: gasUsedOriginal,\n gasLimitNoBuffer,\n txParams,\n } = transaction;\n\n const { from, gas, maxFeePerGas, maxPriorityFeePerGas } = txParams;\n const gasUsed = isMax ? undefined : gasUsedOriginal;\n const finalGas = gasUsed ?? gasLimitNoBuffer ?? gas ?? '0x0';\n\n const result = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n });\n\n const max = calculateGasCost({\n chainId,\n gas: finalGas,\n isMax: true,\n messenger,\n });\n\n const nativeBalance = getTokenBalance(\n messenger,\n from as Hex,\n chainId,\n getNativeToken(chainId),\n );\n\n const hasBalance = new BigNumber(nativeBalance).gte(max.raw);\n\n const gasFeeTokenCost = calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n });\n\n if (gasFeeTokenCost) {\n return gasFeeTokenCost;\n }\n\n return result;\n}\n\n/**\n * Calculate the gas cost for the specified parameters.\n *\n * @param request - Gas cost calculation parameters.\n * @param request.chainId - ID of the chain.\n * @param request.gas - Amount of gas the transaction will use.\n * @param request.isMax - Whether to calculate the maximum fee.\n * @param request.maxFeePerGas - Max fee to pay per gas.\n * @param request.maxPriorityFeePerGas - Max priority fee to pay per gas.\n * @param request.messenger - Controller messenger.\n \n * @returns Estimated gas cost for the transaction.\n */\nexport function calculateGasCost(request: {\n chainId: number | Hex;\n gas: BigNumber.Value;\n isMax?: boolean;\n maxFeePerGas?: BigNumber.Value;\n maxPriorityFeePerGas?: BigNumber.Value;\n messenger: TransactionPayControllerMessenger;\n}): Amount {\n const {\n chainId: chainIdInput,\n gas,\n isMax,\n maxFeePerGas: maxFeePerGasInput,\n maxPriorityFeePerGas: maxPriorityFeePerGasInput,\n messenger,\n } = request;\n\n const chainId = toHex(chainIdInput);\n\n const {\n estimatedBaseFee,\n maxFeePerGas: maxFeePerGasEstimate,\n maxPriorityFeePerGas: maxPriorityFeePerGasEstimate,\n } = getGasFee(chainId, messenger);\n\n const maxFeePerGas = maxFeePerGasInput ?? maxFeePerGasEstimate;\n\n const maxPriorityFeePerGas =\n maxPriorityFeePerGasInput ?? maxPriorityFeePerGasEstimate;\n\n const feePerGas =\n estimatedBaseFee && maxPriorityFeePerGas && !isMax\n ? new BigNumber(estimatedBaseFee).plus(maxPriorityFeePerGas)\n : new BigNumber(maxFeePerGas ?? '0x0');\n\n const rawValue = new BigNumber(gas).multipliedBy(feePerGas);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-18);\n const human = humanValue.toString(10);\n\n const fiatRate = getTokenFiatRate(\n messenger,\n getNativeToken(chainId),\n chainId,\n );\n\n if (!fiatRate) {\n throw new Error('Could not fetch fiat rate for native token');\n }\n\n const usd = humanValue.multipliedBy(fiatRate.usdRate).toString(10);\n const fiat = humanValue.multipliedBy(fiatRate.fiatRate).toString(10);\n\n return {\n fiat,\n human,\n raw,\n usd,\n };\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.chainId - Chain ID.\n * @param request.gasFeeToken - Gas fee token to calculate cost for.\n * @param request.messenger - Controller messenger.\n * @returns Cost of the gas fee token.\n */\nexport function calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n}: {\n chainId: Hex;\n gasFeeToken: GasFeeToken;\n messenger: TransactionPayControllerMessenger;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const { amount, decimals, tokenAddress } = gasFeeToken;\n\n const tokenFiatRate = getTokenFiatRate(messenger, tokenAddress, chainId);\n\n if (!tokenFiatRate) {\n log('Cannot get gas fee token info');\n return undefined;\n }\n\n const rawValue = new BigNumber(amount);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\n\n const fiat = humanValue.multipliedBy(tokenFiatRate.fiatRate).toString(10);\n const usd = humanValue.multipliedBy(tokenFiatRate.usdRate).toString(10);\n\n return {\n isGasFeeToken: true,\n fiat,\n human,\n raw,\n usd,\n };\n}\n\nexport async function estimateGasLimit({\n chainId,\n data,\n fallbackGas,\n fallbackOnSimulationFailure = false,\n from,\n messenger,\n to,\n value,\n}: {\n chainId: Hex;\n data: Hex;\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure?: boolean;\n from: Hex;\n messenger: TransactionPayControllerMessenger;\n to: Hex;\n value?: Hex;\n}): Promise<{\n estimate: number;\n max: number;\n usedFallback: boolean;\n error?: unknown;\n}> {\n const gasBuffer = getGasBuffer(messenger, chainId);\n const networkClientId = getNetworkClientId(messenger, chainId);\n\n let estimateGasError: unknown;\n let simulationError: Error | undefined;\n\n try {\n const { gas: gasHex, simulationFails } = await messenger.call(\n 'TransactionController:estimateGas',\n { from, data, to, value: value ?? '0x0' },\n networkClientId,\n );\n\n if (simulationFails) {\n simulationError = new Error('Gas simulation failed');\n } else {\n const estimatedGas = parseEstimatedGas(gasHex);\n const bufferedGas = Math.ceil(estimatedGas * gasBuffer);\n\n return {\n estimate: bufferedGas,\n max: bufferedGas,\n usedFallback: false,\n };\n }\n } catch (caughtError) {\n estimateGasError = caughtError;\n }\n\n if (simulationError !== undefined && !fallbackOnSimulationFailure) {\n throw simulationError;\n }\n\n const fallbackGasConfig = fallbackGas ?? getFallbackGas(messenger);\n\n return {\n estimate: fallbackGasConfig.estimate,\n max: fallbackGasConfig.max,\n usedFallback: true,\n error: estimateGasError ?? simulationError,\n };\n}\n\n/**\n * Get gas fee estimates for a given chain.\n *\n * @param chainId - Chain ID.\n * @param messenger - Controller messenger.\n * @returns Gas fee estimates for the chain.\n */\nexport function getGasFee(\n chainId: Hex,\n messenger: TransactionPayControllerMessenger,\n): {\n estimatedBaseFee: string | undefined;\n maxFeePerGas: string | undefined;\n maxPriorityFeePerGas: string | undefined;\n} {\n const gasFeeControllerState = messenger.call('GasFeeController:getState');\n\n const chainState = gasFeeControllerState?.gasFeeEstimatesByChainId?.[chainId];\n\n const { estimatedBaseFee: estimatedBaseFeeGwei, medium } =\n (chainState?.gasFeeEstimates as GasFeeEstimates | undefined) ?? {};\n\n const maxFeePerGasGwei = medium?.suggestedMaxFeePerGas;\n const maxPriorityFeePerGasGwei = medium?.suggestedMaxPriorityFeePerGas;\n\n const estimatedBaseFee = estimatedBaseFeeGwei\n ? new BigNumber(estimatedBaseFeeGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxFeePerGas = maxFeePerGasGwei\n ? new BigNumber(maxFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n const maxPriorityFeePerGas = maxPriorityFeePerGasGwei\n ? new BigNumber(maxPriorityFeePerGasGwei).shiftedBy(9).toString(10)\n : undefined;\n\n return { estimatedBaseFee, maxFeePerGas, maxPriorityFeePerGas };\n}\n\nfunction parseEstimatedGas(gasValue: string): number {\n const parsedGas = gasValue.startsWith('0x')\n ? new BigNumber(gasValue.slice(2), 16)\n : new BigNumber(gasValue);\n\n if (!parsedGas.isFinite() || parsedGas.isNaN()) {\n throw new Error(`Invalid gas estimate returned: ${gasValue}`);\n }\n\n return parsedGas.toNumber();\n}\n\n/**\n * Calculate the cost of a gas fee token on a transaction.\n *\n * @param request - Request parameters.\n * @param request.hasBalance - Whether the user has enough balance to cover the gas fee.\n * @param request.messenger - Controller messenger.\n * @param request.transaction - Transaction to calculate gas fee token cost for.\n * @returns Cost of the gas fee token.\n */\nfunction calculateTransactionGasFeeTokenCost({\n hasBalance,\n messenger,\n transaction,\n}: {\n hasBalance: boolean;\n messenger: TransactionPayControllerMessenger;\n transaction: TransactionMeta;\n}): (Amount & { isGasFeeToken?: boolean }) | undefined {\n const {\n chainId,\n gasFeeTokens,\n isGasFeeTokenIgnoredIfBalance,\n selectedGasFeeToken,\n } = transaction;\n\n if (\n !gasFeeTokens ||\n !selectedGasFeeToken ||\n (isGasFeeTokenIgnoredIfBalance && hasBalance)\n ) {\n return undefined;\n }\n\n log('Calculating gas fee token cost', { selectedGasFeeToken, chainId });\n\n const gasFeeToken = gasFeeTokens?.find(\n (singleGasFeeToken) =>\n singleGasFeeToken.tokenAddress.toLowerCase() ===\n selectedGasFeeToken.toLowerCase(),\n );\n\n if (!gasFeeToken) {\n log('Gas fee token not found', {\n gasFeeTokens,\n selectedGasFeeToken,\n });\n\n return undefined;\n }\n\n return calculateGasFeeTokenCost({\n chainId,\n gasFeeToken,\n messenger,\n });\n}\n"]}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.rpcRequest = exports.getNetworkClientId = void 0;
|
|
4
|
+
const network_controller_1 = require("@metamask/network-controller");
|
|
5
|
+
const utils_1 = require("@metamask/utils");
|
|
6
|
+
const logger_1 = require("../logger.cjs");
|
|
7
|
+
const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'provider');
|
|
8
|
+
/**
|
|
9
|
+
* Resolve the network client ID for a chain.
|
|
10
|
+
*
|
|
11
|
+
* When `preferInfura` is true the method tries to locate an Infura endpoint
|
|
12
|
+
* in the chain's network configuration and returns its `networkClientId`.
|
|
13
|
+
* If no Infura endpoint is configured, or if the configuration lookup throws,
|
|
14
|
+
* it falls back to `findNetworkClientIdByChainId`.
|
|
15
|
+
*
|
|
16
|
+
* @param messenger - The TransactionPayController messenger.
|
|
17
|
+
* @param chainId - The chain ID to resolve.
|
|
18
|
+
* @param options - Resolution options.
|
|
19
|
+
* @param options.preferInfura - Prefer the Infura endpoint when available.
|
|
20
|
+
* @returns The resolved network client ID.
|
|
21
|
+
*/
|
|
22
|
+
function getNetworkClientId(messenger, chainId, { preferInfura = false } = {}) {
|
|
23
|
+
if (preferInfura) {
|
|
24
|
+
try {
|
|
25
|
+
const networkConfiguration = messenger.call('NetworkController:getNetworkConfigurationByChainId', chainId);
|
|
26
|
+
const infuraEndpoint = networkConfiguration?.rpcEndpoints.find((endpoint) => endpoint.type === network_controller_1.RpcEndpointType.Infura);
|
|
27
|
+
if (infuraEndpoint) {
|
|
28
|
+
return infuraEndpoint.networkClientId;
|
|
29
|
+
}
|
|
30
|
+
log('No Infura endpoint found for chain', {
|
|
31
|
+
chainId,
|
|
32
|
+
rpcEndpoints: networkConfiguration?.rpcEndpoints,
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
log('Error looking up Infura endpoint', { chainId, error });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return messenger.call('NetworkController:findNetworkClientIdByChainId', chainId);
|
|
40
|
+
}
|
|
41
|
+
exports.getNetworkClientId = getNetworkClientId;
|
|
42
|
+
/**
|
|
43
|
+
* Send an RPC request to the network for the specified chain.
|
|
44
|
+
*
|
|
45
|
+
* @param request - Request parameters.
|
|
46
|
+
* @param request.messenger - The TransactionPayController messenger.
|
|
47
|
+
* @param request.chainId - The chain ID to resolve.
|
|
48
|
+
* @param request.method - The JSON-RPC method name.
|
|
49
|
+
* @param request.params - Optional parameters for the RPC call.
|
|
50
|
+
* @param request.options - Resolution options forwarded to {@link getNetworkClientId}.
|
|
51
|
+
* @returns The RPC response typed as `TResponse`.
|
|
52
|
+
*/
|
|
53
|
+
async function rpcRequest({ messenger, chainId, method, params, options, }) {
|
|
54
|
+
const networkClientId = getNetworkClientId(messenger, chainId, options);
|
|
55
|
+
const { provider } = messenger.call('NetworkController:getNetworkClientById', networkClientId);
|
|
56
|
+
const response = await provider.request({ method, params });
|
|
57
|
+
log(method, { chainId, networkClientId, params, response });
|
|
58
|
+
return response;
|
|
59
|
+
}
|
|
60
|
+
exports.rpcRequest = rpcRequest;
|
|
61
|
+
//# sourceMappingURL=provider.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.cjs","sourceRoot":"","sources":["../../src/utils/provider.ts"],"names":[],"mappings":";;;AACA,qEAA+D;AAE/D,2CAAqD;AAErD,0CAA0C;AAG1C,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,UAAU,CAAC,CAAC;AAgC1D;;;;;;;;;;;;;GAaG;AACH,SAAgB,kBAAkB,CAChC,SAA4C,EAC5C,OAAY,EACZ,EAAE,YAAY,GAAG,KAAK,KAAgC,EAAE;IAExD,IAAI,YAAY,EAAE,CAAC;QACjB,IAAI,CAAC;YACH,MAAM,oBAAoB,GAAG,SAAS,CAAC,IAAI,CACzC,oDAAoD,EACpD,OAAO,CACR,CAAC;YAEF,MAAM,cAAc,GAAG,oBAAoB,EAAE,YAAY,CAAC,IAAI,CAC5D,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,KAAK,oCAAe,CAAC,MAAM,CACvD,CAAC;YAEF,IAAI,cAAc,EAAE,CAAC;gBACnB,OAAO,cAAc,CAAC,eAAe,CAAC;YACxC,CAAC;YAED,GAAG,CAAC,oCAAoC,EAAE;gBACxC,OAAO;gBACP,YAAY,EAAE,oBAAoB,EAAE,YAAY;aACjD,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,kCAAkC,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC,IAAI,CACnB,gDAAgD,EAChD,OAAO,CACR,CAAC;AACJ,CAAC;AAjCD,gDAiCC;AAED;;;;;;;;;;GAUG;AACI,KAAK,UAAU,UAAU,CAAsB,EACpD,SAAS,EACT,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,GACU;IACjB,MAAM,eAAe,GAAG,kBAAkB,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAExE,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAC,IAAI,CACjC,wCAAwC,EACxC,eAAe,CAChB,CAAC;IAEF,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAE5D,GAAG,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IAE5D,OAAO,QAAqB,CAAC;AAC/B,CAAC;AAnBD,gCAmBC","sourcesContent":["import type { NetworkClientId, Provider } from '@metamask/network-controller';\nimport { RpcEndpointType } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionPayControllerMessenger } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'provider');\n\ntype ProviderRequestParams = Parameters<Provider['request']>[0]['params'];\n\n/**\n * Options for network client resolution.\n */\nexport type GetNetworkClientIdOptions = {\n /**\n * When true, attempts to resolve to an Infura endpoint for the chain before\n * falling back to the default selected endpoint. Useful for calls that use\n * block tags (e.g. `pending`) that may not be supported by custom RPCs.\n */\n preferInfura?: boolean;\n};\n\n/**\n * Parameters for {@link rpcRequest}.\n */\nexport type RpcRequestParams = {\n /** The TransactionPayController messenger. */\n messenger: TransactionPayControllerMessenger;\n /** The chain ID to resolve. */\n chainId: Hex;\n /** The JSON-RPC method name. */\n method: string;\n /** Optional parameters for the RPC call. */\n params?: ProviderRequestParams;\n /** Resolution options forwarded to {@link getNetworkClientId}. */\n options?: GetNetworkClientIdOptions;\n};\n\n/**\n * Resolve the network client ID for a chain.\n *\n * When `preferInfura` is true the method tries to locate an Infura endpoint\n * in the chain's network configuration and returns its `networkClientId`.\n * If no Infura endpoint is configured, or if the configuration lookup throws,\n * it falls back to `findNetworkClientIdByChainId`.\n *\n * @param messenger - The TransactionPayController messenger.\n * @param chainId - The chain ID to resolve.\n * @param options - Resolution options.\n * @param options.preferInfura - Prefer the Infura endpoint when available.\n * @returns The resolved network client ID.\n */\nexport function getNetworkClientId(\n messenger: TransactionPayControllerMessenger,\n chainId: Hex,\n { preferInfura = false }: GetNetworkClientIdOptions = {},\n): NetworkClientId {\n if (preferInfura) {\n try {\n const networkConfiguration = messenger.call(\n 'NetworkController:getNetworkConfigurationByChainId',\n chainId,\n );\n\n const infuraEndpoint = networkConfiguration?.rpcEndpoints.find(\n (endpoint) => endpoint.type === RpcEndpointType.Infura,\n );\n\n if (infuraEndpoint) {\n return infuraEndpoint.networkClientId;\n }\n\n log('No Infura endpoint found for chain', {\n chainId,\n rpcEndpoints: networkConfiguration?.rpcEndpoints,\n });\n } catch (error) {\n log('Error looking up Infura endpoint', { chainId, error });\n }\n }\n\n return messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n}\n\n/**\n * Send an RPC request to the network for the specified chain.\n *\n * @param request - Request parameters.\n * @param request.messenger - The TransactionPayController messenger.\n * @param request.chainId - The chain ID to resolve.\n * @param request.method - The JSON-RPC method name.\n * @param request.params - Optional parameters for the RPC call.\n * @param request.options - Resolution options forwarded to {@link getNetworkClientId}.\n * @returns The RPC response typed as `TResponse`.\n */\nexport async function rpcRequest<TResponse = unknown>({\n messenger,\n chainId,\n method,\n params,\n options,\n}: RpcRequestParams): Promise<TResponse> {\n const networkClientId = getNetworkClientId(messenger, chainId, options);\n\n const { provider } = messenger.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n\n const response = await provider.request({ method, params });\n\n log(method, { chainId, networkClientId, params, response });\n\n return response as TResponse;\n}\n"]}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { NetworkClientId, Provider } from "@metamask/network-controller";
|
|
2
|
+
import type { Hex } from "@metamask/utils";
|
|
3
|
+
import type { TransactionPayControllerMessenger } from "../types.cjs";
|
|
4
|
+
type ProviderRequestParams = Parameters<Provider['request']>[0]['params'];
|
|
5
|
+
/**
|
|
6
|
+
* Options for network client resolution.
|
|
7
|
+
*/
|
|
8
|
+
export type GetNetworkClientIdOptions = {
|
|
9
|
+
/**
|
|
10
|
+
* When true, attempts to resolve to an Infura endpoint for the chain before
|
|
11
|
+
* falling back to the default selected endpoint. Useful for calls that use
|
|
12
|
+
* block tags (e.g. `pending`) that may not be supported by custom RPCs.
|
|
13
|
+
*/
|
|
14
|
+
preferInfura?: boolean;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Parameters for {@link rpcRequest}.
|
|
18
|
+
*/
|
|
19
|
+
export type RpcRequestParams = {
|
|
20
|
+
/** The TransactionPayController messenger. */
|
|
21
|
+
messenger: TransactionPayControllerMessenger;
|
|
22
|
+
/** The chain ID to resolve. */
|
|
23
|
+
chainId: Hex;
|
|
24
|
+
/** The JSON-RPC method name. */
|
|
25
|
+
method: string;
|
|
26
|
+
/** Optional parameters for the RPC call. */
|
|
27
|
+
params?: ProviderRequestParams;
|
|
28
|
+
/** Resolution options forwarded to {@link getNetworkClientId}. */
|
|
29
|
+
options?: GetNetworkClientIdOptions;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Resolve the network client ID for a chain.
|
|
33
|
+
*
|
|
34
|
+
* When `preferInfura` is true the method tries to locate an Infura endpoint
|
|
35
|
+
* in the chain's network configuration and returns its `networkClientId`.
|
|
36
|
+
* If no Infura endpoint is configured, or if the configuration lookup throws,
|
|
37
|
+
* it falls back to `findNetworkClientIdByChainId`.
|
|
38
|
+
*
|
|
39
|
+
* @param messenger - The TransactionPayController messenger.
|
|
40
|
+
* @param chainId - The chain ID to resolve.
|
|
41
|
+
* @param options - Resolution options.
|
|
42
|
+
* @param options.preferInfura - Prefer the Infura endpoint when available.
|
|
43
|
+
* @returns The resolved network client ID.
|
|
44
|
+
*/
|
|
45
|
+
export declare function getNetworkClientId(messenger: TransactionPayControllerMessenger, chainId: Hex, { preferInfura }?: GetNetworkClientIdOptions): NetworkClientId;
|
|
46
|
+
/**
|
|
47
|
+
* Send an RPC request to the network for the specified chain.
|
|
48
|
+
*
|
|
49
|
+
* @param request - Request parameters.
|
|
50
|
+
* @param request.messenger - The TransactionPayController messenger.
|
|
51
|
+
* @param request.chainId - The chain ID to resolve.
|
|
52
|
+
* @param request.method - The JSON-RPC method name.
|
|
53
|
+
* @param request.params - Optional parameters for the RPC call.
|
|
54
|
+
* @param request.options - Resolution options forwarded to {@link getNetworkClientId}.
|
|
55
|
+
* @returns The RPC response typed as `TResponse`.
|
|
56
|
+
*/
|
|
57
|
+
export declare function rpcRequest<TResponse = unknown>({ messenger, chainId, method, params, options, }: RpcRequestParams): Promise<TResponse>;
|
|
58
|
+
export {};
|
|
59
|
+
//# sourceMappingURL=provider.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.cts","sourceRoot":"","sources":["../../src/utils/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,qCAAqC;AAE9E,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAIlE,KAAK,qBAAqB,GAAG,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;AAE1E;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC;;;;OAIG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,8CAA8C;IAC9C,SAAS,EAAE,iCAAiC,CAAC;IAC7C,+BAA+B;IAC/B,OAAO,EAAE,GAAG,CAAC;IACb,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,4CAA4C;IAC5C,MAAM,CAAC,EAAE,qBAAqB,CAAC;IAC/B,kEAAkE;IAClE,OAAO,CAAC,EAAE,yBAAyB,CAAC;CACrC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,iCAAiC,EAC5C,OAAO,EAAE,GAAG,EACZ,EAAE,YAAoB,EAAE,GAAE,yBAA8B,GACvD,eAAe,CA6BjB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,UAAU,CAAC,SAAS,GAAG,OAAO,EAAE,EACpD,SAAS,EACT,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,GACR,EAAE,gBAAgB,GAAG,OAAO,CAAC,SAAS,CAAC,CAavC"}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import type { NetworkClientId, Provider } from "@metamask/network-controller";
|
|
2
|
+
import type { Hex } from "@metamask/utils";
|
|
3
|
+
import type { TransactionPayControllerMessenger } from "../types.mjs";
|
|
4
|
+
type ProviderRequestParams = Parameters<Provider['request']>[0]['params'];
|
|
5
|
+
/**
|
|
6
|
+
* Options for network client resolution.
|
|
7
|
+
*/
|
|
8
|
+
export type GetNetworkClientIdOptions = {
|
|
9
|
+
/**
|
|
10
|
+
* When true, attempts to resolve to an Infura endpoint for the chain before
|
|
11
|
+
* falling back to the default selected endpoint. Useful for calls that use
|
|
12
|
+
* block tags (e.g. `pending`) that may not be supported by custom RPCs.
|
|
13
|
+
*/
|
|
14
|
+
preferInfura?: boolean;
|
|
15
|
+
};
|
|
16
|
+
/**
|
|
17
|
+
* Parameters for {@link rpcRequest}.
|
|
18
|
+
*/
|
|
19
|
+
export type RpcRequestParams = {
|
|
20
|
+
/** The TransactionPayController messenger. */
|
|
21
|
+
messenger: TransactionPayControllerMessenger;
|
|
22
|
+
/** The chain ID to resolve. */
|
|
23
|
+
chainId: Hex;
|
|
24
|
+
/** The JSON-RPC method name. */
|
|
25
|
+
method: string;
|
|
26
|
+
/** Optional parameters for the RPC call. */
|
|
27
|
+
params?: ProviderRequestParams;
|
|
28
|
+
/** Resolution options forwarded to {@link getNetworkClientId}. */
|
|
29
|
+
options?: GetNetworkClientIdOptions;
|
|
30
|
+
};
|
|
31
|
+
/**
|
|
32
|
+
* Resolve the network client ID for a chain.
|
|
33
|
+
*
|
|
34
|
+
* When `preferInfura` is true the method tries to locate an Infura endpoint
|
|
35
|
+
* in the chain's network configuration and returns its `networkClientId`.
|
|
36
|
+
* If no Infura endpoint is configured, or if the configuration lookup throws,
|
|
37
|
+
* it falls back to `findNetworkClientIdByChainId`.
|
|
38
|
+
*
|
|
39
|
+
* @param messenger - The TransactionPayController messenger.
|
|
40
|
+
* @param chainId - The chain ID to resolve.
|
|
41
|
+
* @param options - Resolution options.
|
|
42
|
+
* @param options.preferInfura - Prefer the Infura endpoint when available.
|
|
43
|
+
* @returns The resolved network client ID.
|
|
44
|
+
*/
|
|
45
|
+
export declare function getNetworkClientId(messenger: TransactionPayControllerMessenger, chainId: Hex, { preferInfura }?: GetNetworkClientIdOptions): NetworkClientId;
|
|
46
|
+
/**
|
|
47
|
+
* Send an RPC request to the network for the specified chain.
|
|
48
|
+
*
|
|
49
|
+
* @param request - Request parameters.
|
|
50
|
+
* @param request.messenger - The TransactionPayController messenger.
|
|
51
|
+
* @param request.chainId - The chain ID to resolve.
|
|
52
|
+
* @param request.method - The JSON-RPC method name.
|
|
53
|
+
* @param request.params - Optional parameters for the RPC call.
|
|
54
|
+
* @param request.options - Resolution options forwarded to {@link getNetworkClientId}.
|
|
55
|
+
* @returns The RPC response typed as `TResponse`.
|
|
56
|
+
*/
|
|
57
|
+
export declare function rpcRequest<TResponse = unknown>({ messenger, chainId, method, params, options, }: RpcRequestParams): Promise<TResponse>;
|
|
58
|
+
export {};
|
|
59
|
+
//# sourceMappingURL=provider.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.mts","sourceRoot":"","sources":["../../src/utils/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,QAAQ,EAAE,qCAAqC;AAE9E,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAE,iCAAiC,EAAE,qBAAiB;AAIlE,KAAK,qBAAqB,GAAG,UAAU,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC;AAE1E;;GAEG;AACH,MAAM,MAAM,yBAAyB,GAAG;IACtC;;;;OAIG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,CAAC;AAEF;;GAEG;AACH,MAAM,MAAM,gBAAgB,GAAG;IAC7B,8CAA8C;IAC9C,SAAS,EAAE,iCAAiC,CAAC;IAC7C,+BAA+B;IAC/B,OAAO,EAAE,GAAG,CAAC;IACb,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,4CAA4C;IAC5C,MAAM,CAAC,EAAE,qBAAqB,CAAC;IAC/B,kEAAkE;IAClE,OAAO,CAAC,EAAE,yBAAyB,CAAC;CACrC,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,iCAAiC,EAC5C,OAAO,EAAE,GAAG,EACZ,EAAE,YAAoB,EAAE,GAAE,yBAA8B,GACvD,eAAe,CA6BjB;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,UAAU,CAAC,SAAS,GAAG,OAAO,EAAE,EACpD,SAAS,EACT,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,GACR,EAAE,gBAAgB,GAAG,OAAO,CAAC,SAAS,CAAC,CAavC"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { RpcEndpointType } from "@metamask/network-controller";
|
|
2
|
+
import { createModuleLogger } from "@metamask/utils";
|
|
3
|
+
import { projectLogger } from "../logger.mjs";
|
|
4
|
+
const log = createModuleLogger(projectLogger, 'provider');
|
|
5
|
+
/**
|
|
6
|
+
* Resolve the network client ID for a chain.
|
|
7
|
+
*
|
|
8
|
+
* When `preferInfura` is true the method tries to locate an Infura endpoint
|
|
9
|
+
* in the chain's network configuration and returns its `networkClientId`.
|
|
10
|
+
* If no Infura endpoint is configured, or if the configuration lookup throws,
|
|
11
|
+
* it falls back to `findNetworkClientIdByChainId`.
|
|
12
|
+
*
|
|
13
|
+
* @param messenger - The TransactionPayController messenger.
|
|
14
|
+
* @param chainId - The chain ID to resolve.
|
|
15
|
+
* @param options - Resolution options.
|
|
16
|
+
* @param options.preferInfura - Prefer the Infura endpoint when available.
|
|
17
|
+
* @returns The resolved network client ID.
|
|
18
|
+
*/
|
|
19
|
+
export function getNetworkClientId(messenger, chainId, { preferInfura = false } = {}) {
|
|
20
|
+
if (preferInfura) {
|
|
21
|
+
try {
|
|
22
|
+
const networkConfiguration = messenger.call('NetworkController:getNetworkConfigurationByChainId', chainId);
|
|
23
|
+
const infuraEndpoint = networkConfiguration?.rpcEndpoints.find((endpoint) => endpoint.type === RpcEndpointType.Infura);
|
|
24
|
+
if (infuraEndpoint) {
|
|
25
|
+
return infuraEndpoint.networkClientId;
|
|
26
|
+
}
|
|
27
|
+
log('No Infura endpoint found for chain', {
|
|
28
|
+
chainId,
|
|
29
|
+
rpcEndpoints: networkConfiguration?.rpcEndpoints,
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
log('Error looking up Infura endpoint', { chainId, error });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return messenger.call('NetworkController:findNetworkClientIdByChainId', chainId);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Send an RPC request to the network for the specified chain.
|
|
40
|
+
*
|
|
41
|
+
* @param request - Request parameters.
|
|
42
|
+
* @param request.messenger - The TransactionPayController messenger.
|
|
43
|
+
* @param request.chainId - The chain ID to resolve.
|
|
44
|
+
* @param request.method - The JSON-RPC method name.
|
|
45
|
+
* @param request.params - Optional parameters for the RPC call.
|
|
46
|
+
* @param request.options - Resolution options forwarded to {@link getNetworkClientId}.
|
|
47
|
+
* @returns The RPC response typed as `TResponse`.
|
|
48
|
+
*/
|
|
49
|
+
export async function rpcRequest({ messenger, chainId, method, params, options, }) {
|
|
50
|
+
const networkClientId = getNetworkClientId(messenger, chainId, options);
|
|
51
|
+
const { provider } = messenger.call('NetworkController:getNetworkClientById', networkClientId);
|
|
52
|
+
const response = await provider.request({ method, params });
|
|
53
|
+
log(method, { chainId, networkClientId, params, response });
|
|
54
|
+
return response;
|
|
55
|
+
}
|
|
56
|
+
//# sourceMappingURL=provider.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.mjs","sourceRoot":"","sources":["../../src/utils/provider.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,eAAe,EAAE,qCAAqC;AAE/D,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD,OAAO,EAAE,aAAa,EAAE,sBAAkB;AAG1C,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,UAAU,CAAC,CAAC;AAgC1D;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,kBAAkB,CAChC,SAA4C,EAC5C,OAAY,EACZ,EAAE,YAAY,GAAG,KAAK,KAAgC,EAAE;IAExD,IAAI,YAAY,EAAE,CAAC;QACjB,IAAI,CAAC;YACH,MAAM,oBAAoB,GAAG,SAAS,CAAC,IAAI,CACzC,oDAAoD,EACpD,OAAO,CACR,CAAC;YAEF,MAAM,cAAc,GAAG,oBAAoB,EAAE,YAAY,CAAC,IAAI,CAC5D,CAAC,QAAQ,EAAE,EAAE,CAAC,QAAQ,CAAC,IAAI,KAAK,eAAe,CAAC,MAAM,CACvD,CAAC;YAEF,IAAI,cAAc,EAAE,CAAC;gBACnB,OAAO,cAAc,CAAC,eAAe,CAAC;YACxC,CAAC;YAED,GAAG,CAAC,oCAAoC,EAAE;gBACxC,OAAO;gBACP,YAAY,EAAE,oBAAoB,EAAE,YAAY;aACjD,CAAC,CAAC;QACL,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,GAAG,CAAC,kCAAkC,EAAE,EAAE,OAAO,EAAE,KAAK,EAAE,CAAC,CAAC;QAC9D,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC,IAAI,CACnB,gDAAgD,EAChD,OAAO,CACR,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,UAAU,CAAsB,EACpD,SAAS,EACT,OAAO,EACP,MAAM,EACN,MAAM,EACN,OAAO,GACU;IACjB,MAAM,eAAe,GAAG,kBAAkB,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;IAExE,MAAM,EAAE,QAAQ,EAAE,GAAG,SAAS,CAAC,IAAI,CACjC,wCAAwC,EACxC,eAAe,CAChB,CAAC;IAEF,MAAM,QAAQ,GAAG,MAAM,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;IAE5D,GAAG,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,eAAe,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC;IAE5D,OAAO,QAAqB,CAAC;AAC/B,CAAC","sourcesContent":["import type { NetworkClientId, Provider } from '@metamask/network-controller';\nimport { RpcEndpointType } from '@metamask/network-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../logger';\nimport type { TransactionPayControllerMessenger } from '../types';\n\nconst log = createModuleLogger(projectLogger, 'provider');\n\ntype ProviderRequestParams = Parameters<Provider['request']>[0]['params'];\n\n/**\n * Options for network client resolution.\n */\nexport type GetNetworkClientIdOptions = {\n /**\n * When true, attempts to resolve to an Infura endpoint for the chain before\n * falling back to the default selected endpoint. Useful for calls that use\n * block tags (e.g. `pending`) that may not be supported by custom RPCs.\n */\n preferInfura?: boolean;\n};\n\n/**\n * Parameters for {@link rpcRequest}.\n */\nexport type RpcRequestParams = {\n /** The TransactionPayController messenger. */\n messenger: TransactionPayControllerMessenger;\n /** The chain ID to resolve. */\n chainId: Hex;\n /** The JSON-RPC method name. */\n method: string;\n /** Optional parameters for the RPC call. */\n params?: ProviderRequestParams;\n /** Resolution options forwarded to {@link getNetworkClientId}. */\n options?: GetNetworkClientIdOptions;\n};\n\n/**\n * Resolve the network client ID for a chain.\n *\n * When `preferInfura` is true the method tries to locate an Infura endpoint\n * in the chain's network configuration and returns its `networkClientId`.\n * If no Infura endpoint is configured, or if the configuration lookup throws,\n * it falls back to `findNetworkClientIdByChainId`.\n *\n * @param messenger - The TransactionPayController messenger.\n * @param chainId - The chain ID to resolve.\n * @param options - Resolution options.\n * @param options.preferInfura - Prefer the Infura endpoint when available.\n * @returns The resolved network client ID.\n */\nexport function getNetworkClientId(\n messenger: TransactionPayControllerMessenger,\n chainId: Hex,\n { preferInfura = false }: GetNetworkClientIdOptions = {},\n): NetworkClientId {\n if (preferInfura) {\n try {\n const networkConfiguration = messenger.call(\n 'NetworkController:getNetworkConfigurationByChainId',\n chainId,\n );\n\n const infuraEndpoint = networkConfiguration?.rpcEndpoints.find(\n (endpoint) => endpoint.type === RpcEndpointType.Infura,\n );\n\n if (infuraEndpoint) {\n return infuraEndpoint.networkClientId;\n }\n\n log('No Infura endpoint found for chain', {\n chainId,\n rpcEndpoints: networkConfiguration?.rpcEndpoints,\n });\n } catch (error) {\n log('Error looking up Infura endpoint', { chainId, error });\n }\n }\n\n return messenger.call(\n 'NetworkController:findNetworkClientIdByChainId',\n chainId,\n );\n}\n\n/**\n * Send an RPC request to the network for the specified chain.\n *\n * @param request - Request parameters.\n * @param request.messenger - The TransactionPayController messenger.\n * @param request.chainId - The chain ID to resolve.\n * @param request.method - The JSON-RPC method name.\n * @param request.params - Optional parameters for the RPC call.\n * @param request.options - Resolution options forwarded to {@link getNetworkClientId}.\n * @returns The RPC response typed as `TResponse`.\n */\nexport async function rpcRequest<TResponse = unknown>({\n messenger,\n chainId,\n method,\n params,\n options,\n}: RpcRequestParams): Promise<TResponse> {\n const networkClientId = getNetworkClientId(messenger, chainId, options);\n\n const { provider } = messenger.call(\n 'NetworkController:getNetworkClientById',\n networkClientId,\n );\n\n const response = await provider.request({ method, params });\n\n log(method, { chainId, networkClientId, params, response });\n\n return response as TResponse;\n}\n"]}
|
package/dist/utils/token.cjs
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
3
|
exports.normalizeTokenAddress = exports.TokenAddressTarget = exports.buildCaipAssetType = exports.getLiveTokenBalance = exports.getNativeToken = exports.computeRawFromFiatAmount = exports.computeTokenAmounts = exports.getTokenFiatRate = exports.getTokenInfo = exports.getTokenBalance = exports.isSameToken = void 0;
|
|
4
|
-
const
|
|
5
|
-
const providers_1 = require("@ethersproject/providers");
|
|
4
|
+
const abi_1 = require("@ethersproject/abi");
|
|
6
5
|
const controller_utils_1 = require("@metamask/controller-utils");
|
|
7
6
|
const metamask_eth_abis_1 = require("@metamask/metamask-eth-abis");
|
|
8
7
|
const utils_1 = require("@metamask/utils");
|
|
9
8
|
const bignumber_js_1 = require("bignumber.js");
|
|
10
9
|
const constants_1 = require("../constants.cjs");
|
|
11
10
|
const feature_flags_1 = require("./feature-flags.cjs");
|
|
11
|
+
const provider_1 = require("./provider.cjs");
|
|
12
12
|
/**
|
|
13
13
|
* Check if two tokens are the same (same address and chain).
|
|
14
14
|
*
|
|
@@ -214,6 +214,10 @@ exports.getNativeToken = getNativeToken;
|
|
|
214
214
|
* Unlike {@link getTokenBalance}, this bypasses the cached state in
|
|
215
215
|
* `TokenBalancesController` and reads directly from the chain.
|
|
216
216
|
*
|
|
217
|
+
* Uses the Infura RPC endpoint for the chain when one is configured, falling
|
|
218
|
+
* back to the chain's default endpoint. This avoids errors on custom mainnet
|
|
219
|
+
* RPC endpoints that may not support pending block queries.
|
|
220
|
+
*
|
|
217
221
|
* @param messenger - Controller messenger.
|
|
218
222
|
* @param account - Address of the account.
|
|
219
223
|
* @param chainId - Chain ID.
|
|
@@ -221,20 +225,29 @@ exports.getNativeToken = getNativeToken;
|
|
|
221
225
|
* @returns Raw token balance as a decimal string.
|
|
222
226
|
*/
|
|
223
227
|
async function getLiveTokenBalance(messenger, account, chainId, tokenAddress) {
|
|
224
|
-
const
|
|
225
|
-
const { provider } = messenger.call('NetworkController:getNetworkClientById', networkClientId);
|
|
226
|
-
const ethersProvider = new providers_1.Web3Provider(provider);
|
|
228
|
+
const options = { preferInfura: true };
|
|
227
229
|
const isNative = tokenAddress.toLowerCase() === getNativeToken(chainId).toLowerCase();
|
|
228
|
-
// Use `pending` blockTag to bypass the RPC block-cache middleware so callers
|
|
229
|
-
// always observe the latest balance instead of a value pinned to the last
|
|
230
|
-
// polled block.
|
|
231
230
|
if (isNative) {
|
|
232
|
-
const
|
|
233
|
-
|
|
231
|
+
const result = await (0, provider_1.rpcRequest)({
|
|
232
|
+
messenger,
|
|
233
|
+
chainId,
|
|
234
|
+
method: 'eth_getBalance',
|
|
235
|
+
params: [account, 'pending'],
|
|
236
|
+
options,
|
|
237
|
+
});
|
|
238
|
+
return new bignumber_js_1.BigNumber(result, 16).toString(10);
|
|
234
239
|
}
|
|
235
|
-
const
|
|
236
|
-
|
|
237
|
-
|
|
240
|
+
const calldata = new abi_1.Interface(metamask_eth_abis_1.abiERC20).encodeFunctionData('balanceOf', [
|
|
241
|
+
account,
|
|
242
|
+
]);
|
|
243
|
+
const result = await (0, provider_1.rpcRequest)({
|
|
244
|
+
messenger,
|
|
245
|
+
chainId,
|
|
246
|
+
method: 'eth_call',
|
|
247
|
+
params: [{ to: tokenAddress, data: calldata }, 'pending'],
|
|
248
|
+
options,
|
|
249
|
+
});
|
|
250
|
+
return new bignumber_js_1.BigNumber(result, 16).toString(10);
|
|
238
251
|
}
|
|
239
252
|
exports.getLiveTokenBalance = getLiveTokenBalance;
|
|
240
253
|
/**
|
|
@@ -261,9 +274,8 @@ function buildCaipAssetType(chainId, tokenAddress, slip44CoinType) {
|
|
|
261
274
|
exports.buildCaipAssetType = buildCaipAssetType;
|
|
262
275
|
function getTicker(chainId, messenger) {
|
|
263
276
|
try {
|
|
264
|
-
const networkClientId =
|
|
265
|
-
|
|
266
|
-
return networkConfiguration.configuration.ticker;
|
|
277
|
+
const networkClientId = (0, provider_1.getNetworkClientId)(messenger, chainId);
|
|
278
|
+
return messenger.call('NetworkController:getNetworkClientById', networkClientId).configuration.ticker;
|
|
267
279
|
}
|
|
268
280
|
catch {
|
|
269
281
|
return undefined;
|