@metamask-previews/transaction-pay-controller 28.0.2-preview-5d09c14 → 28.0.2-preview-5121808e1
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 +3 -0
- package/dist/strategy/fiat/fiat-direct-musd.d.ts.map +1 -1
- package/dist/strategy/fiat/fiat-direct-musd.js +57 -9
- package/dist/strategy/fiat/fiat-direct-musd.js.map +1 -1
- package/dist/strategy/fiat/fiat-quotes.d.ts.map +1 -1
- package/dist/strategy/fiat/fiat-quotes.js +16 -3
- package/dist/strategy/fiat/fiat-quotes.js.map +1 -1
- package/dist/strategy/fiat/utils.d.ts +31 -0
- package/dist/strategy/fiat/utils.d.ts.map +1 -1
- package/dist/strategy/fiat/utils.js +53 -0
- package/dist/strategy/fiat/utils.js.map +1 -1
- package/dist/types.d.ts +4 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/dist/utils/totals.d.ts.map +1 -1
- package/dist/utils/totals.js +15 -0
- package/dist/utils/totals.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
9
9
|
|
|
10
10
|
### Changed
|
|
11
11
|
|
|
12
|
+
- Use the native Transak buy quote's fee for the MM Pay fiat estimate when Transak Native is the resolved provider, falling back to the aggregator quote's fee when native is unavailable or the lookup fails ([#9317](https://github.com/MetaMask/core/pull/9317))
|
|
13
|
+
- The fee is read via the stateless `TransakService:getBuyQuote` action so the estimate does not write the shared native buy-quote state used by Unified Buy; clients must delegate `TransakService:getBuyQuote` to the `TransactionPayController` messenger.
|
|
14
|
+
- Charge direct Monad mUSD on-ramp fees on top of the entered amount (fee-on-top), so the total is the entered amount plus fees ([#9317](https://github.com/MetaMask/core/pull/9317))
|
|
12
15
|
- Bump `@metamask/utils` from `^11.12.0` to `^12.0.0` ([#10192](https://github.com/MetaMask/core/pull/10192))
|
|
13
16
|
|
|
14
17
|
### Fixed
|
|
@@ -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,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAMxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;
|
|
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,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAMxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAY5C;;;;;;;;;;;GAWG;AACH,wBAAsB,sBAAsB,CAAC,EAC3C,UAAU,EACV,iBAAiB,EACjB,SAAS,EACT,mBAAmB,EACnB,aAAa,EACb,aAAa,GACd,EAAE;IACD,UAAU,EAAE,MAAM,CAAC;IACnB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,SAAS,EAAE,2BAA2B,CAAC,WAAW,CAAC,CAAC;IACpD,mBAAmB,EAAE,GAAG,CAAC;IACzB,aAAa,EAAE,2BAA2B,CAAC;IAC3C,aAAa,EAAE,MAAM,CAAC;CACvB,GAAG,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,GAAG,SAAS,CAAC,CA2DtD;AAED;;;;;GAKG;AACH,wBAAgB,6BAA6B,CAC3C,KAAK,EAAE,IAAI,CAAC,mBAAmB,CAAC,OAAO,CAAC,EAAE,SAAS,CAAC,GAAG,SAAS,GAC/D,OAAO,CAET;AAED;;;;;;;GAOG;AACH,wBAAsB,mCAAmC,CAAC,EACxD,KAAK,EACL,OAAO,GACR,EAAE;IACD,KAAK,EAAE,UAAU,CAAC;IAClB,OAAO,EAAE,yBAAyB,CAAC,SAAS,CAAC,CAAC;CAC/C,GAAG,OAAO,CAAC;IAAE,eAAe,CAAC,EAAE,GAAG,CAAA;CAAE,CAAC,CA4BrC"}
|
|
@@ -7,7 +7,7 @@ import { getFiatVaultDisabled } from '../../utils/feature-flags.js';
|
|
|
7
7
|
import { submitMoneyAccountVaultDeposit } from '../../utils/ma-vault-deposit.js';
|
|
8
8
|
import { buildCaipAssetType, getTokenInfo } from '../../utils/token.js';
|
|
9
9
|
import { MUSD_MONAD_FIAT_ASSET } from './constants.js';
|
|
10
|
-
import { getRampsQuote, getRawSourceAmountFromOrderCryptoAmount, resolveSourceAmountRaw, validateOrderAsset, } from './utils.js';
|
|
10
|
+
import { getNativeTransakRampsFee, getRampsQuote, getRawSourceAmountFromOrderCryptoAmount, resolveSourceAmountRaw, validateOrderAsset, } from './utils.js';
|
|
11
11
|
const log = createModuleLogger(projectLogger, 'fiat-direct-musd');
|
|
12
12
|
const DIRECT_MUSD_ERROR_PREFIX = 'Direct mUSD: ';
|
|
13
13
|
/**
|
|
@@ -36,6 +36,18 @@ export async function getDirectMusdFiatQuote({ amountFiat, fiatPaymentMethod, me
|
|
|
36
36
|
messenger,
|
|
37
37
|
walletAddress: moneyAccountAddress,
|
|
38
38
|
});
|
|
39
|
+
// When Transak Native is the resolved provider, prefer its own quote's fee
|
|
40
|
+
// so the estimate matches what Transak Native will charge. Direct mUSD is
|
|
41
|
+
// fee-on-top (the fee is added to the entered amount), so request the native
|
|
42
|
+
// quote in that mode.
|
|
43
|
+
const nativeRampsFee = await getNativeTransakRampsFee({
|
|
44
|
+
adjustedAmount,
|
|
45
|
+
fiatAsset: MUSD_MONAD_FIAT_ASSET,
|
|
46
|
+
fiatPaymentMethod,
|
|
47
|
+
fiatQuote,
|
|
48
|
+
isFeeExcludedFromFiat: true,
|
|
49
|
+
messenger,
|
|
50
|
+
});
|
|
39
51
|
messenger.call('TransactionPayController:updateFiatPayment', {
|
|
40
52
|
callback: (fiatPayment) => {
|
|
41
53
|
fiatPayment.rampsQuote = fiatQuote;
|
|
@@ -53,6 +65,7 @@ export async function getDirectMusdFiatQuote({ amountFiat, fiatPaymentMethod, me
|
|
|
53
65
|
fiatQuote,
|
|
54
66
|
messenger,
|
|
55
67
|
moneyAccountAddress,
|
|
68
|
+
nativeRampsFee,
|
|
56
69
|
requiredToken,
|
|
57
70
|
});
|
|
58
71
|
}
|
|
@@ -104,7 +117,7 @@ export async function submitDirectMusdAfterFiatCompletion({ order, request, }) {
|
|
|
104
117
|
throw prefixError(error, DIRECT_MUSD_ERROR_PREFIX);
|
|
105
118
|
}
|
|
106
119
|
}
|
|
107
|
-
function combineDirectMusdFiatQuote({ amountFiat, fiatQuote, messenger, moneyAccountAddress, requiredToken, }) {
|
|
120
|
+
function combineDirectMusdFiatQuote({ amountFiat, fiatQuote, messenger, moneyAccountAddress, nativeRampsFee, requiredToken, }) {
|
|
108
121
|
const tokenInfo = getTokenInfo(messenger, MUSD_MONAD_FIAT_ASSET.address, MUSD_MONAD_FIAT_ASSET.chainId);
|
|
109
122
|
if (!tokenInfo) {
|
|
110
123
|
throw new Error('Unable to resolve mUSD token info for direct fiat quote');
|
|
@@ -113,20 +126,45 @@ function combineDirectMusdFiatQuote({ amountFiat, fiatQuote, messenger, moneyAcc
|
|
|
113
126
|
cryptoAmount: fiatQuote.quote.amountOut,
|
|
114
127
|
decimals: tokenInfo.decimals,
|
|
115
128
|
});
|
|
116
|
-
|
|
129
|
+
// Transak Native returns a single total fee, so the aggregator's separate
|
|
130
|
+
// provider/network split collapses: the whole native fee sits in the provider
|
|
131
|
+
// bucket and the source-network fee is zero. The `providerFiat` total stays
|
|
132
|
+
// correct either way.
|
|
133
|
+
const rampsProviderFee = (nativeRampsFee ?? getSafeFee(fiatQuote.quote.providerFee)).toString(10);
|
|
134
|
+
const rampsNetworkFee = nativeRampsFee
|
|
135
|
+
? '0'
|
|
136
|
+
: getSafeFee(fiatQuote.quote.networkFee).toString(10);
|
|
137
|
+
const rampsTotalFee = new BigNumber(rampsProviderFee)
|
|
138
|
+
.plus(rampsNetworkFee)
|
|
139
|
+
.toString(10);
|
|
140
|
+
const targetAmountFiat = getDirectMusdTargetAmountFiat(fiatQuote);
|
|
117
141
|
const sourceAmountHuman = new BigNumber(sourceAmountRaw)
|
|
118
142
|
.shiftedBy(-tokenInfo.decimals)
|
|
119
143
|
.toString(10);
|
|
120
144
|
return {
|
|
145
|
+
// Direct mUSD is fee-on-top: the fee is added to the entered amount, so the
|
|
146
|
+
// fees are NOT already inside the source amount and the total becomes
|
|
147
|
+
// amount + fees (see calculateTotals).
|
|
148
|
+
areFeesIncludedInSourceAmount: false,
|
|
121
149
|
dust: { fiat: '0', usd: '0' },
|
|
122
150
|
estimatedDuration: 0,
|
|
123
151
|
fees: {
|
|
124
152
|
metaMask: { fiat: '0', usd: '0' },
|
|
125
153
|
provider: { fiat: rampsProviderFee, usd: rampsProviderFee },
|
|
126
|
-
providerFiat: { fiat:
|
|
154
|
+
providerFiat: { fiat: rampsTotalFee, usd: rampsTotalFee },
|
|
127
155
|
sourceNetwork: {
|
|
128
|
-
estimate: {
|
|
129
|
-
|
|
156
|
+
estimate: {
|
|
157
|
+
fiat: rampsNetworkFee,
|
|
158
|
+
human: '0',
|
|
159
|
+
raw: '0',
|
|
160
|
+
usd: rampsNetworkFee,
|
|
161
|
+
},
|
|
162
|
+
max: {
|
|
163
|
+
fiat: rampsNetworkFee,
|
|
164
|
+
human: '0',
|
|
165
|
+
raw: '0',
|
|
166
|
+
usd: rampsNetworkFee,
|
|
167
|
+
},
|
|
130
168
|
},
|
|
131
169
|
targetNetwork: { fiat: '0', usd: '0' },
|
|
132
170
|
},
|
|
@@ -153,10 +191,20 @@ function combineDirectMusdFiatQuote({ amountFiat, fiatQuote, messenger, moneyAcc
|
|
|
153
191
|
usd: amountFiat,
|
|
154
192
|
},
|
|
155
193
|
strategy: TransactionPayStrategy.Fiat,
|
|
156
|
-
targetAmount: { fiat:
|
|
194
|
+
targetAmount: { fiat: targetAmountFiat, usd: targetAmountFiat },
|
|
157
195
|
};
|
|
158
196
|
}
|
|
159
|
-
function
|
|
160
|
-
|
|
197
|
+
function getDirectMusdTargetAmountFiat(fiatQuote) {
|
|
198
|
+
const amountOutInFiat = new BigNumber(fiatQuote.quote.amountOutInFiat ?? NaN);
|
|
199
|
+
if (amountOutInFiat.isFinite() && amountOutInFiat.isGreaterThanOrEqualTo(0)) {
|
|
200
|
+
return amountOutInFiat.toString(10);
|
|
201
|
+
}
|
|
202
|
+
return new BigNumber(fiatQuote.quote.amountOut).toString(10);
|
|
203
|
+
}
|
|
204
|
+
function getSafeFee(value) {
|
|
205
|
+
const fee = new BigNumber(value ?? 0);
|
|
206
|
+
return fee.isFinite() && fee.isGreaterThanOrEqualTo(0)
|
|
207
|
+
? fee
|
|
208
|
+
: new BigNumber(0);
|
|
161
209
|
}
|
|
162
210
|
//# sourceMappingURL=fiat-direct-musd.js.map
|
|
@@ -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,6BAA6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,GAAG,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,KAAK,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE;aACnD;YACD,aAAa,EAAE,EAAE,IAAI,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE;SACvC;QACD,QAAQ,EAAE;YACR,UAAU,EAAE,SAAS;YACrB,UAAU,EAAE,SAAS;SACtB;QACD,OAAO,EAAE;YACP,IAAI,EAAE,mBAAmB;YACzB,wBAAwB,EAAE,IAAI;YAC9B,SAAS,EAAE,mBAAmB;YAC9B,gBAAgB,EAAE,eAAe;YACjC,aAAa,EAAE,qBAAqB,CAAC,OAAO;YAC5C,kBAAkB,EAAE,qBAAqB,CAAC,OAAO;YACjD,iBAAiB,EAAE,eAAe;YAClC,mBAAmB,EAAE,eAAe;YACpC,aAAa,EAAE,aAAa,CAAC,OAAO;YACpC,kBAAkB,EAAE,aAAa,CAAC,OAAO;SAC1C;QACD,YAAY,EAAE;YACZ,IAAI,EAAE,UAAU;YAChB,KAAK,EAAE,iBAAiB;YACxB,GAAG,EAAE,eAAe;YACpB,GAAG,EAAE,UAAU;SAChB;QACD,QAAQ,EAAE,sBAAsB,CAAC,IAAI;QACrC,YAAY,EAAE,EAAE,IAAI,EAAE,UAAU,EAAE,GAAG,EAAE,UAAU,EAAE;KACpD,CAAC;AACJ,CAAC;AAED,SAAS,mBAAmB,CAAC,SAAqB;IAChD,OAAO,IAAI,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,WAAW,IAAI,CAAC,CAAC,CAAC,IAAI,CACzD,SAAS,CAAC,KAAK,CAAC,UAAU,IAAI,CAAC,CAChC,CAAC;AACJ,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 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 const rampsProviderFee = getRampsProviderFee(fiatQuote).toString(10);\n const sourceAmountHuman = new BigNumber(sourceAmountRaw)\n .shiftedBy(-tokenInfo.decimals)\n .toString(10);\n\n return {\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: rampsProviderFee, usd: rampsProviderFee },\n sourceNetwork: {\n estimate: { fiat: '0', human: '0', raw: '0', usd: '0' },\n max: { fiat: '0', human: '0', raw: '0', usd: '0' },\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: amountFiat, usd: amountFiat },\n };\n}\n\nfunction getRampsProviderFee(fiatQuote: RampsQuote): BigNumber {\n return new BigNumber(fiatQuote.quote.providerFee ?? 0).plus(\n fiatQuote.quote.networkFee ?? 0,\n );\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,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,wBAAwB,EACxB,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;;;;;;;;;;;GAWG;AACH,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,EA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AAI,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,IAAI,SAAS,CAAC,SAAS,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC,QAAQ,CAAC,EAAE,CAAC,CAAC;AAC/D,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 getNativeTransakRampsFee,\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 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 // When Transak Native is the resolved provider, prefer its own quote's fee\n // so the estimate matches what Transak Native will charge. Direct mUSD is\n // fee-on-top (the fee is added to the entered amount), so request the native\n // quote in that mode.\n const nativeRampsFee = await getNativeTransakRampsFee({\n adjustedAmount,\n fiatAsset: MUSD_MONAD_FIAT_ASSET,\n fiatPaymentMethod,\n fiatQuote,\n isFeeExcludedFromFiat: true,\n messenger,\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 nativeRampsFee,\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 nativeRampsFee,\n requiredToken,\n}: {\n amountFiat: string;\n fiatQuote: RampsQuote;\n messenger: PayStrategyGetQuotesRequest['messenger'];\n moneyAccountAddress: Hex;\n nativeRampsFee: BigNumber | null;\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 // Transak Native returns a single total fee, so the aggregator's separate\n // provider/network split collapses: the whole native fee sits in the provider\n // bucket and the source-network fee is zero. The `providerFiat` total stays\n // correct either way.\n const rampsProviderFee = (\n nativeRampsFee ?? getSafeFee(fiatQuote.quote.providerFee)\n ).toString(10);\n const rampsNetworkFee = nativeRampsFee\n ? '0'\n : getSafeFee(fiatQuote.quote.networkFee).toString(10);\n const rampsTotalFee = new BigNumber(rampsProviderFee)\n .plus(rampsNetworkFee)\n .toString(10);\n const targetAmountFiat = getDirectMusdTargetAmountFiat(fiatQuote);\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\nfunction getDirectMusdTargetAmountFiat(fiatQuote: RampsQuote): 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 new BigNumber(fiatQuote.quote.amountOut).toString(10);\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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fiat-quotes.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-quotes.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,2BAA2B,EAI3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAYxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"fiat-quotes.d.ts","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-quotes.ts"],"names":[],"mappings":"AAUA,OAAO,KAAK,EACV,2BAA2B,EAI3B,mBAAmB,EACpB,MAAM,gBAAgB,CAAC;AAYxB,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAkB5C;;;;;;;;;GASG;AACH,wBAAsB,aAAa,CACjC,OAAO,EAAE,2BAA2B,GACnC,OAAO,CAAC,mBAAmB,CAAC,SAAS,CAAC,EAAE,CAAC,CA0C3C"}
|
|
@@ -6,7 +6,7 @@ import { getDirectMoneyMusdEnabled } from '../../utils/feature-flags.js';
|
|
|
6
6
|
import { buildCaipAssetType, computeRawFromFiatAmount, getTokenFiatRate, getTokenInfo, } from '../../utils/token.js';
|
|
7
7
|
import { getRelayQuotes } from '../relay/relay-quotes.js';
|
|
8
8
|
import { getDirectMusdFiatQuote } from './fiat-direct-musd.js';
|
|
9
|
-
import { deriveFiatAssetForFiatPayment, getRampsQuote, isMoneyAccountDepositTransaction, } from './utils.js';
|
|
9
|
+
import { deriveFiatAssetForFiatPayment, getNativeTransakRampsFee, getRampsQuote, isMoneyAccountDepositTransaction, } from './utils.js';
|
|
10
10
|
const log = createModuleLogger(projectLogger, 'fiat-strategy');
|
|
11
11
|
/**
|
|
12
12
|
* Fetches MM Pay fiat strategy quotes using a relay-first estimation flow.
|
|
@@ -109,6 +109,17 @@ async function executeFiatQuotePipeline(request, options) {
|
|
|
109
109
|
messenger,
|
|
110
110
|
walletAddress: rampsWalletAddress,
|
|
111
111
|
});
|
|
112
|
+
// When Transak Native is the resolved provider, prefer its own quote's fee
|
|
113
|
+
// so the estimate matches what Transak Native will charge. The relay path
|
|
114
|
+
// stays fee-on-top, so request the native quote in the same mode.
|
|
115
|
+
const nativeRampsFee = await getNativeTransakRampsFee({
|
|
116
|
+
adjustedAmount,
|
|
117
|
+
fiatAsset,
|
|
118
|
+
fiatPaymentMethod,
|
|
119
|
+
fiatQuote,
|
|
120
|
+
isFeeExcludedFromFiat: true,
|
|
121
|
+
messenger,
|
|
122
|
+
});
|
|
112
123
|
messenger.call('TransactionPayController:updateFiatPayment', {
|
|
113
124
|
callback: (fiatPayment) => {
|
|
114
125
|
fiatPayment.rampsQuote = fiatQuote;
|
|
@@ -121,6 +132,7 @@ async function executeFiatQuotePipeline(request, options) {
|
|
|
121
132
|
adjustedAmountFiat: adjustedAmountFiat.toString(10),
|
|
122
133
|
amountFiat,
|
|
123
134
|
fiatQuote,
|
|
135
|
+
nativeRampsFee,
|
|
124
136
|
relayQuote,
|
|
125
137
|
}),
|
|
126
138
|
];
|
|
@@ -171,6 +183,7 @@ function buildRelayRequestFromAmountFiat({ amountFiat, fiatAsset, messenger, req
|
|
|
171
183
|
* @param params.adjustedAmountFiat - Fiat amount sent to ramps after adding relay fee estimate.
|
|
172
184
|
* @param params.amountFiat - User-entered fiat amount.
|
|
173
185
|
* @param params.fiatQuote - Selected ramps quote.
|
|
186
|
+
* @param params.nativeRampsFee - Native Transak fee to use in place of the aggregator ramps fee, or null.
|
|
174
187
|
* @param params.relayQuote - Estimated relay quote.
|
|
175
188
|
* @returns A single fiat strategy quote with split fee buckets.
|
|
176
189
|
* @remarks
|
|
@@ -185,8 +198,8 @@ function buildRelayRequestFromAmountFiat({ amountFiat, fiatAsset, messenger, req
|
|
|
185
198
|
* Consumed by UI transaction fee row and tooltip MetaMask fee.
|
|
186
199
|
* - `totals.total` should represent Amount + Transaction Fee using the totals pipeline.
|
|
187
200
|
*/
|
|
188
|
-
function combineQuotes({ adjustedAmountFiat, amountFiat, fiatQuote, relayQuote, }) {
|
|
189
|
-
const rampsProviderFee = getRampsProviderFee(fiatQuote);
|
|
201
|
+
function combineQuotes({ adjustedAmountFiat, amountFiat, fiatQuote, nativeRampsFee, relayQuote, }) {
|
|
202
|
+
const rampsProviderFee = nativeRampsFee ?? getRampsProviderFee(fiatQuote);
|
|
190
203
|
const totalProviderFee = new BigNumber(relayQuote.fees.provider.usd)
|
|
191
204
|
.plus(rampsProviderFee)
|
|
192
205
|
.toString(10);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CAAC,GAAG,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,oBAAoB,CAC3B,UAA2C;IAE3C,OAAO,IAAI,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;SAC/C,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,CAAC;SACvC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,cAAc,CAAC,EACtB,kBAAkB,EAClB,UAAU,GAIX;IACC,OAAO,IAAI,SAAS,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["import type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n NATIVE_TOKEN_ADDRESS,\n TransactionPayStrategy,\n} from '../../constants.js';\nimport { projectLogger } from '../../logger.js';\nimport type {\n PayStrategyGetQuotesRequest,\n QuoteRequest,\n TransactionFiatPayment,\n TransactionPayRequiredToken,\n TransactionPayQuote,\n} from '../../types.js';\nimport { getDirectMoneyMusdEnabled } from '../../utils/feature-flags.js';\nimport {\n buildCaipAssetType,\n computeRawFromFiatAmount,\n getTokenFiatRate,\n getTokenInfo,\n} from '../../utils/token.js';\nimport { getRelayQuotes } from '../relay/relay-quotes.js';\nimport type { RelayQuote } from '../relay/types.js';\nimport type { TransactionPayFiatAsset } from './constants.js';\nimport { getDirectMusdFiatQuote } from './fiat-direct-musd.js';\nimport type { FiatQuote } from './types.js';\nimport {\n deriveFiatAssetForFiatPayment,\n getRampsQuote,\n isMoneyAccountDepositTransaction,\n} from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-strategy');\n\ntype FiatQuotePipelineOptions = {\n amountFiat: string;\n fiatAsset: TransactionPayFiatAsset;\n fiatPaymentMethod: string;\n rampsWalletAddress: Hex;\n requiredTokens: TransactionPayRequiredToken[];\n};\n\n/**\n * Fetches MM Pay fiat strategy quotes using a relay-first estimation flow.\n *\n * When the direct-to-mUSD flag is enabled and the transaction is a Money\n * Account deposit, uses direct mUSD params (asset, wallet, recipient).\n * Otherwise, uses the standard ETH flow.\n *\n * @param request - Strategy quotes request.\n * @returns A single combined fiat strategy quote, or an empty array when inputs/quotes are unavailable.\n */\nexport async function getFiatQuotes(\n request: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<FiatQuote>[]> {\n const { messenger, transaction } = request;\n\n const state = messenger.call('TransactionPayController:getState');\n const transactionData = state.transactionData[transaction.id];\n const amountFiat = transactionData?.fiatPayment?.amountFiat;\n const requiredTokens = transactionData?.tokens ?? [];\n\n if (\n !amountFiat ||\n !request.fiatPaymentMethod ||\n requiredTokens.length !== 1\n ) {\n return [];\n }\n\n const useDirectMusd =\n getDirectMoneyMusdEnabled(messenger) &&\n isMoneyAccountDepositTransaction(transaction);\n\n if (useDirectMusd) {\n const requiredToken = requiredTokens[0];\n\n const directQuote = await getDirectMusdFiatQuote({\n amountFiat,\n fiatPaymentMethod: request.fiatPaymentMethod,\n messenger,\n moneyAccountAddress: transaction.txParams.from as Hex,\n requiredToken,\n transactionId: transaction.id,\n });\n\n return directQuote ? [directQuote] : [];\n }\n\n return executeFiatQuotePipeline(request, {\n amountFiat,\n fiatAsset: deriveFiatAssetForFiatPayment(transaction, messenger),\n fiatPaymentMethod: request.fiatPaymentMethod,\n rampsWalletAddress: request.from,\n requiredTokens,\n });\n}\n\nasync function executeFiatQuotePipeline(\n request: PayStrategyGetQuotesRequest,\n options: FiatQuotePipelineOptions,\n): Promise<TransactionPayQuote<FiatQuote>[]> {\n const {\n accountSupports7702,\n from: walletAddress,\n messenger,\n transaction,\n } = request;\n const {\n amountFiat,\n fiatAsset,\n fiatPaymentMethod,\n rampsWalletAddress,\n requiredTokens,\n } = options;\n const transactionId = transaction.id;\n\n try {\n const requiredToken = requiredTokens[0];\n\n const relayRequest = buildRelayRequestFromAmountFiat({\n amountFiat,\n fiatAsset,\n messenger,\n requiredToken,\n walletAddress,\n });\n\n if (!relayRequest) {\n throw new Error('Failed to build relay request from fiat amount');\n }\n\n const relayQuotes = await getRelayQuotes({\n accountSupports7702,\n from: walletAddress,\n messenger,\n requests: [relayRequest],\n transaction,\n });\n\n const relayQuote = relayQuotes[0];\n if (!relayQuote) {\n throw new Error('No relay quote available for fiat estimation');\n }\n\n const isSourceNative =\n fiatAsset.address.toLowerCase() === NATIVE_TOKEN_ADDRESS.toLowerCase();\n const gasDeductedFromSource =\n isSourceNative || relayQuote.fees.isSourceGasFeeToken === true;\n\n const relayTotalFeeUsd = gasDeductedFromSource\n ? getRelayTotalFeeUsd(relayQuote)\n : getNonGasRelayFeeUsd(relayQuote);\n const adjustedAmountFiat = new BigNumber(amountFiat).plus(relayTotalFeeUsd);\n\n if (\n !adjustedAmountFiat.isFinite() ||\n !adjustedAmountFiat.gt(0) ||\n !relayTotalFeeUsd.isFinite() ||\n !relayTotalFeeUsd.gte(0)\n ) {\n throw new Error('Invalid fiat amount after relay fee adjustment');\n }\n\n const adjustedAmount = adjustedAmountFiat.toNumber();\n\n if (!Number.isFinite(adjustedAmount) || adjustedAmount <= 0) {\n throw new Error('Invalid fiat amount after relay fee adjustment');\n }\n\n log('Fiat quote flow', {\n adjustedAmountFiat: adjustedAmountFiat.toString(10),\n amountFiat,\n rampsWalletAddress,\n relayTotalFeeUsd: relayTotalFeeUsd.toString(10),\n sourceAmountRaw: relayRequest.sourceTokenAmount,\n transactionId,\n });\n\n const fiatQuote = await getRampsQuote({\n adjustedAmount,\n fiatAsset,\n fiatPaymentMethod,\n messenger,\n walletAddress: rampsWalletAddress,\n });\n\n messenger.call('TransactionPayController:updateFiatPayment', {\n callback: (fiatPayment: TransactionFiatPayment) => {\n fiatPayment.rampsQuote = fiatQuote;\n fiatPayment.caipAssetId = buildCaipAssetType(\n fiatAsset.chainId,\n fiatAsset.address,\n );\n },\n transactionId,\n });\n\n return [\n combineQuotes({\n adjustedAmountFiat: adjustedAmountFiat.toString(10),\n amountFiat,\n fiatQuote,\n relayQuote,\n }),\n ];\n } catch (error) {\n log('Failed to fetch fiat quotes', { error, transactionId });\n\n messenger.call('TransactionPayController:updateFiatPayment', {\n callback: (fiatPayment) => {\n fiatPayment.rampsQuote = undefined;\n },\n transactionId,\n });\n }\n\n return [];\n}\n\nfunction buildRelayRequestFromAmountFiat({\n amountFiat,\n fiatAsset,\n messenger,\n requiredToken,\n walletAddress,\n}: {\n amountFiat: string;\n fiatAsset: {\n address: Hex;\n chainId: Hex;\n };\n messenger: PayStrategyGetQuotesRequest['messenger'];\n requiredToken: TransactionPayRequiredToken;\n walletAddress: Hex;\n}): QuoteRequest | undefined {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!sourceFiatRate) {\n return undefined;\n }\n\n const tokenInfo = getTokenInfo(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!tokenInfo) {\n return undefined;\n }\n\n const sourceAmountRaw = computeRawFromFiatAmount(\n amountFiat,\n tokenInfo.decimals,\n sourceFiatRate.usdRate,\n );\n\n if (!sourceAmountRaw) {\n return undefined;\n }\n\n return {\n from: walletAddress,\n // Force EXACT_INPUT mode: source amount is pre-calculated from the fiat\n // amount, so the relay should treat it as a fixed input rather than\n // computing it from the target.\n isPostQuote: true,\n sourceBalanceRaw: sourceAmountRaw,\n sourceChainId: fiatAsset.chainId,\n sourceTokenAddress: fiatAsset.address,\n sourceTokenAmount: sourceAmountRaw,\n targetAmountMinimum: requiredToken.amountRaw,\n targetChainId: requiredToken.chainId,\n targetTokenAddress: requiredToken.address,\n };\n}\n\n/**\n * Combines fiat and relay legs into a single MM Pay fiat strategy quote.\n *\n * @param params - Combined quote inputs.\n * @param params.adjustedAmountFiat - Fiat amount sent to ramps after adding relay fee estimate.\n * @param params.amountFiat - User-entered fiat amount.\n * @param params.fiatQuote - Selected ramps quote.\n * @param params.relayQuote - Estimated relay quote.\n * @returns A single fiat strategy quote with split fee buckets.\n * @remarks\n * Fee mapping contract for MM Pay Fiat strategy:\n * - `fees.provider`: Total provider fee (relay provider/swap fee + ramps provider/network fee).\n * Consumed by UI transaction fee row and tooltip provider fee.\n * - `fees.providerFiat`: Fiat on-ramp provider fees only (`providerFee + networkFee` from ramps quote).\n * Optional breakdown; client can derive relay portion via `provider - providerFiat`.\n * - `fees.sourceNetwork` / `fees.targetNetwork`: Relay settlement network fees.\n * Consumed by UI transaction fee row and tooltip network fee.\n * - `fees.metaMask`: MM Pay fee (currently 100 bps over `amountFiat + adjustedAmountFiat`).\n * Consumed by UI transaction fee row and tooltip MetaMask fee.\n * - `totals.total` should represent Amount + Transaction Fee using the totals pipeline.\n */\nfunction combineQuotes({\n adjustedAmountFiat,\n amountFiat,\n fiatQuote,\n relayQuote,\n}: {\n adjustedAmountFiat: string;\n amountFiat: string;\n fiatQuote: RampsQuote;\n relayQuote: TransactionPayQuote<RelayQuote>;\n}): TransactionPayQuote<FiatQuote> {\n const rampsProviderFee = getRampsProviderFee(fiatQuote);\n const totalProviderFee = new BigNumber(relayQuote.fees.provider.usd)\n .plus(rampsProviderFee)\n .toString(10);\n const rampsProviderFeeStr = rampsProviderFee.toString(10);\n const metaMaskFee = getMetaMaskFee({\n adjustedAmountFiat,\n amountFiat,\n }).toString(10);\n\n return {\n ...relayQuote,\n fees: {\n ...relayQuote.fees,\n metaMask: {\n fiat: metaMaskFee,\n usd: metaMaskFee,\n },\n provider: {\n fiat: totalProviderFee,\n usd: totalProviderFee,\n },\n providerFiat: {\n fiat: rampsProviderFeeStr,\n usd: rampsProviderFeeStr,\n },\n },\n original: {\n rampsQuote: fiatQuote,\n relayQuote: relayQuote.original,\n },\n strategy: TransactionPayStrategy.Fiat,\n };\n}\n\n/**\n * Ramps providers handle network gas fees themselves but report them separately\n * as `networkFee` alongside their `providerFee`. We combine both into a single\n * ramps provider fee for the `providerFiat` breakdown.\n *\n * @param fiatQuote - The ramps quote containing provider and network fees.\n * @returns Combined ramps provider fee as a BigNumber.\n */\nfunction getRampsProviderFee(fiatQuote: RampsQuote): BigNumber {\n return new BigNumber(fiatQuote.quote.providerFee ?? 0).plus(\n fiatQuote.quote.networkFee ?? 0,\n );\n}\n\nfunction getRelayTotalFeeUsd(\n relayQuote: TransactionPayQuote<RelayQuote>,\n): BigNumber {\n return new BigNumber(relayQuote.fees.provider.usd)\n .plus(relayQuote.fees.sourceNetwork.estimate.usd)\n .plus(relayQuote.fees.targetNetwork.usd)\n .plus(relayQuote.fees.metaMask.usd);\n}\n\nfunction getNonGasRelayFeeUsd(\n relayQuote: TransactionPayQuote<RelayQuote>,\n): BigNumber {\n return new BigNumber(relayQuote.fees.provider.usd)\n .plus(relayQuote.fees.targetNetwork.usd)\n .plus(relayQuote.fees.metaMask.usd);\n}\n\nfunction getMetaMaskFee({\n adjustedAmountFiat,\n amountFiat,\n}: {\n adjustedAmountFiat: BigNumber.Value;\n amountFiat: BigNumber.Value;\n}): BigNumber {\n return new BigNumber(amountFiat).plus(adjustedAmountFiat).dividedBy(100);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"fiat-quotes.js","sourceRoot":"","sources":["../../../src/strategy/fiat/fiat-quotes.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,kBAAkB,EAAE,MAAM,iBAAiB,CAAC;AACrD,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EACL,oBAAoB,EACpB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAQhD,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAC;AACzE,OAAO,EACL,kBAAkB,EAClB,wBAAwB,EACxB,gBAAgB,EAChB,YAAY,GACb,MAAM,sBAAsB,CAAC;AA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,CAAC,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACxC,CAAC;AAED,SAAS,cAAc,CAAC,EACtB,kBAAkB,EAClB,UAAU,GAIX;IACC,OAAO,IAAI,SAAS,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["import type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n NATIVE_TOKEN_ADDRESS,\n TransactionPayStrategy,\n} from '../../constants.js';\nimport { projectLogger } from '../../logger.js';\nimport type {\n PayStrategyGetQuotesRequest,\n QuoteRequest,\n TransactionFiatPayment,\n TransactionPayRequiredToken,\n TransactionPayQuote,\n} from '../../types.js';\nimport { getDirectMoneyMusdEnabled } from '../../utils/feature-flags.js';\nimport {\n buildCaipAssetType,\n computeRawFromFiatAmount,\n getTokenFiatRate,\n getTokenInfo,\n} from '../../utils/token.js';\nimport { getRelayQuotes } from '../relay/relay-quotes.js';\nimport type { RelayQuote } from '../relay/types.js';\nimport type { TransactionPayFiatAsset } from './constants.js';\nimport { getDirectMusdFiatQuote } from './fiat-direct-musd.js';\nimport type { FiatQuote } from './types.js';\nimport {\n deriveFiatAssetForFiatPayment,\n getNativeTransakRampsFee,\n getRampsQuote,\n isMoneyAccountDepositTransaction,\n} from './utils.js';\n\nconst log = createModuleLogger(projectLogger, 'fiat-strategy');\n\ntype FiatQuotePipelineOptions = {\n amountFiat: string;\n fiatAsset: TransactionPayFiatAsset;\n fiatPaymentMethod: string;\n rampsWalletAddress: Hex;\n requiredTokens: TransactionPayRequiredToken[];\n};\n\n/**\n * Fetches MM Pay fiat strategy quotes using a relay-first estimation flow.\n *\n * When the direct-to-mUSD flag is enabled and the transaction is a Money\n * Account deposit, uses direct mUSD params (asset, wallet, recipient).\n * Otherwise, uses the standard ETH flow.\n *\n * @param request - Strategy quotes request.\n * @returns A single combined fiat strategy quote, or an empty array when inputs/quotes are unavailable.\n */\nexport async function getFiatQuotes(\n request: PayStrategyGetQuotesRequest,\n): Promise<TransactionPayQuote<FiatQuote>[]> {\n const { messenger, transaction } = request;\n\n const state = messenger.call('TransactionPayController:getState');\n const transactionData = state.transactionData[transaction.id];\n const amountFiat = transactionData?.fiatPayment?.amountFiat;\n const requiredTokens = transactionData?.tokens ?? [];\n\n if (\n !amountFiat ||\n !request.fiatPaymentMethod ||\n requiredTokens.length !== 1\n ) {\n return [];\n }\n\n const useDirectMusd =\n getDirectMoneyMusdEnabled(messenger) &&\n isMoneyAccountDepositTransaction(transaction);\n\n if (useDirectMusd) {\n const requiredToken = requiredTokens[0];\n\n const directQuote = await getDirectMusdFiatQuote({\n amountFiat,\n fiatPaymentMethod: request.fiatPaymentMethod,\n messenger,\n moneyAccountAddress: transaction.txParams.from as Hex,\n requiredToken,\n transactionId: transaction.id,\n });\n\n return directQuote ? [directQuote] : [];\n }\n\n return executeFiatQuotePipeline(request, {\n amountFiat,\n fiatAsset: deriveFiatAssetForFiatPayment(transaction, messenger),\n fiatPaymentMethod: request.fiatPaymentMethod,\n rampsWalletAddress: request.from,\n requiredTokens,\n });\n}\n\nasync function executeFiatQuotePipeline(\n request: PayStrategyGetQuotesRequest,\n options: FiatQuotePipelineOptions,\n): Promise<TransactionPayQuote<FiatQuote>[]> {\n const {\n accountSupports7702,\n from: walletAddress,\n messenger,\n transaction,\n } = request;\n const {\n amountFiat,\n fiatAsset,\n fiatPaymentMethod,\n rampsWalletAddress,\n requiredTokens,\n } = options;\n const transactionId = transaction.id;\n\n try {\n const requiredToken = requiredTokens[0];\n\n const relayRequest = buildRelayRequestFromAmountFiat({\n amountFiat,\n fiatAsset,\n messenger,\n requiredToken,\n walletAddress,\n });\n\n if (!relayRequest) {\n throw new Error('Failed to build relay request from fiat amount');\n }\n\n const relayQuotes = await getRelayQuotes({\n accountSupports7702,\n from: walletAddress,\n messenger,\n requests: [relayRequest],\n transaction,\n });\n\n const relayQuote = relayQuotes[0];\n if (!relayQuote) {\n throw new Error('No relay quote available for fiat estimation');\n }\n\n const isSourceNative =\n fiatAsset.address.toLowerCase() === NATIVE_TOKEN_ADDRESS.toLowerCase();\n const gasDeductedFromSource =\n isSourceNative || relayQuote.fees.isSourceGasFeeToken === true;\n\n const relayTotalFeeUsd = gasDeductedFromSource\n ? getRelayTotalFeeUsd(relayQuote)\n : getNonGasRelayFeeUsd(relayQuote);\n const adjustedAmountFiat = new BigNumber(amountFiat).plus(relayTotalFeeUsd);\n\n if (\n !adjustedAmountFiat.isFinite() ||\n !adjustedAmountFiat.gt(0) ||\n !relayTotalFeeUsd.isFinite() ||\n !relayTotalFeeUsd.gte(0)\n ) {\n throw new Error('Invalid fiat amount after relay fee adjustment');\n }\n\n const adjustedAmount = adjustedAmountFiat.toNumber();\n\n if (!Number.isFinite(adjustedAmount) || adjustedAmount <= 0) {\n throw new Error('Invalid fiat amount after relay fee adjustment');\n }\n\n log('Fiat quote flow', {\n adjustedAmountFiat: adjustedAmountFiat.toString(10),\n amountFiat,\n rampsWalletAddress,\n relayTotalFeeUsd: relayTotalFeeUsd.toString(10),\n sourceAmountRaw: relayRequest.sourceTokenAmount,\n transactionId,\n });\n\n const fiatQuote = await getRampsQuote({\n adjustedAmount,\n fiatAsset,\n fiatPaymentMethod,\n messenger,\n walletAddress: rampsWalletAddress,\n });\n\n // When Transak Native is the resolved provider, prefer its own quote's fee\n // so the estimate matches what Transak Native will charge. The relay path\n // stays fee-on-top, so request the native quote in the same mode.\n const nativeRampsFee = await getNativeTransakRampsFee({\n adjustedAmount,\n fiatAsset,\n fiatPaymentMethod,\n fiatQuote,\n isFeeExcludedFromFiat: true,\n messenger,\n });\n\n messenger.call('TransactionPayController:updateFiatPayment', {\n callback: (fiatPayment: TransactionFiatPayment) => {\n fiatPayment.rampsQuote = fiatQuote;\n fiatPayment.caipAssetId = buildCaipAssetType(\n fiatAsset.chainId,\n fiatAsset.address,\n );\n },\n transactionId,\n });\n\n return [\n combineQuotes({\n adjustedAmountFiat: adjustedAmountFiat.toString(10),\n amountFiat,\n fiatQuote,\n nativeRampsFee,\n relayQuote,\n }),\n ];\n } catch (error) {\n log('Failed to fetch fiat quotes', { error, transactionId });\n\n messenger.call('TransactionPayController:updateFiatPayment', {\n callback: (fiatPayment) => {\n fiatPayment.rampsQuote = undefined;\n },\n transactionId,\n });\n }\n\n return [];\n}\n\nfunction buildRelayRequestFromAmountFiat({\n amountFiat,\n fiatAsset,\n messenger,\n requiredToken,\n walletAddress,\n}: {\n amountFiat: string;\n fiatAsset: {\n address: Hex;\n chainId: Hex;\n };\n messenger: PayStrategyGetQuotesRequest['messenger'];\n requiredToken: TransactionPayRequiredToken;\n walletAddress: Hex;\n}): QuoteRequest | undefined {\n const sourceFiatRate = getTokenFiatRate(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!sourceFiatRate) {\n return undefined;\n }\n\n const tokenInfo = getTokenInfo(\n messenger,\n fiatAsset.address,\n fiatAsset.chainId,\n );\n\n if (!tokenInfo) {\n return undefined;\n }\n\n const sourceAmountRaw = computeRawFromFiatAmount(\n amountFiat,\n tokenInfo.decimals,\n sourceFiatRate.usdRate,\n );\n\n if (!sourceAmountRaw) {\n return undefined;\n }\n\n return {\n from: walletAddress,\n // Force EXACT_INPUT mode: source amount is pre-calculated from the fiat\n // amount, so the relay should treat it as a fixed input rather than\n // computing it from the target.\n isPostQuote: true,\n sourceBalanceRaw: sourceAmountRaw,\n sourceChainId: fiatAsset.chainId,\n sourceTokenAddress: fiatAsset.address,\n sourceTokenAmount: sourceAmountRaw,\n targetAmountMinimum: requiredToken.amountRaw,\n targetChainId: requiredToken.chainId,\n targetTokenAddress: requiredToken.address,\n };\n}\n\n/**\n * Combines fiat and relay legs into a single MM Pay fiat strategy quote.\n *\n * @param params - Combined quote inputs.\n * @param params.adjustedAmountFiat - Fiat amount sent to ramps after adding relay fee estimate.\n * @param params.amountFiat - User-entered fiat amount.\n * @param params.fiatQuote - Selected ramps quote.\n * @param params.nativeRampsFee - Native Transak fee to use in place of the aggregator ramps fee, or null.\n * @param params.relayQuote - Estimated relay quote.\n * @returns A single fiat strategy quote with split fee buckets.\n * @remarks\n * Fee mapping contract for MM Pay Fiat strategy:\n * - `fees.provider`: Total provider fee (relay provider/swap fee + ramps provider/network fee).\n * Consumed by UI transaction fee row and tooltip provider fee.\n * - `fees.providerFiat`: Fiat on-ramp provider fees only (`providerFee + networkFee` from ramps quote).\n * Optional breakdown; client can derive relay portion via `provider - providerFiat`.\n * - `fees.sourceNetwork` / `fees.targetNetwork`: Relay settlement network fees.\n * Consumed by UI transaction fee row and tooltip network fee.\n * - `fees.metaMask`: MM Pay fee (currently 100 bps over `amountFiat + adjustedAmountFiat`).\n * Consumed by UI transaction fee row and tooltip MetaMask fee.\n * - `totals.total` should represent Amount + Transaction Fee using the totals pipeline.\n */\nfunction combineQuotes({\n adjustedAmountFiat,\n amountFiat,\n fiatQuote,\n nativeRampsFee,\n relayQuote,\n}: {\n adjustedAmountFiat: string;\n amountFiat: string;\n fiatQuote: RampsQuote;\n nativeRampsFee: BigNumber | null;\n relayQuote: TransactionPayQuote<RelayQuote>;\n}): TransactionPayQuote<FiatQuote> {\n const rampsProviderFee = nativeRampsFee ?? getRampsProviderFee(fiatQuote);\n const totalProviderFee = new BigNumber(relayQuote.fees.provider.usd)\n .plus(rampsProviderFee)\n .toString(10);\n const rampsProviderFeeStr = rampsProviderFee.toString(10);\n const metaMaskFee = getMetaMaskFee({\n adjustedAmountFiat,\n amountFiat,\n }).toString(10);\n\n return {\n ...relayQuote,\n fees: {\n ...relayQuote.fees,\n metaMask: {\n fiat: metaMaskFee,\n usd: metaMaskFee,\n },\n provider: {\n fiat: totalProviderFee,\n usd: totalProviderFee,\n },\n providerFiat: {\n fiat: rampsProviderFeeStr,\n usd: rampsProviderFeeStr,\n },\n },\n original: {\n rampsQuote: fiatQuote,\n relayQuote: relayQuote.original,\n },\n strategy: TransactionPayStrategy.Fiat,\n };\n}\n\n/**\n * Ramps providers handle network gas fees themselves but report them separately\n * as `networkFee` alongside their `providerFee`. We combine both into a single\n * ramps provider fee for the `providerFiat` breakdown.\n *\n * @param fiatQuote - The ramps quote containing provider and network fees.\n * @returns Combined ramps provider fee as a BigNumber.\n */\nfunction getRampsProviderFee(fiatQuote: RampsQuote): BigNumber {\n return new BigNumber(fiatQuote.quote.providerFee ?? 0).plus(\n fiatQuote.quote.networkFee ?? 0,\n );\n}\n\nfunction getRelayTotalFeeUsd(\n relayQuote: TransactionPayQuote<RelayQuote>,\n): BigNumber {\n return new BigNumber(relayQuote.fees.provider.usd)\n .plus(relayQuote.fees.sourceNetwork.estimate.usd)\n .plus(relayQuote.fees.targetNetwork.usd)\n .plus(relayQuote.fees.metaMask.usd);\n}\n\nfunction getNonGasRelayFeeUsd(\n relayQuote: TransactionPayQuote<RelayQuote>,\n): BigNumber {\n return new BigNumber(relayQuote.fees.provider.usd)\n .plus(relayQuote.fees.targetNetwork.usd)\n .plus(relayQuote.fees.metaMask.usd);\n}\n\nfunction getMetaMaskFee({\n adjustedAmountFiat,\n amountFiat,\n}: {\n adjustedAmountFiat: BigNumber.Value;\n amountFiat: BigNumber.Value;\n}): BigNumber {\n return new BigNumber(amountFiat).plus(adjustedAmountFiat).dividedBy(100);\n}\n"]}
|
|
@@ -2,6 +2,7 @@ import type { Quote as RampsQuote, RampsOrder, RampsOrderCryptoCurrency } from '
|
|
|
2
2
|
import type { TransactionMeta } from '@metamask/transaction-controller';
|
|
3
3
|
import { TransactionType } from '@metamask/transaction-controller';
|
|
4
4
|
import type { Hex } from '@metamask/utils';
|
|
5
|
+
import { BigNumber } from 'bignumber.js';
|
|
5
6
|
import type { TransactionPayControllerMessenger } from '../../types.js';
|
|
6
7
|
import type { RelayQuote } from '../relay/types.js';
|
|
7
8
|
import type { TransactionPayFiatAsset } from './constants.js';
|
|
@@ -145,4 +146,34 @@ export declare function validateRelayRateDrift({ originalQuote, discoveryQuote,
|
|
|
145
146
|
* @returns The provider code, or `null` if the format is invalid.
|
|
146
147
|
*/
|
|
147
148
|
export declare function extractProviderCode(provider: string | undefined): string | null;
|
|
149
|
+
/**
|
|
150
|
+
* When the resolved ramps provider is Transak Native, fetches the native
|
|
151
|
+
* Transak buy quote and returns its total fee so the estimate matches what
|
|
152
|
+
* Transak Native actually charges.
|
|
153
|
+
*
|
|
154
|
+
* The native lookup (`/api/v2/lookup/quotes`) is an unauthenticated, API-key
|
|
155
|
+
* only call, so it is safe to run at estimate time before the user signs in to
|
|
156
|
+
* Transak. Returns `null` when the provider is not Transak Native, or when the
|
|
157
|
+
* native lookup fails or returns an unusable fee, so the caller falls back to
|
|
158
|
+
* the aggregator quote's fee.
|
|
159
|
+
*
|
|
160
|
+
* @param options - Native fee options.
|
|
161
|
+
* @param options.adjustedAmount - Fiat amount (USD) sent to ramps.
|
|
162
|
+
* @param options.fiatAsset - Fiat asset being bought.
|
|
163
|
+
* @param options.fiatPaymentMethod - Selected fiat payment method.
|
|
164
|
+
* @param options.fiatQuote - The resolved aggregator quote (used to detect native).
|
|
165
|
+
* @param options.isFeeExcludedFromFiat - Whether Transak adds its fee on top of
|
|
166
|
+
* the fiat amount (`true`) or carves it out of the amount (`false`). Must mirror
|
|
167
|
+
* the eventual checkout mode so the estimate equals the charge.
|
|
168
|
+
* @param options.messenger - Controller messenger.
|
|
169
|
+
* @returns The native total fee as a BigNumber, or `null` to use the aggregator fee.
|
|
170
|
+
*/
|
|
171
|
+
export declare function getNativeTransakRampsFee({ adjustedAmount, fiatAsset, fiatPaymentMethod, fiatQuote, isFeeExcludedFromFiat, messenger, }: {
|
|
172
|
+
adjustedAmount: number;
|
|
173
|
+
fiatAsset: TransactionPayFiatAsset;
|
|
174
|
+
fiatPaymentMethod: string;
|
|
175
|
+
fiatQuote: RampsQuote;
|
|
176
|
+
isFeeExcludedFromFiat: boolean;
|
|
177
|
+
messenger: TransactionPayControllerMessenger;
|
|
178
|
+
}): Promise<BigNumber | null>;
|
|
148
179
|
//# sourceMappingURL=utils.d.ts.map
|
|
@@ -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;
|
|
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;AAE3C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAGzC,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,GAC9B,eAAe,GA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AAY,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;AAWD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAsB,wBAAwB,CAAC,EAC7C,cAAc,EACd,SAAS,EACT,iBAAiB,EACjB,SAAS,EACT,qBAAqB,EACrB,SAAS,GACV,EAAE;IACD,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,uBAAuB,CAAC;IACnC,iBAAiB,EAAE,MAAM,CAAC;IAC1B,SAAS,EAAE,UAAU,CAAC;IACtB,qBAAqB,EAAE,OAAO,CAAC;IAC/B,SAAS,EAAE,iCAAiC,CAAC;CAC9C,GAAG,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC,CAsC5B"}
|
|
@@ -234,4 +234,57 @@ export function extractProviderCode(provider) {
|
|
|
234
234
|
}
|
|
235
235
|
return parts.length === 1 ? parts[0] : null;
|
|
236
236
|
}
|
|
237
|
+
/**
|
|
238
|
+
* Provider codes that identify Transak's native (non-aggregator) integration.
|
|
239
|
+
* Matches the codes emitted by `TransakService` for production and staging.
|
|
240
|
+
*/
|
|
241
|
+
const NATIVE_TRANSAK_PROVIDER_CODES = [
|
|
242
|
+
'transak-native',
|
|
243
|
+
'transak-native-staging',
|
|
244
|
+
];
|
|
245
|
+
/**
|
|
246
|
+
* When the resolved ramps provider is Transak Native, fetches the native
|
|
247
|
+
* Transak buy quote and returns its total fee so the estimate matches what
|
|
248
|
+
* Transak Native actually charges.
|
|
249
|
+
*
|
|
250
|
+
* The native lookup (`/api/v2/lookup/quotes`) is an unauthenticated, API-key
|
|
251
|
+
* only call, so it is safe to run at estimate time before the user signs in to
|
|
252
|
+
* Transak. Returns `null` when the provider is not Transak Native, or when the
|
|
253
|
+
* native lookup fails or returns an unusable fee, so the caller falls back to
|
|
254
|
+
* the aggregator quote's fee.
|
|
255
|
+
*
|
|
256
|
+
* @param options - Native fee options.
|
|
257
|
+
* @param options.adjustedAmount - Fiat amount (USD) sent to ramps.
|
|
258
|
+
* @param options.fiatAsset - Fiat asset being bought.
|
|
259
|
+
* @param options.fiatPaymentMethod - Selected fiat payment method.
|
|
260
|
+
* @param options.fiatQuote - The resolved aggregator quote (used to detect native).
|
|
261
|
+
* @param options.isFeeExcludedFromFiat - Whether Transak adds its fee on top of
|
|
262
|
+
* the fiat amount (`true`) or carves it out of the amount (`false`). Must mirror
|
|
263
|
+
* the eventual checkout mode so the estimate equals the charge.
|
|
264
|
+
* @param options.messenger - Controller messenger.
|
|
265
|
+
* @returns The native total fee as a BigNumber, or `null` to use the aggregator fee.
|
|
266
|
+
*/
|
|
267
|
+
export async function getNativeTransakRampsFee({ adjustedAmount, fiatAsset, fiatPaymentMethod, fiatQuote, isFeeExcludedFromFiat, messenger, }) {
|
|
268
|
+
const providerCode = extractProviderCode(fiatQuote.provider);
|
|
269
|
+
if (!providerCode || !NATIVE_TRANSAK_PROVIDER_CODES.includes(providerCode)) {
|
|
270
|
+
return null;
|
|
271
|
+
}
|
|
272
|
+
try {
|
|
273
|
+
const assetId = buildCaipAssetType(fiatAsset.chainId, fiatAsset.address);
|
|
274
|
+
const network = assetId.split('/')[0];
|
|
275
|
+
const nativeQuote = await messenger.call('TransakService:getBuyQuote', DEFAULT_FIAT_CURRENCY, assetId, network, fiatPaymentMethod, String(adjustedAmount), isFeeExcludedFromFiat);
|
|
276
|
+
const fee = new BigNumber(nativeQuote.totalFee ?? NaN);
|
|
277
|
+
if (!fee.isFinite() || fee.isLessThan(0)) {
|
|
278
|
+
log('Native Transak quote returned an unusable fee; using aggregator fee', {
|
|
279
|
+
totalFee: nativeQuote.totalFee,
|
|
280
|
+
});
|
|
281
|
+
return null;
|
|
282
|
+
}
|
|
283
|
+
return fee;
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
log('Native Transak fee fetch failed; using aggregator fee', { error });
|
|
287
|
+
return null;
|
|
288
|
+
}
|
|
289
|
+
}
|
|
237
290
|
//# sourceMappingURL=utils.js.map
|
|
@@ -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,mBAAmB,CAAC,SAAS,CAAC,CAAC;IACpD,MAAM,MAAM,GAAG,sBAAsB,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;IAEjE,OAAO,8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amask/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 first matching Ramps quote for a fiat asset and payment method.\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 first matching Ramps quote.\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 quotes = await messenger.call('RampsController:getQuotes', {\n amount: adjustedAmount,\n assetId: buildCaipAssetType(fiatAsset.chainId, fiatAsset.address),\n autoSelectProvider: true,\n fiat: DEFAULT_FIAT_CURRENCY,\n paymentMethods: [fiatPaymentMethod],\n restrictToKnownOrNativeProviders: true,\n walletAddress,\n });\n\n log('Fetched ramps quotes', {\n quotesCount: quotes.success?.length ?? 0,\n });\n\n const quote = quotes.success?.[0];\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,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,mBAAmB,CAAC,SAAS,CAAC,CAAC;IACpD,MAAM,MAAM,GAAG,sBAAsB,CAAC,WAAW,EAAE,YAAY,CAAC,CAAC;IAEjE,OAAO,8BAA8B,CAAC,SAAS,EAAE,MAAM,CAAC,CAAC;AAC3D,CAAC;AAED;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{ 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 first matching Ramps quote for a fiat asset and payment method.\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 first matching Ramps quote.\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 quotes = await messenger.call('RampsController:getQuotes', {\n amount: adjustedAmount,\n assetId: buildCaipAssetType(fiatAsset.chainId, fiatAsset.address),\n autoSelectProvider: true,\n fiat: DEFAULT_FIAT_CURRENCY,\n paymentMethods: [fiatPaymentMethod],\n restrictToKnownOrNativeProviders: true,\n walletAddress,\n });\n\n log('Fetched ramps quotes', {\n quotesCount: quotes.success?.length ?? 0,\n });\n\n const quote = quotes.success?.[0];\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\n/**\n * Provider codes that identify Transak's native (non-aggregator) integration.\n * Matches the codes emitted by `TransakService` for production and staging.\n */\nconst NATIVE_TRANSAK_PROVIDER_CODES = [\n 'transak-native',\n 'transak-native-staging',\n];\n\n/**\n * When the resolved ramps provider is Transak Native, fetches the native\n * Transak buy quote and returns its total fee so the estimate matches what\n * Transak Native actually charges.\n *\n * The native lookup (`/api/v2/lookup/quotes`) is an unauthenticated, API-key\n * only call, so it is safe to run at estimate time before the user signs in to\n * Transak. Returns `null` when the provider is not Transak Native, or when the\n * native lookup fails or returns an unusable fee, so the caller falls back to\n * the aggregator quote's fee.\n *\n * @param options - Native fee options.\n * @param options.adjustedAmount - Fiat amount (USD) sent to ramps.\n * @param options.fiatAsset - Fiat asset being bought.\n * @param options.fiatPaymentMethod - Selected fiat payment method.\n * @param options.fiatQuote - The resolved aggregator quote (used to detect native).\n * @param options.isFeeExcludedFromFiat - Whether Transak adds its fee on top of\n * the fiat amount (`true`) or carves it out of the amount (`false`). Must mirror\n * the eventual checkout mode so the estimate equals the charge.\n * @param options.messenger - Controller messenger.\n * @returns The native total fee as a BigNumber, or `null` to use the aggregator fee.\n */\nexport async function getNativeTransakRampsFee({\n adjustedAmount,\n fiatAsset,\n fiatPaymentMethod,\n fiatQuote,\n isFeeExcludedFromFiat,\n messenger,\n}: {\n adjustedAmount: number;\n fiatAsset: TransactionPayFiatAsset;\n fiatPaymentMethod: string;\n fiatQuote: RampsQuote;\n isFeeExcludedFromFiat: boolean;\n messenger: TransactionPayControllerMessenger;\n}): Promise<BigNumber | null> {\n const providerCode = extractProviderCode(fiatQuote.provider);\n\n if (!providerCode || !NATIVE_TRANSAK_PROVIDER_CODES.includes(providerCode)) {\n return null;\n }\n\n try {\n const assetId = buildCaipAssetType(fiatAsset.chainId, fiatAsset.address);\n const network = assetId.split('/')[0];\n\n const nativeQuote = await messenger.call(\n 'TransakService:getBuyQuote',\n DEFAULT_FIAT_CURRENCY,\n assetId,\n network,\n fiatPaymentMethod,\n String(adjustedAmount),\n isFeeExcludedFromFiat,\n );\n\n const fee = new BigNumber(nativeQuote.totalFee ?? NaN);\n\n if (!fee.isFinite() || fee.isLessThan(0)) {\n log(\n 'Native Transak quote returned an unusable fee; using aggregator fee',\n {\n totalFee: nativeQuote.totalFee,\n },\n );\n return null;\n }\n\n return fee;\n } catch (error) {\n log('Native Transak fee fetch failed; using aggregator fee', { error });\n return null;\n }\n}\n"]}
|
package/dist/types.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ import type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metam
|
|
|
13
13
|
import type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';
|
|
14
14
|
import type { NetworkControllerGetNetworkConfigurationByChainIdAction } from '@metamask/network-controller';
|
|
15
15
|
import type { Quote as RampsQuote } from '@metamask/ramps-controller';
|
|
16
|
-
import type { RampsControllerGetOrderAction, RampsControllerGetQuotesAction } from '@metamask/ramps-controller';
|
|
16
|
+
import type { RampsControllerGetOrderAction, RampsControllerGetQuotesAction, RampsControllerTransakGetBuyQuoteAction, TransakServiceGetBuyQuoteAction } from '@metamask/ramps-controller';
|
|
17
17
|
import type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';
|
|
18
18
|
import type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';
|
|
19
19
|
import type { AuthorizationList, TransactionControllerAddTransactionBatchAction, TransactionControllerEstimateGasAction, TransactionControllerEstimateGasBatchAction, TransactionControllerUnapprovedTransactionAddedEvent } from '@metamask/transaction-controller';
|
|
@@ -22,7 +22,7 @@ import type { Hex, Json } from '@metamask/utils';
|
|
|
22
22
|
import type { Draft } from 'immer';
|
|
23
23
|
import type { CONTROLLER_NAME, PaymentOverride, TransactionPayStrategy } from './constants.js';
|
|
24
24
|
import type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';
|
|
25
|
-
export type AllowedActions = AccountTrackerControllerGetStateAction | AssetsControllerGetStateForTransactionPayAction | CurrencyRateControllerGetStateAction | GetGasFeeState | KeyringControllerGetStateAction | KeyringControllerSignTypedMessageAction | NetworkControllerFindNetworkClientIdByChainIdAction | NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetNetworkConfigurationByChainIdAction | RampsControllerGetOrderAction | RampsControllerGetQuotesAction | RemoteFeatureFlagControllerGetStateAction | TokenBalancesControllerGetStateAction | TokenRatesControllerGetStateAction | TokensControllerGetStateAction | SentinelApiServiceActions | TransactionControllerAddTransactionAction | TransactionControllerAddTransactionBatchAction | TransactionControllerEstimateGasAction | TransactionControllerEstimateGasBatchAction | TransactionControllerGetGasFeeTokensAction | TransactionControllerGetStateAction | TransactionControllerUpdateTransactionAction;
|
|
25
|
+
export type AllowedActions = AccountTrackerControllerGetStateAction | AssetsControllerGetStateForTransactionPayAction | CurrencyRateControllerGetStateAction | GetGasFeeState | KeyringControllerGetStateAction | KeyringControllerSignTypedMessageAction | NetworkControllerFindNetworkClientIdByChainIdAction | NetworkControllerGetNetworkClientByIdAction | NetworkControllerGetNetworkConfigurationByChainIdAction | RampsControllerGetOrderAction | RampsControllerGetQuotesAction | RampsControllerTransakGetBuyQuoteAction | TransakServiceGetBuyQuoteAction | RemoteFeatureFlagControllerGetStateAction | TokenBalancesControllerGetStateAction | TokenRatesControllerGetStateAction | TokensControllerGetStateAction | SentinelApiServiceActions | TransactionControllerAddTransactionAction | TransactionControllerAddTransactionBatchAction | TransactionControllerEstimateGasAction | TransactionControllerEstimateGasBatchAction | TransactionControllerGetGasFeeTokensAction | TransactionControllerGetStateAction | TransactionControllerUpdateTransactionAction;
|
|
26
26
|
export type AllowedEvents = AssetsControllerStateChangeEvent | CurrencyRateStateChange | KeyringControllerUnlockEvent | TokenRatesControllerStateChangeEvent | TokensControllerStateChangeEvent | TransactionControllerStateChangeEvent | TransactionControllerUnapprovedTransactionAddedEvent;
|
|
27
27
|
export type TransactionPayControllerGetStateAction = ControllerGetStateAction<typeof CONTROLLER_NAME, TransactionPayControllerState>;
|
|
28
28
|
/** Configurable properties of a transaction. */
|
|
@@ -444,6 +444,8 @@ export type TransactionPayQuote<OriginalQuote> = {
|
|
|
444
444
|
fees: TransactionPayFees;
|
|
445
445
|
/** Whether fees are subtracted from the destination amount, meaning the input amount is static. */
|
|
446
446
|
isInputBased?: boolean;
|
|
447
|
+
/** Whether the reported fees are already included in the source amount. */
|
|
448
|
+
areFeesIncludedInSourceAmount?: boolean;
|
|
447
449
|
/** Raw quote data returned by the provider. */
|
|
448
450
|
original: OriginalQuote;
|
|
449
451
|
/** Associated quote request. */
|
package/dist/types.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,+CAA+C,EAC/C,gCAAgC,EACjC,MAAM,6BAA6B,CAAC;AACrC,OAAO,KAAK,EACV,oCAAoC,EACpC,uBAAuB,EACvB,qCAAqC,EACtC,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,kCAAkC,EAAE,MAAM,8BAA8B,CAAC;AACvF,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,8BAA8B,CAAC;AACzF,OAAO,KAAK,EACV,8BAA8B,EAC9B,gCAAgC,EACjC,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,sCAAsC,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,KAAK,EAAE,0BA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b,EAAE;IACD,WAAW,EAAE,eAAe,CAAC;IAC7B,YAAY,CAAC,EAAE,OAAO,CAAC;CACxB,KAAK,OAAO,CAAC;IACZ,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,IAAI,EAAE,GAAG,CAAC;IACV,EAAE,EAAE,GAAG,CAAC;IACR,KAAK,EAAE,GAAG,CAAC;CACZ,CAAC,CAAC;AAEH,qEAAqE;AACrE,MAAM,MAAM,mBAAmB,GAAG;IAChC,qEAAqE;IACrE,uBAAuB,EAAE,CAAC,MAAM,EAAE;QAAE,GAAG,EAAE,GAAG,CAAA;KAAE,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IAEhE,4EAA4E;IAC5E,wBAAwB,EAAE,CAAC,MAAM,EAAE;QACjC,GAAG,EAAE,GAAG,CAAC;QACT,aAAa,EAAE,GAAG,CAAC;QACnB,KAAK,EAAE;YAAE,MAAM,EAAE,GAAG,CAAC;YAAC,IAAI,EAAE,GAAG,CAAC;YAAC,KAAK,EAAE,MAAM,CAAA;SAAE,EAAE,CAAC;KACpD,KAAK,OAAO,CAAC;QAAE,UAAU,EAAE,GAAG,CAAA;KAAE,CAAC,CAAC;CACpC,CAAC;AAEF,0CAA0C;AAC1C,MAAM,MAAM,MAAM,GAAG,SAAS,GAAG;IAC/B,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IAEd,gEAAgE;IAChE,GAAG,EAAE,MAAM,CAAC;CACb,CAAC"}
|
package/dist/types.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AA4QA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringControllerUnlockEvent,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkConfigurationByChainIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n BatchTransactionParams,\n TransactionControllerAddTransactionAction,\n TransactionControllerGetGasFeeTokensAction,\n TransactionControllerGetStateAction,\n TransactionControllerStateChangeEvent,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n CONTROLLER_NAME,\n PaymentOverride,\n TransactionPayStrategy,\n} from './constants.js';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | SentinelApiServiceActions\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | CurrencyRateStateChange\n | KeyringControllerUnlockEvent\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction (or `paymentOverride` batch) is executed\n * atomically with the Relay quote. Defaults to `true` (embedded in the quote\n * and executed by the Relay solver). When `false`, Pay does not embed the\n * target/override calls in the quote; the quote only bridges the required\n * asset to `recipient`, and the calls are submitted separately after Relay\n * completion. Used by flows whose second-leg amount is only known after\n * Relay settles (EXACT_INPUT max flows) or that require the second leg to\n * originate from a different signer than the Relay solver.\n */\n atomic?: boolean;\n\n /**\n * Whether the source of funds is HyperLiquid (HyperCore).\n * When true, the Relay strategy uses the HyperLiquid 2-step withdrawal\n * flow: (1) authorize nonce-mapping, (2) sendAsset to Relay solver.\n */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n */\n isPostQuote?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request. Use this for post-quote flows where the user's funds originate\n * from a smart contract account (e.g. Predict Safe proxy) so that refunds\n * go back to that account rather than the EOA.\n */\n refundTo?: Hex;\n};\n\n/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Request passed to {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataRequest = {\n /** Amount of the source token in human-readable format. */\n amount: string;\n\n /** Metadata of the original transaction. */\n transaction: TransactionMeta;\n\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Response returned by {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataResponse = {\n /** Batch transaction params to prepend to the submit batch. */\n calls: BatchTransactionParams[];\n\n /** Optional recipient address for the funding token transfer. */\n recipient?: Hex;\n\n /** Optional EIP-7702 authorization list from delegation. */\n authorizationList?: AuthorizationList;\n};\n\n/**\n * Callback invoked during submit when `paymentOverride` is defined.\n * Returns batch transaction params to prepend to the submit batch.\n */\nexport type GetPaymentOverrideDataCallback = (\n request: GetPaymentOverrideDataRequest,\n) => Promise<GetPaymentOverrideDataResponse>;\n\nexport type GetAmountDataRequest = {\n /** Raw token amount (atomic units) to encode into calldata. */\n amount: string;\n\n /** Metadata of the transaction whose nested calls need updating. */\n transaction: TransactionMeta;\n};\n\nexport type GetAmountDataResponse = {\n /** Per-nested-call data updates; empty when no update is needed. */\n updates: { nestedTransactionIndex: number; data: Hex }[];\n};\n\n/**\n * Optional callback that re-encodes nested transaction calldata for a given\n * token amount. Used by transaction types with non-standard nested data\n * (e.g. vault approve + deposit) that cannot be derived from the amount alone\n * without client-side context (vault config, RPC providers, etc.).\n */\nexport type GetAmountDataCallback = (\n request: GetAmountDataRequest,\n) => Promise<GetAmountDataResponse>;\n\n/** Request passed to {@link GetBalanceCallback}. */\nexport type GetBalanceRequest = {\n /** Metadata of the transaction whose source balance is being resolved. */\n transaction: TransactionMeta;\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Balance override returned by {@link GetBalanceCallback}. */\nexport type GetBalanceResponse = {\n /** Balance in atomic format without factoring token decimals. */\n balanceRaw: string;\n};\n\n/**\n * Optional client-supplied callback that overrides the built-in\n * pay-token / required-token balance lookup used for `isMaxAmount`\n * source-amount calculation. Enables alternate balance sources\n * (perps, predict, money-account, post-quote, etc.) without adding\n * conditional branches inside the controller. MUST be synchronous:\n * it runs inside the controller state-update block.\n * Return `undefined` to fall back to the built-in token balance.\n */\nexport type GetBalanceCallback = (\n request: GetBalanceRequest,\n) => GetBalanceResponse | undefined;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Optional callback to re-encode nested transaction calldata for a given amount. */\n getAmountData?: GetAmountDataCallback;\n\n /** Optional callback to override the source balance used for max-amount calculation. */\n getBalance?: GetBalanceCallback;\n\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** Optional fiat execution configuration. */\n fiatOptions?: TransactionPayFiatOptions;\n\n /**\n * Optional callback invoked during quote execution when `paymentOverride` is defined.\n * Returns additional transactions to be submitted alongside the quote batch.\n */\n getPaymentOverrideData?: GetPaymentOverrideDataCallback;\n\n /** Callback to select the PayStrategy for a transaction. */\n getStrategy?: (transaction: TransactionMeta) => TransactionPayStrategy;\n\n /** Callback to select ordered PayStrategies for a transaction. */\n getStrategies?: (transaction: TransactionMeta) => TransactionPayStrategy[];\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Callbacks for the Polymarket relayer; required only for the Polymarket deposit-wallet flow. */\n polymarket?: PolymarketCallbacks;\n\n /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** Optional fiat execution configuration. */\nexport type TransactionPayFiatOptions = {\n /** Test funding source used to bypass fiat on-ramp execution during local QA. */\n testFundingSource?: Hex;\n\n /** Optional human amount to transfer from the test funding source. */\n testAmountOverride?: string;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Fiat payment method state. */\n fiatPayment?: TransactionFiatPayment;\n\n /** Whether quotes are currently being retrieved. */\n isLoading: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n * Used when funds need to be moved after a transaction completes\n * (e.g., bridging output to a different token/chain).\n */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /**\n * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Most relevant structured validation error from the latest quote attempt. */\n quoteError?: QuoteErrorInfo;\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/**\n * Machine-readable discriminator for a quote validation failure.\n *\n * Used for analytics and tests. Human-readable copy is carried by `message`\n * and `detail` on {@link QuoteErrorInfo}.\n */\nexport type QuoteErrorReason =\n | 'balance-unavailable'\n | 'insufficient-source-balance'\n | 'insufficient-transfer-balance'\n | 'no-quotes'\n | 'simulation-failed';\n\n/**\n * Structured description of why a quote failed validation.\n *\n * `message` and `detail` are formatted (English) copy ready to display; `reason`\n * is a machine-readable discriminator for analytics and tests.\n */\nexport type QuoteErrorInfo = {\n /** Short, display-ready summary of the failure. */\n message: string;\n\n /** Machine-readable discriminator for the failure. */\n reason: QuoteErrorReason;\n\n /** Optional display-ready detail rows (e.g. Required / Current / Missing). */\n detail?: string[];\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether this quote is the direct mUSD-to-Money-Account fiat flow. */\n isDirectMusdMoneyAccount?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** Optional recipient address for Relay requests. When set, overrides the default `from` address. */\n recipient?: Hex;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /** Whether to skip processTransactions in relay-quotes. Defaults to `isPostQuote`. */\n skipProcessTransactions?: boolean;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n\n /**\n * One-time HyperLiquid activation fee (USD) reserved from the source amount\n * for an unactivated HyperCore account. The source amount sent to the\n * provider is reduced by this amount so HyperLiquid retains enough balance\n * for the fee, and the amount is surfaced as part of the provider fee.\n */\n hyperliquidActivationFeeUsd?: string;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Whether fees are subtracted from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /**\n * Resolved wallet address for the transaction.\n * This is `accountOverride ?? txParams.from`, pre-computed by the quote\n * orchestrator so that individual strategies do not need to re-derive it.\n */\n from: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Whether the selected quotes subtract fees from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n isSubsidized,\n}: {\n transaction: TransactionMeta;\n isSubsidized?: boolean;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Client-supplied callbacks for the Polymarket relayer protocol. */\nexport type PolymarketCallbacks = {\n /** Derive the deposit-wallet address (CREATE2) for the given EOA. */\n getDepositWalletAddress: (params: { eoa: Hex }) => Promise<Hex>;\n\n /** Sign and broadcast a deposit-wallet batch, returning the source hash. */\n submitDepositWalletBatch: (params: {\n eoa: Hex;\n depositWallet: Hex;\n calls: { target: Hex; data: Hex; value: string }[];\n }) => Promise<{ sourceHash: Hex }>;\n};\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAgRA;;;GAGG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAwB;IAChE,aAAa;IACb,iBAAiB;IACjB,eAAe;CAChB,CAAC","sourcesContent":["import type {\n AssetsControllerGetStateForTransactionPayAction,\n AssetsControllerStateChangeEvent,\n} from '@metamask/assets-controller';\nimport type {\n CurrencyRateControllerGetStateAction,\n CurrencyRateStateChange,\n TokenBalancesControllerGetStateAction,\n} from '@metamask/assets-controllers';\nimport type { TokenRatesControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { TokenRatesControllerStateChangeEvent } from '@metamask/assets-controllers';\nimport type {\n TokensControllerGetStateAction,\n TokensControllerStateChangeEvent,\n} from '@metamask/assets-controllers';\nimport type { AccountTrackerControllerGetStateAction } from '@metamask/assets-controllers';\nimport type { ControllerStateChangeEvent } from '@metamask/base-controller';\nimport type { ControllerGetStateAction } from '@metamask/base-controller';\nimport type { GetGasFeeState } from '@metamask/gas-fee-controller';\nimport type {\n KeyringControllerGetStateAction,\n KeyringControllerSignTypedMessageAction,\n KeyringControllerUnlockEvent,\n KeyringTypes,\n} from '@metamask/keyring-controller';\nimport type { Messenger } from '@metamask/messenger';\nimport type { NetworkControllerFindNetworkClientIdByChainIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkClientByIdAction } from '@metamask/network-controller';\nimport type { NetworkControllerGetNetworkConfigurationByChainIdAction } from '@metamask/network-controller';\nimport type { Quote as RampsQuote } from '@metamask/ramps-controller';\nimport type {\n RampsControllerGetOrderAction,\n RampsControllerGetQuotesAction,\n RampsControllerTransakGetBuyQuoteAction,\n TransakServiceGetBuyQuoteAction,\n} from '@metamask/ramps-controller';\nimport type { RemoteFeatureFlagControllerGetStateAction } from '@metamask/remote-feature-flag-controller';\nimport type { SentinelApiServiceActions } from '@metamask/sentinel-api-service';\nimport type {\n AuthorizationList,\n TransactionControllerAddTransactionBatchAction,\n TransactionControllerEstimateGasAction,\n TransactionControllerEstimateGasBatchAction,\n TransactionControllerUnapprovedTransactionAddedEvent,\n} from '@metamask/transaction-controller';\nimport type {\n BatchTransaction,\n BatchTransactionParams,\n TransactionControllerAddTransactionAction,\n TransactionControllerGetGasFeeTokensAction,\n TransactionControllerGetStateAction,\n TransactionControllerStateChangeEvent,\n TransactionControllerUpdateTransactionAction,\n TransactionMeta,\n} from '@metamask/transaction-controller';\nimport type { Hex, Json } from '@metamask/utils';\nimport type { Draft } from 'immer';\n\nimport type {\n CONTROLLER_NAME,\n PaymentOverride,\n TransactionPayStrategy,\n} from './constants.js';\nimport type { TransactionPayControllerMethodActions } from './TransactionPayController-method-action-types.js';\n\nexport type AllowedActions =\n | AccountTrackerControllerGetStateAction\n | AssetsControllerGetStateForTransactionPayAction\n | CurrencyRateControllerGetStateAction\n | GetGasFeeState\n | KeyringControllerGetStateAction\n | KeyringControllerSignTypedMessageAction\n | NetworkControllerFindNetworkClientIdByChainIdAction\n | NetworkControllerGetNetworkClientByIdAction\n | NetworkControllerGetNetworkConfigurationByChainIdAction\n | RampsControllerGetOrderAction\n | RampsControllerGetQuotesAction\n | RampsControllerTransakGetBuyQuoteAction\n | TransakServiceGetBuyQuoteAction\n | RemoteFeatureFlagControllerGetStateAction\n | TokenBalancesControllerGetStateAction\n | TokenRatesControllerGetStateAction\n | TokensControllerGetStateAction\n | SentinelApiServiceActions\n | TransactionControllerAddTransactionAction\n | TransactionControllerAddTransactionBatchAction\n | TransactionControllerEstimateGasAction\n | TransactionControllerEstimateGasBatchAction\n | TransactionControllerGetGasFeeTokensAction\n | TransactionControllerGetStateAction\n | TransactionControllerUpdateTransactionAction;\n\nexport type AllowedEvents =\n | AssetsControllerStateChangeEvent\n | CurrencyRateStateChange\n | KeyringControllerUnlockEvent\n | TokenRatesControllerStateChangeEvent\n | TokensControllerStateChangeEvent\n | TransactionControllerStateChangeEvent\n | TransactionControllerUnapprovedTransactionAddedEvent;\n\nexport type TransactionPayControllerGetStateAction = ControllerGetStateAction<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n>;\n\n/** Configurable properties of a transaction. */\nexport type TransactionConfig = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction (or `paymentOverride` batch) is executed\n * atomically with the Relay quote. Defaults to `true` (embedded in the quote\n * and executed by the Relay solver). When `false`, Pay does not embed the\n * target/override calls in the quote; the quote only bridges the required\n * asset to `recipient`, and the calls are submitted separately after Relay\n * completion. Used by flows whose second-leg amount is only known after\n * Relay settles (EXACT_INPUT max flows) or that require the second leg to\n * originate from a different signer than the Relay solver.\n */\n atomic?: boolean;\n\n /**\n * Whether the source of funds is HyperLiquid (HyperCore).\n * When true, the Relay strategy uses the HyperLiquid 2-step withdrawal\n * flow: (1) authorize nonce-mapping, (2) sendAsset to Relay solver.\n */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n */\n isPostQuote?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request. Use this for post-quote flows where the user's funds originate\n * from a smart contract account (e.g. Predict Safe proxy) so that refunds\n * go back to that account rather than the EOA.\n */\n refundTo?: Hex;\n};\n\n/** Callback to update transaction config. */\nexport type TransactionConfigCallback = (config: TransactionConfig) => void;\n\n/** Request passed to {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataRequest = {\n /** Amount of the source token in human-readable format. */\n amount: string;\n\n /** Metadata of the original transaction. */\n transaction: TransactionMeta;\n\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Response returned by {@link GetPaymentOverrideDataCallback}. */\nexport type GetPaymentOverrideDataResponse = {\n /** Batch transaction params to prepend to the submit batch. */\n calls: BatchTransactionParams[];\n\n /** Optional recipient address for the funding token transfer. */\n recipient?: Hex;\n\n /** Optional EIP-7702 authorization list from delegation. */\n authorizationList?: AuthorizationList;\n};\n\n/**\n * Callback invoked during submit when `paymentOverride` is defined.\n * Returns batch transaction params to prepend to the submit batch.\n */\nexport type GetPaymentOverrideDataCallback = (\n request: GetPaymentOverrideDataRequest,\n) => Promise<GetPaymentOverrideDataResponse>;\n\nexport type GetAmountDataRequest = {\n /** Raw token amount (atomic units) to encode into calldata. */\n amount: string;\n\n /** Metadata of the transaction whose nested calls need updating. */\n transaction: TransactionMeta;\n};\n\nexport type GetAmountDataResponse = {\n /** Per-nested-call data updates; empty when no update is needed. */\n updates: { nestedTransactionIndex: number; data: Hex }[];\n};\n\n/**\n * Optional callback that re-encodes nested transaction calldata for a given\n * token amount. Used by transaction types with non-standard nested data\n * (e.g. vault approve + deposit) that cannot be derived from the amount alone\n * without client-side context (vault config, RPC providers, etc.).\n */\nexport type GetAmountDataCallback = (\n request: GetAmountDataRequest,\n) => Promise<GetAmountDataResponse>;\n\n/** Request passed to {@link GetBalanceCallback}. */\nexport type GetBalanceRequest = {\n /** Metadata of the transaction whose source balance is being resolved. */\n transaction: TransactionMeta;\n /** Pay-controller state for the transaction. */\n transactionData: TransactionData;\n};\n\n/** Balance override returned by {@link GetBalanceCallback}. */\nexport type GetBalanceResponse = {\n /** Balance in atomic format without factoring token decimals. */\n balanceRaw: string;\n};\n\n/**\n * Optional client-supplied callback that overrides the built-in\n * pay-token / required-token balance lookup used for `isMaxAmount`\n * source-amount calculation. Enables alternate balance sources\n * (perps, predict, money-account, post-quote, etc.) without adding\n * conditional branches inside the controller. MUST be synchronous:\n * it runs inside the controller state-update block.\n * Return `undefined` to fall back to the built-in token balance.\n */\nexport type GetBalanceCallback = (\n request: GetBalanceRequest,\n) => GetBalanceResponse | undefined;\n\n/** Callback to update fiat payment state. */\nexport type TransactionFiatPaymentCallback = (\n fiatPayment: TransactionFiatPayment,\n) => void;\n\nexport type TransactionPayControllerStateChangeEvent =\n ControllerStateChangeEvent<\n typeof CONTROLLER_NAME,\n TransactionPayControllerState\n >;\n\nexport type TransactionPayControllerActions =\n | TransactionPayControllerGetStateAction\n | TransactionPayControllerMethodActions;\n\nexport type TransactionPayControllerEvents =\n TransactionPayControllerStateChangeEvent;\n\nexport type TransactionPayControllerMessenger = Messenger<\n typeof CONTROLLER_NAME,\n TransactionPayControllerActions | AllowedActions,\n TransactionPayControllerEvents | AllowedEvents\n>;\n\n/**\n * Keyring types that support EIP-7702 authorization signing.\n * Hardware wallets, snap keyrings, and custody keyrings are excluded.\n */\nexport const KEYRING_TYPES_SUPPORTING_7702: `${KeyringTypes}`[] = [\n 'HD Key Tree',\n 'Simple Key Pair',\n 'Money Keyring',\n];\n\n/** Options for the TransactionPayController. */\nexport type TransactionPayControllerOptions = {\n /** Optional callback to re-encode nested transaction calldata for a given amount. */\n getAmountData?: GetAmountDataCallback;\n\n /** Optional callback to override the source balance used for max-amount calculation. */\n getBalance?: GetBalanceCallback;\n\n /** Callback to convert a transaction into a redeem delegation. */\n getDelegationTransaction: GetDelegationTransactionCallback;\n\n /** Optional fiat execution configuration. */\n fiatOptions?: TransactionPayFiatOptions;\n\n /**\n * Optional callback invoked during quote execution when `paymentOverride` is defined.\n * Returns additional transactions to be submitted alongside the quote batch.\n */\n getPaymentOverrideData?: GetPaymentOverrideDataCallback;\n\n /** Callback to select the PayStrategy for a transaction. */\n getStrategy?: (transaction: TransactionMeta) => TransactionPayStrategy;\n\n /** Callback to select ordered PayStrategies for a transaction. */\n getStrategies?: (transaction: TransactionMeta) => TransactionPayStrategy[];\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Callbacks for the Polymarket relayer; required only for the Polymarket deposit-wallet flow. */\n polymarket?: PolymarketCallbacks;\n\n /** Initial state of the controller. */\n state?: Partial<TransactionPayControllerState>;\n};\n\n/** State of the TransactionPayController. */\nexport type TransactionPayControllerState = {\n /** State relating to each transaction, keyed by transaction ID. */\n transactionData: Record<string, TransactionData>;\n};\n\n/** Optional fiat execution configuration. */\nexport type TransactionPayFiatOptions = {\n /** Test funding source used to bypass fiat on-ramp execution during local QA. */\n testFundingSource?: Hex;\n\n /** Optional human amount to transfer from the test funding source. */\n testAmountOverride?: string;\n};\n\n/** State relating to a single transaction. */\nexport type TransactionData = {\n /**\n * Optional address to override the default account used by the transaction.\n * When `isPostQuote` is true, used as the recipient of the MM Pay transfer.\n * When `isPostQuote` is false, it provides the funds and pays for gas.\n */\n accountOverride?: Hex;\n\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Fiat payment method state. */\n fiatPayment?: TransactionFiatPayment;\n\n /** Whether quotes are currently being retrieved. */\n isLoading: boolean;\n\n /** Whether the user has selected the maximum amount. */\n isMaxAmount?: boolean;\n\n /**\n * Whether this is a post-quote transaction.\n * When true, the paymentToken represents the destination token,\n * and the quote source is derived from the transaction's output token.\n * Used when funds need to be moved after a transaction completes\n * (e.g., bridging output to a different token/chain).\n */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** When true, a quote is always fetched even when the source and target tokens are identical. */\n isQuoteRequired?: boolean;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /**\n * Token selected for the transaction.\n * - For standard flows (isPostQuote=false): This is the SOURCE/payment token\n * - For post-quote flows (isPostQuote=true): This is the DESTINATION token\n */\n paymentToken?: TransactionPaymentToken;\n\n /** Quotes retrieved for the transaction. */\n quotes?: TransactionPayQuote<Json>[];\n\n /** Most relevant structured validation error from the latest quote attempt. */\n quoteError?: QuoteErrorInfo;\n\n /** Timestamp of when quotes were last updated. */\n quotesLastUpdated?: number;\n\n /** Amounts of payment token required for each required token. */\n sourceAmounts?: TransactionPaySourceAmount[];\n\n /** Tokens required by the transaction. */\n tokens: TransactionPayRequiredToken[];\n\n /** Calculated totals for the transaction. */\n totals?: TransactionPayTotals;\n};\n\n/** Fiat payment state stored per transaction. */\nexport type TransactionFiatPayment = {\n /** Entered fiat amount for the selected payment method. */\n amountFiat?: string;\n\n /** CAIP-19 asset id derived from the transaction type for the fiat on-ramp. */\n caipAssetId?: string;\n\n /** Order identifier in normalized format (/providers/{provider}/orders/{id}). */\n orderId?: string;\n\n /** The ramps quote received from the ramps provider. */\n rampsQuote?: RampsQuote;\n\n /** Selected fiat payment method ID. */\n selectedPaymentMethodId?: string;\n};\n\n/** A token required by a transaction. */\nexport type TransactionPayRequiredToken = {\n /** Address of the required token. */\n address: Hex;\n\n /** Whether to allow quotes that return less than the minimum amount requested. */\n allowUnderMinimum: boolean;\n\n /** Amount required in the selected currency. */\n amountFiat: string;\n\n /** Amount required in a human-readable format factoring token decimals. */\n amountHuman: string;\n\n /** Amount required in atomic format without factoring token decimals. */\n amountRaw: string;\n\n /** Amount required in USD. */\n amountUsd: string;\n\n /** Balance of the required token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the required token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the required token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the required token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the required token. */\n chainId: Hex;\n\n /** Decimals of the required token. */\n decimals: number;\n\n /** Whether to skip transfer of this token if balance is already sufficient. */\n skipIfBalance: boolean;\n\n /** Symbol of the required token. */\n symbol: string;\n};\n\n/** Amount of payment token required by a required token. */\nexport type TransactionPaySourceAmount = {\n /** Amount of payment token required in the selected currency. */\n sourceAmountHuman: string;\n\n /** Amount of payment token required in atomic format without factoring token decimals. */\n sourceAmountRaw: string;\n\n /** Balance of the source token in atomic format (for post-quote flows). */\n sourceBalanceRaw?: string;\n\n /** Chain ID of the source token (for post-quote flows). */\n sourceChainId?: Hex;\n\n /** Address of the source token (for post-quote flows). */\n sourceTokenAddress?: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n};\n\n/**\n * Machine-readable discriminator for a quote validation failure.\n *\n * Used for analytics and tests. Human-readable copy is carried by `message`\n * and `detail` on {@link QuoteErrorInfo}.\n */\nexport type QuoteErrorReason =\n | 'balance-unavailable'\n | 'insufficient-source-balance'\n | 'insufficient-transfer-balance'\n | 'no-quotes'\n | 'simulation-failed';\n\n/**\n * Structured description of why a quote failed validation.\n *\n * `message` and `detail` are formatted (English) copy ready to display; `reason`\n * is a machine-readable discriminator for analytics and tests.\n */\nexport type QuoteErrorInfo = {\n /** Short, display-ready summary of the failure. */\n message: string;\n\n /** Machine-readable discriminator for the failure. */\n reason: QuoteErrorReason;\n\n /** Optional display-ready detail rows (e.g. Required / Current / Missing). */\n detail?: string[];\n};\n\n/** Source token used to pay for required tokens. */\nexport type TransactionPaymentToken = {\n /** Address of the payment token. */\n address: Hex;\n\n /** Balance of the payment token in the selected currency. */\n balanceFiat: string;\n\n /** Balance of the payment token in a human-readable format factoring token decimals. */\n balanceHuman: string;\n\n /** Balance of the payment token in atomic format without factoring token decimals. */\n balanceRaw: string;\n\n /** Balance of the payment token in USD. */\n balanceUsd: string;\n\n /** Chain ID of the payment token. */\n chainId: Hex;\n\n /** Decimals of the payment token. */\n decimals: number;\n\n /** Symbol of the payment token. */\n symbol: string;\n};\n\n/** Callback to update state for a single transaction. */\nexport type UpdateTransactionDataCallback = (\n /** ID of the transaction to update. */\n transactionId: string,\n /** Function that receives a draft of the transaction data to update. */\n fn: (data: Draft<TransactionData>) => void,\n) => void;\n\n/** Conversion rates from the native currency to other currencies. */\nexport type FiatRates = {\n /** Conversion rate for the native currency to the selected fiat currency. */\n fiatRate: string;\n\n /** Conversion rate for the native currency to USD. */\n usdRate: string;\n};\n\n/** Request for a quote to retrieve a required token. */\nexport type QuoteRequest = {\n /**\n * Whether the target transaction is executed atomically with the Relay\n * quote. See {@link TransactionConfig.atomic}.\n */\n atomic?: boolean;\n\n /** Address of the user's account. */\n from: Hex;\n\n /** Whether the transaction is a maximum amount transaction. */\n isMaxAmount?: boolean;\n\n /** Whether this is a post-quote flow. */\n isPostQuote?: boolean;\n\n /** Whether the source of funds is HyperLiquid (HyperCore). */\n isHyperliquidSource?: boolean;\n\n /** Whether the source of funds is a Polymarket deposit wallet. */\n isPolymarketDepositWallet?: boolean;\n\n /** Whether this quote is the direct mUSD-to-Money-Account fiat flow. */\n isDirectMusdMoneyAccount?: boolean;\n\n /** Overrides the payment source for the transaction. */\n paymentOverride?: PaymentOverride;\n\n /** Optional recipient address for Relay requests. When set, overrides the default `from` address. */\n recipient?: Hex;\n\n /**\n * Optional address to receive refunds if the quote provider transaction fails.\n * When set, overrides the default refund recipient (EOA) in the quote\n * request.\n */\n refundTo?: Hex;\n\n /** Whether to skip processTransactions in relay-quotes. Defaults to `isPostQuote`. */\n skipProcessTransactions?: boolean;\n\n /** Balance of the source token in atomic format without factoring token decimals. */\n sourceBalanceRaw: string;\n\n /** Chain ID of the source token. */\n sourceChainId: Hex;\n\n /** Address of the source token. */\n sourceTokenAddress: Hex;\n\n /** Amount of the required token in atomic format without factoring token decimals. */\n sourceTokenAmount: string;\n\n /** Minimum amount required of the target token in atomic format without factoring token decimals. */\n targetAmountMinimum: string;\n\n /** Chain ID of the target token. */\n targetChainId: Hex;\n\n /** Address of the target token. */\n targetTokenAddress: Hex;\n\n /**\n * One-time HyperLiquid activation fee (USD) reserved from the source amount\n * for an unactivated HyperCore account. The source amount sent to the\n * provider is reduced by this amount so HyperLiquid retains enough balance\n * for the fee, and the amount is surfaced as part of the provider fee.\n */\n hyperliquidActivationFeeUsd?: string;\n};\n\n/** Fees associated with a transaction pay quote. */\nexport type TransactionPayFees = {\n /** Whether a gas fee token is used to pay source network fees. */\n isSourceGasFeeToken?: boolean;\n\n /** Whether a gas fee token is used to pay target network fees. */\n isTargetGasFeeToken?: boolean;\n\n /** Fee charged by MetaMask. */\n metaMask: FiatValue;\n\n /** Fee charged by the quote provider. */\n provider: FiatValue;\n\n /** Fee charged by fiat on-ramp provider (breakdown of the provider total). */\n providerFiat?: FiatValue;\n\n /** Network fee for transactions on the source network. */\n sourceNetwork: {\n estimate: Amount;\n max: Amount;\n };\n\n /** Network fee for transactions on the target network. */\n targetNetwork: FiatValue;\n};\n\n/** Quote returned to retrieve a required token using the payment token. */\nexport type TransactionPayQuote<OriginalQuote> = {\n /** Additional amount provided by the quote beyond the minimum requested. */\n dust: FiatValue;\n\n /** Duration estimated for the transaction to complete in seconds. */\n estimatedDuration: number;\n\n /** Fees associated with the transaction pay quote. */\n fees: TransactionPayFees;\n\n /** Whether fees are subtracted from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Whether the reported fees are already included in the source amount. */\n areFeesIncludedInSourceAmount?: boolean;\n\n /** Raw quote data returned by the provider. */\n original: OriginalQuote;\n\n /** Associated quote request. */\n request: QuoteRequest;\n\n /** Amount of source token required. */\n sourceAmount: Amount;\n\n /** Name of the strategy used to retrieve the quote. */\n strategy: TransactionPayStrategy;\n\n /** Amount of target token provided. */\n targetAmount: FiatValue;\n};\n\n/** Request to get quotes for a transaction. */\nexport type PayStrategyGetQuotesRequest = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Selected fiat payment method ID, if applicable. */\n fiatPaymentMethod?: string;\n\n /**\n * Resolved wallet address for the transaction.\n * This is `accountOverride ?? txParams.from`, pre-computed by the quote\n * orchestrator so that individual strategies do not need to re-derive it.\n */\n from: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quote requests for required tokens. */\n requests: QuoteRequest[];\n\n /**\n * Signal that aborts when a newer quote request supersedes this one.\n * Strategies that perform their own network IO should forward this to\n * their fetch calls so cancelled requests release network resources.\n */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to submit quotes for a transaction. */\nexport type PayStrategyExecuteRequest<OriginalRequest> = {\n /** Whether the account supports EIP-7702 authorization signing. */\n accountSupports7702: boolean;\n\n /** Callback to determine if the transaction is a smart transaction. */\n isSmartTransaction: (chainId: Hex) => boolean;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes to be submitted. */\n quotes: TransactionPayQuote<OriginalRequest>[];\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get batch transactions for quotes. */\nexport type PayStrategyGetBatchRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes for required tokens. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n};\n\n/** Request to check whether retrieved quotes can be executed by a strategy. */\nexport type PayStrategyCheckQuoteSupportRequest<OriginalQuote> = {\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n\n /** Quotes returned by the strategy. */\n quotes: TransactionPayQuote<OriginalQuote>[];\n\n /** Signal that aborts when a newer quote request supersedes this one. */\n signal?: AbortSignal;\n\n /** Metadata of the original target transaction. */\n transaction: TransactionMeta;\n};\n\n/** Request to get refresh interval for a specific strategy. */\nexport type PayStrategyGetRefreshIntervalRequest = {\n /** Chain ID of the source or payment token. */\n chainId: Hex;\n\n /** Controller messenger. */\n messenger: TransactionPayControllerMessenger;\n};\n\n/** Strategy used to obtain required tokens for a transaction. */\nexport type PayStrategy<OriginalQuote> = {\n /**\n * Check if the strategy supports the given request.\n * Defaults to true if not implemented.\n */\n supports?: (\n request: PayStrategyGetQuotesRequest,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve quotes for required tokens. */\n getQuotes: (\n request: PayStrategyGetQuotesRequest,\n ) => Promise<TransactionPayQuote<OriginalQuote>[]>;\n\n /**\n * Check if the returned quotes are supported after provider quote\n * construction and gas planning.\n *\n * Use this for limitations that are only knowable once quote metadata is\n * available, such as whether execution will require an EIP-7702\n * authorization list.\n */\n checkQuoteSupport?: (\n request: PayStrategyCheckQuoteSupportRequest<OriginalQuote>,\n ) => boolean | Promise<boolean>;\n\n /** Retrieve batch transactions for quotes, if supported by the strategy. */\n getBatchTransactions?: (\n request: PayStrategyGetBatchRequest<OriginalQuote>,\n ) => Promise<BatchTransaction[]>;\n\n /**\n * Retrieve refresh interval for the strategy, if applicable.\n * Defaults to 30 seconds.\n */\n getRefreshInterval?: (\n request: PayStrategyGetRefreshIntervalRequest,\n ) => Promise<number | undefined>;\n\n /** Execute or submit the quotes to obtain required tokens. */\n execute: (request: PayStrategyExecuteRequest<OriginalQuote>) => Promise<{\n transactionHash?: Hex;\n }>;\n};\n\n/** Single fiat value in alternate currencies. */\nexport type FiatValue = {\n /** Value in the selected fiat currency. */\n fiat: string;\n\n /** Value in USD. */\n usd: string;\n};\n\n/** Calculated totals for a target transaction and all quotes. */\nexport type TransactionPayTotals = {\n /** Total estimated duration for the target transaction and all quotes. */\n estimatedDuration: number;\n\n /** Total fees for the target transaction and all quotes. */\n fees: TransactionPayFees;\n\n /** Whether the selected quotes subtract fees from the destination amount, meaning the input amount is static. */\n isInputBased?: boolean;\n\n /** Total amount of source token required. */\n sourceAmount: Amount;\n\n /** Total amount of target token provided. */\n targetAmount: FiatValue;\n\n /** Overall total cost for the target transaction and all quotes. */\n total: FiatValue;\n};\n\n/** Request to update the payment token for a transaction. */\nexport type UpdatePaymentTokenRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Address of the new payment token. */\n tokenAddress: Hex;\n\n /** Chain ID of the new payment token. */\n chainId: Hex;\n};\n\n/** Request to update fiat payment state for a transaction. */\nexport type UpdateFiatPaymentRequest = {\n /** ID of the transaction to update. */\n transactionId: string;\n\n /** Callback to mutate fiat payment state. */\n callback: TransactionFiatPaymentCallback;\n};\n\n/** Callback to convert a transaction to a redeem delegation. */\nexport type GetDelegationTransactionCallback = ({\n transaction,\n isSubsidized,\n}: {\n transaction: TransactionMeta;\n isSubsidized?: boolean;\n}) => Promise<{\n authorizationList?: AuthorizationList;\n data: Hex;\n to: Hex;\n value: Hex;\n}>;\n\n/** Client-supplied callbacks for the Polymarket relayer protocol. */\nexport type PolymarketCallbacks = {\n /** Derive the deposit-wallet address (CREATE2) for the given EOA. */\n getDepositWalletAddress: (params: { eoa: Hex }) => Promise<Hex>;\n\n /** Sign and broadcast a deposit-wallet batch, returning the source hash. */\n submitDepositWalletBatch: (params: {\n eoa: Hex;\n depositWallet: Hex;\n calls: { target: Hex; data: Hex; value: string }[];\n }) => Promise<{ sourceHash: Hex }>;\n};\n\n/** Single amount in alternate formats. */\nexport type Amount = FiatValue & {\n /** Amount in human-readable format factoring token decimals. */\n human: string;\n\n /** Amount in atomic format without factoring token decimals. */\n raw: string;\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"totals.d.ts","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAIxE,OAAO,KAAK,EAEV,iCAAiC,EACjC,mBAAmB,EACnB,2BAA2B,EAC3B,oBAAoB,EACrB,MAAM,aAAa,CAAC;AAIrB;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,EAC9B,iBAAiB,EACjB,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,GACZ,EAAE;IACD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,MAAM,EAAE,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;IACvC,SAAS,EAAE,iCAAiC,CAAC;IAC7C,MAAM,EAAE,2BAA2B,EAAE,CAAC;IACtC,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,oBAAoB,
|
|
1
|
+
{"version":3,"file":"totals.d.ts","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kCAAkC,CAAC;AAIxE,OAAO,KAAK,EAEV,iCAAiC,EACjC,mBAAmB,EACnB,2BAA2B,EAC3B,oBAAoB,EACrB,MAAM,aAAa,CAAC;AAIrB;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,EAC9B,iBAAiB,EACjB,MAAM,EACN,SAAS,EACT,MAAM,EACN,WAAW,GACZ,EAAE;IACD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,MAAM,EAAE,mBAAmB,CAAC,OAAO,CAAC,EAAE,CAAC;IACvC,SAAS,EAAE,iCAAiC,CAAC;IAC7C,MAAM,EAAE,2BAA2B,EAAE,CAAC;IACtC,WAAW,EAAE,eAAe,CAAC;CAC9B,GAAG,oBAAoB,CAwHvB"}
|
package/dist/utils/totals.js
CHANGED
|
@@ -50,17 +50,25 @@ export function calculateTotals({ fiatPaymentAmount, quotes, messenger, tokens,
|
|
|
50
50
|
tokenAmount: amountUsd,
|
|
51
51
|
useTargetAmount: isInputBased,
|
|
52
52
|
});
|
|
53
|
+
const includedFees = sumFiat(quotes
|
|
54
|
+
.filter((quote) => quote.areFeesIncludedInSourceAmount)
|
|
55
|
+
.map((quote) => ({
|
|
56
|
+
fiat: getQuoteFeeTotal(quote, 'fiat'),
|
|
57
|
+
usd: getQuoteFeeTotal(quote, 'usd'),
|
|
58
|
+
})));
|
|
53
59
|
const totalFiat = new BigNumber(providerFee.fiat)
|
|
54
60
|
.plus(metaMaskFee.fiat)
|
|
55
61
|
.plus(sourceNetworkFeeEstimate.fiat)
|
|
56
62
|
.plus(targetNetworkFee.fiat)
|
|
57
63
|
.plus(sourceAmountFiat)
|
|
64
|
+
.minus(includedFees.fiat)
|
|
58
65
|
.toString(10);
|
|
59
66
|
const totalUsd = new BigNumber(providerFee.usd)
|
|
60
67
|
.plus(metaMaskFee.usd)
|
|
61
68
|
.plus(sourceNetworkFeeEstimate.usd)
|
|
62
69
|
.plus(targetNetworkFee.usd)
|
|
63
70
|
.plus(sourceAmountUsd)
|
|
71
|
+
.minus(includedFees.usd)
|
|
64
72
|
.toString(10);
|
|
65
73
|
const estimatedDuration = Number(sumProperty(quotes, (quote) => quote.estimatedDuration));
|
|
66
74
|
const isSourceGasFeeToken = quotes.some((quote) => quote.fees.isSourceGasFeeToken);
|
|
@@ -89,6 +97,13 @@ export function calculateTotals({ fiatPaymentAmount, quotes, messenger, tokens,
|
|
|
89
97
|
},
|
|
90
98
|
};
|
|
91
99
|
}
|
|
100
|
+
function getQuoteFeeTotal(quote, currency) {
|
|
101
|
+
return new BigNumber(quote.fees.provider[currency])
|
|
102
|
+
.plus(quote.fees.metaMask[currency])
|
|
103
|
+
.plus(quote.fees.sourceNetwork.estimate[currency])
|
|
104
|
+
.plus(quote.fees.targetNetwork[currency])
|
|
105
|
+
.toString(10);
|
|
106
|
+
}
|
|
92
107
|
/**
|
|
93
108
|
* Get the source amount to include in totals.
|
|
94
109
|
*
|
package/dist/utils/totals.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"totals.js","sourceRoot":"","sources":["../../src/utils/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AAS,CAAC,CAAC,CAAC,CAAC;SACxE,QAAQ,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\n\nimport { TransactionPayStrategy } from '../constants.js';\nimport type {\n FiatValue,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPayTotals,\n} from '../types.js';\nimport { sumAmounts } from './amounts.js';\nimport { calculateTransactionGasCost } from './gas.js';\n\n/**\n * Calculate totals for a list of quotes and tokens.\n *\n * @param request - Request parameters.\n * @param request.fiatPaymentAmount - The amount of the transaction in fiat.\n * @param request.quotes - List of bridge quotes.\n * @param request.messenger - Controller messenger.\n * @param request.tokens - List of required tokens.\n * @param request.transaction - Transaction metadata.\n * @returns The calculated totals in USD and fiat currency.\n */\nexport function calculateTotals({\n fiatPaymentAmount,\n quotes,\n messenger,\n tokens,\n transaction,\n}: {\n fiatPaymentAmount?: string;\n quotes: TransactionPayQuote<unknown>[];\n messenger: TransactionPayControllerMessenger;\n tokens: TransactionPayRequiredToken[];\n transaction: TransactionMeta;\n}): TransactionPayTotals {\n const metaMaskFee = sumFiat(quotes.map((quote) => quote.fees.metaMask));\n const providerFee = sumFiat(quotes.map((quote) => quote.fees.provider));\n const providerFiatFee = sumFiat(\n quotes.map((quote) => quote.fees.providerFiat ?? { fiat: '0', usd: '0' }),\n );\n const hasFiatStrategy = quotes.some(\n (quote) => quote.strategy === TransactionPayStrategy.Fiat,\n );\n\n const sourceNetworkFeeMax = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.max),\n );\n\n const sourceNetworkFeeEstimate = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.estimate),\n );\n\n const transactionNetworkFee = calculateTransactionGasCost(\n transaction,\n messenger,\n );\n\n const targetNetworkFee = quotes?.length\n ? {\n ...sumFiat(quotes.map((quote) => quote.fees.targetNetwork)),\n isGasFeeToken: false,\n }\n : transactionNetworkFee;\n\n const sourceAmount = sumAmounts(quotes.map((quote) => quote.sourceAmount));\n const targetAmount = sumFiat(quotes.map((quote) => quote.targetAmount));\n\n const quoteTokens = tokens.filter(\n (singleToken) => !singleToken.skipIfBalance,\n );\n\n const amountFiat = sumProperty(quoteTokens, (token) => token.amountFiat);\n const amountUsd = sumProperty(quoteTokens, (token) => token.amountUsd);\n const hasQuotes = quotes.length > 0;\n const isInputBased =\n hasQuotes && quotes.every((quote) => quote.isInputBased === true);\n\n const sourceAmountFiat = getSourceAmount({\n hasFiatStrategy,\n fiatPaymentAmount,\n hasQuotes,\n targetAmount: targetAmount.fiat,\n tokenAmount: amountFiat,\n useTargetAmount: isInputBased,\n });\n\n const sourceAmountUsd = getSourceAmount({\n hasFiatStrategy,\n fiatPaymentAmount,\n hasQuotes,\n targetAmount: targetAmount.usd,\n tokenAmount: amountUsd,\n useTargetAmount: isInputBased,\n });\n\n const totalFiat = new BigNumber(providerFee.fiat)\n .plus(metaMaskFee.fiat)\n .plus(sourceNetworkFeeEstimate.fiat)\n .plus(targetNetworkFee.fiat)\n .plus(sourceAmountFiat)\n .toString(10);\n\n const totalUsd = new BigNumber(providerFee.usd)\n .plus(metaMaskFee.usd)\n .plus(sourceNetworkFeeEstimate.usd)\n .plus(targetNetworkFee.usd)\n .plus(sourceAmountUsd)\n .toString(10);\n\n const estimatedDuration = Number(\n sumProperty(quotes, (quote) => quote.estimatedDuration),\n );\n\n const isSourceGasFeeToken = quotes.some(\n (quote) => quote.fees.isSourceGasFeeToken,\n );\n\n const isTargetGasFeeToken =\n Boolean(targetNetworkFee.isGasFeeToken) ||\n quotes.some((quote) => quote.fees.isTargetGasFeeToken);\n\n return {\n estimatedDuration,\n fees: {\n isSourceGasFeeToken,\n isTargetGasFeeToken,\n providerFiat: providerFiatFee,\n metaMask: metaMaskFee,\n provider: providerFee,\n sourceNetwork: {\n estimate: sourceNetworkFeeEstimate,\n max: sourceNetworkFeeMax,\n },\n targetNetwork: targetNetworkFee,\n },\n isInputBased,\n sourceAmount,\n targetAmount,\n total: {\n fiat: totalFiat,\n usd: totalUsd,\n },\n };\n}\n\n/**\n * Get the source amount to include in totals.\n *\n * @param request - Request parameters.\n * @param request.hasFiatStrategy - Whether a fiat strategy quote is present.\n * @param request.fiatPaymentAmount - The fiat payment amount, if applicable.\n * @param request.hasQuotes - Whether any quotes are present.\n * @param request.targetAmount - The target amount from quotes.\n * @param request.tokenAmount - The summed token amount.\n * @param request.useTargetAmount - Whether fees are already included in the source amount.\n * @returns The payment amount to include in totals.\n */\nfunction getSourceAmount({\n hasFiatStrategy,\n fiatPaymentAmount,\n hasQuotes,\n targetAmount,\n tokenAmount,\n useTargetAmount,\n}: {\n hasFiatStrategy: boolean;\n fiatPaymentAmount?: string;\n hasQuotes: boolean;\n targetAmount: string;\n tokenAmount: string;\n useTargetAmount: boolean;\n}): string {\n if (hasFiatStrategy) {\n return fiatPaymentAmount ?? '0';\n }\n\n if (useTargetAmount && hasQuotes) {\n return targetAmount;\n }\n\n return tokenAmount;\n}\n\n/**\n * Sum a list of fiat value.\n *\n * @param data - List of fiat values.\n * @returns Total fiat value.\n */\nfunction sumFiat(data: FiatValue[]): FiatValue {\n const fiat = sumProperty(data, (item) => item.fiat);\n const usd = sumProperty(data, (item) => item.usd);\n return { fiat, usd };\n}\n\n/**\n * Sum a specific property from a list of items.\n *\n * @param data - List of items.\n * @param getProperty - Function to extract the property to sum from each item.\n * @returns The summed value as a string.\n */\nfunction sumProperty<DataType>(\n data: DataType[],\n getProperty: (item: DataType) => BigNumber.Value,\n): string {\n return data\n .map(getProperty)\n .reduce<BigNumber>((total, value) => total.plus(value), new BigNumber(0))\n .toString(10);\n}\n"]}
|
|
1
|
+
{"version":3,"file":"totals.js","sourceRoot":"","sources":["../../src/utils/totals.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC;AAEzC,OAAO,EAAE,sBAAsB,EAAE,MAAM,iBAAiB,CAAC;AA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AAiB,IAAI,GAAG,CAAC;IAClC,CAAC;IAED,IAAI,eAAe,IAAI,SAAS,EAAE,CAAC;QACjC,OAAO,YAAY,CAAC;IACtB,CAAC;IAED,OAAO,WAAW,CAAC;AACrB,CAAC;AAED;;;;;GAKG;AACH,SAAS,OAAO,CAAC,IAAiB;IAChC,MAAM,IAAI,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACpD,MAAM,GAAG,GAAG,WAAW,CAAC,IAAI,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC;IAClD,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,CAAC;AACvB,CAAC;AAED;;;;;;GAMG;AACH,SAAS,WAAW,CAClB,IAAgB,EAChB,WAAgD;IAEhD,OAAO,IAAI;SACR,GAAG,CAAC,WAAW,CAAC;SAChB,MAAM,CAAY,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,IAAI,SAAS,CAAC,CAAC,CAAC,CAAC;SACxE,QAAQ,CAAC,EAAE,CAAC,CAAC;AAClB,CAAC","sourcesContent":["import type { TransactionMeta } from '@metamask/transaction-controller';\nimport { BigNumber } from 'bignumber.js';\n\nimport { TransactionPayStrategy } from '../constants.js';\nimport type {\n FiatValue,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n TransactionPayRequiredToken,\n TransactionPayTotals,\n} from '../types.js';\nimport { sumAmounts } from './amounts.js';\nimport { calculateTransactionGasCost } from './gas.js';\n\n/**\n * Calculate totals for a list of quotes and tokens.\n *\n * @param request - Request parameters.\n * @param request.fiatPaymentAmount - The amount of the transaction in fiat.\n * @param request.quotes - List of bridge quotes.\n * @param request.messenger - Controller messenger.\n * @param request.tokens - List of required tokens.\n * @param request.transaction - Transaction metadata.\n * @returns The calculated totals in USD and fiat currency.\n */\nexport function calculateTotals({\n fiatPaymentAmount,\n quotes,\n messenger,\n tokens,\n transaction,\n}: {\n fiatPaymentAmount?: string;\n quotes: TransactionPayQuote<unknown>[];\n messenger: TransactionPayControllerMessenger;\n tokens: TransactionPayRequiredToken[];\n transaction: TransactionMeta;\n}): TransactionPayTotals {\n const metaMaskFee = sumFiat(quotes.map((quote) => quote.fees.metaMask));\n const providerFee = sumFiat(quotes.map((quote) => quote.fees.provider));\n const providerFiatFee = sumFiat(\n quotes.map((quote) => quote.fees.providerFiat ?? { fiat: '0', usd: '0' }),\n );\n const hasFiatStrategy = quotes.some(\n (quote) => quote.strategy === TransactionPayStrategy.Fiat,\n );\n\n const sourceNetworkFeeMax = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.max),\n );\n\n const sourceNetworkFeeEstimate = sumAmounts(\n quotes.map((quote) => quote.fees.sourceNetwork.estimate),\n );\n\n const transactionNetworkFee = calculateTransactionGasCost(\n transaction,\n messenger,\n );\n\n const targetNetworkFee = quotes?.length\n ? {\n ...sumFiat(quotes.map((quote) => quote.fees.targetNetwork)),\n isGasFeeToken: false,\n }\n : transactionNetworkFee;\n\n const sourceAmount = sumAmounts(quotes.map((quote) => quote.sourceAmount));\n const targetAmount = sumFiat(quotes.map((quote) => quote.targetAmount));\n\n const quoteTokens = tokens.filter(\n (singleToken) => !singleToken.skipIfBalance,\n );\n\n const amountFiat = sumProperty(quoteTokens, (token) => token.amountFiat);\n const amountUsd = sumProperty(quoteTokens, (token) => token.amountUsd);\n const hasQuotes = quotes.length > 0;\n const isInputBased =\n hasQuotes && quotes.every((quote) => quote.isInputBased === true);\n\n const sourceAmountFiat = getSourceAmount({\n hasFiatStrategy,\n fiatPaymentAmount,\n hasQuotes,\n targetAmount: targetAmount.fiat,\n tokenAmount: amountFiat,\n useTargetAmount: isInputBased,\n });\n\n const sourceAmountUsd = getSourceAmount({\n hasFiatStrategy,\n fiatPaymentAmount,\n hasQuotes,\n targetAmount: targetAmount.usd,\n tokenAmount: amountUsd,\n useTargetAmount: isInputBased,\n });\n\n const includedFees = sumFiat(\n quotes\n .filter((quote) => quote.areFeesIncludedInSourceAmount)\n .map((quote) => ({\n fiat: getQuoteFeeTotal(quote, 'fiat'),\n usd: getQuoteFeeTotal(quote, 'usd'),\n })),\n );\n\n const totalFiat = new BigNumber(providerFee.fiat)\n .plus(metaMaskFee.fiat)\n .plus(sourceNetworkFeeEstimate.fiat)\n .plus(targetNetworkFee.fiat)\n .plus(sourceAmountFiat)\n .minus(includedFees.fiat)\n .toString(10);\n\n const totalUsd = new BigNumber(providerFee.usd)\n .plus(metaMaskFee.usd)\n .plus(sourceNetworkFeeEstimate.usd)\n .plus(targetNetworkFee.usd)\n .plus(sourceAmountUsd)\n .minus(includedFees.usd)\n .toString(10);\n\n const estimatedDuration = Number(\n sumProperty(quotes, (quote) => quote.estimatedDuration),\n );\n\n const isSourceGasFeeToken = quotes.some(\n (quote) => quote.fees.isSourceGasFeeToken,\n );\n\n const isTargetGasFeeToken =\n Boolean(targetNetworkFee.isGasFeeToken) ||\n quotes.some((quote) => quote.fees.isTargetGasFeeToken);\n\n return {\n estimatedDuration,\n fees: {\n isSourceGasFeeToken,\n isTargetGasFeeToken,\n providerFiat: providerFiatFee,\n metaMask: metaMaskFee,\n provider: providerFee,\n sourceNetwork: {\n estimate: sourceNetworkFeeEstimate,\n max: sourceNetworkFeeMax,\n },\n targetNetwork: targetNetworkFee,\n },\n isInputBased,\n sourceAmount,\n targetAmount,\n total: {\n fiat: totalFiat,\n usd: totalUsd,\n },\n };\n}\n\nfunction getQuoteFeeTotal(\n quote: TransactionPayQuote<unknown>,\n currency: keyof FiatValue,\n): string {\n return new BigNumber(quote.fees.provider[currency])\n .plus(quote.fees.metaMask[currency])\n .plus(quote.fees.sourceNetwork.estimate[currency])\n .plus(quote.fees.targetNetwork[currency])\n .toString(10);\n}\n\n/**\n * Get the source amount to include in totals.\n *\n * @param request - Request parameters.\n * @param request.hasFiatStrategy - Whether a fiat strategy quote is present.\n * @param request.fiatPaymentAmount - The fiat payment amount, if applicable.\n * @param request.hasQuotes - Whether any quotes are present.\n * @param request.targetAmount - The target amount from quotes.\n * @param request.tokenAmount - The summed token amount.\n * @param request.useTargetAmount - Whether fees are already included in the source amount.\n * @returns The payment amount to include in totals.\n */\nfunction getSourceAmount({\n hasFiatStrategy,\n fiatPaymentAmount,\n hasQuotes,\n targetAmount,\n tokenAmount,\n useTargetAmount,\n}: {\n hasFiatStrategy: boolean;\n fiatPaymentAmount?: string;\n hasQuotes: boolean;\n targetAmount: string;\n tokenAmount: string;\n useTargetAmount: boolean;\n}): string {\n if (hasFiatStrategy) {\n return fiatPaymentAmount ?? '0';\n }\n\n if (useTargetAmount && hasQuotes) {\n return targetAmount;\n }\n\n return tokenAmount;\n}\n\n/**\n * Sum a list of fiat value.\n *\n * @param data - List of fiat values.\n * @returns Total fiat value.\n */\nfunction sumFiat(data: FiatValue[]): FiatValue {\n const fiat = sumProperty(data, (item) => item.fiat);\n const usd = sumProperty(data, (item) => item.usd);\n return { fiat, usd };\n}\n\n/**\n * Sum a specific property from a list of items.\n *\n * @param data - List of items.\n * @param getProperty - Function to extract the property to sum from each item.\n * @returns The summed value as a string.\n */\nfunction sumProperty<DataType>(\n data: DataType[],\n getProperty: (item: DataType) => BigNumber.Value,\n): string {\n return data\n .map(getProperty)\n .reduce<BigNumber>((total, value) => total.plus(value), new BigNumber(0))\n .toString(10);\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/transaction-pay-controller",
|
|
3
|
-
"version": "28.0.2-preview-
|
|
3
|
+
"version": "28.0.2-preview-5121808e1",
|
|
4
4
|
"description": "Manages alternate payment strategies to provide required funds for transactions in MetaMask",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|