@metamask-previews/transaction-pay-controller 30.4.0-preview-4a273a7 → 30.4.1-preview-c3d36da85

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
@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Changed
11
+
12
+ - Bump `@metamask/assets-controller` from `^20.2.0` to `^20.2.1` ([#11285](https://github.com/MetaMask/core/pull/11285))
13
+
14
+ ### Fixed
15
+
16
+ - Quote Across perps deposits in the 6 decimals Across uses for HyperCore USDC-PERPS, instead of requesting 100 times the deposit amount ([#11270](https://github.com/MetaMask/core/pull/11270))
17
+ - Reject Across perps deposit quotes whose USDC-PERPS decimals differ from those used to scale the request, so the next strategy is tried instead of showing a mispriced quote.
18
+
19
+ ## [30.4.1]
20
+
21
+ ### Added
22
+
23
+ - Support fiat payments for `membershipSubscription` transactions ([#11256](https://github.com/MetaMask/core/pull/11256))
24
+ - Add `membershipSubscription` to the default fiat-enabled transaction types and fiat asset map.
25
+ - Treat `membershipSubscription` as a Money Account deposit, so it uses the direct mUSD on-ramp when `directMoneyMusdEnabled` is set, and CHOMP vault recovery on the second leg.
26
+
10
27
  ## [30.4.0]
11
28
 
12
29
  ### Added
@@ -1787,7 +1804,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
1787
1804
 
1788
1805
  - Initial release ([#6820](https://github.com/MetaMask/core/pull/6820))
1789
1806
 
1790
- [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.4.0...HEAD
1807
+ [Unreleased]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.4.1...HEAD
1808
+ [30.4.1]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.4.0...@metamask/transaction-pay-controller@30.4.1
1791
1809
  [30.4.0]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.3.3...@metamask/transaction-pay-controller@30.4.0
1792
1810
  [30.3.3]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.3.2...@metamask/transaction-pay-controller@30.3.3
1793
1811
  [30.3.2]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.3.1...@metamask/transaction-pay-controller@30.3.2
@@ -12,7 +12,7 @@ import { estimateQuoteGasLimits } from '../../utils/quote-gas.js';
12
12
  import { getTokenFiatRate } from '../../utils/token.js';
13
13
  import { getAcrossDestination } from './across-actions.js';
14
14
  import { hasUnsupportedTransactionAuthorizationList } from './authorization-list.js';
15
- import { normalizeAcrossRequest } from './perps.js';
15
+ import { normalizeAcrossRequest, validateAcrossPerpsQuote } from './perps.js';
16
16
  import { isAcrossQuoteRequest } from './requests.js';
17
17
  import { getAcrossOrderedTransactions, getOriginalTransactionGas, } from './transactions.js';
18
18
  const log = createModuleLogger(projectLogger, 'across-strategy');
@@ -68,6 +68,7 @@ async function getSingleQuote(request, fullRequest) {
68
68
  slippage: slippageDecimal,
69
69
  tradeType,
70
70
  });
71
+ validateAcrossPerpsQuote(normalizedRequest, quote);
71
72
  const originalQuote = {
72
73
  quote,
73
74
  request: {
@@ -1 +1 @@
1
- {"version":3,"file":"across-quotes.js","sourceRoot":"","sources":["../../../src/strategy/across/across-quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,kCAAkC,CAAC;AAG1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,oBAAoB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAShD,OAAO,EAAE,mBAAmB,EAAE,UAAU,EAAE,M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A0B,EAAE,YAAY;QACxC,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;IACpC,MAAM,oBAAoB,GACxB,0BAA0B,EAAE,oBAAoB;QAChD,WAAW,CAAC,QAAQ,CAAC,oBAAoB,CAAC;IAE5C,OAAO;QACL,QAAQ,EAAE,gBAAgB,CAAC;YACzB,OAAO,EAAE,WAAW,CAAC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC;YACrD,GAAG;YACH,YAAY;YACZ,oBAAoB;YACpB,SAAS;SACV,CAAC;QACF,GAAG,EAAE,gBAAgB,CAAC;YACpB,OAAO,EAAE,WAAW,CAAC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC;YACrD,GAAG;YACH,KAAK,EAAE,IAAI;YACX,YAAY;YACZ,oBAAoB;YACpB,SAAS;SACV,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import { successfulFetch, toHex } from '@metamask/controller-utils';\nimport {\n TransactionType,\n hasTransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { TransactionPayStrategy } from '../../constants.js';\nimport { projectLogger } from '../../logger.js';\nimport type {\n Amount,\n FiatRates,\n PayStrategyGetQuotesRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { getFiatValueFromUsd, sumAmounts } from '../../utils/amounts.js';\nimport {\n getPayStrategiesConfig,\n getSlippage,\n} from '../../utils/feature-flags.js';\nimport { resolveGasStationCost } from '../../utils/gas-payment.js';\nimport { calculateGasCost } from '../../utils/gas.js';\nimport { estimateQuoteGasLimits } from '../../utils/quote-gas.js';\nimport type { QuoteGasTransaction } from '../../utils/quote-gas.js';\nimport { getTokenFiatRate } from '../../utils/token.js';\nimport type { AcrossDestination } from './across-actions.js';\nimport { getAcrossDestination } from './across-actions.js';\nimport { hasUnsupportedTransactionAuthorizationList } from './authorization-list.js';\nimport { normalizeAcrossRequest } from './perps.js';\nimport { isAcrossQuoteRequest } from './requests.js';\nimport {\n getAcrossOrderedTransactions,\n getOriginalTransactionGas,\n} from './transactions.js';\nimport type {\n AcrossAction,\n AcrossActionRequestBody,\n AcrossGasLimits,\n AcrossQuote,\n AcrossSwapApprovalResponse,\n} from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'across-strategy');\n\nconst UNSUPPORTED_AUTHORIZATION_LIST_ERROR =\n 'Across does not support type-4/EIP-7702 authorization lists yet';\n\ntype AcrossQuoteWithoutMetaMask = Omit<AcrossQuote, 'metamask'>;\n\n/**\n * Fetch Across quotes.\n *\n * @param request - Request object.\n * @returns Array of quotes.\n */\nexport async function getAcrossQuotes(\n request: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>[]> {\n const { requests } = request;\n\n log('Fetching quotes', requests);\n\n try {\n const normalizedRequests = requests.filter(isAcrossQuoteRequest);\n\n if (normalizedRequests.length === 0) {\n return [];\n }\n\n if (\n hasUnsupportedTransactionAuthorizationList(\n request.transaction,\n normalizedRequests,\n )\n ) {\n throw new Error(UNSUPPORTED_AUTHORIZATION_LIST_ERROR);\n }\n\n return await Promise.all(\n normalizedRequests.map((singleRequest) =>\n getQuoteWithGasStationHandling(singleRequest, request),\n ),\n );\n } catch (error) {\n log('Error fetching quotes', { error });\n throw new Error(`Failed to fetch Across quotes: ${String(error)}`);\n }\n}\n\nasync function getSingleQuote(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n const { messenger, signal, transaction } = fullRequest;\n const normalizedRequest = normalizeAcrossRequest(request, transaction);\n const {\n from,\n isMaxAmount,\n sourceChainId,\n sourceTokenAddress,\n sourceTokenAmount,\n targetAmountMinimum,\n targetChainId,\n targetTokenAddress,\n } = normalizedRequest;\n\n const config = getPayStrategiesConfig(messenger);\n const slippageDecimal = getSlippage(\n messenger,\n sourceChainId,\n sourceTokenAddress,\n );\n\n const useExactInput = isMaxAmount\n ? true\n : normalizedRequest.isPostQuote === true;\n const amount = useExactInput ? sourceTokenAmount : targetAmountMinimum;\n const tradeType = useExactInput ? 'exactInput' : 'exactOutput';\n const destination = getAcrossDestinationForRequest(\n transaction,\n request,\n from,\n );\n\n const quote = await requestAcrossApproval({\n actions: destination.actions,\n amount,\n apiBase: config.across.apiBase,\n depositor: from,\n destinationChainId: targetChainId,\n inputToken: sourceTokenAddress,\n originChainId: sourceChainId,\n outputToken: targetTokenAddress,\n recipient: destination.recipient,\n signal,\n refundAddress: normalizedRequest.refundTo,\n slippage: slippageDecimal,\n tradeType,\n });\n\n const originalQuote: AcrossQuoteWithoutMetaMask = {\n quote,\n request: {\n actions: destination.actions,\n amount,\n tradeType,\n },\n };\n\n return await normalizeQuote(originalQuote, normalizedRequest, fullRequest);\n}\n\nfunction getAcrossDestinationForRequest(\n transaction: TransactionMeta,\n request: QuoteRequest,\n recipient: Hex,\n): AcrossDestination {\n if (request.isPostQuote) {\n return {\n actions: [],\n recipient,\n };\n }\n\n return getAcrossDestination(transaction, request);\n}\n\nasync function getQuoteWithGasStationHandling(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n // Phase 1 uses the requested source amount to discover whether Across will\n // pay source-chain gas with the source token, and what the max gas cost is.\n // Phase 2 repeats the quote with that max gas cost reserved from the source\n // amount, so execution can fund both the Across deposit and token-paid gas.\n const phase1Quote = await getSingleQuote(request, fullRequest);\n\n if (\n (!request.isMaxAmount && !request.isPostQuote) ||\n !phase1Quote.fees.isSourceGasFeeToken\n ) {\n return phase1Quote;\n }\n\n const requiresSourceGasReservation =\n request.isPostQuote === true &&\n hasTransactionType(fullRequest.transaction, [\n TransactionType.predictWithdraw,\n ]);\n\n const adjustedSourceAmount = new BigNumber(request.sourceTokenAmount)\n .minus(phase1Quote.fees.sourceNetwork.max.raw)\n .integerValue(BigNumber.ROUND_DOWN);\n\n if (!adjustedSourceAmount.isGreaterThan(0)) {\n log('Insufficient balance after gas subtraction for Across quote');\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw source amount cannot cover source gas fee token',\n );\n }\n return phase1Quote;\n }\n\n log('Subtracting gas from source for Across quote', {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n gasCostRaw: phase1Quote.fees.sourceNetwork.max.raw,\n originalSourceAmount: request.sourceTokenAmount,\n });\n\n try {\n const phase2Quote = await getSingleQuote(\n {\n ...request,\n sourceTokenAmount: adjustedSourceAmount.toFixed(\n 0,\n BigNumber.ROUND_DOWN,\n ),\n },\n fullRequest,\n );\n\n if (!phase2Quote.fees.isSourceGasFeeToken) {\n log('Across phase 2 lost gas fee token eligibility');\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw quote lost source gas fee token eligibility',\n );\n }\n return phase1Quote;\n }\n\n const phase2GasCost = new BigNumber(phase2Quote.fees.sourceNetwork.max.raw);\n\n if (\n adjustedSourceAmount\n .plus(phase2GasCost)\n .isGreaterThan(request.sourceTokenAmount)\n ) {\n log('Across phase 2 quote exceeds original source amount', {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n gasCostRaw: phase2GasCost.toString(10),\n originalSourceAmount: request.sourceTokenAmount,\n });\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw source gas fee token quote exceeds source amount',\n );\n }\n return phase1Quote;\n }\n\n return phase2Quote;\n } catch (error) {\n log(\n requiresSourceGasReservation\n ? 'Across phase 2 quote failed after source gas reservation'\n : 'Across phase 2 quote failed, falling back to phase 1',\n { error },\n );\n if (requiresSourceGasReservation) {\n throw error;\n }\n return phase1Quote;\n }\n}\n\ntype AcrossApprovalRequest = {\n actions: AcrossAction[];\n amount: string;\n apiBase: string;\n depositor: Hex;\n destinationChainId: Hex;\n inputToken: Hex;\n originChainId: Hex;\n outputToken: Hex;\n recipient: Hex;\n refundAddress?: Hex;\n signal?: AbortSignal;\n slippage?: number;\n tradeType: 'exactInput' | 'exactOutput';\n};\n\nasync function requestAcrossApproval(\n request: AcrossApprovalRequest,\n): Promise<AcrossSwapApprovalResponse> {\n const {\n actions,\n amount,\n apiBase,\n depositor,\n destinationChainId,\n inputToken,\n originChainId,\n outputToken,\n recipient,\n refundAddress,\n signal,\n slippage,\n tradeType,\n } = request;\n\n const params = new URLSearchParams();\n params.set('tradeType', tradeType);\n params.set('amount', amount);\n params.set('inputToken', inputToken);\n params.set('outputToken', outputToken);\n params.set('originChainId', String(parseInt(originChainId, 16)));\n params.set('destinationChainId', String(parseInt(destinationChainId, 16)));\n params.set('depositor', depositor);\n params.set('recipient', recipient);\n\n if (refundAddress !== undefined) {\n params.set('refundAddress', refundAddress);\n }\n\n if (slippage !== undefined) {\n params.set('slippage', String(slippage));\n }\n\n const body: AcrossActionRequestBody = { actions };\n const url = `${apiBase}/swap/approval?${params.toString()}`;\n const options: RequestInit = {\n body: JSON.stringify(body),\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n signal,\n };\n\n const response = await successfulFetch(url, options);\n\n return (await response.json()) as AcrossSwapApprovalResponse;\n}\n\nasync function normalizeQuote(\n original: AcrossQuoteWithoutMetaMask,\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n const { messenger } = fullRequest;\n const { quote } = original;\n\n const { usdToFiatRate, sourceFiatRate, targetFiatRate } = getFiatRates(\n messenger,\n quote,\n );\n\n const dustUsd = calculateDustUsd(quote, request, targetFiatRate);\n const dust = getFiatValueFromUsd(dustUsd, usdToFiatRate);\n\n const {\n gasLimits,\n is7702,\n isGasFeeToken: isSourceGasFeeToken,\n requiresAuthorizationList,\n sourceNetwork,\n } = await calculateSourceNetworkCost(\n quote,\n messenger,\n request,\n fullRequest.transaction,\n fullRequest.accountSupports7702,\n );\n\n const targetNetwork = getFiatValueFromUsd(new BigNumber(0), usdToFiatRate);\n\n const inputAmountRaw = quote.inputAmount ?? '0';\n const outputAmountRaw = new BigNumber(\n quote.expectedOutputAmount ??\n quote.minOutputAmount ??\n request.targetAmountMinimum ??\n '0',\n ).toString(10);\n\n const sourceAmount = getAmountFromTokenAmount({\n amountRaw: inputAmountRaw,\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n });\n\n const providerUsd = calculateProviderUsd(\n quote,\n inputAmountRaw,\n sourceFiatRate,\n targetFiatRate,\n quote.expectedOutputAmount,\n );\n const provider = getFiatValueFromUsd(providerUsd, usdToFiatRate);\n const metaMaskFee = getFiatValueFromUsd(\n new BigNumber(quote.fees?.app?.amountUsd ?? '0').abs(),\n usdToFiatRate,\n );\n\n const targetAmount = getAmountFromTokenAmount({\n amountRaw: outputAmountRaw,\n decimals: quote.outputToken.decimals,\n fiatRate: targetFiatRate,\n });\n\n const metamask = {\n gasLimits,\n is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n };\n\n return {\n dust,\n estimatedDuration: quote.expectedFillTime ?? 0,\n fees: {\n isSourceGasFeeToken,\n metaMask: metaMaskFee,\n provider,\n sourceNetwork,\n targetNetwork,\n },\n isInputBased: original.request.tradeType === 'exactInput',\n original: {\n ...original,\n metamask,\n },\n request,\n sourceAmount,\n targetAmount,\n strategy: TransactionPayStrategy.Across,\n };\n}\n\nfunction getFiatRates(\n messenger: TransactionPayControllerMessenger,\n quote: AcrossSwapApprovalResponse,\n): {\n sourceFiatRate: FiatRates;\n targetFiatRate: FiatRates;\n usdToFiatRate: BigNumber;\n} {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n quote.inputToken.address,\n toHex(quote.inputToken.chainId),\n );\n\n if (!sourceFiatRate) {\n throw new Error('Source token fiat rate not found');\n }\n\n const targetFiatRate =\n getTokenFiatRate(\n messenger,\n quote.outputToken.address,\n toHex(quote.outputToken.chainId),\n ) ?? sourceFiatRate;\n\n const usdToFiatRate = new BigNumber(sourceFiatRate.fiatRate).dividedBy(\n sourceFiatRate.usdRate,\n );\n\n return { sourceFiatRate, targetFiatRate, usdToFiatRate };\n}\n\nfunction calculateDustUsd(\n quote: AcrossSwapApprovalResponse,\n request: QuoteRequest,\n targetFiatRate: FiatRates,\n): BigNumber {\n const expectedOutputRaw = quote.expectedOutputAmount;\n\n if (expectedOutputRaw === undefined) {\n return new BigNumber(0);\n }\n\n const expectedOutput = new BigNumber(expectedOutputRaw);\n const minimumOutput = new BigNumber(\n quote.minOutputAmount ?? request.targetAmountMinimum ?? '0',\n );\n\n const dustRaw = expectedOutput.minus(minimumOutput).isNegative()\n ? new BigNumber(0)\n : expectedOutput.minus(minimumOutput);\n const dustHuman = dustRaw.shiftedBy(-quote.outputToken.decimals);\n\n return dustHuman.multipliedBy(targetFiatRate.usdRate);\n}\n\nfunction calculateProviderUsd(\n quote: AcrossSwapApprovalResponse,\n inputAmountRaw: string,\n sourceFiatRate: FiatRates,\n targetFiatRate: FiatRates,\n expectedOutputRaw?: string,\n): BigNumber {\n const totalFeeUsd = quote.fees?.total?.amountUsd;\n\n if (totalFeeUsd !== undefined) {\n return new BigNumber(totalFeeUsd).abs();\n }\n\n if (expectedOutputRaw === undefined) {\n return new BigNumber(0);\n }\n\n const expectedOutput = new BigNumber(expectedOutputRaw);\n\n if (expectedOutput.lte(0)) {\n return new BigNumber(0);\n }\n\n const inputAmountUsd = new BigNumber(inputAmountRaw)\n .shiftedBy(-quote.inputToken.decimals)\n .multipliedBy(sourceFiatRate.usdRate);\n const expectedOutputUsd = expectedOutput\n .shiftedBy(-quote.outputToken.decimals)\n .multipliedBy(targetFiatRate.usdRate);\n const providerFeeUsd = inputAmountUsd.minus(expectedOutputUsd);\n\n return providerFeeUsd.isNegative() ? new BigNumber(0) : providerFeeUsd;\n}\n\nfunction getAmountFromTokenAmount({\n amountRaw,\n decimals,\n fiatRate,\n}: {\n amountRaw: string;\n decimals: number;\n fiatRate: FiatRates;\n}): Amount {\n const rawValue = new BigNumber(amountRaw);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\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\nasync function calculateSourceNetworkCost(\n quote: AcrossSwapApprovalResponse,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n transaction: TransactionMeta,\n accountSupports7702: boolean,\n): Promise<{\n sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n gasLimits: AcrossGasLimits;\n isGasFeeToken?: boolean;\n is7702: boolean;\n requiresAuthorizationList?: true;\n}> {\n const acrossFallbackGas =\n getPayStrategiesConfig(messenger).across.fallbackGas;\n const { from, sourceChainId, sourceTokenAddress } = request;\n const orderedTransactions = getAcrossOrderedTransactions({ quote });\n const { swapTx } = quote;\n const swapChainId = toHex(swapTx.chainId);\n const isPredictWithdraw =\n request.isPostQuote === true &&\n hasTransactionType(transaction, [TransactionType.predictWithdraw]);\n const relaxPrefundedSourceEstimate =\n isPredictWithdraw &&\n new BigNumber(request.sourceTokenAmount).gt(request.sourceBalanceRaw);\n const gasEstimateTransactions = orderedTransactions.map(\n (orderedTransaction) => ({\n chainId: toHex(orderedTransaction.chainId),\n data: orderedTransaction.data,\n from,\n gas: orderedTransaction.gas,\n to: orderedTransaction.to,\n value: orderedTransaction.value ?? '0x0',\n }),\n );\n\n const gasEstimates = await estimateAcrossQuoteGasLimits({\n fallbackGas: acrossFallbackGas,\n fallbackOnSimulationFailure: relaxPrefundedSourceEstimate,\n messenger,\n transactions: gasEstimateTransactions,\n });\n\n const { batchGasLimit, is7702, requiresAuthorizationList, totalGasEstimate } =\n gasEstimates;\n\n let sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n let gasLimits: AcrossGasLimits;\n\n if (is7702) {\n if (!batchGasLimit) {\n throw new Error('Across combined batch gas estimate missing');\n }\n\n const estimate = calculateGasCost({\n chainId: swapChainId,\n gas: batchGasLimit.estimate,\n maxFeePerGas: swapTx.maxFeePerGas,\n maxPriorityFeePerGas: swapTx.maxPriorityFeePerGas,\n messenger,\n });\n const max = calculateGasCost({\n chainId: swapChainId,\n gas: batchGasLimit.max,\n isMax: true,\n maxFeePerGas: swapTx.maxFeePerGas,\n maxPriorityFeePerGas: swapTx.maxPriorityFeePerGas,\n messenger,\n });\n\n sourceNetwork = {\n estimate,\n max,\n };\n gasLimits = [\n {\n estimate: batchGasLimit.estimate,\n max: batchGasLimit.max,\n },\n ];\n } else {\n const transactionGasLimits = orderedTransactions.map(\n (orderedTransaction, index) => ({\n gasEstimate: gasEstimates.gasLimits[index],\n orderedTransaction,\n }),\n );\n\n const estimate = sumAmounts(\n transactionGasLimits.map(({ gasEstimate, orderedTransaction }) =>\n calculateGasCost({\n chainId: toHex(orderedTransaction.chainId),\n gas: gasEstimate.estimate,\n maxFeePerGas: orderedTransaction.maxFeePerGas,\n maxPriorityFeePerGas: orderedTransaction.maxPriorityFeePerGas,\n messenger,\n }),\n ),\n );\n\n const max = sumAmounts(\n transactionGasLimits.map(({ gasEstimate, orderedTransaction }) =>\n calculateGasCost({\n chainId: toHex(orderedTransaction.chainId),\n gas: gasEstimate.max,\n isMax: true,\n maxFeePerGas: orderedTransaction.maxFeePerGas,\n maxPriorityFeePerGas: orderedTransaction.maxPriorityFeePerGas,\n messenger,\n }),\n ),\n );\n\n sourceNetwork = {\n estimate,\n max,\n };\n gasLimits = transactionGasLimits.map(({ gasEstimate }) => ({\n estimate: gasEstimate.estimate,\n max: gasEstimate.max,\n }));\n }\n\n const result = {\n sourceNetwork,\n is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n gasLimits,\n totalGasEstimate,\n totalGasLimit: gasEstimates.totalGasLimit,\n };\n\n const finalResult = request.isPostQuote\n ? combinePostQuoteGas(result, transaction, swapTx, messenger)\n : result;\n\n const firstTransaction = orderedTransactions[0];\n\n // Predict withdraws always consult the gas station: the user's source token\n // lives in the Safe, so a healthy native balance does not mean they can\n // actually pay gas. They do require an EIP-7702 capable account, since the\n // withdraw is submitted as a 7702 batch.\n const { amount: gasFeeTokenCost, isAvailable } = await resolveGasStationCost({\n accountSupports7702: isPredictWithdraw ? accountSupports7702 : undefined,\n firstStepData: {\n data: firstTransaction.data,\n to: firstTransaction.to,\n value: firstTransaction.value,\n },\n messenger,\n nativeGasCostRaw: isPredictWithdraw\n ? undefined\n : finalResult.sourceNetwork.max.raw,\n request: {\n from,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate: finalResult.totalGasEstimate,\n totalItemCount: Math.max(\n orderedTransactions.length + (request.isPostQuote ? 1 : 0),\n finalResult.gasLimits.length,\n ),\n });\n\n let gasFeeTokenNetwork:\n | TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork']\n | undefined;\n\n if (gasFeeTokenCost) {\n gasFeeTokenNetwork = {\n estimate: gasFeeTokenCost,\n max: gasFeeTokenCost,\n };\n } else if (isAvailable && isPredictWithdraw) {\n gasFeeTokenNetwork = calculateSourceGasFeeTokenNetworkFallback({\n messenger,\n nativeSourceNetwork: finalResult.sourceNetwork,\n quote,\n request,\n });\n }\n\n if (!gasFeeTokenNetwork) {\n return finalResult;\n }\n\n log('Using gas fee token for Across source network', {\n gasFeeTokenCost: gasFeeTokenNetwork.max,\n });\n\n return {\n isGasFeeToken: true,\n sourceNetwork: gasFeeTokenNetwork,\n is7702: finalResult.is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n gasLimits: finalResult.gasLimits,\n };\n}\n\nfunction calculateSourceGasFeeTokenNetworkFallback({\n messenger,\n nativeSourceNetwork,\n quote,\n request,\n}: {\n messenger: TransactionPayControllerMessenger;\n nativeSourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n quote: AcrossSwapApprovalResponse;\n request: QuoteRequest;\n}): TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'] | undefined {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n request.sourceTokenAddress,\n request.sourceChainId,\n );\n\n if (!sourceFiatRate) {\n return undefined;\n }\n\n const estimate = calculateSourceGasFeeTokenAmountFallback({\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n nativeGasCost: nativeSourceNetwork.estimate,\n });\n const max = calculateSourceGasFeeTokenAmountFallback({\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n nativeGasCost: nativeSourceNetwork.max,\n });\n\n if (!estimate || !max) {\n return undefined;\n }\n\n return { estimate, max };\n}\n\nfunction calculateSourceGasFeeTokenAmountFallback({\n decimals,\n fiatRate,\n nativeGasCost,\n}: {\n decimals: number;\n fiatRate: FiatRates;\n nativeGasCost: Amount;\n}): Amount | undefined {\n const usdRate = new BigNumber(fiatRate.usdRate);\n const nativeGasUsd = new BigNumber(nativeGasCost.usd);\n\n if (\n !usdRate.isFinite() ||\n !usdRate.isGreaterThan(0) ||\n !nativeGasUsd.isFinite() ||\n !nativeGasUsd.isGreaterThan(0)\n ) {\n return undefined;\n }\n\n const amountRaw = nativeGasUsd\n .dividedBy(usdRate)\n .shiftedBy(decimals)\n .integerValue(BigNumber.ROUND_CEIL)\n .toFixed(0);\n\n return getAmountFromTokenAmount({\n amountRaw,\n decimals,\n fiatRate,\n });\n}\n\nasync function estimateAcrossQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure,\n messenger,\n transactions,\n}: {\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure: boolean;\n messenger: TransactionPayControllerMessenger;\n transactions: QuoteGasTransaction[];\n}): Promise<Awaited<ReturnType<typeof estimateQuoteGasLimits>>> {\n try {\n const gasEstimates = await estimateQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure,\n messenger,\n transactions,\n });\n\n if (\n fallbackOnSimulationFailure &&\n fallbackGas !== undefined &&\n gasEstimates.is7702 &&\n gasEstimates.batchGasLimit !== undefined &&\n gasEstimates.batchGasLimit.max > fallbackGas.max\n ) {\n // Prefunded Predict withdraws can produce inflated 7702 batch estimates\n // because the source account does not yet hold the funds. Keep the gas\n // reservation bounded by the configured Across fallback for this path.\n return {\n ...gasEstimates,\n batchGasLimit: fallbackGas,\n gasLimits: [fallbackGas],\n totalGasEstimate: fallbackGas.estimate,\n totalGasLimit: fallbackGas.max,\n };\n }\n\n return gasEstimates;\n } catch (error) {\n if (!fallbackOnSimulationFailure || transactions.length <= 1) {\n throw error;\n }\n\n const perTransactionGasEstimates = await Promise.all(\n transactions.map((transaction) =>\n estimateQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure: true,\n messenger,\n transactions: [transaction],\n }),\n ),\n );\n const gasLimits = perTransactionGasEstimates.map(\n (estimate) => estimate.gasLimits[0],\n );\n const totalGasEstimate = gasLimits.reduce(\n (total, gasLimit) => total + gasLimit.estimate,\n 0,\n );\n const totalGasLimit = gasLimits.reduce(\n (total, gasLimit) => total + gasLimit.max,\n 0,\n );\n\n return {\n gasLimits,\n is7702: false,\n totalGasEstimate,\n totalGasLimit,\n usedBatch: false,\n };\n }\n}\n\nfunction combinePostQuoteGas(\n gasResult: {\n sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n gasLimits: AcrossGasLimits;\n is7702: boolean;\n requiresAuthorizationList?: true;\n totalGasEstimate: number;\n totalGasLimit: number;\n },\n transaction: TransactionMeta,\n swapTx: AcrossSwapApprovalResponse['swapTx'],\n messenger: TransactionPayControllerMessenger,\n): typeof gasResult {\n const originalTxGas = getOriginalTransactionGas(transaction);\n\n if (originalTxGas === undefined) {\n return gasResult;\n }\n\n const gasLimits = gasResult.is7702\n ? [\n {\n estimate: gasResult.gasLimits[0].estimate + originalTxGas,\n max: gasResult.gasLimits[0].max + originalTxGas,\n },\n ]\n : [\n {\n estimate: originalTxGas,\n max: originalTxGas,\n },\n ...gasResult.gasLimits,\n ];\n\n const totalGasEstimate = gasResult.totalGasEstimate + originalTxGas;\n const totalGasLimit = gasResult.totalGasLimit + originalTxGas;\n const originalSourceNetwork = calculateOriginalSourceNetworkCost({\n gas: originalTxGas,\n messenger,\n swapTx,\n transaction,\n });\n\n return {\n ...gasResult,\n sourceNetwork: {\n estimate: sumAmounts([\n gasResult.sourceNetwork.estimate,\n originalSourceNetwork.estimate,\n ]),\n max: sumAmounts([gasResult.sourceNetwork.max, originalSourceNetwork.max]),\n },\n gasLimits,\n totalGasEstimate,\n totalGasLimit,\n };\n}\n\nfunction calculateOriginalSourceNetworkCost({\n gas,\n messenger,\n swapTx,\n transaction,\n}: {\n gas: number;\n messenger: TransactionPayControllerMessenger;\n swapTx: AcrossSwapApprovalResponse['swapTx'];\n transaction: TransactionMeta;\n}): TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'] {\n const originalTransactionWithGas = transaction.nestedTransactions?.find(\n (tx) => tx.gas,\n );\n const maxFeePerGas =\n originalTransactionWithGas?.maxFeePerGas ??\n transaction.txParams.maxFeePerGas;\n const maxPriorityFeePerGas =\n originalTransactionWithGas?.maxPriorityFeePerGas ??\n transaction.txParams.maxPriorityFeePerGas;\n\n return {\n estimate: calculateGasCost({\n chainId: transaction.chainId ?? toHex(swapTx.chainId),\n gas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n }),\n max: calculateGasCost({\n chainId: transaction.chainId ?? toHex(swapTx.chainId),\n gas,\n isMax: true,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n }),\n };\n}\n"]}
1
+ {"version":3,"file":"across-quotes.js","sourceRoot":"","sources":["../../../src/strategy/across/across-quotes.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,KAAK,EAAE,MAAM,4BAA4B,CAAC;AACpE,OAAO,EACL,eAAe,EACf,kBAAkB,GACnB,MAAM,kCAAkC,CAAC;AAG1C,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB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;QACT,gBAAgB;QAChB,aAAa;KACd,CAAC;AACJ,CAAC;AAED,SAAS,kCAAkC,CAAC,EAC1C,GAAG,EACH,SAAS,EACT,MAAM,EACN,WAAW,GAMZ;IACC,MAAM,0BAA0B,GAAG,WAAW,CAAC,kBAAkB,EAAE,IAAI,CACrE,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,CAAC,GAAG,CACf,CAAC;IACF,MAAM,YAAY,GAChB,0BAA0B,EAAE,YAAY;QACxC,WAAW,CAAC,QAAQ,CAAC,YAAY,CAAC;IACpC,MAAM,oBAAoB,GACxB,0BAA0B,EAAE,oBAAoB;QAChD,WAAW,CAAC,QAAQ,CAAC,oBAAoB,CAAC;IAE5C,OAAO;QACL,QAAQ,EAAE,gBAAgB,CAAC;YACzB,OAAO,EAAE,WAAW,CAAC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC;YACrD,GAAG;YACH,YAAY;YACZ,oBAAoB;YACpB,SAAS;SACV,CAAC;QACF,GAAG,EAAE,gBAAgB,CAAC;YACpB,OAAO,EAAE,WAAW,CAAC,OAAO,IAAI,KAAK,CAAC,MAAM,CAAC,OAAO,CAAC;YACrD,GAAG;YACH,KAAK,EAAE,IAAI;YACX,YAAY;YACZ,oBAAoB;YACpB,SAAS;SACV,CAAC;KACH,CAAC;AACJ,CAAC","sourcesContent":["import { successfulFetch, toHex } from '@metamask/controller-utils';\nimport {\n TransactionType,\n hasTransactionType,\n} from '@metamask/transaction-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { TransactionPayStrategy } from '../../constants.js';\nimport { projectLogger } from '../../logger.js';\nimport type {\n Amount,\n FiatRates,\n PayStrategyGetQuotesRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types.js';\nimport { getFiatValueFromUsd, sumAmounts } from '../../utils/amounts.js';\nimport {\n getPayStrategiesConfig,\n getSlippage,\n} from '../../utils/feature-flags.js';\nimport { resolveGasStationCost } from '../../utils/gas-payment.js';\nimport { calculateGasCost } from '../../utils/gas.js';\nimport { estimateQuoteGasLimits } from '../../utils/quote-gas.js';\nimport type { QuoteGasTransaction } from '../../utils/quote-gas.js';\nimport { getTokenFiatRate } from '../../utils/token.js';\nimport type { AcrossDestination } from './across-actions.js';\nimport { getAcrossDestination } from './across-actions.js';\nimport { hasUnsupportedTransactionAuthorizationList } from './authorization-list.js';\nimport { normalizeAcrossRequest, validateAcrossPerpsQuote } from './perps.js';\nimport { isAcrossQuoteRequest } from './requests.js';\nimport {\n getAcrossOrderedTransactions,\n getOriginalTransactionGas,\n} from './transactions.js';\nimport type {\n AcrossAction,\n AcrossActionRequestBody,\n AcrossGasLimits,\n AcrossQuote,\n AcrossSwapApprovalResponse,\n} from './types.js';\n\nconst log = createModuleLogger(projectLogger, 'across-strategy');\n\nconst UNSUPPORTED_AUTHORIZATION_LIST_ERROR =\n 'Across does not support type-4/EIP-7702 authorization lists yet';\n\ntype AcrossQuoteWithoutMetaMask = Omit<AcrossQuote, 'metamask'>;\n\n/**\n * Fetch Across quotes.\n *\n * @param request - Request object.\n * @returns Array of quotes.\n */\nexport async function getAcrossQuotes(\n request: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>[]> {\n const { requests } = request;\n\n log('Fetching quotes', requests);\n\n try {\n const normalizedRequests = requests.filter(isAcrossQuoteRequest);\n\n if (normalizedRequests.length === 0) {\n return [];\n }\n\n if (\n hasUnsupportedTransactionAuthorizationList(\n request.transaction,\n normalizedRequests,\n )\n ) {\n throw new Error(UNSUPPORTED_AUTHORIZATION_LIST_ERROR);\n }\n\n return await Promise.all(\n normalizedRequests.map((singleRequest) =>\n getQuoteWithGasStationHandling(singleRequest, request),\n ),\n );\n } catch (error) {\n log('Error fetching quotes', { error });\n throw new Error(`Failed to fetch Across quotes: ${String(error)}`);\n }\n}\n\nasync function getSingleQuote(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n const { messenger, signal, transaction } = fullRequest;\n const normalizedRequest = normalizeAcrossRequest(request, transaction);\n const {\n from,\n isMaxAmount,\n sourceChainId,\n sourceTokenAddress,\n sourceTokenAmount,\n targetAmountMinimum,\n targetChainId,\n targetTokenAddress,\n } = normalizedRequest;\n\n const config = getPayStrategiesConfig(messenger);\n const slippageDecimal = getSlippage(\n messenger,\n sourceChainId,\n sourceTokenAddress,\n );\n\n const useExactInput = isMaxAmount\n ? true\n : normalizedRequest.isPostQuote === true;\n const amount = useExactInput ? sourceTokenAmount : targetAmountMinimum;\n const tradeType = useExactInput ? 'exactInput' : 'exactOutput';\n const destination = getAcrossDestinationForRequest(\n transaction,\n request,\n from,\n );\n\n const quote = await requestAcrossApproval({\n actions: destination.actions,\n amount,\n apiBase: config.across.apiBase,\n depositor: from,\n destinationChainId: targetChainId,\n inputToken: sourceTokenAddress,\n originChainId: sourceChainId,\n outputToken: targetTokenAddress,\n recipient: destination.recipient,\n signal,\n refundAddress: normalizedRequest.refundTo,\n slippage: slippageDecimal,\n tradeType,\n });\n\n validateAcrossPerpsQuote(normalizedRequest, quote);\n\n const originalQuote: AcrossQuoteWithoutMetaMask = {\n quote,\n request: {\n actions: destination.actions,\n amount,\n tradeType,\n },\n };\n\n return await normalizeQuote(originalQuote, normalizedRequest, fullRequest);\n}\n\nfunction getAcrossDestinationForRequest(\n transaction: TransactionMeta,\n request: QuoteRequest,\n recipient: Hex,\n): AcrossDestination {\n if (request.isPostQuote) {\n return {\n actions: [],\n recipient,\n };\n }\n\n return getAcrossDestination(transaction, request);\n}\n\nasync function getQuoteWithGasStationHandling(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n // Phase 1 uses the requested source amount to discover whether Across will\n // pay source-chain gas with the source token, and what the max gas cost is.\n // Phase 2 repeats the quote with that max gas cost reserved from the source\n // amount, so execution can fund both the Across deposit and token-paid gas.\n const phase1Quote = await getSingleQuote(request, fullRequest);\n\n if (\n (!request.isMaxAmount && !request.isPostQuote) ||\n !phase1Quote.fees.isSourceGasFeeToken\n ) {\n return phase1Quote;\n }\n\n const requiresSourceGasReservation =\n request.isPostQuote === true &&\n hasTransactionType(fullRequest.transaction, [\n TransactionType.predictWithdraw,\n ]);\n\n const adjustedSourceAmount = new BigNumber(request.sourceTokenAmount)\n .minus(phase1Quote.fees.sourceNetwork.max.raw)\n .integerValue(BigNumber.ROUND_DOWN);\n\n if (!adjustedSourceAmount.isGreaterThan(0)) {\n log('Insufficient balance after gas subtraction for Across quote');\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw source amount cannot cover source gas fee token',\n );\n }\n return phase1Quote;\n }\n\n log('Subtracting gas from source for Across quote', {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n gasCostRaw: phase1Quote.fees.sourceNetwork.max.raw,\n originalSourceAmount: request.sourceTokenAmount,\n });\n\n try {\n const phase2Quote = await getSingleQuote(\n {\n ...request,\n sourceTokenAmount: adjustedSourceAmount.toFixed(\n 0,\n BigNumber.ROUND_DOWN,\n ),\n },\n fullRequest,\n );\n\n if (!phase2Quote.fees.isSourceGasFeeToken) {\n log('Across phase 2 lost gas fee token eligibility');\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw quote lost source gas fee token eligibility',\n );\n }\n return phase1Quote;\n }\n\n const phase2GasCost = new BigNumber(phase2Quote.fees.sourceNetwork.max.raw);\n\n if (\n adjustedSourceAmount\n .plus(phase2GasCost)\n .isGreaterThan(request.sourceTokenAmount)\n ) {\n log('Across phase 2 quote exceeds original source amount', {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n gasCostRaw: phase2GasCost.toString(10),\n originalSourceAmount: request.sourceTokenAmount,\n });\n if (requiresSourceGasReservation) {\n throw new Error(\n 'Across Predict withdraw source gas fee token quote exceeds source amount',\n );\n }\n return phase1Quote;\n }\n\n return phase2Quote;\n } catch (error) {\n log(\n requiresSourceGasReservation\n ? 'Across phase 2 quote failed after source gas reservation'\n : 'Across phase 2 quote failed, falling back to phase 1',\n { error },\n );\n if (requiresSourceGasReservation) {\n throw error;\n }\n return phase1Quote;\n }\n}\n\ntype AcrossApprovalRequest = {\n actions: AcrossAction[];\n amount: string;\n apiBase: string;\n depositor: Hex;\n destinationChainId: Hex;\n inputToken: Hex;\n originChainId: Hex;\n outputToken: Hex;\n recipient: Hex;\n refundAddress?: Hex;\n signal?: AbortSignal;\n slippage?: number;\n tradeType: 'exactInput' | 'exactOutput';\n};\n\nasync function requestAcrossApproval(\n request: AcrossApprovalRequest,\n): Promise<AcrossSwapApprovalResponse> {\n const {\n actions,\n amount,\n apiBase,\n depositor,\n destinationChainId,\n inputToken,\n originChainId,\n outputToken,\n recipient,\n refundAddress,\n signal,\n slippage,\n tradeType,\n } = request;\n\n const params = new URLSearchParams();\n params.set('tradeType', tradeType);\n params.set('amount', amount);\n params.set('inputToken', inputToken);\n params.set('outputToken', outputToken);\n params.set('originChainId', String(parseInt(originChainId, 16)));\n params.set('destinationChainId', String(parseInt(destinationChainId, 16)));\n params.set('depositor', depositor);\n params.set('recipient', recipient);\n\n if (refundAddress !== undefined) {\n params.set('refundAddress', refundAddress);\n }\n\n if (slippage !== undefined) {\n params.set('slippage', String(slippage));\n }\n\n const body: AcrossActionRequestBody = { actions };\n const url = `${apiBase}/swap/approval?${params.toString()}`;\n const options: RequestInit = {\n body: JSON.stringify(body),\n headers: {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n signal,\n };\n\n const response = await successfulFetch(url, options);\n\n return (await response.json()) as AcrossSwapApprovalResponse;\n}\n\nasync function normalizeQuote(\n original: AcrossQuoteWithoutMetaMask,\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<AcrossQuote>> {\n const { messenger } = fullRequest;\n const { quote } = original;\n\n const { usdToFiatRate, sourceFiatRate, targetFiatRate } = getFiatRates(\n messenger,\n quote,\n );\n\n const dustUsd = calculateDustUsd(quote, request, targetFiatRate);\n const dust = getFiatValueFromUsd(dustUsd, usdToFiatRate);\n\n const {\n gasLimits,\n is7702,\n isGasFeeToken: isSourceGasFeeToken,\n requiresAuthorizationList,\n sourceNetwork,\n } = await calculateSourceNetworkCost(\n quote,\n messenger,\n request,\n fullRequest.transaction,\n fullRequest.accountSupports7702,\n );\n\n const targetNetwork = getFiatValueFromUsd(new BigNumber(0), usdToFiatRate);\n\n const inputAmountRaw = quote.inputAmount ?? '0';\n const outputAmountRaw = new BigNumber(\n quote.expectedOutputAmount ??\n quote.minOutputAmount ??\n request.targetAmountMinimum ??\n '0',\n ).toString(10);\n\n const sourceAmount = getAmountFromTokenAmount({\n amountRaw: inputAmountRaw,\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n });\n\n const providerUsd = calculateProviderUsd(\n quote,\n inputAmountRaw,\n sourceFiatRate,\n targetFiatRate,\n quote.expectedOutputAmount,\n );\n const provider = getFiatValueFromUsd(providerUsd, usdToFiatRate);\n const metaMaskFee = getFiatValueFromUsd(\n new BigNumber(quote.fees?.app?.amountUsd ?? '0').abs(),\n usdToFiatRate,\n );\n\n const targetAmount = getAmountFromTokenAmount({\n amountRaw: outputAmountRaw,\n decimals: quote.outputToken.decimals,\n fiatRate: targetFiatRate,\n });\n\n const metamask = {\n gasLimits,\n is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n };\n\n return {\n dust,\n estimatedDuration: quote.expectedFillTime ?? 0,\n fees: {\n isSourceGasFeeToken,\n metaMask: metaMaskFee,\n provider,\n sourceNetwork,\n targetNetwork,\n },\n isInputBased: original.request.tradeType === 'exactInput',\n original: {\n ...original,\n metamask,\n },\n request,\n sourceAmount,\n targetAmount,\n strategy: TransactionPayStrategy.Across,\n };\n}\n\nfunction getFiatRates(\n messenger: TransactionPayControllerMessenger,\n quote: AcrossSwapApprovalResponse,\n): {\n sourceFiatRate: FiatRates;\n targetFiatRate: FiatRates;\n usdToFiatRate: BigNumber;\n} {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n quote.inputToken.address,\n toHex(quote.inputToken.chainId),\n );\n\n if (!sourceFiatRate) {\n throw new Error('Source token fiat rate not found');\n }\n\n const targetFiatRate =\n getTokenFiatRate(\n messenger,\n quote.outputToken.address,\n toHex(quote.outputToken.chainId),\n ) ?? sourceFiatRate;\n\n const usdToFiatRate = new BigNumber(sourceFiatRate.fiatRate).dividedBy(\n sourceFiatRate.usdRate,\n );\n\n return { sourceFiatRate, targetFiatRate, usdToFiatRate };\n}\n\nfunction calculateDustUsd(\n quote: AcrossSwapApprovalResponse,\n request: QuoteRequest,\n targetFiatRate: FiatRates,\n): BigNumber {\n const expectedOutputRaw = quote.expectedOutputAmount;\n\n if (expectedOutputRaw === undefined) {\n return new BigNumber(0);\n }\n\n const expectedOutput = new BigNumber(expectedOutputRaw);\n const minimumOutput = new BigNumber(\n quote.minOutputAmount ?? request.targetAmountMinimum ?? '0',\n );\n\n const dustRaw = expectedOutput.minus(minimumOutput).isNegative()\n ? new BigNumber(0)\n : expectedOutput.minus(minimumOutput);\n const dustHuman = dustRaw.shiftedBy(-quote.outputToken.decimals);\n\n return dustHuman.multipliedBy(targetFiatRate.usdRate);\n}\n\nfunction calculateProviderUsd(\n quote: AcrossSwapApprovalResponse,\n inputAmountRaw: string,\n sourceFiatRate: FiatRates,\n targetFiatRate: FiatRates,\n expectedOutputRaw?: string,\n): BigNumber {\n const totalFeeUsd = quote.fees?.total?.amountUsd;\n\n if (totalFeeUsd !== undefined) {\n return new BigNumber(totalFeeUsd).abs();\n }\n\n if (expectedOutputRaw === undefined) {\n return new BigNumber(0);\n }\n\n const expectedOutput = new BigNumber(expectedOutputRaw);\n\n if (expectedOutput.lte(0)) {\n return new BigNumber(0);\n }\n\n const inputAmountUsd = new BigNumber(inputAmountRaw)\n .shiftedBy(-quote.inputToken.decimals)\n .multipliedBy(sourceFiatRate.usdRate);\n const expectedOutputUsd = expectedOutput\n .shiftedBy(-quote.outputToken.decimals)\n .multipliedBy(targetFiatRate.usdRate);\n const providerFeeUsd = inputAmountUsd.minus(expectedOutputUsd);\n\n return providerFeeUsd.isNegative() ? new BigNumber(0) : providerFeeUsd;\n}\n\nfunction getAmountFromTokenAmount({\n amountRaw,\n decimals,\n fiatRate,\n}: {\n amountRaw: string;\n decimals: number;\n fiatRate: FiatRates;\n}): Amount {\n const rawValue = new BigNumber(amountRaw);\n const raw = rawValue.toString(10);\n\n const humanValue = rawValue.shiftedBy(-decimals);\n const human = humanValue.toString(10);\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\nasync function calculateSourceNetworkCost(\n quote: AcrossSwapApprovalResponse,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n transaction: TransactionMeta,\n accountSupports7702: boolean,\n): Promise<{\n sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n gasLimits: AcrossGasLimits;\n isGasFeeToken?: boolean;\n is7702: boolean;\n requiresAuthorizationList?: true;\n}> {\n const acrossFallbackGas =\n getPayStrategiesConfig(messenger).across.fallbackGas;\n const { from, sourceChainId, sourceTokenAddress } = request;\n const orderedTransactions = getAcrossOrderedTransactions({ quote });\n const { swapTx } = quote;\n const swapChainId = toHex(swapTx.chainId);\n const isPredictWithdraw =\n request.isPostQuote === true &&\n hasTransactionType(transaction, [TransactionType.predictWithdraw]);\n const relaxPrefundedSourceEstimate =\n isPredictWithdraw &&\n new BigNumber(request.sourceTokenAmount).gt(request.sourceBalanceRaw);\n const gasEstimateTransactions = orderedTransactions.map(\n (orderedTransaction) => ({\n chainId: toHex(orderedTransaction.chainId),\n data: orderedTransaction.data,\n from,\n gas: orderedTransaction.gas,\n to: orderedTransaction.to,\n value: orderedTransaction.value ?? '0x0',\n }),\n );\n\n const gasEstimates = await estimateAcrossQuoteGasLimits({\n fallbackGas: acrossFallbackGas,\n fallbackOnSimulationFailure: relaxPrefundedSourceEstimate,\n messenger,\n transactions: gasEstimateTransactions,\n });\n\n const { batchGasLimit, is7702, requiresAuthorizationList, totalGasEstimate } =\n gasEstimates;\n\n let sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n let gasLimits: AcrossGasLimits;\n\n if (is7702) {\n if (!batchGasLimit) {\n throw new Error('Across combined batch gas estimate missing');\n }\n\n const estimate = calculateGasCost({\n chainId: swapChainId,\n gas: batchGasLimit.estimate,\n maxFeePerGas: swapTx.maxFeePerGas,\n maxPriorityFeePerGas: swapTx.maxPriorityFeePerGas,\n messenger,\n });\n const max = calculateGasCost({\n chainId: swapChainId,\n gas: batchGasLimit.max,\n isMax: true,\n maxFeePerGas: swapTx.maxFeePerGas,\n maxPriorityFeePerGas: swapTx.maxPriorityFeePerGas,\n messenger,\n });\n\n sourceNetwork = {\n estimate,\n max,\n };\n gasLimits = [\n {\n estimate: batchGasLimit.estimate,\n max: batchGasLimit.max,\n },\n ];\n } else {\n const transactionGasLimits = orderedTransactions.map(\n (orderedTransaction, index) => ({\n gasEstimate: gasEstimates.gasLimits[index],\n orderedTransaction,\n }),\n );\n\n const estimate = sumAmounts(\n transactionGasLimits.map(({ gasEstimate, orderedTransaction }) =>\n calculateGasCost({\n chainId: toHex(orderedTransaction.chainId),\n gas: gasEstimate.estimate,\n maxFeePerGas: orderedTransaction.maxFeePerGas,\n maxPriorityFeePerGas: orderedTransaction.maxPriorityFeePerGas,\n messenger,\n }),\n ),\n );\n\n const max = sumAmounts(\n transactionGasLimits.map(({ gasEstimate, orderedTransaction }) =>\n calculateGasCost({\n chainId: toHex(orderedTransaction.chainId),\n gas: gasEstimate.max,\n isMax: true,\n maxFeePerGas: orderedTransaction.maxFeePerGas,\n maxPriorityFeePerGas: orderedTransaction.maxPriorityFeePerGas,\n messenger,\n }),\n ),\n );\n\n sourceNetwork = {\n estimate,\n max,\n };\n gasLimits = transactionGasLimits.map(({ gasEstimate }) => ({\n estimate: gasEstimate.estimate,\n max: gasEstimate.max,\n }));\n }\n\n const result = {\n sourceNetwork,\n is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n gasLimits,\n totalGasEstimate,\n totalGasLimit: gasEstimates.totalGasLimit,\n };\n\n const finalResult = request.isPostQuote\n ? combinePostQuoteGas(result, transaction, swapTx, messenger)\n : result;\n\n const firstTransaction = orderedTransactions[0];\n\n // Predict withdraws always consult the gas station: the user's source token\n // lives in the Safe, so a healthy native balance does not mean they can\n // actually pay gas. They do require an EIP-7702 capable account, since the\n // withdraw is submitted as a 7702 batch.\n const { amount: gasFeeTokenCost, isAvailable } = await resolveGasStationCost({\n accountSupports7702: isPredictWithdraw ? accountSupports7702 : undefined,\n firstStepData: {\n data: firstTransaction.data,\n to: firstTransaction.to,\n value: firstTransaction.value,\n },\n messenger,\n nativeGasCostRaw: isPredictWithdraw\n ? undefined\n : finalResult.sourceNetwork.max.raw,\n request: {\n from,\n sourceChainId,\n sourceTokenAddress,\n },\n totalGasEstimate: finalResult.totalGasEstimate,\n totalItemCount: Math.max(\n orderedTransactions.length + (request.isPostQuote ? 1 : 0),\n finalResult.gasLimits.length,\n ),\n });\n\n let gasFeeTokenNetwork:\n | TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork']\n | undefined;\n\n if (gasFeeTokenCost) {\n gasFeeTokenNetwork = {\n estimate: gasFeeTokenCost,\n max: gasFeeTokenCost,\n };\n } else if (isAvailable && isPredictWithdraw) {\n gasFeeTokenNetwork = calculateSourceGasFeeTokenNetworkFallback({\n messenger,\n nativeSourceNetwork: finalResult.sourceNetwork,\n quote,\n request,\n });\n }\n\n if (!gasFeeTokenNetwork) {\n return finalResult;\n }\n\n log('Using gas fee token for Across source network', {\n gasFeeTokenCost: gasFeeTokenNetwork.max,\n });\n\n return {\n isGasFeeToken: true,\n sourceNetwork: gasFeeTokenNetwork,\n is7702: finalResult.is7702,\n ...(requiresAuthorizationList ? { requiresAuthorizationList } : {}),\n gasLimits: finalResult.gasLimits,\n };\n}\n\nfunction calculateSourceGasFeeTokenNetworkFallback({\n messenger,\n nativeSourceNetwork,\n quote,\n request,\n}: {\n messenger: TransactionPayControllerMessenger;\n nativeSourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n quote: AcrossSwapApprovalResponse;\n request: QuoteRequest;\n}): TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'] | undefined {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n request.sourceTokenAddress,\n request.sourceChainId,\n );\n\n if (!sourceFiatRate) {\n return undefined;\n }\n\n const estimate = calculateSourceGasFeeTokenAmountFallback({\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n nativeGasCost: nativeSourceNetwork.estimate,\n });\n const max = calculateSourceGasFeeTokenAmountFallback({\n decimals: quote.inputToken.decimals,\n fiatRate: sourceFiatRate,\n nativeGasCost: nativeSourceNetwork.max,\n });\n\n if (!estimate || !max) {\n return undefined;\n }\n\n return { estimate, max };\n}\n\nfunction calculateSourceGasFeeTokenAmountFallback({\n decimals,\n fiatRate,\n nativeGasCost,\n}: {\n decimals: number;\n fiatRate: FiatRates;\n nativeGasCost: Amount;\n}): Amount | undefined {\n const usdRate = new BigNumber(fiatRate.usdRate);\n const nativeGasUsd = new BigNumber(nativeGasCost.usd);\n\n if (\n !usdRate.isFinite() ||\n !usdRate.isGreaterThan(0) ||\n !nativeGasUsd.isFinite() ||\n !nativeGasUsd.isGreaterThan(0)\n ) {\n return undefined;\n }\n\n const amountRaw = nativeGasUsd\n .dividedBy(usdRate)\n .shiftedBy(decimals)\n .integerValue(BigNumber.ROUND_CEIL)\n .toFixed(0);\n\n return getAmountFromTokenAmount({\n amountRaw,\n decimals,\n fiatRate,\n });\n}\n\nasync function estimateAcrossQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure,\n messenger,\n transactions,\n}: {\n fallbackGas?: {\n estimate: number;\n max: number;\n };\n fallbackOnSimulationFailure: boolean;\n messenger: TransactionPayControllerMessenger;\n transactions: QuoteGasTransaction[];\n}): Promise<Awaited<ReturnType<typeof estimateQuoteGasLimits>>> {\n try {\n const gasEstimates = await estimateQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure,\n messenger,\n transactions,\n });\n\n if (\n fallbackOnSimulationFailure &&\n fallbackGas !== undefined &&\n gasEstimates.is7702 &&\n gasEstimates.batchGasLimit !== undefined &&\n gasEstimates.batchGasLimit.max > fallbackGas.max\n ) {\n // Prefunded Predict withdraws can produce inflated 7702 batch estimates\n // because the source account does not yet hold the funds. Keep the gas\n // reservation bounded by the configured Across fallback for this path.\n return {\n ...gasEstimates,\n batchGasLimit: fallbackGas,\n gasLimits: [fallbackGas],\n totalGasEstimate: fallbackGas.estimate,\n totalGasLimit: fallbackGas.max,\n };\n }\n\n return gasEstimates;\n } catch (error) {\n if (!fallbackOnSimulationFailure || transactions.length <= 1) {\n throw error;\n }\n\n const perTransactionGasEstimates = await Promise.all(\n transactions.map((transaction) =>\n estimateQuoteGasLimits({\n fallbackGas,\n fallbackOnSimulationFailure: true,\n messenger,\n transactions: [transaction],\n }),\n ),\n );\n const gasLimits = perTransactionGasEstimates.map(\n (estimate) => estimate.gasLimits[0],\n );\n const totalGasEstimate = gasLimits.reduce(\n (total, gasLimit) => total + gasLimit.estimate,\n 0,\n );\n const totalGasLimit = gasLimits.reduce(\n (total, gasLimit) => total + gasLimit.max,\n 0,\n );\n\n return {\n gasLimits,\n is7702: false,\n totalGasEstimate,\n totalGasLimit,\n usedBatch: false,\n };\n }\n}\n\nfunction combinePostQuoteGas(\n gasResult: {\n sourceNetwork: TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'];\n gasLimits: AcrossGasLimits;\n is7702: boolean;\n requiresAuthorizationList?: true;\n totalGasEstimate: number;\n totalGasLimit: number;\n },\n transaction: TransactionMeta,\n swapTx: AcrossSwapApprovalResponse['swapTx'],\n messenger: TransactionPayControllerMessenger,\n): typeof gasResult {\n const originalTxGas = getOriginalTransactionGas(transaction);\n\n if (originalTxGas === undefined) {\n return gasResult;\n }\n\n const gasLimits = gasResult.is7702\n ? [\n {\n estimate: gasResult.gasLimits[0].estimate + originalTxGas,\n max: gasResult.gasLimits[0].max + originalTxGas,\n },\n ]\n : [\n {\n estimate: originalTxGas,\n max: originalTxGas,\n },\n ...gasResult.gasLimits,\n ];\n\n const totalGasEstimate = gasResult.totalGasEstimate + originalTxGas;\n const totalGasLimit = gasResult.totalGasLimit + originalTxGas;\n const originalSourceNetwork = calculateOriginalSourceNetworkCost({\n gas: originalTxGas,\n messenger,\n swapTx,\n transaction,\n });\n\n return {\n ...gasResult,\n sourceNetwork: {\n estimate: sumAmounts([\n gasResult.sourceNetwork.estimate,\n originalSourceNetwork.estimate,\n ]),\n max: sumAmounts([gasResult.sourceNetwork.max, originalSourceNetwork.max]),\n },\n gasLimits,\n totalGasEstimate,\n totalGasLimit,\n };\n}\n\nfunction calculateOriginalSourceNetworkCost({\n gas,\n messenger,\n swapTx,\n transaction,\n}: {\n gas: number;\n messenger: TransactionPayControllerMessenger;\n swapTx: AcrossSwapApprovalResponse['swapTx'];\n transaction: TransactionMeta;\n}): TransactionPayQuote<AcrossQuote>['fees']['sourceNetwork'] {\n const originalTransactionWithGas = transaction.nestedTransactions?.find(\n (tx) => tx.gas,\n );\n const maxFeePerGas =\n originalTransactionWithGas?.maxFeePerGas ??\n transaction.txParams.maxFeePerGas;\n const maxPriorityFeePerGas =\n originalTransactionWithGas?.maxPriorityFeePerGas ??\n transaction.txParams.maxPriorityFeePerGas;\n\n return {\n estimate: calculateGasCost({\n chainId: transaction.chainId ?? toHex(swapTx.chainId),\n gas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n }),\n max: calculateGasCost({\n chainId: transaction.chainId ?? toHex(swapTx.chainId),\n gas,\n isMax: true,\n maxFeePerGas,\n maxPriorityFeePerGas,\n messenger,\n }),\n };\n}\n"]}
@@ -1,7 +1,14 @@
1
1
  import type { TransactionMeta } from '@metamask/transaction-controller';
2
2
  import type { Hex } from '@metamask/utils';
3
3
  import type { QuoteRequest } from '../../types.js';
4
+ import type { AcrossSwapApprovalResponse } from './types.js';
4
5
  export declare const ACROSS_HYPERCORE_USDC_PERPS_ADDRESS: Hex;
6
+ /**
7
+ * Decimals Across uses for HyperCore USDC-PERPS. This differs from the 8
8
+ * decimals of HyperCore USDC used by other strategies, as the HyperCore perps
9
+ * ledger accounts in 6 decimals.
10
+ */
11
+ export declare const ACROSS_HYPERCORE_USDC_PERPS_DECIMALS = 6;
5
12
  /**
6
13
  * Convert the transaction-pay request into the Across route shape required for
7
14
  * direct perps deposits, targeting the HyperCore USDC-PERPS token.
@@ -11,4 +18,16 @@ export declare const ACROSS_HYPERCORE_USDC_PERPS_ADDRESS: Hex;
11
18
  * @returns Normalized request for Across quoting.
12
19
  */
13
20
  export declare function normalizeAcrossRequest(request: QuoteRequest, transaction: Pick<TransactionMeta, 'txParams' | 'nestedTransactions'>): QuoteRequest;
21
+ /**
22
+ * Ensure an Across quote for a HyperCore USDC-PERPS deposit uses the decimals
23
+ * the request amount was scaled to.
24
+ *
25
+ * If Across changes the USDC-PERPS decimals again, the requested amount would
26
+ * be misinterpreted by orders of magnitude. Throwing lets the strategy loop
27
+ * fall back to the next strategy instead of presenting a mispriced quote.
28
+ *
29
+ * @param request - Normalized Across quote request.
30
+ * @param quote - Across swap approval response.
31
+ */
32
+ export declare function validateAcrossPerpsQuote(request: Pick<QuoteRequest, 'targetChainId' | 'targetTokenAddress'>, quote: AcrossSwapApprovalResponse): void;
14
33
  //# sourceMappingURL=perps.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"perps.d.ts","sourceRoot":"","sources":["../../../src/strategy/across/perps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAE3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAGnD,eAAO,MAAM,mCAAmC,EACE,GAAG,CAAC;AAEtD;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,IAAI,CAAC,eAAe,EAAE,UAAU,GAAG,oBAAoB,CAAC,GACpE,YAAY,CAMd"}
1
+ {"version":3,"file":"perps.d.ts","sourceRoot":"","sources":["../../../src/strategy/across/perps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAG3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,gBAAgB,CAAC;AAEnD,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAE7D,eAAO,MAAM,mCAAmC,EACE,GAAG,CAAC;AAEtD;;;;GAIG;AACH,eAAO,MAAM,oCAAoC,IAAI,CAAC;AAEtD;;;;;;;GAOG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,IAAI,CAAC,eAAe,EAAE,UAAU,GAAG,oBAAoB,CAAC,GACpE,YAAY,CAOd;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,wBAAwB,CACtC,OAAO,EAAE,IAAI,CAAC,YAAY,EAAE,eAAe,GAAG,oBAAoB,CAAC,EACnE,KAAK,EAAE,0BAA0B,GAChC,IAAI,CAiBN"}
@@ -1,5 +1,12 @@
1
+ import { CHAIN_ID_HYPERCORE } from '../../constants.js';
1
2
  import { normalizePerpsDepositRequest } from '../../utils/perps.js';
2
3
  export const ACROSS_HYPERCORE_USDC_PERPS_ADDRESS = '0x2100000000000000000000000000000000000000';
4
+ /**
5
+ * Decimals Across uses for HyperCore USDC-PERPS. This differs from the 8
6
+ * decimals of HyperCore USDC used by other strategies, as the HyperCore perps
7
+ * ledger accounts in 6 decimals.
8
+ */
9
+ export const ACROSS_HYPERCORE_USDC_PERPS_DECIMALS = 6;
3
10
  /**
4
11
  * Convert the transaction-pay request into the Across route shape required for
5
12
  * direct perps deposits, targeting the HyperCore USDC-PERPS token.
@@ -9,6 +16,29 @@ export const ACROSS_HYPERCORE_USDC_PERPS_ADDRESS = '0x21000000000000000000000000
9
16
  * @returns Normalized request for Across quoting.
10
17
  */
11
18
  export function normalizeAcrossRequest(request, transaction) {
12
- return normalizePerpsDepositRequest(request, transaction, ACROSS_HYPERCORE_USDC_PERPS_ADDRESS);
19
+ return normalizePerpsDepositRequest(request, transaction, ACROSS_HYPERCORE_USDC_PERPS_ADDRESS, ACROSS_HYPERCORE_USDC_PERPS_DECIMALS);
20
+ }
21
+ /**
22
+ * Ensure an Across quote for a HyperCore USDC-PERPS deposit uses the decimals
23
+ * the request amount was scaled to.
24
+ *
25
+ * If Across changes the USDC-PERPS decimals again, the requested amount would
26
+ * be misinterpreted by orders of magnitude. Throwing lets the strategy loop
27
+ * fall back to the next strategy instead of presenting a mispriced quote.
28
+ *
29
+ * @param request - Normalized Across quote request.
30
+ * @param quote - Across swap approval response.
31
+ */
32
+ export function validateAcrossPerpsQuote(request, quote) {
33
+ const isPerpsDeposit = request.targetChainId === CHAIN_ID_HYPERCORE &&
34
+ request.targetTokenAddress.toLowerCase() ===
35
+ ACROSS_HYPERCORE_USDC_PERPS_ADDRESS.toLowerCase();
36
+ if (!isPerpsDeposit) {
37
+ return;
38
+ }
39
+ const { decimals } = quote.outputToken;
40
+ if (decimals !== ACROSS_HYPERCORE_USDC_PERPS_DECIMALS) {
41
+ throw new Error(`Unexpected Across USDC-PERPS decimals - Expected: ${ACROSS_HYPERCORE_USDC_PERPS_DECIMALS} | Received: ${decimals}`);
42
+ }
13
43
  }
14
44
  //# sourceMappingURL=perps.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"perps.js","sourceRoot":"","sources":["../../../src/strategy/across/perps.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAEpE,MAAM,CAAC,MAAM,mCAAmC,GAC9C,4CAAmD,CAAC;AAEtD;;;;;;;GAOG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAqB,EACrB,WAAqE;IAErE,OAAO,4BAA4B,CACjC,OAAO,EACP,WAAW,EACX,mCAAmC,CACpC,CAAC;AACJ,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport type { QuoteRequest } from '../../types.js';\nimport { normalizePerpsDepositRequest } from '../../utils/perps.js';\n\nexport const ACROSS_HYPERCORE_USDC_PERPS_ADDRESS =\n '0x2100000000000000000000000000000000000000' as Hex;\n\n/**\n * Convert the transaction-pay request into the Across route shape required for\n * direct perps deposits, targeting the HyperCore USDC-PERPS token.\n *\n * @param request - Transaction pay quote request.\n * @param transaction - Parent transaction whose calls are inspected.\n * @returns Normalized request for Across quoting.\n */\nexport function normalizeAcrossRequest(\n request: QuoteRequest,\n transaction: Pick<TransactionMeta, 'txParams' | 'nestedTransactions'>,\n): QuoteRequest {\n return normalizePerpsDepositRequest(\n request,\n transaction,\n ACROSS_HYPERCORE_USDC_PERPS_ADDRESS,\n );\n}\n"]}
1
+ {"version":3,"file":"perps.js","sourceRoot":"","sources":["../../../src/strategy/across/perps.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,kBAAkB,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,EAAE,4BAA4B,EAAE,MAAM,sBAAsB,CAAC;AAGpE,MAAM,CAAC,MAAM,mCAAmC,GAC9C,4CAAmD,CAAC;AAEtD;;;;GAIG;AACH,MAAM,CAAC,MAAM,oCAAoC,GAAG,CAAC,CAAC;AAEtD;;;;;;;GAOG;AACH,MAAM,UAAU,sBAAsB,CACpC,OAAqB,EACrB,WAAqE;IAErE,OAAO,4BAA4B,CACjC,OAAO,EACP,WAAW,EACX,mCAAmC,EACnC,oCAAoC,CACrC,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,MAAM,UAAU,wBAAwB,CACtC,OAAmE,EACnE,KAAiC;IAEjC,MAAM,cAAc,GAClB,OAAO,CAAC,aAAa,KAAK,kBAAkB;QAC5C,OAAO,CAAC,kBAAkB,CAAC,WAAW,EAAE;YACtC,mCAAmC,CAAC,WAAW,EAAE,CAAC;IAEtD,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,OAAO;IACT,CAAC;IAED,MAAM,EAAE,QAAQ,EAAE,GAAG,KAAK,CAAC,WAAW,CAAC;IAEvC,IAAI,QAAQ,KAAK,oCAAoC,EAAE,CAAC;QACtD,MAAM,IAAI,KAAK,CACb,qDAAqD,oCAAoC,gBAAgB,QAAQ,EAAE,CACpH,CAAC;IACJ,CAAC;AACH,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport { CHAIN_ID_HYPERCORE } from '../../constants.js';\nimport type { QuoteRequest } from '../../types.js';\nimport { normalizePerpsDepositRequest } from '../../utils/perps.js';\nimport type { AcrossSwapApprovalResponse } from './types.js';\n\nexport const ACROSS_HYPERCORE_USDC_PERPS_ADDRESS =\n '0x2100000000000000000000000000000000000000' as Hex;\n\n/**\n * Decimals Across uses for HyperCore USDC-PERPS. This differs from the 8\n * decimals of HyperCore USDC used by other strategies, as the HyperCore perps\n * ledger accounts in 6 decimals.\n */\nexport const ACROSS_HYPERCORE_USDC_PERPS_DECIMALS = 6;\n\n/**\n * Convert the transaction-pay request into the Across route shape required for\n * direct perps deposits, targeting the HyperCore USDC-PERPS token.\n *\n * @param request - Transaction pay quote request.\n * @param transaction - Parent transaction whose calls are inspected.\n * @returns Normalized request for Across quoting.\n */\nexport function normalizeAcrossRequest(\n request: QuoteRequest,\n transaction: Pick<TransactionMeta, 'txParams' | 'nestedTransactions'>,\n): QuoteRequest {\n return normalizePerpsDepositRequest(\n request,\n transaction,\n ACROSS_HYPERCORE_USDC_PERPS_ADDRESS,\n ACROSS_HYPERCORE_USDC_PERPS_DECIMALS,\n );\n}\n\n/**\n * Ensure an Across quote for a HyperCore USDC-PERPS deposit uses the decimals\n * the request amount was scaled to.\n *\n * If Across changes the USDC-PERPS decimals again, the requested amount would\n * be misinterpreted by orders of magnitude. Throwing lets the strategy loop\n * fall back to the next strategy instead of presenting a mispriced quote.\n *\n * @param request - Normalized Across quote request.\n * @param quote - Across swap approval response.\n */\nexport function validateAcrossPerpsQuote(\n request: Pick<QuoteRequest, 'targetChainId' | 'targetTokenAddress'>,\n quote: AcrossSwapApprovalResponse,\n): void {\n const isPerpsDeposit =\n request.targetChainId === CHAIN_ID_HYPERCORE &&\n request.targetTokenAddress.toLowerCase() ===\n ACROSS_HYPERCORE_USDC_PERPS_ADDRESS.toLowerCase();\n\n if (!isPerpsDeposit) {\n return;\n }\n\n const { decimals } = quote.outputToken;\n\n if (decimals !== ACROSS_HYPERCORE_USDC_PERPS_DECIMALS) {\n throw new Error(\n `Unexpected Across USDC-PERPS decimals - Expected: ${ACROSS_HYPERCORE_USDC_PERPS_DECIMALS} | Received: ${decimals}`,\n );\n }\n}\n"]}
@@ -7,6 +7,11 @@ export type TransactionPayFiatAsset = {
7
7
  };
8
8
  export declare const ETH_MAINNET_FIAT_ASSET: TransactionPayFiatAsset;
9
9
  export declare const FIAT_ASSET_ID_BY_TX_TYPE: Partial<Record<TransactionType, TransactionPayFiatAsset>>;
10
+ /**
11
+ * Transaction types that deposit into the Money Account vault, so share the
12
+ * Money Account fiat handling (direct mUSD on-ramp and CHOMP recovery).
13
+ */
14
+ export declare const MONEY_ACCOUNT_DEPOSIT_TYPES: TransactionType[];
10
15
  export declare const FIAT_ENABLED_TYPES: TransactionType[];
11
16
  /** Fiat asset descriptor for mUSD on Monad. */
12
17
  export declare const MUSD_MONAD_FIAT_ASSET: TransactionPayFiatAsset;
@@ -1 +1 @@
1
- {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAW3C,eAAO,MAAM,qBAAqB,QAAQ,CAAC;AAE3C,MAAM,MAAM,uBAAuB,GAAG;IACpC,OAAO,EAAE,GAAG,CAAC;IACb,OAAO,EAAE,GAAG,CAAC;CACd,CAAC;AAYF,eAAO,MAAM,sBAAsB,EAAE,uBAGpC,CAAC;AAEF,eAAO,MAAM,wBAAwB,EAAE,OAAO,CAC5C,MAAM,CAAC,eAAe,EAAE,uBAAuB,CAAC,CAKjD,CAAC;AAEF,eAAO,MAAM,kBAAkB,EAAE,eAAe,EAI/C,CAAC;AAEF,+CAA+C;AAC/C,eAAO,MAAM,qBAAqB,EAAE,uBAGnC,CAAC"}
1
+ {"version":3,"file":"constants.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAW3C,eAAO,MAAM,qBAAqB,QAAQ,CAAC;AAE3C,MAAM,MAAM,uBAAuB,GAAG;IACpC,OAAO,EAAE,GAAG,CAAC;IACb,OAAO,EAAE,GAAG,CAAC;CACd,CAAC;AAYF,eAAO,MAAM,sBAAsB,EAAE,uBAGpC,CAAC;AAEF,eAAO,MAAM,wBAAwB,EAAE,OAAO,CAC5C,MAAM,CAAC,eAAe,EAAE,uBAAuB,CAAC,CAMjD,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,2BAA2B,EAAE,eAAe,EAGxD,CAAC;AAEF,eAAO,MAAM,kBAAkB,EAAE,eAAe,EAI/C,CAAC;AAEF,+CAA+C;AAC/C,eAAO,MAAM,qBAAqB,EAAE,uBAGnC,CAAC"}
@@ -14,12 +14,21 @@ export const ETH_MAINNET_FIAT_ASSET = {
14
14
  chainId: CHAIN_ID_MAINNET,
15
15
  };
16
16
  export const FIAT_ASSET_ID_BY_TX_TYPE = {
17
+ [TransactionType.membershipSubscription]: ETH_MAINNET_FIAT_ASSET,
17
18
  [TransactionType.moneyAccountDeposit]: ETH_MAINNET_FIAT_ASSET,
18
19
  [TransactionType.perpsDeposit]: ARBITRUM_ETH_FIAT_ASSET,
19
20
  [TransactionType.predictDeposit]: POLYGON_POL_FIAT_ASSET,
20
21
  };
21
- export const FIAT_ENABLED_TYPES = [
22
+ /**
23
+ * Transaction types that deposit into the Money Account vault, so share the
24
+ * Money Account fiat handling (direct mUSD on-ramp and CHOMP recovery).
25
+ */
26
+ export const MONEY_ACCOUNT_DEPOSIT_TYPES = [
27
+ TransactionType.membershipSubscription,
22
28
  TransactionType.moneyAccountDeposit,
29
+ ];
30
+ export const FIAT_ENABLED_TYPES = [
31
+ ...MONEY_ACCOUNT_DEPOSIT_TYPES,
23
32
  TransactionType.perpsDeposit,
24
33
  TransactionType.predictDeposit,
25
34
  ];
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/strategy/fiat/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAGnE,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AAO3C,MAAM,sBAAsB,GAA4B;IACtD,OAAO,EAAE,4CAA4C;IACrD,OAAO,EAAE,gBAAgB;CAC1B,CAAC;AAEF,MAAM,uBAAuB,GAA4B;IACvD,OAAO,EAAE,oBAAoB;IAC7B,OAAO,EAAE,iBAAiB;CAC3B,CAAC;AAEF,MAAM,CAAC,MAAM,sBAAsB,GAA4B;IAC7D,OAAO,EAAE,oBAAoB;IAC7B,OAAO,EAAE,gBAAgB;CAC1B,CAAC;AAEF,MAAM,CAAC,MAAM,wBAAwB,GAEjC;IACF,CAAC,eAAe,CAAC,mBAAmB,CAAC,EAAE,sBAAsB;IAC7D,CAAC,eAAe,CAAC,YAAY,CAAC,EAAE,uBAAuB;IACvD,CAAC,eAAe,CAAC,cAAc,CAAC,EAAE,sBAAsB;CACzD,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAsB;IACnD,eAAe,CAAC,mBAAmB;IACnC,eAAe,CAAC,YAAY;IAC5B,eAAe,CAAC,cAAc;CAC/B,CAAC;AAEF,+CAA+C;AAC/C,MAAM,CAAC,MAAM,qBAAqB,GAA4B;IAC5D,OAAO,EAAE,kBAAkB;IAC3B,OAAO,EAAE,cAAc;CACxB,CAAC","sourcesContent":["import { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport {\n CHAIN_ID_ARBITRUM,\n CHAIN_ID_MAINNET,\n CHAIN_ID_MONAD,\n CHAIN_ID_POLYGON,\n MUSD_MONAD_ADDRESS,\n NATIVE_TOKEN_ADDRESS,\n} from '../../constants.js';\n\nexport const DEFAULT_FIAT_CURRENCY = 'USD';\n\nexport type TransactionPayFiatAsset = {\n address: Hex;\n chainId: Hex;\n};\n\nconst POLYGON_POL_FIAT_ASSET: TransactionPayFiatAsset = {\n address: '0x0000000000000000000000000000000000001010',\n chainId: CHAIN_ID_POLYGON,\n};\n\nconst ARBITRUM_ETH_FIAT_ASSET: TransactionPayFiatAsset = {\n address: NATIVE_TOKEN_ADDRESS,\n chainId: CHAIN_ID_ARBITRUM,\n};\n\nexport const ETH_MAINNET_FIAT_ASSET: TransactionPayFiatAsset = {\n address: NATIVE_TOKEN_ADDRESS,\n chainId: CHAIN_ID_MAINNET,\n};\n\nexport const FIAT_ASSET_ID_BY_TX_TYPE: Partial<\n Record<TransactionType, TransactionPayFiatAsset>\n> = {\n [TransactionType.moneyAccountDeposit]: ETH_MAINNET_FIAT_ASSET,\n [TransactionType.perpsDeposit]: ARBITRUM_ETH_FIAT_ASSET,\n [TransactionType.predictDeposit]: POLYGON_POL_FIAT_ASSET,\n};\n\nexport const FIAT_ENABLED_TYPES: TransactionType[] = [\n TransactionType.moneyAccountDeposit,\n TransactionType.perpsDeposit,\n TransactionType.predictDeposit,\n];\n\n/** Fiat asset descriptor for mUSD on Monad. */\nexport const MUSD_MONAD_FIAT_ASSET: TransactionPayFiatAsset = {\n address: MUSD_MONAD_ADDRESS,\n chainId: CHAIN_ID_MONAD,\n};\n"]}
1
+ {"version":3,"file":"constants.js","sourceRoot":"","sources":["../../../src/strategy/fiat/constants.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAGnE,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,cAAc,EACd,gBAAgB,EAChB,kBAAkB,EAClB,oBAAoB,GACrB,MAAM,oBAAoB,CAAC;AAE5B,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAC;AAO3C,MAAM,sBAAsB,GAA4B;IACtD,OAAO,EAAE,4CAA4C;IACrD,OAAO,EAAE,gBAAgB;CAC1B,CAAC;AAEF,MAAM,uBAAuB,GAA4B;IACvD,OAAO,EAAE,oBAAoB;IAC7B,OAAO,EAAE,iBAAiB;CAC3B,CAAC;AAEF,MAAM,CAAC,MAAM,sBAAsB,GAA4B;IAC7D,OAAO,EAAE,oBAAoB;IAC7B,OAAO,EAAE,gBAAgB;CAC1B,CAAC;AAEF,MAAM,CAAC,MAAM,wBAAwB,GAEjC;IACF,CAAC,eAAe,CAAC,sBAAsB,CAAC,EAAE,sBAAsB;IAChE,CAAC,eAAe,CAAC,mBAAmB,CAAC,EAAE,sBAAsB;IAC7D,CAAC,eAAe,CAAC,YAAY,CAAC,EAAE,uBAAuB;IACvD,CAAC,eAAe,CAAC,cAAc,CAAC,EAAE,sBAAsB;CACzD,CAAC;AAEF;;;GAGG;AACH,MAAM,CAAC,MAAM,2BAA2B,GAAsB;IAC5D,eAAe,CAAC,sBAAsB;IACtC,eAAe,CAAC,mBAAmB;CACpC,CAAC;AAEF,MAAM,CAAC,MAAM,kBAAkB,GAAsB;IACnD,GAAG,2BAA2B;IAC9B,eAAe,CAAC,YAAY;IAC5B,eAAe,CAAC,cAAc;CAC/B,CAAC;AAEF,+CAA+C;AAC/C,MAAM,CAAC,MAAM,qBAAqB,GAA4B;IAC5D,OAAO,EAAE,kBAAkB;IAC3B,OAAO,EAAE,cAAc;CACxB,CAAC","sourcesContent":["import { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\n\nimport {\n CHAIN_ID_ARBITRUM,\n CHAIN_ID_MAINNET,\n CHAIN_ID_MONAD,\n CHAIN_ID_POLYGON,\n MUSD_MONAD_ADDRESS,\n NATIVE_TOKEN_ADDRESS,\n} from '../../constants.js';\n\nexport const DEFAULT_FIAT_CURRENCY = 'USD';\n\nexport type TransactionPayFiatAsset = {\n address: Hex;\n chainId: Hex;\n};\n\nconst POLYGON_POL_FIAT_ASSET: TransactionPayFiatAsset = {\n address: '0x0000000000000000000000000000000000001010',\n chainId: CHAIN_ID_POLYGON,\n};\n\nconst ARBITRUM_ETH_FIAT_ASSET: TransactionPayFiatAsset = {\n address: NATIVE_TOKEN_ADDRESS,\n chainId: CHAIN_ID_ARBITRUM,\n};\n\nexport const ETH_MAINNET_FIAT_ASSET: TransactionPayFiatAsset = {\n address: NATIVE_TOKEN_ADDRESS,\n chainId: CHAIN_ID_MAINNET,\n};\n\nexport const FIAT_ASSET_ID_BY_TX_TYPE: Partial<\n Record<TransactionType, TransactionPayFiatAsset>\n> = {\n [TransactionType.membershipSubscription]: ETH_MAINNET_FIAT_ASSET,\n [TransactionType.moneyAccountDeposit]: ETH_MAINNET_FIAT_ASSET,\n [TransactionType.perpsDeposit]: ARBITRUM_ETH_FIAT_ASSET,\n [TransactionType.predictDeposit]: POLYGON_POL_FIAT_ASSET,\n};\n\n/**\n * Transaction types that deposit into the Money Account vault, so share the\n * Money Account fiat handling (direct mUSD on-ramp and CHOMP recovery).\n */\nexport const MONEY_ACCOUNT_DEPOSIT_TYPES: TransactionType[] = [\n TransactionType.membershipSubscription,\n TransactionType.moneyAccountDeposit,\n];\n\nexport const FIAT_ENABLED_TYPES: TransactionType[] = [\n ...MONEY_ACCOUNT_DEPOSIT_TYPES,\n TransactionType.perpsDeposit,\n TransactionType.predictDeposit,\n];\n\n/** Fiat asset descriptor for mUSD on Monad. */\nexport const MUSD_MONAD_FIAT_ASSET: TransactionPayFiatAsset = {\n address: MUSD_MONAD_ADDRESS,\n chainId: CHAIN_ID_MONAD,\n};\n"]}
@@ -22,8 +22,9 @@ export declare function resolveTransactionType(transaction: TransactionMeta, ena
22
22
  /**
23
23
  * Checks whether a transaction is a Money Account deposit.
24
24
  *
25
- * Handles both direct `moneyAccountDeposit` transactions and EIP-7702
26
- * batch transactions that contain a `moneyAccountDeposit` nested call.
25
+ * Matches any of `MONEY_ACCOUNT_DEPOSIT_TYPES` (`moneyAccountDeposit` and
26
+ * `membershipSubscription`), either as the transaction type or as a nested
27
+ * call in an EIP-7702 batch.
27
28
  * Uses {@link resolveTransactionType} with `FIAT_ENABLED_TYPES` to
28
29
  * correctly skip non-deposit nested types (e.g. `tokenMethodApprove`).
29
30
  *
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,KAAK,IAAI,UAAU,EACnB,UAAU,EACV,wBAAwB,EACzB,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,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uCAAuC,CAAC,EACtD,YAAY,EACZ,QAAQ,GACT,EAAE;IACD,YAAY,EAAE,UAAU,CAAC,cAAc,CAAC,CAAC;IACzC,QAAQ,EAAE,MAAM,CAAC;CAClB,GAAG,MAAM,CAmBT;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,sBAAsB,CAAC,EACrC,aAAa,EACb,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,EAAE;IACD,aAAa,EAAE,UAAU,CAAC;IAC1B,cAAc,EAAE,UAAU,CAAC;IAC3B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,aAAa,EAAE,MAAM,CAAC;CACvB,GAAG,IAAI,CA2CP;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,MAAM,GAAG,IAAI,CAYf"}
@@ -5,7 +5,7 @@ import { projectLogger } from '../../logger.js';
5
5
  import { getFiatAssetPerTransactionType, getFiatEnabledTypes, } from '../../utils/feature-flags.js';
6
6
  import { buildCaipAssetType } from '../../utils/token.js';
7
7
  import { getTransferredAmountFromTxHash } from '../../utils/transaction.js';
8
- import { DEFAULT_FIAT_CURRENCY, FIAT_ENABLED_TYPES } from './constants.js';
8
+ import { DEFAULT_FIAT_CURRENCY, FIAT_ENABLED_TYPES, MONEY_ACCOUNT_DEPOSIT_TYPES, } from './constants.js';
9
9
  const log = createModuleLogger(projectLogger, 'fiat-utils');
10
10
  export function deriveFiatAssetForFiatPayment(transaction, messenger) {
11
11
  const enabledTypes = getFiatEnabledTypes(messenger);
@@ -34,8 +34,9 @@ export function resolveTransactionType(transaction, enabledTypes) {
34
34
  /**
35
35
  * Checks whether a transaction is a Money Account deposit.
36
36
  *
37
- * Handles both direct `moneyAccountDeposit` transactions and EIP-7702
38
- * batch transactions that contain a `moneyAccountDeposit` nested call.
37
+ * Matches any of `MONEY_ACCOUNT_DEPOSIT_TYPES` (`moneyAccountDeposit` and
38
+ * `membershipSubscription`), either as the transaction type or as a nested
39
+ * call in an EIP-7702 batch.
39
40
  * Uses {@link resolveTransactionType} with `FIAT_ENABLED_TYPES` to
40
41
  * correctly skip non-deposit nested types (e.g. `tokenMethodApprove`).
41
42
  *
@@ -43,8 +44,8 @@ export function resolveTransactionType(transaction, enabledTypes) {
43
44
  * @returns `true` if the transaction is a Money Account deposit.
44
45
  */
45
46
  export function isMoneyAccountDepositTransaction(transaction) {
46
- return (resolveTransactionType(transaction, FIAT_ENABLED_TYPES) ===
47
- TransactionType.moneyAccountDeposit);
47
+ const type = resolveTransactionType(transaction, FIAT_ENABLED_TYPES);
48
+ return type !== undefined && MONEY_ACCOUNT_DEPOSIT_TYPES.includes(type);
48
49
  }
49
50
  /**
50
51
  * Fetches the best matching Ramps quote for a fiat asset and payment method,
@@ -1 +1 @@
1
- {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/strategy/fiat/utils.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EACL,8BAA8B,EAC9B,mBAAmB,GACpB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,8BAA8B,EAAE,MAAM,4BAA4B,CAAC;AAG5E,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAE3E,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;AAE5D,MAAM,UAAU,6BAA6B,CAC3C,WAA4B,EAC5B,SAA4C;IAE5C,MAAM,YAAY,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;IACpD,MAAM,MAAM,GAAG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4CAA4C;YAC1C,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,mBAAmB,OAAO,CACpE,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CACjC,QAA4B;IAE5B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAElD,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,WAAW,EAAE,CAAC;QAC7B,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;IAC1B,CAAC;IAED,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9C,CAAC","sourcesContent":["import type {\n Quote as RampsQuote,\n RampsOrder,\n RampsOrderCryptoCurrency,\n} from '@metamask/ramps-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger.js';\nimport type { TransactionPayControllerMessenger } from '../../types.js';\nimport {\n getFiatAssetPerTransactionType,\n getFiatEnabledTypes,\n} from '../../utils/feature-flags.js';\nimport { buildCaipAssetType } from '../../utils/token.js';\nimport { getTransferredAmountFromTxHash } from '../../utils/transaction.js';\nimport type { RelayQuote } from '../relay/types.js';\nimport type { TransactionPayFiatAsset } from './constants.js';\nimport { DEFAULT_FIAT_CURRENCY, FIAT_ENABLED_TYPES } from './constants.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-utils');\n\nexport function deriveFiatAssetForFiatPayment(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayFiatAsset {\n const enabledTypes = getFiatEnabledTypes(messenger);\n const txType = resolveTransactionType(transaction, enabledTypes);\n\n return getFiatAssetPerTransactionType(messenger, txType);\n}\n\n/**\n * Resolves the effective transaction type for fiat strategy purposes.\n *\n * For non-batch transactions returns the transaction's own type.\n * For batch transactions returns the first nested transaction type\n * that appears in the enabled types list, or the batch type itself\n * if no nested type matches.\n *\n * @param transaction - The transaction metadata to inspect.\n * @param enabledTypes - Transaction types eligible for fiat payment.\n * @returns The resolved transaction type, or `undefined`.\n */\nexport function resolveTransactionType(\n transaction: TransactionMeta,\n enabledTypes: TransactionType[],\n): TransactionType | undefined {\n if (transaction.type !== TransactionType.batch) {\n return transaction.type;\n }\n\n const nestedType = transaction.nestedTransactions?.find(\n (tx) => tx.type && enabledTypes.includes(tx.type),\n )?.type;\n\n return nestedType ?? transaction.type;\n}\n\n/**\n * Checks whether a transaction is a Money Account deposit.\n *\n * Handles both direct `moneyAccountDeposit` transactions and EIP-7702\n * batch transactions that contain a `moneyAccountDeposit` nested call.\n * Uses {@link resolveTransactionType} with `FIAT_ENABLED_TYPES` to\n * correctly skip non-deposit nested types (e.g. `tokenMethodApprove`).\n *\n * @param transaction - The transaction metadata to inspect.\n * @returns `true` if the transaction is a Money Account deposit.\n */\nexport function isMoneyAccountDepositTransaction(\n transaction: TransactionMeta,\n): boolean {\n return (\n resolveTransactionType(transaction, FIAT_ENABLED_TYPES) ===\n TransactionType.moneyAccountDeposit\n );\n}\n\n/**\n * Fetches the best matching Ramps quote for a fiat asset and payment method,\n * with provider fees reconciled to what the resolved provider actually charges.\n *\n * The `RampsController:getQuoteWithFees` action owns the provider check and the\n * native buy-quote lookup, so a Transak Native quote already carries the native\n * fee in its `providerFee`/`networkFee`/`totalFees` fields. MM Pay deposits are\n * fee-on-top, so the quote is requested with `isFeeExcludedFromFiat: true`.\n *\n * @param options - Quote options.\n * @param options.adjustedAmount - Fiat amount sent to Ramps.\n * @param options.errorMessage - Error thrown when no matching quote is returned.\n * @param options.fiatAsset - Fiat asset to buy.\n * @param options.fiatPaymentMethod - Selected fiat payment method.\n * @param options.messenger - Controller messenger.\n * @param options.walletAddress - Wallet address that receives the on-ramped asset.\n * @returns The best matching Ramps quote with reconciled fees.\n */\nexport async function getRampsQuote({\n adjustedAmount,\n errorMessage = 'No matching ramps quote found for selected provider',\n fiatAsset,\n fiatPaymentMethod,\n messenger,\n walletAddress,\n}: {\n adjustedAmount: number;\n errorMessage?: string;\n fiatAsset: TransactionPayFiatAsset;\n fiatPaymentMethod: string;\n messenger: TransactionPayControllerMessenger;\n walletAddress: string;\n}): Promise<RampsQuote> {\n const quote = await messenger.call('RampsController:getQuoteWithFees', {\n amount: adjustedAmount,\n assetId: buildCaipAssetType(fiatAsset.chainId, fiatAsset.address),\n autoSelectProvider: true,\n fiat: DEFAULT_FIAT_CURRENCY,\n isFeeExcludedFromFiat: true,\n paymentMethods: [fiatPaymentMethod],\n restrictToKnownOrNativeProviders: true,\n walletAddress,\n });\n\n log('Fetched ramps quote', { hasQuote: Boolean(quote) });\n\n if (!quote) {\n throw new Error(errorMessage);\n }\n\n return quote;\n}\n\n/**\n * Validates that a completed order's crypto asset matches the expected fiat asset.\n *\n * @param options - The validation options.\n * @param options.expectedAsset - The expected fiat asset derived from the transaction type.\n * @param options.orderCrypto - The crypto currency information from the completed order.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nexport function validateOrderAsset({\n expectedAsset,\n orderCrypto,\n transactionId,\n}: {\n expectedAsset: TransactionPayFiatAsset;\n orderCrypto: RampsOrderCryptoCurrency | undefined;\n transactionId: string;\n}): void {\n const orderAssetId = orderCrypto?.assetId?.toLowerCase();\n const expectedAssetId = buildCaipAssetType(\n expectedAsset.chainId,\n expectedAsset.address,\n ).toLowerCase();\n const expectedChainId = expectedAssetId.split('/')[0];\n const orderChainId = orderCrypto?.chainId?.toLowerCase();\n\n if (orderAssetId && orderAssetId !== expectedAssetId) {\n throw new Error(\n `Order asset mismatch for transaction ${transactionId}: ` +\n `expected ${expectedAssetId}, got ${orderAssetId}`,\n );\n }\n\n if (orderChainId && orderChainId !== expectedChainId) {\n throw new Error(\n `Order chain mismatch for transaction ${transactionId}: ` +\n `expected ${expectedChainId}, got ${orderChainId}`,\n );\n }\n}\n\n/**\n * Resolves the raw source amount for a completed fiat order, read from the\n * on-chain transfer identified by `order.txHash`.\n *\n * Throws when the order has no transaction hash or no matching transfer,\n * rather than trusting the provider-reported `order.cryptoAmount`.\n *\n * @param options - The resolution options.\n * @param options.messenger - Controller messenger for network access.\n * @param options.order - The completed on-ramp order.\n * @param options.fiatAsset - The fiat asset describing the expected token.\n * @param options.walletAddress - Recipient wallet address for on-chain lookup.\n * @returns The raw (atomic) source amount.\n */\nexport async function resolveSourceAmountRaw({\n messenger,\n order,\n fiatAsset,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n order: RampsOrder;\n fiatAsset: TransactionPayFiatAsset;\n walletAddress: Hex;\n}): Promise<string> {\n if (!order.txHash) {\n throw new Error('Missing fiat order transaction hash');\n }\n\n const { amountRaw } = await getTransferredAmountFromTxHash({\n messenger,\n txHash: order.txHash,\n chainId: fiatAsset.chainId,\n tokenAddress: fiatAsset.address,\n walletAddress,\n });\n\n if (!amountRaw) {\n throw new Error(\n `Could not determine transferred amount from transaction ${order.txHash}`,\n );\n }\n\n log('Resolved source amount from on-chain transaction', {\n amountRaw,\n txHash: order.txHash,\n });\n\n return amountRaw;\n}\n\n/**\n * Converts the order's human-readable crypto amount to a raw token amount.\n *\n * @param options - The conversion options.\n * @param options.cryptoAmount - Human-readable crypto amount from the completed order.\n * @param options.decimals - Token decimals for the fiat asset.\n * @returns The raw token amount as a string.\n */\nexport function getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount,\n decimals,\n}: {\n cryptoAmount: RampsOrder['cryptoAmount'];\n decimals: number;\n}): string {\n const normalizedAmount = new BigNumber(String(cryptoAmount));\n\n if (!normalizedAmount.isFinite() || normalizedAmount.lte(0)) {\n throw new Error(\n `Invalid fiat order crypto amount: ${String(cryptoAmount)}`,\n );\n }\n\n const rawAmount = normalizedAmount\n .shiftedBy(decimals)\n .decimalPlaces(0, BigNumber.ROUND_DOWN)\n .toFixed(0);\n\n if (!new BigNumber(rawAmount).gt(0)) {\n throw new Error('Computed fiat order source amount is not positive');\n }\n\n return rawAmount;\n}\n\n/**\n * Validates that the relay exchange rate hasn't drifted significantly between\n * the original quoting phase and the post-settlement discovery quote.\n *\n * Compares the USD output/input ratio from both quotes. This normalises for\n * different source amounts (quoting phase uses a theoretical amount, discovery\n * uses the actual settled amount) so the comparison reflects genuine rate\n * movement rather than amount differences.\n *\n * @param options - The validation options.\n * @param options.originalQuote - Relay quote from the original quoting phase.\n * @param options.discoveryQuote - Relay quote from the post-settlement discovery.\n * @param options.maxRateDriftPercent - Maximum allowed rate drift percentage.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nexport function validateRelayRateDrift({\n originalQuote,\n discoveryQuote,\n maxRateDriftPercent,\n transactionId,\n}: {\n originalQuote: RelayQuote;\n discoveryQuote: RelayQuote;\n maxRateDriftPercent: number;\n transactionId: string;\n}): void {\n const originalIn = new BigNumber(originalQuote.details.currencyIn.amountUsd);\n const originalOut = new BigNumber(\n originalQuote.details.currencyOut.amountUsd,\n );\n const discoveryIn = new BigNumber(\n discoveryQuote.details.currencyIn.amountUsd,\n );\n const discoveryOut = new BigNumber(\n discoveryQuote.details.currencyOut.amountUsd,\n );\n\n if (\n !originalIn.gt(0) ||\n !originalOut.gt(0) ||\n !discoveryIn.gt(0) ||\n !discoveryOut.gt(0)\n ) {\n return;\n }\n\n const originalRate = originalOut.dividedBy(originalIn);\n const discoveryRate = discoveryOut.dividedBy(discoveryIn);\n\n const driftPercent = originalRate\n .minus(discoveryRate)\n .dividedBy(originalRate)\n .multipliedBy(100);\n\n log('Relay rate drift check', {\n originalRate: originalRate.toFixed(6),\n discoveryRate: discoveryRate.toFixed(6),\n driftPercent: driftPercent.toFixed(2),\n maxRateDriftPercent,\n transactionId,\n });\n\n if (driftPercent.gt(maxRateDriftPercent)) {\n throw new Error(\n `Relay rate drift too high for transaction ` +\n `${driftPercent.toFixed(2)}% exceeds ${maxRateDriftPercent}% max`,\n );\n }\n}\n\n/**\n * Extracts the provider code from a ramps provider string.\n *\n * Accepts the canonical provider code (e.g. `transak-native`) and, for\n * backwards compatibility, the legacy path form (e.g. `/providers/transak-native`).\n *\n * @param provider - Canonical provider code, or legacy provider path.\n * @returns The provider code, or `null` if the format is invalid.\n */\nexport function extractProviderCode(\n provider: string | undefined,\n): string | null {\n if (!provider) {\n return null;\n }\n\n const parts = provider.split('/').filter(Boolean);\n\n if (parts[0] === 'providers') {\n return parts[1] ?? null;\n }\n\n return parts.length === 1 ? parts[0] : null;\n}\n"]}
1
+ {"version":3,"file":"utils.js","sourceRoot":"","sources":["../../../src/strategy/fiat/utils.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAEnE,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,OAAO,EACL,8BAA8B,EAC9B,mBAAmB,GACpB,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,kBAAkB,EAAE,MAAM,sBAAsB,CAAC;AAC1D,OAAO,EAAE,8BAA8B,EAAE,MAAM,4BAA4B,CAAC;AAG5E,OAAO,EACL,qBAAqB,EACrB,kBAAkB,EAClB,2BAA2B,GAC5B,MAAM,gBAAgB,CAAC;AAExB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;AAE5D,MAAM,UAAU,6BAA6B,CAC3C,WAA4B,EAC5B,SAA4C;IAE5C,MAAM,YAAY,GAAG,mBAAmB,CAAC,SAAS,CAAC,CAAC;IACpD,MAAM,MAAM,GAA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AAC,mBAAmB,CAAC,EAAE,CAAC;QACzC,MAAM,IAAI,KAAK,CACb,4CAA4C;YAC1C,GAAG,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,aAAa,mBAAmB,OAAO,CACpE,CAAC;IACJ,CAAC;AACH,CAAC;AAED;;;;;;;;GAQG;AACH,MAAM,UAAU,mBAAmB,CACjC,QAA4B;IAE5B,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,KAAK,GAAG,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IAElD,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,WAAW,EAAE,CAAC;QAC7B,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,IAAI,CAAC;IAC1B,CAAC;IAED,OAAO,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC;AAC9C,CAAC","sourcesContent":["import type {\n Quote as RampsQuote,\n RampsOrder,\n RampsOrderCryptoCurrency,\n} from '@metamask/ramps-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger.js';\nimport type { TransactionPayControllerMessenger } from '../../types.js';\nimport {\n getFiatAssetPerTransactionType,\n getFiatEnabledTypes,\n} from '../../utils/feature-flags.js';\nimport { buildCaipAssetType } from '../../utils/token.js';\nimport { getTransferredAmountFromTxHash } from '../../utils/transaction.js';\nimport type { RelayQuote } from '../relay/types.js';\nimport type { TransactionPayFiatAsset } from './constants.js';\nimport {\n DEFAULT_FIAT_CURRENCY,\n FIAT_ENABLED_TYPES,\n MONEY_ACCOUNT_DEPOSIT_TYPES,\n} from './constants.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-utils');\n\nexport function deriveFiatAssetForFiatPayment(\n transaction: TransactionMeta,\n messenger: TransactionPayControllerMessenger,\n): TransactionPayFiatAsset {\n const enabledTypes = getFiatEnabledTypes(messenger);\n const txType = resolveTransactionType(transaction, enabledTypes);\n\n return getFiatAssetPerTransactionType(messenger, txType);\n}\n\n/**\n * Resolves the effective transaction type for fiat strategy purposes.\n *\n * For non-batch transactions returns the transaction's own type.\n * For batch transactions returns the first nested transaction type\n * that appears in the enabled types list, or the batch type itself\n * if no nested type matches.\n *\n * @param transaction - The transaction metadata to inspect.\n * @param enabledTypes - Transaction types eligible for fiat payment.\n * @returns The resolved transaction type, or `undefined`.\n */\nexport function resolveTransactionType(\n transaction: TransactionMeta,\n enabledTypes: TransactionType[],\n): TransactionType | undefined {\n if (transaction.type !== TransactionType.batch) {\n return transaction.type;\n }\n\n const nestedType = transaction.nestedTransactions?.find(\n (tx) => tx.type && enabledTypes.includes(tx.type),\n )?.type;\n\n return nestedType ?? transaction.type;\n}\n\n/**\n * Checks whether a transaction is a Money Account deposit.\n *\n * Matches any of `MONEY_ACCOUNT_DEPOSIT_TYPES` (`moneyAccountDeposit` and\n * `membershipSubscription`), either as the transaction type or as a nested\n * call in an EIP-7702 batch.\n * Uses {@link resolveTransactionType} with `FIAT_ENABLED_TYPES` to\n * correctly skip non-deposit nested types (e.g. `tokenMethodApprove`).\n *\n * @param transaction - The transaction metadata to inspect.\n * @returns `true` if the transaction is a Money Account deposit.\n */\nexport function isMoneyAccountDepositTransaction(\n transaction: TransactionMeta,\n): boolean {\n const type = resolveTransactionType(transaction, FIAT_ENABLED_TYPES);\n\n return type !== undefined && MONEY_ACCOUNT_DEPOSIT_TYPES.includes(type);\n}\n\n/**\n * Fetches the best matching Ramps quote for a fiat asset and payment method,\n * with provider fees reconciled to what the resolved provider actually charges.\n *\n * The `RampsController:getQuoteWithFees` action owns the provider check and the\n * native buy-quote lookup, so a Transak Native quote already carries the native\n * fee in its `providerFee`/`networkFee`/`totalFees` fields. MM Pay deposits are\n * fee-on-top, so the quote is requested with `isFeeExcludedFromFiat: true`.\n *\n * @param options - Quote options.\n * @param options.adjustedAmount - Fiat amount sent to Ramps.\n * @param options.errorMessage - Error thrown when no matching quote is returned.\n * @param options.fiatAsset - Fiat asset to buy.\n * @param options.fiatPaymentMethod - Selected fiat payment method.\n * @param options.messenger - Controller messenger.\n * @param options.walletAddress - Wallet address that receives the on-ramped asset.\n * @returns The best matching Ramps quote with reconciled fees.\n */\nexport async function getRampsQuote({\n adjustedAmount,\n errorMessage = 'No matching ramps quote found for selected provider',\n fiatAsset,\n fiatPaymentMethod,\n messenger,\n walletAddress,\n}: {\n adjustedAmount: number;\n errorMessage?: string;\n fiatAsset: TransactionPayFiatAsset;\n fiatPaymentMethod: string;\n messenger: TransactionPayControllerMessenger;\n walletAddress: string;\n}): Promise<RampsQuote> {\n const quote = await messenger.call('RampsController:getQuoteWithFees', {\n amount: adjustedAmount,\n assetId: buildCaipAssetType(fiatAsset.chainId, fiatAsset.address),\n autoSelectProvider: true,\n fiat: DEFAULT_FIAT_CURRENCY,\n isFeeExcludedFromFiat: true,\n paymentMethods: [fiatPaymentMethod],\n restrictToKnownOrNativeProviders: true,\n walletAddress,\n });\n\n log('Fetched ramps quote', { hasQuote: Boolean(quote) });\n\n if (!quote) {\n throw new Error(errorMessage);\n }\n\n return quote;\n}\n\n/**\n * Validates that a completed order's crypto asset matches the expected fiat asset.\n *\n * @param options - The validation options.\n * @param options.expectedAsset - The expected fiat asset derived from the transaction type.\n * @param options.orderCrypto - The crypto currency information from the completed order.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nexport function validateOrderAsset({\n expectedAsset,\n orderCrypto,\n transactionId,\n}: {\n expectedAsset: TransactionPayFiatAsset;\n orderCrypto: RampsOrderCryptoCurrency | undefined;\n transactionId: string;\n}): void {\n const orderAssetId = orderCrypto?.assetId?.toLowerCase();\n const expectedAssetId = buildCaipAssetType(\n expectedAsset.chainId,\n expectedAsset.address,\n ).toLowerCase();\n const expectedChainId = expectedAssetId.split('/')[0];\n const orderChainId = orderCrypto?.chainId?.toLowerCase();\n\n if (orderAssetId && orderAssetId !== expectedAssetId) {\n throw new Error(\n `Order asset mismatch for transaction ${transactionId}: ` +\n `expected ${expectedAssetId}, got ${orderAssetId}`,\n );\n }\n\n if (orderChainId && orderChainId !== expectedChainId) {\n throw new Error(\n `Order chain mismatch for transaction ${transactionId}: ` +\n `expected ${expectedChainId}, got ${orderChainId}`,\n );\n }\n}\n\n/**\n * Resolves the raw source amount for a completed fiat order, read from the\n * on-chain transfer identified by `order.txHash`.\n *\n * Throws when the order has no transaction hash or no matching transfer,\n * rather than trusting the provider-reported `order.cryptoAmount`.\n *\n * @param options - The resolution options.\n * @param options.messenger - Controller messenger for network access.\n * @param options.order - The completed on-ramp order.\n * @param options.fiatAsset - The fiat asset describing the expected token.\n * @param options.walletAddress - Recipient wallet address for on-chain lookup.\n * @returns The raw (atomic) source amount.\n */\nexport async function resolveSourceAmountRaw({\n messenger,\n order,\n fiatAsset,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n order: RampsOrder;\n fiatAsset: TransactionPayFiatAsset;\n walletAddress: Hex;\n}): Promise<string> {\n if (!order.txHash) {\n throw new Error('Missing fiat order transaction hash');\n }\n\n const { amountRaw } = await getTransferredAmountFromTxHash({\n messenger,\n txHash: order.txHash,\n chainId: fiatAsset.chainId,\n tokenAddress: fiatAsset.address,\n walletAddress,\n });\n\n if (!amountRaw) {\n throw new Error(\n `Could not determine transferred amount from transaction ${order.txHash}`,\n );\n }\n\n log('Resolved source amount from on-chain transaction', {\n amountRaw,\n txHash: order.txHash,\n });\n\n return amountRaw;\n}\n\n/**\n * Converts the order's human-readable crypto amount to a raw token amount.\n *\n * @param options - The conversion options.\n * @param options.cryptoAmount - Human-readable crypto amount from the completed order.\n * @param options.decimals - Token decimals for the fiat asset.\n * @returns The raw token amount as a string.\n */\nexport function getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount,\n decimals,\n}: {\n cryptoAmount: RampsOrder['cryptoAmount'];\n decimals: number;\n}): string {\n const normalizedAmount = new BigNumber(String(cryptoAmount));\n\n if (!normalizedAmount.isFinite() || normalizedAmount.lte(0)) {\n throw new Error(\n `Invalid fiat order crypto amount: ${String(cryptoAmount)}`,\n );\n }\n\n const rawAmount = normalizedAmount\n .shiftedBy(decimals)\n .decimalPlaces(0, BigNumber.ROUND_DOWN)\n .toFixed(0);\n\n if (!new BigNumber(rawAmount).gt(0)) {\n throw new Error('Computed fiat order source amount is not positive');\n }\n\n return rawAmount;\n}\n\n/**\n * Validates that the relay exchange rate hasn't drifted significantly between\n * the original quoting phase and the post-settlement discovery quote.\n *\n * Compares the USD output/input ratio from both quotes. This normalises for\n * different source amounts (quoting phase uses a theoretical amount, discovery\n * uses the actual settled amount) so the comparison reflects genuine rate\n * movement rather than amount differences.\n *\n * @param options - The validation options.\n * @param options.originalQuote - Relay quote from the original quoting phase.\n * @param options.discoveryQuote - Relay quote from the post-settlement discovery.\n * @param options.maxRateDriftPercent - Maximum allowed rate drift percentage.\n * @param options.transactionId - Transaction ID for error reporting.\n */\nexport function validateRelayRateDrift({\n originalQuote,\n discoveryQuote,\n maxRateDriftPercent,\n transactionId,\n}: {\n originalQuote: RelayQuote;\n discoveryQuote: RelayQuote;\n maxRateDriftPercent: number;\n transactionId: string;\n}): void {\n const originalIn = new BigNumber(originalQuote.details.currencyIn.amountUsd);\n const originalOut = new BigNumber(\n originalQuote.details.currencyOut.amountUsd,\n );\n const discoveryIn = new BigNumber(\n discoveryQuote.details.currencyIn.amountUsd,\n );\n const discoveryOut = new BigNumber(\n discoveryQuote.details.currencyOut.amountUsd,\n );\n\n if (\n !originalIn.gt(0) ||\n !originalOut.gt(0) ||\n !discoveryIn.gt(0) ||\n !discoveryOut.gt(0)\n ) {\n return;\n }\n\n const originalRate = originalOut.dividedBy(originalIn);\n const discoveryRate = discoveryOut.dividedBy(discoveryIn);\n\n const driftPercent = originalRate\n .minus(discoveryRate)\n .dividedBy(originalRate)\n .multipliedBy(100);\n\n log('Relay rate drift check', {\n originalRate: originalRate.toFixed(6),\n discoveryRate: discoveryRate.toFixed(6),\n driftPercent: driftPercent.toFixed(2),\n maxRateDriftPercent,\n transactionId,\n });\n\n if (driftPercent.gt(maxRateDriftPercent)) {\n throw new Error(\n `Relay rate drift too high for transaction ` +\n `${driftPercent.toFixed(2)}% exceeds ${maxRateDriftPercent}% max`,\n );\n }\n}\n\n/**\n * Extracts the provider code from a ramps provider string.\n *\n * Accepts the canonical provider code (e.g. `transak-native`) and, for\n * backwards compatibility, the legacy path form (e.g. `/providers/transak-native`).\n *\n * @param provider - Canonical provider code, or legacy provider path.\n * @returns The provider code, or `null` if the format is invalid.\n */\nexport function extractProviderCode(\n provider: string | undefined,\n): string | null {\n if (!provider) {\n return null;\n }\n\n const parts = provider.split('/').filter(Boolean);\n\n if (parts[0] === 'providers') {\n return parts[1] ?? null;\n }\n\n return parts.length === 1 ? parts[0] : null;\n}\n"]}
@@ -29,16 +29,20 @@ export declare function isPerpsDepositRequest(request: Pick<QuoteRequest, 'isPos
29
29
  * deposit.
30
30
  *
31
31
  * Transaction pay starts from the parent on-chain asset (Arbitrum USDC,
32
- * 6 decimals), while HyperCore expects an 8-decimal amount, so the target
33
- * amount is shifted accordingly.
32
+ * 6 decimals), so the target amount is shifted to the decimals the strategy's
33
+ * quote API uses for the HyperCore token. This defaults to the 8 decimals of
34
+ * HyperCore USDC, but providers may represent it differently (e.g. Across
35
+ * quotes USDC-PERPS in 6 decimals).
34
36
  *
35
37
  * @param request - Quote request from the transaction-pay controller.
36
38
  * @param transaction - Parent transaction whose calls are inspected.
37
39
  * @param hypercoreUsdcAddress - Strategy-specific HyperCore USDC address to
38
40
  * set as the target token.
41
+ * @param targetDecimals - Decimals of the HyperCore token in the strategy's
42
+ * quote API.
39
43
  * @returns Normalized request, or the original request if not a perps deposit.
40
44
  */
41
- export declare function normalizePerpsDepositRequest(request: QuoteRequest, transaction: PerpsTransaction | undefined, hypercoreUsdcAddress: Hex): QuoteRequest;
45
+ export declare function normalizePerpsDepositRequest(request: QuoteRequest, transaction: PerpsTransaction | undefined, hypercoreUsdcAddress: Hex, targetDecimals?: number): QuoteRequest;
42
46
  /**
43
47
  * Rewrite a Hyperliquid perps-withdraw quote request so the source is
44
48
  * HyperCore USDC rather than Arbitrum USDC.
@@ -1 +1 @@
1
- {"version":3,"file":"perps.d.ts","sourceRoot":"","sources":["../../src/utils/perps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAU3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAMhD,KAAK,gBAAgB,GAAG,IAAI,CAC1B,eAAe,EACf,UAAU,GAAG,oBAAoB,CAClC,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CACvC,WAAW,EAAE,gBAAgB,GAAG,SAAS,GACxC,OAAO,CAeT;AAED;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,IAAI,CACX,YAAY,EACZ,aAAa,GAAG,eAAe,GAAG,oBAAoB,CACvD,EACD,WAAW,EAAE,gBAAgB,GAAG,SAAS,GACxC,OAAO,CAQT;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,gBAAgB,GAAG,SAAS,EACzC,oBAAoB,EAAE,GAAG,GACxB,YAAY,CAWd;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,YAAY,EACrB,oBAAoB,EAAE,GAAG,GACxB,YAAY,CAad"}
1
+ {"version":3,"file":"perps.d.ts","sourceRoot":"","sources":["../../src/utils/perps.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AACxE,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAU3C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAMhD,KAAK,gBAAgB,GAAG,IAAI,CAC1B,eAAe,EACf,UAAU,GAAG,oBAAoB,CAClC,CAAC;AAEF;;;;;;;;;;GAUG;AACH,wBAAgB,yBAAyB,CACvC,WAAW,EAAE,gBAAgB,GAAG,SAAS,GACxC,OAAO,CAeT;AAED;;;;;;;;GAQG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,IAAI,CACX,YAAY,EACZ,aAAa,GAAG,eAAe,GAAG,oBAAoB,CACvD,EACD,WAAW,EAAE,gBAAgB,GAAG,SAAS,GACxC,OAAO,CAQT;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,4BAA4B,CAC1C,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,gBAAgB,GAAG,SAAS,EACzC,oBAAoB,EAAE,GAAG,EACzB,cAAc,GAAE,MAAgC,GAC/C,YAAY,CAad;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,6BAA6B,CAC3C,OAAO,EAAE,YAAY,EACrB,oBAAoB,EAAE,GAAG,GACxB,YAAY,CAad"}
@@ -45,22 +45,28 @@ export function isPerpsDepositRequest(request, transaction) {
45
45
  * deposit.
46
46
  *
47
47
  * Transaction pay starts from the parent on-chain asset (Arbitrum USDC,
48
- * 6 decimals), while HyperCore expects an 8-decimal amount, so the target
49
- * amount is shifted accordingly.
48
+ * 6 decimals), so the target amount is shifted to the decimals the strategy's
49
+ * quote API uses for the HyperCore token. This defaults to the 8 decimals of
50
+ * HyperCore USDC, but providers may represent it differently (e.g. Across
51
+ * quotes USDC-PERPS in 6 decimals).
50
52
  *
51
53
  * @param request - Quote request from the transaction-pay controller.
52
54
  * @param transaction - Parent transaction whose calls are inspected.
53
55
  * @param hypercoreUsdcAddress - Strategy-specific HyperCore USDC address to
54
56
  * set as the target token.
57
+ * @param targetDecimals - Decimals of the HyperCore token in the strategy's
58
+ * quote API.
55
59
  * @returns Normalized request, or the original request if not a perps deposit.
56
60
  */
57
- export function normalizePerpsDepositRequest(request, transaction, hypercoreUsdcAddress) {
61
+ export function normalizePerpsDepositRequest(request, transaction, hypercoreUsdcAddress, targetDecimals = HYPERCORE_USDC_DECIMALS) {
58
62
  if (!isPerpsDepositRequest(request, transaction)) {
59
63
  return request;
60
64
  }
61
65
  return {
62
66
  ...request,
63
- targetAmountMinimum: toHypercoreAmount(request.targetAmountMinimum),
67
+ targetAmountMinimum: new BigNumber(request.targetAmountMinimum)
68
+ .shiftedBy(targetDecimals - USDC_DECIMALS)
69
+ .toFixed(0),
64
70
  targetChainId: CHAIN_ID_HYPERCORE,
65
71
  targetTokenAddress: hypercoreUsdcAddress,
66
72
  };
@@ -1 +1 @@
1
- {"version":3,"file":"perps.js","sourceRoot":"","sources":["../../src/utils/perps.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,uBAAuB,EACvB,aAAa,GACd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,6BAA6B,EAAE,MAAM,0BAA0B,CAAC;AAEzE,MAAM,gCAAgC,GACpC,4CAA4C,CAAC;AAO/C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,yBAAyB,CACvC,WAAyC;IAEzC,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,KAAK,GAAG;QACZ,WAAW,CAAC,QAAQ;QACpB,GAAG,CAAC,WAAW,CAAC,kBAAkB,IAAI,EAAE,CAAC;KAC1C,CAAC;IAEF,OAAO,KAAK,CAAC,IAAI,CACf,CAAC,IAAI,EAAE,EAAE,CACP,eAAe,CAAC,IAAI,EAAE,EAAE,CAAC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AAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,CAAC;QACH,OAAO,6BAA6B,CAAC,IAAW,CAAC,CAAC;IACpD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,SAAS,eAAe,CAAC,OAA2B;IAClD,OAAO,OAAO,EAAE,WAAW,EAAE,KAAK,gCAAgC,CAAC;AACrE,CAAC;AAED,SAAS,iBAAiB,CAAC,MAAc;IACvC,OAAO,IAAI,SAAS,CAAC,MAAM,CAAC;SACzB,SAAS,CAAC,uBAAuB,GAAG,aAAa,CAAC;SAClD,OAAO,CAAC,CAAC,CAAC,CAAC;AAChB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ARBITRUM_USDC_ADDRESS,\n CHAIN_ID_ARBITRUM,\n CHAIN_ID_HYPERCORE,\n HYPERCORE_USDC_DECIMALS,\n USDC_DECIMALS,\n} from '../constants.js';\nimport type { QuoteRequest } from '../types.js';\nimport { extractErc20TransferRecipient } from './polymarket/calldata.js';\n\nconst HYPERLIQUID_BRIDGE_ADDRESS_LOWER =\n '0x2df1c51e09aecf9cacb7bc98cb1742757f163df7';\n\ntype PerpsTransaction = Pick<\n TransactionMeta,\n 'txParams' | 'nestedTransactions'\n>;\n\n/**\n * Detect whether a transaction is a Hyperliquid perps deposit by inspecting\n * the parent transaction (and any nested transactions) for a call to the\n * Hyperliquid bridge or an ERC-20 transfer to it.\n *\n * Transaction type is intentionally NOT consulted so that any caller\n * funnelling a bridge deposit through Pay is supported.\n *\n * @param transaction - Parent transaction whose calls are inspected.\n * @returns Whether the transaction deposits into the Hyperliquid bridge.\n */\nexport function isPerpsDepositTransaction(\n transaction: PerpsTransaction | undefined,\n): boolean {\n if (!transaction) {\n return false;\n }\n\n const calls = [\n transaction.txParams,\n ...(transaction.nestedTransactions ?? []),\n ];\n\n return calls.some(\n (call) =>\n isBridgeAddress(call?.to) ||\n isBridgeAddress(getTransferRecipient(call?.data)),\n );\n}\n\n/**\n * Detect whether a quote request is a Hyperliquid perps deposit, meaning the\n * parent transaction deposits into the Hyperliquid bridge and the request\n * targets the Arbitrum USDC it requires.\n *\n * @param request - Quote request from the transaction-pay controller.\n * @param transaction - Parent transaction whose calls are inspected.\n * @returns Whether the request matches a Hyperliquid perps deposit.\n */\nexport function isPerpsDepositRequest(\n request: Pick<\n QuoteRequest,\n 'isPostQuote' | 'targetChainId' | 'targetTokenAddress'\n >,\n transaction: PerpsTransaction | undefined,\n): boolean {\n return (\n request.isPostQuote !== true &&\n request.targetChainId === CHAIN_ID_ARBITRUM &&\n request.targetTokenAddress.toLowerCase() ===\n ARBITRUM_USDC_ADDRESS.toLowerCase() &&\n isPerpsDepositTransaction(transaction)\n );\n}\n\n/**\n * Rewrite a Hyperliquid perps-deposit quote request into a HyperCore direct\n * deposit.\n *\n * Transaction pay starts from the parent on-chain asset (Arbitrum USDC,\n * 6 decimals), while HyperCore expects an 8-decimal amount, so the target\n * amount is shifted accordingly.\n *\n * @param request - Quote request from the transaction-pay controller.\n * @param transaction - Parent transaction whose calls are inspected.\n * @param hypercoreUsdcAddress - Strategy-specific HyperCore USDC address to\n * set as the target token.\n * @returns Normalized request, or the original request if not a perps deposit.\n */\nexport function normalizePerpsDepositRequest(\n request: QuoteRequest,\n transaction: PerpsTransaction | undefined,\n hypercoreUsdcAddress: Hex,\n): QuoteRequest {\n if (!isPerpsDepositRequest(request, transaction)) {\n return request;\n }\n\n return {\n ...request,\n targetAmountMinimum: toHypercoreAmount(request.targetAmountMinimum),\n targetChainId: CHAIN_ID_HYPERCORE,\n targetTokenAddress: hypercoreUsdcAddress,\n };\n}\n\n/**\n * Rewrite a Hyperliquid perps-withdraw quote request so the source is\n * HyperCore USDC rather than Arbitrum USDC.\n *\n * The source amount is provided in 6 decimals and shifted to the 8 decimals\n * HyperCore expects.\n *\n * @param request - Quote request from the transaction-pay controller.\n * @param hypercoreUsdcAddress - Strategy-specific HyperCore USDC address to\n * set as the source token.\n * @returns Normalized request, or the original request if not a perps withdraw.\n */\nexport function normalizePerpsWithdrawRequest(\n request: QuoteRequest,\n hypercoreUsdcAddress: Hex,\n): QuoteRequest {\n if (!request.isHyperliquidSource) {\n return request;\n }\n\n return {\n ...request,\n sourceChainId: CHAIN_ID_HYPERCORE,\n sourceTokenAddress: hypercoreUsdcAddress,\n sourceTokenAmount: request.sourceTokenAmount\n ? toHypercoreAmount(request.sourceTokenAmount)\n : request.sourceTokenAmount,\n };\n}\n\nfunction getTransferRecipient(data: string | undefined): Hex | undefined {\n if (!data) {\n return undefined;\n }\n\n try {\n return extractErc20TransferRecipient(data as Hex);\n } catch {\n return undefined;\n }\n}\n\nfunction isBridgeAddress(address: string | undefined): boolean {\n return address?.toLowerCase() === HYPERLIQUID_BRIDGE_ADDRESS_LOWER;\n}\n\nfunction toHypercoreAmount(amount: string): string {\n return new BigNumber(amount)\n .shiftedBy(HYPERCORE_USDC_DECIMALS - USDC_DECIMALS)\n .toFixed(0);\n}\n"]}
1
+ {"version":3,"file":"perps.js","sourceRoot":"","sources":["../../src/utils/perps.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,kBAAkB,EAClB,uBAAuB,EACvB,aAAa,GACd,MAAM,iBAAiB,CAAC;AAEzB,OAAO,EAAE,6BAA6B,EAAE,MAAM,0BAA0B,CAAC;AAEzE,MAAM,gCAAgC,GACpC,4CAA4C,CAAC;AAO/C;;;;;;;;;;GAUG;AACH,MAAM,UAAU,yBAAyB,CACvC,WAAyC;IAEzC,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,KAAK,GAAG;QACZ,WAAW,CAAC,QAAQ;QACpB,GAAG,CAAC,WAAW,CAAC,kBAAkB,IAAI,E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AiB,EAAE,OAAO,CAAC,iBAAiB;YAC1C,CAAC,CAAC,iBAAiB,CAAC,OAAO,CAAC,iBAAiB,CAAC;YAC9C,CAAC,CAAC,OAAO,CAAC,iBAAiB;KAC9B,CAAC;AACJ,CAAC;AAED,SAAS,oBAAoB,CAAC,IAAwB;IACpD,IAAI,CAAC,IAAI,EAAE,CAAC;QACV,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,CAAC;QACH,OAAO,6BAA6B,CAAC,IAAW,CAAC,CAAC;IACpD,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,SAAS,eAAe,CAAC,OAA2B;IAClD,OAAO,OAAO,EAAE,WAAW,EAAE,KAAK,gCAAgC,CAAC;AACrE,CAAC;AAED,SAAS,iBAAiB,CAAC,MAAc;IACvC,OAAO,IAAI,SAAS,CAAC,MAAM,CAAC;SACzB,SAAS,CAAC,uBAAuB,GAAG,aAAa,CAAC;SAClD,OAAO,CAAC,CAAC,CAAC,CAAC;AAChB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ARBITRUM_USDC_ADDRESS,\n CHAIN_ID_ARBITRUM,\n CHAIN_ID_HYPERCORE,\n HYPERCORE_USDC_DECIMALS,\n USDC_DECIMALS,\n} from '../constants.js';\nimport type { QuoteRequest } from '../types.js';\nimport { extractErc20TransferRecipient } from './polymarket/calldata.js';\n\nconst HYPERLIQUID_BRIDGE_ADDRESS_LOWER =\n '0x2df1c51e09aecf9cacb7bc98cb1742757f163df7';\n\ntype PerpsTransaction = Pick<\n TransactionMeta,\n 'txParams' | 'nestedTransactions'\n>;\n\n/**\n * Detect whether a transaction is a Hyperliquid perps deposit by inspecting\n * the parent transaction (and any nested transactions) for a call to the\n * Hyperliquid bridge or an ERC-20 transfer to it.\n *\n * Transaction type is intentionally NOT consulted so that any caller\n * funnelling a bridge deposit through Pay is supported.\n *\n * @param transaction - Parent transaction whose calls are inspected.\n * @returns Whether the transaction deposits into the Hyperliquid bridge.\n */\nexport function isPerpsDepositTransaction(\n transaction: PerpsTransaction | undefined,\n): boolean {\n if (!transaction) {\n return false;\n }\n\n const calls = [\n transaction.txParams,\n ...(transaction.nestedTransactions ?? []),\n ];\n\n return calls.some(\n (call) =>\n isBridgeAddress(call?.to) ||\n isBridgeAddress(getTransferRecipient(call?.data)),\n );\n}\n\n/**\n * Detect whether a quote request is a Hyperliquid perps deposit, meaning the\n * parent transaction deposits into the Hyperliquid bridge and the request\n * targets the Arbitrum USDC it requires.\n *\n * @param request - Quote request from the transaction-pay controller.\n * @param transaction - Parent transaction whose calls are inspected.\n * @returns Whether the request matches a Hyperliquid perps deposit.\n */\nexport function isPerpsDepositRequest(\n request: Pick<\n QuoteRequest,\n 'isPostQuote' | 'targetChainId' | 'targetTokenAddress'\n >,\n transaction: PerpsTransaction | undefined,\n): boolean {\n return (\n request.isPostQuote !== true &&\n request.targetChainId === CHAIN_ID_ARBITRUM &&\n request.targetTokenAddress.toLowerCase() ===\n ARBITRUM_USDC_ADDRESS.toLowerCase() &&\n isPerpsDepositTransaction(transaction)\n );\n}\n\n/**\n * Rewrite a Hyperliquid perps-deposit quote request into a HyperCore direct\n * deposit.\n *\n * Transaction pay starts from the parent on-chain asset (Arbitrum USDC,\n * 6 decimals), so the target amount is shifted to the decimals the strategy's\n * quote API uses for the HyperCore token. This defaults to the 8 decimals of\n * HyperCore USDC, but providers may represent it differently (e.g. Across\n * quotes USDC-PERPS in 6 decimals).\n *\n * @param request - Quote request from the transaction-pay controller.\n * @param transaction - Parent transaction whose calls are inspected.\n * @param hypercoreUsdcAddress - Strategy-specific HyperCore USDC address to\n * set as the target token.\n * @param targetDecimals - Decimals of the HyperCore token in the strategy's\n * quote API.\n * @returns Normalized request, or the original request if not a perps deposit.\n */\nexport function normalizePerpsDepositRequest(\n request: QuoteRequest,\n transaction: PerpsTransaction | undefined,\n hypercoreUsdcAddress: Hex,\n targetDecimals: number = HYPERCORE_USDC_DECIMALS,\n): QuoteRequest {\n if (!isPerpsDepositRequest(request, transaction)) {\n return request;\n }\n\n return {\n ...request,\n targetAmountMinimum: new BigNumber(request.targetAmountMinimum)\n .shiftedBy(targetDecimals - USDC_DECIMALS)\n .toFixed(0),\n targetChainId: CHAIN_ID_HYPERCORE,\n targetTokenAddress: hypercoreUsdcAddress,\n };\n}\n\n/**\n * Rewrite a Hyperliquid perps-withdraw quote request so the source is\n * HyperCore USDC rather than Arbitrum USDC.\n *\n * The source amount is provided in 6 decimals and shifted to the 8 decimals\n * HyperCore expects.\n *\n * @param request - Quote request from the transaction-pay controller.\n * @param hypercoreUsdcAddress - Strategy-specific HyperCore USDC address to\n * set as the source token.\n * @returns Normalized request, or the original request if not a perps withdraw.\n */\nexport function normalizePerpsWithdrawRequest(\n request: QuoteRequest,\n hypercoreUsdcAddress: Hex,\n): QuoteRequest {\n if (!request.isHyperliquidSource) {\n return request;\n }\n\n return {\n ...request,\n sourceChainId: CHAIN_ID_HYPERCORE,\n sourceTokenAddress: hypercoreUsdcAddress,\n sourceTokenAmount: request.sourceTokenAmount\n ? toHypercoreAmount(request.sourceTokenAmount)\n : request.sourceTokenAmount,\n };\n}\n\nfunction getTransferRecipient(data: string | undefined): Hex | undefined {\n if (!data) {\n return undefined;\n }\n\n try {\n return extractErc20TransferRecipient(data as Hex);\n } catch {\n return undefined;\n }\n}\n\nfunction isBridgeAddress(address: string | undefined): boolean {\n return address?.toLowerCase() === HYPERLIQUID_BRIDGE_ADDRESS_LOWER;\n}\n\nfunction toHypercoreAmount(amount: string): string {\n return new BigNumber(amount)\n .shiftedBy(HYPERCORE_USDC_DECIMALS - USDC_DECIMALS)\n .toFixed(0);\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@metamask-previews/transaction-pay-controller",
3
- "version": "30.4.0-preview-4a273a7",
3
+ "version": "30.4.1-preview-c3d36da85",
4
4
  "description": "Manages alternate payment strategies to provide required funds for transactions in MetaMask",
5
5
  "keywords": [
6
6
  "Ethereum",
@@ -56,7 +56,7 @@
56
56
  "@ethersproject/contracts": "^5.7.0",
57
57
  "@ethersproject/providers": "^5.8.0",
58
58
  "@metamask/accounts-controller": "^40.1.0",
59
- "@metamask/assets-controller": "^20.2.0",
59
+ "@metamask/assets-controller": "^20.2.1",
60
60
  "@metamask/base-controller": "^10.1.0",
61
61
  "@metamask/controller-utils": "^13.0.0",
62
62
  "@metamask/gas-fee-controller": "^27.0.0",