@metamask-previews/transaction-pay-controller 30.0.3-preview-44b7ded21 → 30.1.0-preview-2750df1dc
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 +18 -1
- package/dist/strategy/fiat/fiat-direct-musd.d.ts.map +1 -1
- package/dist/strategy/fiat/fiat-direct-musd.js +17 -12
- package/dist/strategy/fiat/fiat-direct-musd.js.map +1 -1
- package/dist/strategy/fiat/fiat-submit.js +1 -1
- package/dist/strategy/fiat/fiat-submit.js.map +1 -1
- package/dist/strategy/fiat/utils.d.ts +6 -24
- package/dist/strategy/fiat/utils.d.ts.map +1 -1
- package/dist/strategy/fiat/utils.js +21 -37
- package/dist/strategy/fiat/utils.js.map +1 -1
- package/dist/strategy/relay/relay-quotes.d.ts.map +1 -1
- package/dist/strategy/relay/relay-quotes.js +10 -40
- package/dist/strategy/relay/relay-quotes.js.map +1 -1
- package/dist/strategy/relay/relay-submit.d.ts.map +1 -1
- package/dist/strategy/relay/relay-submit.js +59 -110
- package/dist/strategy/relay/relay-submit.js.map +1 -1
- package/dist/strategy/server/server-api.d.ts +2 -2
- package/dist/strategy/server/server-api.d.ts.map +1 -1
- package/dist/strategy/server/server-api.js.map +1 -1
- package/dist/strategy/server/server-quotes.d.ts.map +1 -1
- package/dist/strategy/server/server-quotes.js +122 -21
- package/dist/strategy/server/server-quotes.js.map +1 -1
- package/dist/strategy/server/server-submit.d.ts.map +1 -1
- package/dist/strategy/server/server-submit.js +38 -2
- package/dist/strategy/server/server-submit.js.map +1 -1
- package/dist/strategy/server/server-support.d.ts +0 -2
- package/dist/strategy/server/server-support.d.ts.map +1 -1
- package/dist/strategy/server/server-support.js +0 -5
- package/dist/strategy/server/server-support.js.map +1 -1
- package/dist/strategy/server/types.d.ts +6 -9
- package/dist/strategy/server/types.d.ts.map +1 -1
- package/dist/strategy/server/types.js +0 -6
- package/dist/strategy/server/types.js.map +1 -1
- package/dist/types.d.ts +10 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/chomp.d.ts +32 -0
- package/dist/utils/chomp.d.ts.map +1 -1
- package/dist/utils/chomp.js +73 -0
- package/dist/utils/chomp.js.map +1 -1
- package/dist/utils/second-leg.d.ts +71 -0
- package/dist/utils/second-leg.d.ts.map +1 -0
- package/dist/utils/second-leg.js +281 -0
- package/dist/utils/second-leg.js.map +1 -0
- package/package.json +2 -2
- package/dist/utils/ma-vault-deposit.d.ts +0 -40
- package/dist/utils/ma-vault-deposit.d.ts.map +0 -1
- package/dist/utils/ma-vault-deposit.js +0 -230
- package/dist/utils/ma-vault-deposit.js.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,9 +7,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [30.1.0]
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Support submitting target calls as a separate second leg when the quote provider cannot execute them ([#10501](https://github.com/MetaMask/core/pull/10501))
|
|
15
|
+
- Add `requiresSecondLeg` to `TransactionPayQuote`.
|
|
16
|
+
- `ServerStrategy` now supports non-atomic requests.
|
|
17
|
+
- Non-atomic quotes settle funds on the account that executes the calls.
|
|
18
|
+
|
|
10
19
|
### Changed
|
|
11
20
|
|
|
12
21
|
- Bump `@metamask/transaction-controller` from `^72.1.0` to `^72.2.0` ([#10772](https://github.com/MetaMask/core/pull/10772))
|
|
22
|
+
- Fail fiat and second-leg submissions when the settled amount cannot be read from an on-chain transaction, rather than falling back to `order.cryptoAmount` or the quote minimum ([#10501](https://github.com/MetaMask/core/pull/10501))
|
|
23
|
+
- Bump `@metamask/assets-controller` from `^18.0.1` to `^19.0.0` ([#10788](https://github.com/MetaMask/core/pull/10788))
|
|
24
|
+
|
|
25
|
+
### Fixed
|
|
26
|
+
|
|
27
|
+
- Zero source network fees for Relay quotes on Polymarket deposit-wallet Predict withdraws, as the Polymarket relayer pays origin gas ([#10501](https://github.com/MetaMask/core/pull/10501))
|
|
28
|
+
- Set `isIntentComplete` on the parent transaction only after the non-atomic second leg of a Relay quote is submitted, so a failed second leg no longer leaves a failed transaction flagged as complete ([#10501](https://github.com/MetaMask/core/pull/10501))
|
|
13
29
|
|
|
14
30
|
## [30.0.3]
|
|
15
31
|
|
|
@@ -1688,7 +1704,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
1688
1704
|
|
|
1689
1705
|
- Initial release ([#6820](https://github.com/MetaMask/core/pull/6820))
|
|
1690
1706
|
|
|
1691
|
-
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.0
|
|
1707
|
+
[Unreleased]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.1.0...HEAD
|
|
1708
|
+
[30.1.0]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.0.3...@metamask/transaction-pay-controller@30.1.0
|
|
1692
1709
|
[30.0.3]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.0.2...@metamask/transaction-pay-controller@30.0.3
|
|
1693
1710
|
[30.0.2]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.0.1...@metamask/transaction-pay-controller@30.0.2
|
|
1694
1711
|
[30.0.1]: https://github.com/MetaMask/core/compare/@metamask/transaction-pay-controller@30.0.0...@metamask/transaction-pay-controller@30.0.1
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fiat-direct-musd.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-direct-musd.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,UAAU,EACX,MAAM,4BAA4B,CAAC;AACpC,OAAO,KAAK,EAAE,GAAG,EAAE,MAAM,iBAAiB,CAAC;AAM3C,OAAO,KAAK,EACV,yBAAyB,EACzB,2BAA2B,EAE3B,2BAA2B,EAC3B,mBAA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EAAE,GAAG,CAAA;CAAE,CAAC,CAiCrC"}
|
|
@@ -4,10 +4,10 @@ import { TransactionPayStrategy } from '../../constants.js';
|
|
|
4
4
|
import { projectLogger } from '../../logger.js';
|
|
5
5
|
import { prefixError } from '../../utils/error-prefix.js';
|
|
6
6
|
import { getFiatVaultDisabled } from '../../utils/feature-flags.js';
|
|
7
|
-
import {
|
|
7
|
+
import { submitSecondLeg } from '../../utils/second-leg.js';
|
|
8
8
|
import { buildCaipAssetType, getTokenInfo } from '../../utils/token.js';
|
|
9
9
|
import { MUSD_MONAD_FIAT_ASSET } from './constants.js';
|
|
10
|
-
import { getRampsQuote, getRawSourceAmountFromOrderCryptoAmount,
|
|
10
|
+
import { getRampsQuote, getRawSourceAmountFromOrderCryptoAmount, validateOrderAsset, } from './utils.js';
|
|
11
11
|
const log = createModuleLogger(projectLogger, 'fiat-direct-musd');
|
|
12
12
|
const DIRECT_MUSD_ERROR_PREFIX = 'Direct mUSD: ';
|
|
13
13
|
/**
|
|
@@ -83,24 +83,29 @@ export function isDirectMusdMoneyAccountQuote(quote) {
|
|
|
83
83
|
*/
|
|
84
84
|
export async function submitDirectMusdAfterFiatCompletion({ order, request, }) {
|
|
85
85
|
const { messenger, transaction } = request;
|
|
86
|
+
const moneyAccountAddress = transaction.txParams.from;
|
|
86
87
|
try {
|
|
87
88
|
validateOrderAsset({
|
|
88
89
|
expectedAsset: MUSD_MONAD_FIAT_ASSET,
|
|
89
90
|
orderCrypto: order.cryptoCurrency,
|
|
90
91
|
transactionId: transaction.id,
|
|
91
92
|
});
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
93
|
+
// Kill switch: leave the on-ramped mUSD in the Money Account rather than
|
|
94
|
+
// depositing it into the vault.
|
|
95
|
+
if (getFiatVaultDisabled(messenger)) {
|
|
96
|
+
log('Skipping vault deposit because the fiat vault is disabled', {
|
|
97
|
+
moneyAccountAddress,
|
|
98
|
+
transactionId: transaction.id,
|
|
99
|
+
});
|
|
100
|
+
return { transactionHash: '0x' };
|
|
101
|
+
}
|
|
102
|
+
return await submitSecondLeg({
|
|
103
|
+
chainId: MUSD_MONAD_FIAT_ASSET.chainId,
|
|
104
|
+
from: moneyAccountAddress,
|
|
100
105
|
messenger,
|
|
101
|
-
|
|
106
|
+
settlementHash: order.txHash,
|
|
107
|
+
tokenAddress: MUSD_MONAD_FIAT_ASSET.address,
|
|
102
108
|
transaction,
|
|
103
|
-
vaultDisabled: getFiatVaultDisabled(messenger),
|
|
104
109
|
});
|
|
105
110
|
}
|
|
106
111
|
catch (error) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fiat-direct-musd.js","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-direct-musd.ts"],"names":[],"mappings":"AAKA,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;AAQhD,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,8BAA8B,EAAE,MAAM,iCAAiC,CAAC;AACjF,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EACL,aAAa,EACb,uCAAuC,EACvC,sBAAsB,EACtB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAEpB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,kBAAkB,CAAC,CAAC;AAClE,MAAM,wBAAwB,GAAG,eAAe,CAAC;AAEjD;;;;;;;;;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IACtC,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,SAAS,UAAU,CAAC,KAAkC;IACpD,MAAM,GAAG,GAAG,IAAI,SAAS,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;IACtC,OAAO,GAAG,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import type {\n Quote as RampsQuote,\n RampsOrder,\n} from '@metamask/ramps-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 PayStrategyExecuteRequest,\n PayStrategyGetQuotesRequest,\n TransactionFiatPayment,\n TransactionPayRequiredToken,\n TransactionPayQuote,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport { getFiatVaultDisabled } from '../../utils/feature-flags.js';\nimport { submitMoneyAccountVaultDeposit } from '../../utils/ma-vault-deposit.js';\nimport { buildCaipAssetType, getTokenInfo } from '../../utils/token.js';\nimport { MUSD_MONAD_FIAT_ASSET } from './constants.js';\nimport type { FiatQuote } from './types.js';\nimport {\n getRampsQuote,\n getRawSourceAmountFromOrderCryptoAmount,\n resolveSourceAmountRaw,\n validateOrderAsset,\n} from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-direct-musd');\nconst DIRECT_MUSD_ERROR_PREFIX = 'Direct mUSD: ';\n\n/**\n * Returns a direct mUSD fiat quote to the Money Account.\n *\n * @param options - Direct quote options.\n * @param options.amountFiat - Fiat amount entered by the user.\n * @param options.fiatPaymentMethod - Selected fiat payment method.\n * @param options.messenger - Controller messenger.\n * @param options.moneyAccountAddress - Money Account receiving the on-ramped mUSD.\n * @param options.requiredToken - Required token from the original Money Account transaction.\n * @param options.transactionId - Transaction ID for state updates and logs.\n * @returns Direct mUSD Fiat quote, or undefined when unavailable.\n */\nexport async function getDirectMusdFiatQuote({\n amountFiat,\n fiatPaymentMethod,\n messenger,\n moneyAccountAddress,\n requiredToken,\n transactionId,\n}: {\n amountFiat: string;\n fiatPaymentMethod: string;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n requiredToken: TransactionPayRequiredToken;\n transactionId: string;\n}): Promise<TransactionPayQuote<FiatQuote> | undefined> {\n try {\n const adjustedAmount = Number(amountFiat);\n\n if (!Number.isFinite(adjustedAmount) || adjustedAmount <= 0) {\n throw new Error('Invalid fiat amount for direct mUSD quote');\n }\n\n // `getRampsQuote` requests `getQuoteWithFees`, so a Transak Native quote\n // already carries the native fee (fee-on-top for direct mUSD) in its\n // provider/network fee fields.\n const fiatQuote = await getRampsQuote({\n adjustedAmount,\n errorMessage: 'No matching ramps quote found for direct mUSD provider',\n fiatAsset: MUSD_MONAD_FIAT_ASSET,\n fiatPaymentMethod,\n messenger,\n walletAddress: moneyAccountAddress,\n });\n\n messenger.call('TransactionPayController:updateFiatPayment', {\n callback: (fiatPayment: TransactionFiatPayment) => {\n fiatPayment.rampsQuote = fiatQuote;\n fiatPayment.caipAssetId = buildCaipAssetType(\n MUSD_MONAD_FIAT_ASSET.chainId,\n MUSD_MONAD_FIAT_ASSET.address,\n );\n },\n transactionId,\n });\n\n log('Direct mUSD fiat quote flow', {\n amountFiat,\n moneyAccountAddress,\n transactionId,\n });\n\n return combineDirectMusdFiatQuote({\n amountFiat,\n fiatQuote,\n messenger,\n moneyAccountAddress,\n requiredToken,\n });\n } catch (error) {\n log('Direct mUSD fiat quote failed', { error, transactionId });\n return undefined;\n }\n}\n\n/**\n * Detects a direct mUSD Money Account quote from its stored request marker.\n *\n * @param quote - Quote to inspect.\n * @returns True when the quote originated from the direct mUSD fiat path.\n */\nexport function isDirectMusdMoneyAccountQuote(\n quote: Pick<TransactionPayQuote<unknown>, 'request'> | undefined,\n): boolean {\n return quote?.request.isDirectMusdMoneyAccount === true;\n}\n\n/**\n * Submits the direct mUSD post-Ramp path after fiat settlement.\n *\n * @param options - Submit options.\n * @param options.order - Completed fiat order.\n * @param options.request - Strategy execute request.\n * @returns Hash of the submitted direct mUSD transaction, if available.\n */\nexport async function submitDirectMusdAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, transaction } = request;\n\n try {\n validateOrderAsset({\n expectedAsset: MUSD_MONAD_FIAT_ASSET,\n orderCrypto: order.cryptoCurrency,\n transactionId: transaction.id,\n });\n\n const { amountRaw: sourceAmountRaw, fromBlock } =\n await resolveSourceAmountRaw({\n messenger,\n order,\n fiatAsset: MUSD_MONAD_FIAT_ASSET,\n walletAddress: transaction.txParams.from as Hex,\n });\n\n return await submitMoneyAccountVaultDeposit({\n fromBlock,\n messenger,\n sourceAmountRaw,\n transaction,\n vaultDisabled: getFiatVaultDisabled(messenger),\n });\n } catch (error) {\n throw prefixError(error, DIRECT_MUSD_ERROR_PREFIX);\n }\n}\n\nfunction combineDirectMusdFiatQuote({\n amountFiat,\n fiatQuote,\n messenger,\n moneyAccountAddress,\n requiredToken,\n}: {\n amountFiat: string;\n fiatQuote: RampsQuote;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n requiredToken: TransactionPayRequiredToken;\n}): TransactionPayQuote<FiatQuote> {\n const tokenInfo = getTokenInfo(\n messenger,\n MUSD_MONAD_FIAT_ASSET.address,\n MUSD_MONAD_FIAT_ASSET.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error('Unable to resolve mUSD token info for direct fiat quote');\n }\n\n const sourceAmountRaw = getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount: fiatQuote.quote.amountOut,\n decimals: tokenInfo.decimals,\n });\n // `getQuoteWithFees` already reconciled the fee split to the resolved\n // provider (for Transak Native, the native total split across provider and\n // network), so the provider/network fields can be mapped straight into the\n // fee buckets.\n const rampsProviderFee = getSafeFee(fiatQuote.quote.providerFee).toString(10);\n const rampsNetworkFee = getSafeFee(fiatQuote.quote.networkFee).toString(10);\n const rampsTotalFee = new BigNumber(rampsProviderFee)\n .plus(rampsNetworkFee)\n .toString(10);\n const targetAmountFiat = getDirectMusdTargetAmountFiat(fiatQuote, amountFiat);\n const sourceAmountHuman = new BigNumber(sourceAmountRaw)\n .shiftedBy(-tokenInfo.decimals)\n .toString(10);\n\n return {\n // Direct mUSD is fee-on-top: the fee is added to the entered amount, so the\n // fees are NOT already inside the source amount and the total becomes\n // amount + fees (see calculateTotals).\n areFeesIncludedInSourceAmount: false,\n dust: { fiat: '0', usd: '0' },\n estimatedDuration: 0,\n fees: {\n metaMask: { fiat: '0', usd: '0' },\n provider: { fiat: rampsProviderFee, usd: rampsProviderFee },\n providerFiat: { fiat: rampsTotalFee, usd: rampsTotalFee },\n sourceNetwork: {\n estimate: {\n fiat: rampsNetworkFee,\n human: '0',\n raw: '0',\n usd: rampsNetworkFee,\n },\n max: {\n fiat: rampsNetworkFee,\n human: '0',\n raw: '0',\n usd: rampsNetworkFee,\n },\n },\n targetNetwork: { fiat: '0', usd: '0' },\n },\n original: {\n rampsQuote: fiatQuote,\n relayQuote: undefined,\n },\n request: {\n from: moneyAccountAddress,\n isDirectMusdMoneyAccount: true,\n recipient: moneyAccountAddress,\n sourceBalanceRaw: sourceAmountRaw,\n sourceChainId: MUSD_MONAD_FIAT_ASSET.chainId,\n sourceTokenAddress: MUSD_MONAD_FIAT_ASSET.address,\n sourceTokenAmount: sourceAmountRaw,\n targetAmountMinimum: sourceAmountRaw,\n targetChainId: requiredToken.chainId,\n targetTokenAddress: requiredToken.address,\n },\n sourceAmount: {\n fiat: amountFiat,\n human: sourceAmountHuman,\n raw: sourceAmountRaw,\n usd: amountFiat,\n },\n strategy: TransactionPayStrategy.Fiat,\n targetAmount: { fiat: targetAmountFiat, usd: targetAmountFiat },\n };\n}\n\n/**\n * Resolves the fiat value of the received mUSD for a direct deposit quote.\n *\n * Prefers the quote's `amountOutInFiat`. When that is missing, it falls back to\n * the entered fiat amount rather than `amountOut`, which is a crypto amount and\n * would otherwise put crypto units into a fiat field.\n *\n * @param fiatQuote - The resolved ramps quote.\n * @param amountFiat - The entered fiat amount, used as the fallback.\n * @returns The target amount in fiat.\n */\nfunction getDirectMusdTargetAmountFiat(\n fiatQuote: RampsQuote,\n amountFiat: string,\n): string {\n const amountOutInFiat = new BigNumber(fiatQuote.quote.amountOutInFiat ?? NaN);\n if (amountOutInFiat.isFinite() && amountOutInFiat.isGreaterThanOrEqualTo(0)) {\n return amountOutInFiat.toString(10);\n }\n\n return amountFiat;\n}\n\nfunction getSafeFee(value: BigNumber.Value | undefined): BigNumber {\n const fee = new BigNumber(value ?? 0);\n return fee.isFinite() && fee.isGreaterThanOrEqualTo(0)\n ? fee\n : new BigNumber(0);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fiat-direct-musd.js","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-direct-musd.ts"],"names":[],"mappings":"AAKA,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;AAQhD,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EAAE,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AACpE,OAAO,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAC;AAC5D,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACxE,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EACL,aAAa,EACb,uCAAuC,EACvC,k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AAE;KAChE,CAAC;AACJ,CAAC;AAED;;;;;;;;;;GAUG;AACH,SAAS,6BAA6B,CACpC,SAAqB,EACrB,UAAkB;IAElB,MAAM,eAAe,GAAG,IAAI,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,eAAe,IAAI,GAAG,CAAC,CAAC;IAC9E,IAAI,eAAe,CAAC,QAAQ,EAAE,IAAI,eAAe,CAAC,sBAAsB,CAAC,CAAC,CAAC,EAAE,CAAC;QAC5E,OAAO,eAAe,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;IACtC,CAAC;IAED,OAAO,UAAU,CAAC;AACpB,CAAC;AAED,SAAS,UAAU,CAAC,KAAkC;IACpD,MAAM,GAAG,GAAG,IAAI,SAAS,CAAC,KAAK,IAAI,CAAC,CAAC,CAAC;IACtC,OAAO,GAAG,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,sBAAsB,CAAC,CAAC,CAAC;QACpD,CAAC,CAAC,GAAG;QACL,CAAC,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;AACvB,CAAC","sourcesContent":["import type {\n Quote as RampsQuote,\n RampsOrder,\n} from '@metamask/ramps-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 PayStrategyExecuteRequest,\n PayStrategyGetQuotesRequest,\n TransactionFiatPayment,\n TransactionPayRequiredToken,\n TransactionPayQuote,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport { getFiatVaultDisabled } from '../../utils/feature-flags.js';\nimport { submitSecondLeg } from '../../utils/second-leg.js';\nimport { buildCaipAssetType, getTokenInfo } from '../../utils/token.js';\nimport { MUSD_MONAD_FIAT_ASSET } from './constants.js';\nimport type { FiatQuote } from './types.js';\nimport {\n getRampsQuote,\n getRawSourceAmountFromOrderCryptoAmount,\n validateOrderAsset,\n} from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-direct-musd');\nconst DIRECT_MUSD_ERROR_PREFIX = 'Direct mUSD: ';\n\n/**\n * Returns a direct mUSD fiat quote to the Money Account.\n *\n * @param options - Direct quote options.\n * @param options.amountFiat - Fiat amount entered by the user.\n * @param options.fiatPaymentMethod - Selected fiat payment method.\n * @param options.messenger - Controller messenger.\n * @param options.moneyAccountAddress - Money Account receiving the on-ramped mUSD.\n * @param options.requiredToken - Required token from the original Money Account transaction.\n * @param options.transactionId - Transaction ID for state updates and logs.\n * @returns Direct mUSD Fiat quote, or undefined when unavailable.\n */\nexport async function getDirectMusdFiatQuote({\n amountFiat,\n fiatPaymentMethod,\n messenger,\n moneyAccountAddress,\n requiredToken,\n transactionId,\n}: {\n amountFiat: string;\n fiatPaymentMethod: string;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n requiredToken: TransactionPayRequiredToken;\n transactionId: string;\n}): Promise<TransactionPayQuote<FiatQuote> | undefined> {\n try {\n const adjustedAmount = Number(amountFiat);\n\n if (!Number.isFinite(adjustedAmount) || adjustedAmount <= 0) {\n throw new Error('Invalid fiat amount for direct mUSD quote');\n }\n\n // `getRampsQuote` requests `getQuoteWithFees`, so a Transak Native quote\n // already carries the native fee (fee-on-top for direct mUSD) in its\n // provider/network fee fields.\n const fiatQuote = await getRampsQuote({\n adjustedAmount,\n errorMessage: 'No matching ramps quote found for direct mUSD provider',\n fiatAsset: MUSD_MONAD_FIAT_ASSET,\n fiatPaymentMethod,\n messenger,\n walletAddress: moneyAccountAddress,\n });\n\n messenger.call('TransactionPayController:updateFiatPayment', {\n callback: (fiatPayment: TransactionFiatPayment) => {\n fiatPayment.rampsQuote = fiatQuote;\n fiatPayment.caipAssetId = buildCaipAssetType(\n MUSD_MONAD_FIAT_ASSET.chainId,\n MUSD_MONAD_FIAT_ASSET.address,\n );\n },\n transactionId,\n });\n\n log('Direct mUSD fiat quote flow', {\n amountFiat,\n moneyAccountAddress,\n transactionId,\n });\n\n return combineDirectMusdFiatQuote({\n amountFiat,\n fiatQuote,\n messenger,\n moneyAccountAddress,\n requiredToken,\n });\n } catch (error) {\n log('Direct mUSD fiat quote failed', { error, transactionId });\n return undefined;\n }\n}\n\n/**\n * Detects a direct mUSD Money Account quote from its stored request marker.\n *\n * @param quote - Quote to inspect.\n * @returns True when the quote originated from the direct mUSD fiat path.\n */\nexport function isDirectMusdMoneyAccountQuote(\n quote: Pick<TransactionPayQuote<unknown>, 'request'> | undefined,\n): boolean {\n return quote?.request.isDirectMusdMoneyAccount === true;\n}\n\n/**\n * Submits the direct mUSD post-Ramp path after fiat settlement.\n *\n * @param options - Submit options.\n * @param options.order - Completed fiat order.\n * @param options.request - Strategy execute request.\n * @returns Hash of the submitted direct mUSD transaction, if available.\n */\nexport async function submitDirectMusdAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, transaction } = request;\n const moneyAccountAddress = transaction.txParams.from as Hex;\n\n try {\n validateOrderAsset({\n expectedAsset: MUSD_MONAD_FIAT_ASSET,\n orderCrypto: order.cryptoCurrency,\n transactionId: transaction.id,\n });\n\n // Kill switch: leave the on-ramped mUSD in the Money Account rather than\n // depositing it into the vault.\n if (getFiatVaultDisabled(messenger)) {\n log('Skipping vault deposit because the fiat vault is disabled', {\n moneyAccountAddress,\n transactionId: transaction.id,\n });\n\n return { transactionHash: '0x' };\n }\n\n return await submitSecondLeg({\n chainId: MUSD_MONAD_FIAT_ASSET.chainId,\n from: moneyAccountAddress,\n messenger,\n settlementHash: order.txHash as Hex | undefined,\n tokenAddress: MUSD_MONAD_FIAT_ASSET.address,\n transaction,\n });\n } catch (error) {\n throw prefixError(error, DIRECT_MUSD_ERROR_PREFIX);\n }\n}\n\nfunction combineDirectMusdFiatQuote({\n amountFiat,\n fiatQuote,\n messenger,\n moneyAccountAddress,\n requiredToken,\n}: {\n amountFiat: string;\n fiatQuote: RampsQuote;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n requiredToken: TransactionPayRequiredToken;\n}): TransactionPayQuote<FiatQuote> {\n const tokenInfo = getTokenInfo(\n messenger,\n MUSD_MONAD_FIAT_ASSET.address,\n MUSD_MONAD_FIAT_ASSET.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error('Unable to resolve mUSD token info for direct fiat quote');\n }\n\n const sourceAmountRaw = getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount: fiatQuote.quote.amountOut,\n decimals: tokenInfo.decimals,\n });\n // `getQuoteWithFees` already reconciled the fee split to the resolved\n // provider (for Transak Native, the native total split across provider and\n // network), so the provider/network fields can be mapped straight into the\n // fee buckets.\n const rampsProviderFee = getSafeFee(fiatQuote.quote.providerFee).toString(10);\n const rampsNetworkFee = getSafeFee(fiatQuote.quote.networkFee).toString(10);\n const rampsTotalFee = new BigNumber(rampsProviderFee)\n .plus(rampsNetworkFee)\n .toString(10);\n const targetAmountFiat = getDirectMusdTargetAmountFiat(fiatQuote, amountFiat);\n const sourceAmountHuman = new BigNumber(sourceAmountRaw)\n .shiftedBy(-tokenInfo.decimals)\n .toString(10);\n\n return {\n // Direct mUSD is fee-on-top: the fee is added to the entered amount, so the\n // fees are NOT already inside the source amount and the total becomes\n // amount + fees (see calculateTotals).\n areFeesIncludedInSourceAmount: false,\n dust: { fiat: '0', usd: '0' },\n estimatedDuration: 0,\n fees: {\n metaMask: { fiat: '0', usd: '0' },\n provider: { fiat: rampsProviderFee, usd: rampsProviderFee },\n providerFiat: { fiat: rampsTotalFee, usd: rampsTotalFee },\n sourceNetwork: {\n estimate: {\n fiat: rampsNetworkFee,\n human: '0',\n raw: '0',\n usd: rampsNetworkFee,\n },\n max: {\n fiat: rampsNetworkFee,\n human: '0',\n raw: '0',\n usd: rampsNetworkFee,\n },\n },\n targetNetwork: { fiat: '0', usd: '0' },\n },\n original: {\n rampsQuote: fiatQuote,\n relayQuote: undefined,\n },\n request: {\n from: moneyAccountAddress,\n isDirectMusdMoneyAccount: true,\n recipient: moneyAccountAddress,\n sourceBalanceRaw: sourceAmountRaw,\n sourceChainId: MUSD_MONAD_FIAT_ASSET.chainId,\n sourceTokenAddress: MUSD_MONAD_FIAT_ASSET.address,\n sourceTokenAmount: sourceAmountRaw,\n targetAmountMinimum: sourceAmountRaw,\n targetChainId: requiredToken.chainId,\n targetTokenAddress: requiredToken.address,\n },\n sourceAmount: {\n fiat: amountFiat,\n human: sourceAmountHuman,\n raw: sourceAmountRaw,\n usd: amountFiat,\n },\n strategy: TransactionPayStrategy.Fiat,\n targetAmount: { fiat: targetAmountFiat, usd: targetAmountFiat },\n };\n}\n\n/**\n * Resolves the fiat value of the received mUSD for a direct deposit quote.\n *\n * Prefers the quote's `amountOutInFiat`. When that is missing, it falls back to\n * the entered fiat amount rather than `amountOut`, which is a crypto amount and\n * would otherwise put crypto units into a fiat field.\n *\n * @param fiatQuote - The resolved ramps quote.\n * @param amountFiat - The entered fiat amount, used as the fallback.\n * @returns The target amount in fiat.\n */\nfunction getDirectMusdTargetAmountFiat(\n fiatQuote: RampsQuote,\n amountFiat: string,\n): string {\n const amountOutInFiat = new BigNumber(fiatQuote.quote.amountOutInFiat ?? NaN);\n if (amountOutInFiat.isFinite() && amountOutInFiat.isGreaterThanOrEqualTo(0)) {\n return amountOutInFiat.toString(10);\n }\n\n return amountFiat;\n}\n\nfunction getSafeFee(value: BigNumber.Value | undefined): BigNumber {\n const fee = new BigNumber(value ?? 0);\n return fee.isFinite() && fee.isGreaterThanOrEqualTo(0)\n ? fee\n : new BigNumber(0);\n}\n"]}
|
|
@@ -180,7 +180,7 @@ async function submitRelayAfterFiatCompletion({ order, request, }) {
|
|
|
180
180
|
transactionId,
|
|
181
181
|
});
|
|
182
182
|
const baseRequest = fiatQuote.request;
|
|
183
|
-
const
|
|
183
|
+
const sourceAmountRaw = await resolveSourceAmountRaw({
|
|
184
184
|
messenger,
|
|
185
185
|
order,
|
|
186
186
|
fiatAsset,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fiat-submit.js","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAOhD,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EACL,0BAA0B,EAC1B,yBAAyB,GAC1B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EACL,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnF,OAAO,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAErE,OAAO,EACL,6BAA6B,EAC7B,mBAAmB,EACnB,sBAAsB,EACtB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAEpB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAC7D,MAAM,sBAAsB,GAAG,aAAa,CAAC;AAE7C,MAAM,yBAAyB,GAAuB;IACpD,gBAAgB,CAAC,SAAS;IAC1B,gBAAgB,CAAC,MAAM;IACvB,gBAAgB,CAAC,SAAS;CAC3B,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,OAA6C;IAE7C,MAAM,EAAE,SAAS,EAAE,WAAW,EAAE,GAAG,OAAO,CAAC;IAC3C,MAAM,aAAa,GAAG,WAAW,CAAC,EAAE,CAAC;IACr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sOrderStatus } from '@metamask/ramps-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../../logger.js';\nimport type {\n PayStrategy,\n PayStrategyExecuteRequest,\n TransactionPayFiatOptions,\n TransactionPayControllerMessenger,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport {\n getFiatOrderPollIntervalMs,\n getFiatOrderPollTimeoutMs,\n} from '../../utils/feature-flags.js';\nimport { updateTransaction } from '../../utils/transaction.js';\nimport {\n isDirectMusdMoneyAccountQuote,\n submitDirectMusdAfterFiatCompletion,\n} from './fiat-direct-musd.js';\nimport { submitSimpleRelay } from './fiat-submit-simple.js';\nimport { submitWithTransactionData } from './fiat-submit-with-transaction-data.js';\nimport { fundFiatOrderFromTestSource } from './fiat-test-funding.js';\nimport type { FiatQuote } from './types.js';\nimport {\n deriveFiatAssetForFiatPayment,\n extractProviderCode,\n resolveSourceAmountRaw,\n validateOrderAsset,\n} from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-submit');\nconst POST_RAMP_ERROR_PREFIX = 'Post-Ramp: ';\n\nconst TERMINAL_FAILURE_STATUSES: RampsOrderStatus[] = [\n RampsOrderStatus.Cancelled,\n RampsOrderStatus.Failed,\n RampsOrderStatus.IdExpired,\n];\n\n/**\n * Submits fiat strategy quotes by polling the on-ramp order until completion,\n * then re-quoting and submitting the relay leg with the settled crypto amount.\n *\n * @param request - Strategy execute request containing fiat quotes, messenger, and transaction metadata.\n * @param request.messenger - Controller messenger for cross-controller calls.\n * @param request.quotes - Fiat quotes to execute (exactly one expected).\n * @param request.transaction - Original transaction metadata.\n * @param request.isSmartTransaction - Callback to check smart transaction eligibility.\n * @returns An object containing the relay transaction hash if available.\n */\nexport async function submitFiatQuotes(\n request: PayStrategyExecuteRequest<FiatQuote>,\n): ReturnType<PayStrategy<FiatQuote>['execute']> {\n const { messenger, transaction } = request;\n const transactionId = transaction.id;\n const state = messenger.call('TransactionPayController:getState');\n const transactionData = state.transactionData[transactionId];\n\n const walletAddress = getWalletAddress({\n quotes: request.quotes,\n transaction,\n accountOverride: transactionData?.accountOverride,\n });\n\n const fiatPayment = transactionData?.fiatPayment;\n const orderId = fiatPayment?.orderId;\n\n if (!orderId) {\n throw new Error('Missing order ID');\n }\n\n const providerCode = extractProviderCode(fiatPayment?.rampsQuote?.provider);\n\n if (!providerCode) {\n throw new Error('Missing provider code');\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Persist fiat order metadata',\n },\n (tx) => {\n tx.metamaskPay ??= {};\n tx.metamaskPay.fiat = { orderId, provider: providerCode };\n },\n );\n\n log('Starting fiat order polling', {\n orderId,\n providerCode,\n transactionId,\n });\n\n const fiatQuote = request.quotes[0];\n\n if (!fiatQuote) {\n throw new Error('Missing quote');\n }\n\n const fiatOptions = getFiatOptions(messenger);\n\n const order = fiatOptions?.testFundingSource\n ? await fundFiatOrderFromTestSource({\n fiat: fiatOptions,\n messenger,\n quote: fiatQuote,\n transaction,\n })\n : await waitForOrderCompletion({\n messenger,\n orderCode: orderId,\n providerCode,\n transactionId,\n walletAddress,\n });\n\n log('Fiat order completed', {\n cryptoAmount: order.cryptoAmount,\n orderId,\n transactionId,\n });\n\n try {\n await waitForKeyringUnlock(messenger, transactionId);\n\n const result = await submitRelayAfterFiatCompletion({\n order,\n request,\n });\n\n if (result.transactionHash === undefined) {\n throw new Error('Missing transaction hash');\n }\n\n return result;\n } catch (error) {\n throw prefixError(error, POST_RAMP_ERROR_PREFIX);\n }\n}\n\nfunction getFiatOptions(\n messenger: TransactionPayControllerMessenger,\n): TransactionPayFiatOptions | undefined {\n try {\n return messenger.call('TransactionPayController:getFiatOptions');\n } catch (error) {\n log('Failed to retrieve fiat options', error);\n return undefined;\n }\n}\n\n/**\n * Polls the on-ramp order until it reaches a terminal status.\n *\n * @param options - The polling options.\n * @param options.messenger - Controller messenger for calling `RampsController:getOrder`.\n * @param options.orderCode - The order identifier within the provider.\n * @param options.providerCode - The on-ramp provider code (e.g. \"transak\").\n * @param options.transactionId - Transaction ID for logging.\n * @param options.walletAddress - Wallet address associated with the order.\n * @returns The completed order data.\n */\nasync function waitForOrderCompletion({\n messenger,\n orderCode,\n providerCode,\n transactionId,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n orderCode: string;\n providerCode: string;\n transactionId: string;\n walletAddress: string;\n}): Promise<RampsOrder> {\n const pollIntervalMs = getFiatOrderPollIntervalMs(messenger);\n const pollTimeoutMs = getFiatOrderPollTimeoutMs(messenger);\n const startTime = Date.now();\n let lastStatus: string | undefined;\n\n while (true) {\n let order: RampsOrder | undefined;\n\n try {\n order = await messenger.call(\n 'RampsController:getOrder',\n providerCode,\n orderCode,\n walletAddress,\n );\n } catch (error) {\n log('Order polling network error', error);\n }\n\n if (order) {\n lastStatus = order.status;\n\n log('Polled fiat order', {\n orderStatus: order.status,\n providerCode,\n transactionId,\n });\n\n if (order.status === RampsOrderStatus.Completed) {\n return order;\n }\n\n if (TERMINAL_FAILURE_STATUSES.includes(order.status)) {\n throw new Error(`Fiat order ${order.status.toLowerCase()}`);\n }\n }\n\n if (Date.now() - startTime >= pollTimeoutMs) {\n throw new Error(\n `Fiat order polling timed out (last status: ${lastStatus})`,\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n}\n\n/**\n * Re-quotes and submits the relay leg using the settled amount from a completed fiat order.\n *\n * @param options - The submission options.\n * @param options.order - The completed on-ramp order containing the settled crypto amount.\n * @param options.request - The original fiat strategy execute request.\n * @returns An object containing the relay transaction hash if available.\n */\nasync function submitRelayAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, quotes, transaction } = request;\n const transactionId = transaction.id;\n\n if (quotes.length > 1) {\n throw new Error('Multiple fiat quotes are not supported for submission');\n }\n\n const fiatQuote = quotes[0];\n const isDirectMusd = isDirectMusdMoneyAccountQuote(fiatQuote);\n\n if (isDirectMusd) {\n return await submitDirectMusdAfterFiatCompletion({\n order,\n request,\n });\n }\n\n const fiatAsset = deriveFiatAssetForFiatPayment(transaction, messenger);\n\n validateOrderAsset({\n expectedAsset: fiatAsset,\n orderCrypto: order.cryptoCurrency,\n transactionId,\n });\n\n const baseRequest = fiatQuote.request;\n\n const { amountRaw: sourceAmountRaw } = await resolveSourceAmountRaw({\n messenger,\n order,\n fiatAsset,\n walletAddress: baseRequest.from,\n });\n\n if (!fiatQuote.original.relayQuote) {\n throw new Error('Missing Relay quote');\n }\n\n const hasNestedCalldata = (transaction.nestedTransactions?.length ?? 0) >= 2;\n\n // Transactions with nested calldata (e.g. moneyAccountDeposit with\n // approve + deposit) need a three-phase flow: discovery quote to learn\n // the target amount, calldata re-encoding, then a delegation quote.\n // Simple deposits (Perps, Predict) skip straight to a single EXACT_INPUT\n // relay quote — cheaper fees, no leftover dust, one fewer request.\n if (hasNestedCalldata) {\n return await submitWithTransactionData({\n baseRequest,\n request,\n sourceAmountRaw,\n transaction,\n });\n }\n\n return await submitSimpleRelay({\n baseRequest,\n request,\n sourceAmountRaw,\n transaction,\n });\n}\n\nfunction getWalletAddress({\n quotes,\n transaction,\n accountOverride,\n}: {\n quotes: PayStrategyExecuteRequest<FiatQuote>['quotes'];\n transaction: PayStrategyExecuteRequest<FiatQuote>['transaction'];\n accountOverride: Hex | undefined;\n}): Hex {\n const address = isDirectMusdMoneyAccountQuote(quotes[0])\n ? transaction.txParams.from\n : (accountOverride ?? transaction.txParams.from);\n\n if (!address) {\n throw new Error('Missing wallet address');\n }\n\n return address as Hex;\n}\n\nfunction waitForKeyringUnlock(\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n): Promise<void> {\n const { isUnlocked } = messenger.call('KeyringController:getState');\n\n if (isUnlocked) {\n return Promise.resolve();\n }\n\n log(\n 'KeyringController is locked; waiting for unlock before fiat submit second leg',\n {\n transactionId,\n },\n );\n\n return new Promise((resolve) => {\n const handler = (): void => {\n messenger.unsubscribe('KeyringController:unlock', handler);\n\n log('KeyringController unlocked; resuming fiat submit second leg', {\n transactionId,\n });\n\n resolve();\n };\n\n messenger.subscribe('KeyringController:unlock', handler);\n });\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fiat-submit.js","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-submit.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,gBAAgB,EAAE,MAAM,4BAA4B,CAAC;AAE9D,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AAErD,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAOhD,OAAO,EAAE,WAAW,EAAE,MAAM,6BAA6B,CAAC;AAC1D,OAAO,EACL,0BAA0B,EAC1B,yBAAyB,GAC1B,MAAM,8BAA8B,CAAC;AACtC,OAAO,EAAE,iBAAiB,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EACL,6BAA6B,EAC7B,mCAAmC,GACpC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,yBAAyB,EAAE,MAAM,wCAAwC,CAAC;AACnF,OAAO,EAAE,2BAA2B,EAAE,MAAM,wBAAwB,CAAC;AAErE,OAAO,EACL,6BAA6B,EAC7B,mBAAmB,EACnB,sBAAsB,EACtB,kBAAkB,GACnB,MAAM,YAAY,CAAC;AAEpB,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,aAAa,CAAC,CAAC;AAC7D,MAAM,sBAAsB,GAAG,aAAa,CAAC;AAE7C,MAAM,yBAAyB,GAAuB;IACpD,gBAAgB,CAAC,SAAS;IAC1B,gBAAgB,CAAC,MAAM;IACvB,gBAAgB,CAAC,SAAS;CAC3B,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,OAA6C;IAE7C,MAAM,EAAE,SAA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AC,CAAC;AACL,CAAC","sourcesContent":["import type { RampsOrder } from '@metamask/ramps-controller';\nimport { RampsOrderStatus } from '@metamask/ramps-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { projectLogger } from '../../logger.js';\nimport type {\n PayStrategy,\n PayStrategyExecuteRequest,\n TransactionPayFiatOptions,\n TransactionPayControllerMessenger,\n} from '../../types.js';\nimport { prefixError } from '../../utils/error-prefix.js';\nimport {\n getFiatOrderPollIntervalMs,\n getFiatOrderPollTimeoutMs,\n} from '../../utils/feature-flags.js';\nimport { updateTransaction } from '../../utils/transaction.js';\nimport {\n isDirectMusdMoneyAccountQuote,\n submitDirectMusdAfterFiatCompletion,\n} from './fiat-direct-musd.js';\nimport { submitSimpleRelay } from './fiat-submit-simple.js';\nimport { submitWithTransactionData } from './fiat-submit-with-transaction-data.js';\nimport { fundFiatOrderFromTestSource } from './fiat-test-funding.js';\nimport type { FiatQuote } from './types.js';\nimport {\n deriveFiatAssetForFiatPayment,\n extractProviderCode,\n resolveSourceAmountRaw,\n validateOrderAsset,\n} from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-submit');\nconst POST_RAMP_ERROR_PREFIX = 'Post-Ramp: ';\n\nconst TERMINAL_FAILURE_STATUSES: RampsOrderStatus[] = [\n RampsOrderStatus.Cancelled,\n RampsOrderStatus.Failed,\n RampsOrderStatus.IdExpired,\n];\n\n/**\n * Submits fiat strategy quotes by polling the on-ramp order until completion,\n * then re-quoting and submitting the relay leg with the settled crypto amount.\n *\n * @param request - Strategy execute request containing fiat quotes, messenger, and transaction metadata.\n * @param request.messenger - Controller messenger for cross-controller calls.\n * @param request.quotes - Fiat quotes to execute (exactly one expected).\n * @param request.transaction - Original transaction metadata.\n * @param request.isSmartTransaction - Callback to check smart transaction eligibility.\n * @returns An object containing the relay transaction hash if available.\n */\nexport async function submitFiatQuotes(\n request: PayStrategyExecuteRequest<FiatQuote>,\n): ReturnType<PayStrategy<FiatQuote>['execute']> {\n const { messenger, transaction } = request;\n const transactionId = transaction.id;\n const state = messenger.call('TransactionPayController:getState');\n const transactionData = state.transactionData[transactionId];\n\n const walletAddress = getWalletAddress({\n quotes: request.quotes,\n transaction,\n accountOverride: transactionData?.accountOverride,\n });\n\n const fiatPayment = transactionData?.fiatPayment;\n const orderId = fiatPayment?.orderId;\n\n if (!orderId) {\n throw new Error('Missing order ID');\n }\n\n const providerCode = extractProviderCode(fiatPayment?.rampsQuote?.provider);\n\n if (!providerCode) {\n throw new Error('Missing provider code');\n }\n\n updateTransaction(\n {\n transactionId,\n messenger,\n note: 'Persist fiat order metadata',\n },\n (tx) => {\n tx.metamaskPay ??= {};\n tx.metamaskPay.fiat = { orderId, provider: providerCode };\n },\n );\n\n log('Starting fiat order polling', {\n orderId,\n providerCode,\n transactionId,\n });\n\n const fiatQuote = request.quotes[0];\n\n if (!fiatQuote) {\n throw new Error('Missing quote');\n }\n\n const fiatOptions = getFiatOptions(messenger);\n\n const order = fiatOptions?.testFundingSource\n ? await fundFiatOrderFromTestSource({\n fiat: fiatOptions,\n messenger,\n quote: fiatQuote,\n transaction,\n })\n : await waitForOrderCompletion({\n messenger,\n orderCode: orderId,\n providerCode,\n transactionId,\n walletAddress,\n });\n\n log('Fiat order completed', {\n cryptoAmount: order.cryptoAmount,\n orderId,\n transactionId,\n });\n\n try {\n await waitForKeyringUnlock(messenger, transactionId);\n\n const result = await submitRelayAfterFiatCompletion({\n order,\n request,\n });\n\n if (result.transactionHash === undefined) {\n throw new Error('Missing transaction hash');\n }\n\n return result;\n } catch (error) {\n throw prefixError(error, POST_RAMP_ERROR_PREFIX);\n }\n}\n\nfunction getFiatOptions(\n messenger: TransactionPayControllerMessenger,\n): TransactionPayFiatOptions | undefined {\n try {\n return messenger.call('TransactionPayController:getFiatOptions');\n } catch (error) {\n log('Failed to retrieve fiat options', error);\n return undefined;\n }\n}\n\n/**\n * Polls the on-ramp order until it reaches a terminal status.\n *\n * @param options - The polling options.\n * @param options.messenger - Controller messenger for calling `RampsController:getOrder`.\n * @param options.orderCode - The order identifier within the provider.\n * @param options.providerCode - The on-ramp provider code (e.g. \"transak\").\n * @param options.transactionId - Transaction ID for logging.\n * @param options.walletAddress - Wallet address associated with the order.\n * @returns The completed order data.\n */\nasync function waitForOrderCompletion({\n messenger,\n orderCode,\n providerCode,\n transactionId,\n walletAddress,\n}: {\n messenger: TransactionPayControllerMessenger;\n orderCode: string;\n providerCode: string;\n transactionId: string;\n walletAddress: string;\n}): Promise<RampsOrder> {\n const pollIntervalMs = getFiatOrderPollIntervalMs(messenger);\n const pollTimeoutMs = getFiatOrderPollTimeoutMs(messenger);\n const startTime = Date.now();\n let lastStatus: string | undefined;\n\n while (true) {\n let order: RampsOrder | undefined;\n\n try {\n order = await messenger.call(\n 'RampsController:getOrder',\n providerCode,\n orderCode,\n walletAddress,\n );\n } catch (error) {\n log('Order polling network error', error);\n }\n\n if (order) {\n lastStatus = order.status;\n\n log('Polled fiat order', {\n orderStatus: order.status,\n providerCode,\n transactionId,\n });\n\n if (order.status === RampsOrderStatus.Completed) {\n return order;\n }\n\n if (TERMINAL_FAILURE_STATUSES.includes(order.status)) {\n throw new Error(`Fiat order ${order.status.toLowerCase()}`);\n }\n }\n\n if (Date.now() - startTime >= pollTimeoutMs) {\n throw new Error(\n `Fiat order polling timed out (last status: ${lastStatus})`,\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));\n }\n}\n\n/**\n * Re-quotes and submits the relay leg using the settled amount from a completed fiat order.\n *\n * @param options - The submission options.\n * @param options.order - The completed on-ramp order containing the settled crypto amount.\n * @param options.request - The original fiat strategy execute request.\n * @returns An object containing the relay transaction hash if available.\n */\nasync function submitRelayAfterFiatCompletion({\n order,\n request,\n}: {\n order: RampsOrder;\n request: PayStrategyExecuteRequest<FiatQuote>;\n}): Promise<{ transactionHash?: Hex }> {\n const { messenger, quotes, transaction } = request;\n const transactionId = transaction.id;\n\n if (quotes.length > 1) {\n throw new Error('Multiple fiat quotes are not supported for submission');\n }\n\n const fiatQuote = quotes[0];\n const isDirectMusd = isDirectMusdMoneyAccountQuote(fiatQuote);\n\n if (isDirectMusd) {\n return await submitDirectMusdAfterFiatCompletion({\n order,\n request,\n });\n }\n\n const fiatAsset = deriveFiatAssetForFiatPayment(transaction, messenger);\n\n validateOrderAsset({\n expectedAsset: fiatAsset,\n orderCrypto: order.cryptoCurrency,\n transactionId,\n });\n\n const baseRequest = fiatQuote.request;\n\n const sourceAmountRaw = await resolveSourceAmountRaw({\n messenger,\n order,\n fiatAsset,\n walletAddress: baseRequest.from,\n });\n\n if (!fiatQuote.original.relayQuote) {\n throw new Error('Missing Relay quote');\n }\n\n const hasNestedCalldata = (transaction.nestedTransactions?.length ?? 0) >= 2;\n\n // Transactions with nested calldata (e.g. moneyAccountDeposit with\n // approve + deposit) need a three-phase flow: discovery quote to learn\n // the target amount, calldata re-encoding, then a delegation quote.\n // Simple deposits (Perps, Predict) skip straight to a single EXACT_INPUT\n // relay quote — cheaper fees, no leftover dust, one fewer request.\n if (hasNestedCalldata) {\n return await submitWithTransactionData({\n baseRequest,\n request,\n sourceAmountRaw,\n transaction,\n });\n }\n\n return await submitSimpleRelay({\n baseRequest,\n request,\n sourceAmountRaw,\n transaction,\n });\n}\n\nfunction getWalletAddress({\n quotes,\n transaction,\n accountOverride,\n}: {\n quotes: PayStrategyExecuteRequest<FiatQuote>['quotes'];\n transaction: PayStrategyExecuteRequest<FiatQuote>['transaction'];\n accountOverride: Hex | undefined;\n}): Hex {\n const address = isDirectMusdMoneyAccountQuote(quotes[0])\n ? transaction.txParams.from\n : (accountOverride ?? transaction.txParams.from);\n\n if (!address) {\n throw new Error('Missing wallet address');\n }\n\n return address as Hex;\n}\n\nfunction waitForKeyringUnlock(\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n): Promise<void> {\n const { isUnlocked } = messenger.call('KeyringController:getState');\n\n if (isUnlocked) {\n return Promise.resolve();\n }\n\n log(\n 'KeyringController is locked; waiting for unlock before fiat submit second leg',\n {\n transactionId,\n },\n );\n\n return new Promise((resolve) => {\n const handler = (): void => {\n messenger.unsubscribe('KeyringController:unlock', handler);\n\n log('KeyringController unlocked; resuming fiat submit second leg', {\n transactionId,\n });\n\n resolve();\n };\n\n messenger.subscribe('KeyringController:unlock', handler);\n });\n}\n"]}
|
|
@@ -71,43 +71,25 @@ export declare function validateOrderAsset({ expectedAsset, orderCrypto, transac
|
|
|
71
71
|
transactionId: string;
|
|
72
72
|
}): void;
|
|
73
73
|
/**
|
|
74
|
-
*
|
|
75
|
-
|
|
76
|
-
export type ResolvedSourceAmount = {
|
|
77
|
-
/** Raw (atomic) source amount as a decimal string. */
|
|
78
|
-
amountRaw: string;
|
|
79
|
-
/**
|
|
80
|
-
* Block number of the ramps settlement transaction as a 0x-prefixed hex
|
|
81
|
-
* string. Populated when `order.txHash` is present and the on-chain receipt
|
|
82
|
-
* was successfully fetched (ERC-20 only). Use this as the `fromBlock` for
|
|
83
|
-
* CHOMP idempotency log queries — it reuses the receipt already fetched for
|
|
84
|
-
* the amount and requires no additional network request.
|
|
85
|
-
*/
|
|
86
|
-
fromBlock: Hex | undefined;
|
|
87
|
-
};
|
|
88
|
-
/**
|
|
89
|
-
* Resolves the raw source amount for a completed fiat order.
|
|
90
|
-
*
|
|
91
|
-
* Attempts to read the actual transferred amount from the on-chain transaction
|
|
92
|
-
* identified by `order.txHash`. If the on-chain read fails or returns
|
|
93
|
-
* no amount, falls back to computing the amount from `order.cryptoAmount`.
|
|
74
|
+
* Resolves the raw source amount for a completed fiat order, read from the
|
|
75
|
+
* on-chain transfer identified by `order.txHash`.
|
|
94
76
|
*
|
|
95
|
-
*
|
|
96
|
-
*
|
|
77
|
+
* Throws when the order has no transaction hash or no matching transfer,
|
|
78
|
+
* rather than trusting the provider-reported `order.cryptoAmount`.
|
|
97
79
|
*
|
|
98
80
|
* @param options - The resolution options.
|
|
99
81
|
* @param options.messenger - Controller messenger for network access.
|
|
100
82
|
* @param options.order - The completed on-ramp order.
|
|
101
83
|
* @param options.fiatAsset - The fiat asset describing the expected token.
|
|
102
84
|
* @param options.walletAddress - Recipient wallet address for on-chain lookup.
|
|
103
|
-
* @returns The raw (atomic) source amount
|
|
85
|
+
* @returns The raw (atomic) source amount.
|
|
104
86
|
*/
|
|
105
87
|
export declare function resolveSourceAmountRaw({ messenger, order, fiatAsset, walletAddress, }: {
|
|
106
88
|
messenger: TransactionPayControllerMessenger;
|
|
107
89
|
order: RampsOrder;
|
|
108
90
|
fiatAsset: TransactionPayFiatAsset;
|
|
109
91
|
walletAddress: Hex;
|
|
110
|
-
}): Promise<
|
|
92
|
+
}): Promise<string>;
|
|
111
93
|
/**
|
|
112
94
|
* Converts the order's human-readable crypto amount to a raw token amount.
|
|
113
95
|
*
|
|
@@ -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,iBAAiB,CAAC;AAK3C,OAAO,KAAK,EAAE,iCAAiC,EAAE,MAAM,gBAAgB,CAAC;AAOxE,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,gBAAgB,CAAC;AAK9D,wBAAgB,6BAA6B,CAC3C,WAAW,EAAE,eAAe,EAC5B,SAAS,EAAE,iCAAiC,GAC3C,uBAAuB,CAKzB;AAED;;;;;;;;;;;GAWG;AACH,wBAAgB,sBAAsB,CACpC,WAAW,EAAE,eAAe,EAC5B,YAAY,EAAE,eAAe,EAAE,G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H,wBAAgB,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"}
|
|
@@ -3,7 +3,7 @@ import { createModuleLogger } from '@metamask/utils';
|
|
|
3
3
|
import { BigNumber } from 'bignumber.js';
|
|
4
4
|
import { projectLogger } from '../../logger.js';
|
|
5
5
|
import { getFiatAssetPerTransactionType, getFiatEnabledTypes, } from '../../utils/feature-flags.js';
|
|
6
|
-
import { buildCaipAssetType
|
|
6
|
+
import { buildCaipAssetType } from '../../utils/token.js';
|
|
7
7
|
import { getTransferredAmountFromTxHash } from '../../utils/transaction.js';
|
|
8
8
|
import { DEFAULT_FIAT_CURRENCY, FIAT_ENABLED_TYPES } from './constants.js';
|
|
9
9
|
const log = createModuleLogger(projectLogger, 'fiat-utils');
|
|
@@ -104,54 +104,38 @@ export function validateOrderAsset({ expectedAsset, orderCrypto, transactionId,
|
|
|
104
104
|
}
|
|
105
105
|
}
|
|
106
106
|
/**
|
|
107
|
-
* Resolves the raw source amount for a completed fiat order
|
|
107
|
+
* Resolves the raw source amount for a completed fiat order, read from the
|
|
108
|
+
* on-chain transfer identified by `order.txHash`.
|
|
108
109
|
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
* no amount, falls back to computing the amount from `order.cryptoAmount`.
|
|
112
|
-
*
|
|
113
|
-
* Also returns the receipt `blockNumber` from the ramps tx when available, so
|
|
114
|
-
* callers can use it as a CHOMP idempotency baseline without any extra request.
|
|
110
|
+
* Throws when the order has no transaction hash or no matching transfer,
|
|
111
|
+
* rather than trusting the provider-reported `order.cryptoAmount`.
|
|
115
112
|
*
|
|
116
113
|
* @param options - The resolution options.
|
|
117
114
|
* @param options.messenger - Controller messenger for network access.
|
|
118
115
|
* @param options.order - The completed on-ramp order.
|
|
119
116
|
* @param options.fiatAsset - The fiat asset describing the expected token.
|
|
120
117
|
* @param options.walletAddress - Recipient wallet address for on-chain lookup.
|
|
121
|
-
* @returns The raw (atomic) source amount
|
|
118
|
+
* @returns The raw (atomic) source amount.
|
|
122
119
|
*/
|
|
123
120
|
export async function resolveSourceAmountRaw({ messenger, order, fiatAsset, walletAddress, }) {
|
|
124
|
-
if (order.txHash) {
|
|
125
|
-
|
|
126
|
-
const { amountRaw: onChainAmount, blockNumber } = await getTransferredAmountFromTxHash({
|
|
127
|
-
messenger,
|
|
128
|
-
txHash: order.txHash,
|
|
129
|
-
chainId: fiatAsset.chainId,
|
|
130
|
-
tokenAddress: fiatAsset.address,
|
|
131
|
-
walletAddress,
|
|
132
|
-
});
|
|
133
|
-
if (onChainAmount) {
|
|
134
|
-
log('Resolved source amount from on-chain transaction', {
|
|
135
|
-
txHash: order.txHash,
|
|
136
|
-
onChainAmount,
|
|
137
|
-
blockNumber,
|
|
138
|
-
});
|
|
139
|
-
return { amountRaw: onChainAmount, fromBlock: blockNumber };
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
catch (error) {
|
|
143
|
-
log('Failed to read on-chain amount, falling back to order.cryptoAmount', { txHash: order.txHash, error });
|
|
144
|
-
}
|
|
121
|
+
if (!order.txHash) {
|
|
122
|
+
throw new Error('Missing fiat order transaction hash');
|
|
145
123
|
}
|
|
146
|
-
const
|
|
147
|
-
|
|
148
|
-
|
|
124
|
+
const { amountRaw } = await getTransferredAmountFromTxHash({
|
|
125
|
+
messenger,
|
|
126
|
+
txHash: order.txHash,
|
|
127
|
+
chainId: fiatAsset.chainId,
|
|
128
|
+
tokenAddress: fiatAsset.address,
|
|
129
|
+
walletAddress,
|
|
130
|
+
});
|
|
131
|
+
if (!amountRaw) {
|
|
132
|
+
throw new Error(`Could not determine transferred amount from transaction ${order.txHash}`);
|
|
149
133
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
134
|
+
log('Resolved source amount from on-chain transaction', {
|
|
135
|
+
amountRaw,
|
|
136
|
+
txHash: order.txHash,
|
|
153
137
|
});
|
|
154
|
-
return
|
|
138
|
+
return amountRaw;
|
|
155
139
|
}
|
|
156
140
|
/**
|
|
157
141
|
* Converts the order's human-readable crypto amount to a raw token amount.
|
|
@@ -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,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACxE,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,mB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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, getTokenInfo } 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 * Result from {@link resolveSourceAmountRaw}.\n */\nexport type ResolvedSourceAmount = {\n /** Raw (atomic) source amount as a decimal string. */\n amountRaw: string;\n /**\n * Block number of the ramps settlement transaction as a 0x-prefixed hex\n * string. Populated when `order.txHash` is present and the on-chain receipt\n * was successfully fetched (ERC-20 only). Use this as the `fromBlock` for\n * CHOMP idempotency log queries — it reuses the receipt already fetched for\n * the amount and requires no additional network request.\n */\n fromBlock: Hex | undefined;\n};\n\n/**\n * Resolves the raw source amount for a completed fiat order.\n *\n * Attempts to read the actual transferred amount from the on-chain transaction\n * identified by `order.txHash`. If the on-chain read fails or returns\n * no amount, falls back to computing the amount from `order.cryptoAmount`.\n *\n * Also returns the receipt `blockNumber` from the ramps tx when available, so\n * callers can use it as a CHOMP idempotency baseline without any extra request.\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 and optional receipt block number.\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<ResolvedSourceAmount> {\n if (order.txHash) {\n try {\n const { amountRaw: onChainAmount, blockNumber } =\n await getTransferredAmountFromTxHash({\n messenger,\n txHash: order.txHash,\n chainId: fiatAsset.chainId,\n tokenAddress: fiatAsset.address,\n walletAddress,\n });\n\n if (onChainAmount) {\n log('Resolved source amount from on-chain transaction', {\n txHash: order.txHash,\n onChainAmount,\n blockNumber,\n });\n return { amountRaw: onChainAmount, fromBlock: blockNumber };\n }\n } catch (error) {\n log(\n 'Failed to read on-chain amount, falling back to order.cryptoAmount',\n { txHash: order.txHash, error },\n );\n }\n }\n\n const tokenInfo = getTokenInfo(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!tokenInfo) {\n throw new Error(\n `Unable to resolve token info for fiat asset ${fiatAsset.address} on chain ${fiatAsset.chainId}`,\n );\n }\n\n const amountRaw = getRawSourceAmountFromOrderCryptoAmount({\n cryptoAmount: order.cryptoAmount,\n decimals: tokenInfo.decimals,\n });\n\n return { amountRaw, fromBlock: undefined };\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,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,MAAM,gBAAgB,CAAC;AAE3E,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,YAAY,CAAC,CAAC;AAE5D,MAAM,UAAU,6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B,aAAa;KACd,CAAC,CAAC;IAEH,IAAI,YAAY,CAAC,EAAE,CAAC,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 { 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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relay-quotes.d.ts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-quotes.ts"],"names":[],"mappings":"AA0BA,OAAO,KAAK,EAGV,2BAA2B,EAG3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;
|
|
1
|
+
{"version":3,"file":"relay-quotes.d.ts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-quotes.ts"],"names":[],"mappings":"AA0BA,OAAO,KAAK,EAGV,2BAA2B,EAG3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAyCxB,OAAO,KAAK,EACV,UAAU,EAIX,MAAM,YAAY,CAAC;AAuBpB;;;;;GAKG;AACH,wBAAsB,cAAc,CAClC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,mBAAmB,CAAC,UAAU,CAAC,EAAE,CAAC,CAsE5C"}
|
|
@@ -11,6 +11,7 @@ import { getFeatureFlags, getRelayOriginGasOverhead, getSlippage, getStablecoins
|
|
|
11
11
|
import { GasPaymentMode, resolveGasPayment, resolveGasStationCost, } from '../../utils/gas-payment.js';
|
|
12
12
|
import { calculateGasCost } from '../../utils/gas.js';
|
|
13
13
|
import { estimateQuoteGasLimits } from '../../utils/quote-gas.js';
|
|
14
|
+
import { resolveNonAtomicRecipient } from '../../utils/second-leg.js';
|
|
14
15
|
import { getNativeToken, getTokenFiatRate, normalizeTokenAddress, TokenAddressTarget, } from '../../utils/token.js';
|
|
15
16
|
import { getQuotePricing } from '../../utils/trade-type.js';
|
|
16
17
|
import { TOKEN_TRANSFER_FOUR_BYTE } from './constants.js';
|
|
@@ -240,39 +241,6 @@ function normalizeAuthorizationList(authorizationList) {
|
|
|
240
241
|
yParity: Number(a.yParity),
|
|
241
242
|
}));
|
|
242
243
|
}
|
|
243
|
-
/**
|
|
244
|
-
* Derives the Relay quote recipient for non-atomic flows, where the second leg
|
|
245
|
-
* runs after settlement so funds must land directly on the account submitting
|
|
246
|
-
* that leg.
|
|
247
|
-
*
|
|
248
|
-
* Post-quote flows (e.g. Perps/Predict withdraw to Money Account) ask the
|
|
249
|
-
* client `getPaymentOverrideData` callback, which knows the Money Account
|
|
250
|
-
* address that cannot be derived from the request. Non-post-quote flows (e.g.
|
|
251
|
-
* max-amount Money Account deposit) use the parent transaction's own `from`,
|
|
252
|
-
* which is the Money Account rather than the funding EOA in `request.from`.
|
|
253
|
-
*
|
|
254
|
-
* @param transaction - Transaction metadata.
|
|
255
|
-
* @param request - Quote request.
|
|
256
|
-
* @param messenger - Controller messenger.
|
|
257
|
-
* @returns The recipient address, or `undefined` for atomic flows.
|
|
258
|
-
*/
|
|
259
|
-
async function resolveNonAtomicRecipient(transaction, request, messenger) {
|
|
260
|
-
if (request.atomic !== false) {
|
|
261
|
-
return undefined;
|
|
262
|
-
}
|
|
263
|
-
if (!request.isPostQuote) {
|
|
264
|
-
return transaction.txParams?.from ?? request.from;
|
|
265
|
-
}
|
|
266
|
-
const { transactionData: transactionDataList } = messenger.call('TransactionPayController:getState');
|
|
267
|
-
const transactionData = transactionDataList[transaction.id];
|
|
268
|
-
const amountHuman = transactionData?.tokens?.[0]?.amountHuman ?? '0';
|
|
269
|
-
const { recipient } = await messenger.call('TransactionPayController:getPaymentOverrideData', {
|
|
270
|
-
amount: amountHuman,
|
|
271
|
-
transaction,
|
|
272
|
-
transactionData,
|
|
273
|
-
});
|
|
274
|
-
return recipient;
|
|
275
|
-
}
|
|
276
244
|
/**
|
|
277
245
|
* Add tranasction data to request body if needed.
|
|
278
246
|
*
|
|
@@ -326,11 +294,10 @@ async function processTransactions(transaction, request, requestBody, messenger)
|
|
|
326
294
|
requestBody.recipient = getTransferRecipient(tokenTransferData);
|
|
327
295
|
requestBody.refundTo = request.from;
|
|
328
296
|
}
|
|
329
|
-
const fundingRecipient = transaction.txParams?.from ?? request.from;
|
|
330
297
|
requestBody.txs = [
|
|
331
298
|
{
|
|
332
299
|
to: request.targetTokenAddress,
|
|
333
|
-
data: buildTokenTransferData(
|
|
300
|
+
data: buildTokenTransferData(transaction.txParams.from, request.targetAmountMinimum),
|
|
334
301
|
value: '0x0',
|
|
335
302
|
},
|
|
336
303
|
{
|
|
@@ -549,14 +516,16 @@ function getFiatRates(messenger, request) {
|
|
|
549
516
|
*/
|
|
550
517
|
async function calculateSourceNetworkCost(quote, messenger, request, transaction, accountSupports7702) {
|
|
551
518
|
const { from, sourceChainId, sourceTokenAddress } = request;
|
|
552
|
-
//
|
|
553
|
-
// redeem a signed delegation,
|
|
554
|
-
// is an off-chain HL sendAsset signature rather than an on-chain
|
|
555
|
-
// transaction
|
|
519
|
+
// None of these flows bill origin gas to the user: the execute flow has a
|
|
520
|
+
// relayer redeem a signed delegation, a HyperLiquid withdrawal's "deposit"
|
|
521
|
+
// step is an off-chain HL sendAsset signature rather than an on-chain
|
|
522
|
+
// transaction, and a Polymarket deposit-wallet withdraw is submitted by the
|
|
523
|
+
// Polymarket relayer.
|
|
556
524
|
const isExecuteFlow = Boolean(quote.metamask?.isExecute);
|
|
557
525
|
const isHyperliquidWithdrawal = Boolean(request.isHyperliquidSource);
|
|
526
|
+
const isPolymarketDepositWallet = Boolean(request.isPolymarketDepositWallet);
|
|
558
527
|
const gasPayment = resolveGasPayment({
|
|
559
|
-
isDelegated: isExecuteFlow || isHyperliquidWithdrawal,
|
|
528
|
+
isDelegated: isExecuteFlow || isHyperliquidWithdrawal || isPolymarketDepositWallet,
|
|
560
529
|
sourceTokenAddress,
|
|
561
530
|
sponsorship: {
|
|
562
531
|
accountSupports7702,
|
|
@@ -568,6 +537,7 @@ async function calculateSourceNetworkCost(quote, messenger, request, transaction
|
|
|
568
537
|
log('Zeroing network fees as the user does not pay origin gas', {
|
|
569
538
|
isExecuteFlow,
|
|
570
539
|
isHyperliquidWithdrawal,
|
|
540
|
+
isPolymarketDepositWallet,
|
|
571
541
|
});
|
|
572
542
|
return {
|
|
573
543
|
estimate: ZERO_AMOUNT,
|