@metamask-previews/transaction-pay-controller 27.1.0-preview-e0510042f → 27.1.0-preview-ec24abb79
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 -3
- package/dist/strategy/fiat/fiat-direct-musd.cjs +53 -10
- package/dist/strategy/fiat/fiat-direct-musd.cjs.map +1 -1
- package/dist/strategy/fiat/fiat-direct-musd.d.cts.map +1 -1
- package/dist/strategy/fiat/fiat-direct-musd.d.mts.map +1 -1
- package/dist/strategy/fiat/fiat-direct-musd.mjs +54 -11
- package/dist/strategy/fiat/fiat-direct-musd.mjs.map +1 -1
- package/dist/strategy/fiat/fiat-quotes.cjs +38 -12
- package/dist/strategy/fiat/fiat-quotes.cjs.map +1 -1
- package/dist/strategy/fiat/fiat-quotes.mjs +39 -13
- package/dist/strategy/fiat/fiat-quotes.mjs.map +1 -1
- package/dist/strategy/fiat/utils.cjs +45 -101
- package/dist/strategy/fiat/utils.cjs.map +1 -1
- package/dist/strategy/fiat/utils.d.cts +28 -37
- package/dist/strategy/fiat/utils.d.cts.map +1 -1
- package/dist/strategy/fiat/utils.d.mts +28 -37
- package/dist/strategy/fiat/utils.d.mts.map +1 -1
- package/dist/strategy/fiat/utils.mjs +43 -97
- package/dist/strategy/fiat/utils.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +4 -2
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +4 -2
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/totals.cjs +15 -0
- package/dist/utils/totals.cjs.map +1 -1
- package/dist/utils/totals.d.cts.map +1 -1
- package/dist/utils/totals.d.mts.map +1 -1
- package/dist/utils/totals.mjs +15 -0
- package/dist/utils/totals.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -147,42 +147,33 @@ export declare function validateRelayRateDrift({ originalQuote, discoveryQuote,
|
|
|
147
147
|
*/
|
|
148
148
|
export declare function extractProviderCode(provider: string | undefined): string | null;
|
|
149
149
|
/**
|
|
150
|
-
*
|
|
151
|
-
*
|
|
152
|
-
*
|
|
153
|
-
*
|
|
154
|
-
*
|
|
155
|
-
*
|
|
156
|
-
*
|
|
157
|
-
*
|
|
158
|
-
*
|
|
159
|
-
*
|
|
160
|
-
* @
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
* @param fiatQuote - The ramps quote containing provider and network fees.
|
|
172
|
-
* @returns Combined on-ramp provider fee.
|
|
173
|
-
*/
|
|
174
|
-
export declare function getRampsProviderFiatFee(fiatQuote: RampsQuote): BigNumber;
|
|
175
|
-
/**
|
|
176
|
-
* Normalized on-ramp fee composition. A valid provider-reported total wins;
|
|
177
|
-
* otherwise the total is derived from the safe component values.
|
|
178
|
-
*
|
|
179
|
-
* @param fiatQuote - Ramps quote containing fee fields.
|
|
180
|
-
* @returns Safe component and total fee values.
|
|
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.
|
|
181
170
|
*/
|
|
182
|
-
export declare function
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
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>;
|
|
188
179
|
//# sourceMappingURL=utils.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.d.mts","sourceRoot":"","sources":["../../../src/strategy/fiat/utils.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,KAAK,IAAI,UAAU,EACnB,UAAU,EACV,wBAAwB,EACzB,mCAAmC;AACpC,OAAO,KAAK,EAAE,eAAe,EAAE,yCAAyC;AACxE,OAAO,EAAE,eAAe,EAAE,yCAAyC;AACnE,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAE3C,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAGzC,OAAO,KAAK,EAAE,iCAAiC,EAAE,wBAAuB;AAOxE,OAAO,KAAK,EAAE,UAAU,EAAE,2BAA0B;AACpD,OAAO,KAAK,EAAE,uBAAuB,EAAE,wBAAuB;AAK9D,wBAAgB,6BAA6B,CAC3C,WAAW,EAAE,eAAe,E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ChC;AAED;;;;;;;GAOG;AACH,wBAAgB,uCAAuC,CAAC,EACtD,YAAY,EACZ,QAAQ,GACT,EAAE;IACD,YAAY,EAAE,UAAU,CAAC,cAAc,CAAC,CAAC;IACzC,QAAQ,EAAE,MAAM,CAAC;CAClB,GAAG,MAAM,CAmBT;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,sBAAsB,CAAC,EACrC,aAAa,EACb,cAAc,EACd,mBAAmB,EACnB,aAAa,GACd,EAAE;IACD,aAAa,EAAE,UAAU,CAAC;IAC1B,cAAc,EAAE,UAAU,CAAC;IAC3B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,aAAa,EAAE,MAAM,CAAC;CACvB,GAAG,IAAI,CA2CP;AAED;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CACjC,QAAQ,EAAE,MAAM,GAAG,SAAS,GAC3B,MAAM,GAAG,IAAI,CAYf;AAQD;;;;;;;;;;;;;;;;;;;;;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,CAmC5B"}
|
|
@@ -59,7 +59,7 @@ export function isMoneyAccountDepositTransaction(transaction) {
|
|
|
59
59
|
* @returns The first matching Ramps quote.
|
|
60
60
|
*/
|
|
61
61
|
export async function getRampsQuote({ adjustedAmount, errorMessage = 'No matching ramps quote found for selected provider', fiatAsset, fiatPaymentMethod, messenger, walletAddress, }) {
|
|
62
|
-
const
|
|
62
|
+
const quotes = await messenger.call('RampsController:getQuotes', {
|
|
63
63
|
amount: adjustedAmount,
|
|
64
64
|
assetId: buildCaipAssetType(fiatAsset.chainId, fiatAsset.address),
|
|
65
65
|
autoSelectProvider: true,
|
|
@@ -67,34 +67,14 @@ export async function getRampsQuote({ adjustedAmount, errorMessage = 'No matchin
|
|
|
67
67
|
paymentMethods: [fiatPaymentMethod],
|
|
68
68
|
restrictToKnownOrNativeProviders: true,
|
|
69
69
|
walletAddress,
|
|
70
|
-
};
|
|
71
|
-
const quotes = await messenger.call('RampsController:getQuotes', quoteRequest);
|
|
70
|
+
});
|
|
72
71
|
log('Fetched ramps quotes', {
|
|
73
72
|
quotesCount: quotes.success?.length ?? 0,
|
|
74
73
|
});
|
|
75
|
-
|
|
74
|
+
const quote = quotes.success?.[0];
|
|
76
75
|
if (!quote) {
|
|
77
76
|
throw new Error(errorMessage);
|
|
78
77
|
}
|
|
79
|
-
const isTransak = quote.provider
|
|
80
|
-
.replace(/^\/providers\//u, '')
|
|
81
|
-
.startsWith('transak');
|
|
82
|
-
if (isTransak) {
|
|
83
|
-
const feeOnTopQuotes = await messenger.call('RampsController:getQuotes', {
|
|
84
|
-
...quoteRequest,
|
|
85
|
-
autoSelectProvider: false,
|
|
86
|
-
providers: [quote.provider],
|
|
87
|
-
isFeeExcludedFromFiat: true,
|
|
88
|
-
forceRefresh: true,
|
|
89
|
-
});
|
|
90
|
-
quote = feeOnTopQuotes.success?.[0];
|
|
91
|
-
if (!quote) {
|
|
92
|
-
throw new Error(errorMessage);
|
|
93
|
-
}
|
|
94
|
-
if (quote.quote.feeMode?.effective !== 'fee-on-top') {
|
|
95
|
-
throw new Error('Transak did not return a fee-on-top quote');
|
|
96
|
-
}
|
|
97
|
-
}
|
|
98
78
|
return quote;
|
|
99
79
|
}
|
|
100
80
|
/**
|
|
@@ -255,87 +235,53 @@ export function extractProviderCode(provider) {
|
|
|
255
235
|
return parts.length === 1 ? parts[0] : null;
|
|
256
236
|
}
|
|
257
237
|
/**
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
* Ramps quotes type their fee fields as `number | string | undefined`, and a
|
|
261
|
-
* provider can report a value we cannot use (missing, `NaN`, or negative).
|
|
262
|
-
* Treating those as zero matches how the rest of the ramps surface reads fee
|
|
263
|
-
* fields (`partnerFees ?? 0` in the client analytics payloads, `extraFee ?? 0`
|
|
264
|
-
* in the aggregator quote list), so quotes stay usable instead of being
|
|
265
|
-
* discarded over a single bad field.
|
|
266
|
-
*
|
|
267
|
-
* @param value - Raw fee value from a ramps quote.
|
|
268
|
-
* @returns The fee as a non-negative finite BigNumber, or zero.
|
|
238
|
+
* Provider codes that identify Transak's native (non-aggregator) integration.
|
|
239
|
+
* Matches the codes emitted by `TransakService` for production and staging.
|
|
269
240
|
*/
|
|
270
|
-
|
|
271
|
-
const fee = new BigNumber(value ?? 0);
|
|
272
|
-
return fee.isFinite() && fee.isGreaterThanOrEqualTo(0)
|
|
273
|
-
? fee
|
|
274
|
-
: new BigNumber(0);
|
|
275
|
-
}
|
|
276
|
-
function getValidatedFee(value, field, strict) {
|
|
277
|
-
if (value === undefined) {
|
|
278
|
-
return new BigNumber(0);
|
|
279
|
-
}
|
|
280
|
-
const fee = new BigNumber(value);
|
|
281
|
-
if (fee.isFinite() && fee.isGreaterThanOrEqualTo(0)) {
|
|
282
|
-
return fee;
|
|
283
|
-
}
|
|
284
|
-
if (strict) {
|
|
285
|
-
throw new Error(`Malformed fee-on-top ${field}`);
|
|
286
|
-
}
|
|
287
|
-
return new BigNumber(0);
|
|
288
|
-
}
|
|
241
|
+
const NATIVE_TRANSAK_PROVIDER_CODES = ['transak-native', 'transak-native-staging'];
|
|
289
242
|
/**
|
|
290
|
-
*
|
|
243
|
+
* When the resolved ramps provider is Transak Native, fetches the native
|
|
244
|
+
* Transak buy quote and returns its total fee so the estimate matches what
|
|
245
|
+
* Transak Native actually charges.
|
|
291
246
|
*
|
|
292
|
-
*
|
|
293
|
-
*
|
|
294
|
-
*
|
|
295
|
-
*
|
|
247
|
+
* The native lookup (`/api/v2/lookup/quotes`) is an unauthenticated, API-key
|
|
248
|
+
* only call, so it is safe to run at estimate time before the user signs in to
|
|
249
|
+
* Transak. Returns `null` when the provider is not Transak Native, or when the
|
|
250
|
+
* native lookup fails or returns an unusable fee, so the caller falls back to
|
|
251
|
+
* the aggregator quote's fee.
|
|
296
252
|
*
|
|
297
|
-
* @param
|
|
298
|
-
* @
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
*
|
|
305
|
-
*
|
|
306
|
-
*
|
|
307
|
-
* @param fiatQuote - Ramps quote containing fee fields.
|
|
308
|
-
* @returns Safe component and total fee values.
|
|
253
|
+
* @param options - Native fee options.
|
|
254
|
+
* @param options.adjustedAmount - Fiat amount (USD) sent to ramps.
|
|
255
|
+
* @param options.fiatAsset - Fiat asset being bought.
|
|
256
|
+
* @param options.fiatPaymentMethod - Selected fiat payment method.
|
|
257
|
+
* @param options.fiatQuote - The resolved aggregator quote (used to detect native).
|
|
258
|
+
* @param options.isFeeExcludedFromFiat - Whether Transak adds its fee on top of
|
|
259
|
+
* the fiat amount (`true`) or carves it out of the amount (`false`). Must mirror
|
|
260
|
+
* the eventual checkout mode so the estimate equals the charge.
|
|
261
|
+
* @param options.messenger - Controller messenger.
|
|
262
|
+
* @returns The native total fee as a BigNumber, or `null` to use the aggregator fee.
|
|
309
263
|
*/
|
|
310
|
-
export function
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
const extraFee = getValidatedFee(fiatQuote.quote.extraFee, 'extraFee', strict);
|
|
315
|
-
const componentTotal = providerFee.plus(networkFee).plus(extraFee);
|
|
316
|
-
const rawReportedTotal = fiatQuote.quote.totalFees === undefined
|
|
317
|
-
? undefined
|
|
318
|
-
: new BigNumber(fiatQuote.quote.totalFees);
|
|
319
|
-
let reportedTotal = componentTotal;
|
|
320
|
-
if (rawReportedTotal?.isFinite() &&
|
|
321
|
-
rawReportedTotal.isGreaterThanOrEqualTo(0)) {
|
|
322
|
-
reportedTotal = rawReportedTotal;
|
|
264
|
+
export async function getNativeTransakRampsFee({ adjustedAmount, fiatAsset, fiatPaymentMethod, fiatQuote, isFeeExcludedFromFiat, messenger, }) {
|
|
265
|
+
const providerCode = extractProviderCode(fiatQuote.provider);
|
|
266
|
+
if (!providerCode || !NATIVE_TRANSAK_PROVIDER_CODES.includes(providerCode)) {
|
|
267
|
+
return null;
|
|
323
268
|
}
|
|
324
|
-
|
|
325
|
-
|
|
269
|
+
try {
|
|
270
|
+
const assetId = buildCaipAssetType(fiatAsset.chainId, fiatAsset.address);
|
|
271
|
+
const network = assetId.split('/')[0];
|
|
272
|
+
const nativeQuote = await messenger.call('RampsController:transakGetBuyQuote', DEFAULT_FIAT_CURRENCY, assetId, network, fiatPaymentMethod, String(adjustedAmount), isFeeExcludedFromFiat);
|
|
273
|
+
const fee = new BigNumber(nativeQuote.totalFee ?? NaN);
|
|
274
|
+
if (!fee.isFinite() || fee.isLessThan(0)) {
|
|
275
|
+
log('Native Transak quote returned an unusable fee; using aggregator fee', {
|
|
276
|
+
totalFee: nativeQuote.totalFee,
|
|
277
|
+
});
|
|
278
|
+
return null;
|
|
279
|
+
}
|
|
280
|
+
return fee;
|
|
326
281
|
}
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
.integerValue()
|
|
331
|
-
.isEqualTo(componentTotal.shiftedBy(2).integerValue())) {
|
|
332
|
-
throw new Error('Malformed fee-on-top fee total');
|
|
282
|
+
catch (error) {
|
|
283
|
+
log('Native Transak fee fetch failed; using aggregator fee', { error });
|
|
284
|
+
return null;
|
|
333
285
|
}
|
|
334
|
-
return {
|
|
335
|
-
providerFee,
|
|
336
|
-
networkFee,
|
|
337
|
-
extraFee,
|
|
338
|
-
totalFees: reportedTotal,
|
|
339
|
-
};
|
|
340
286
|
}
|
|
341
287
|
//# sourceMappingURL=utils.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.mjs","sour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AW;QACX,UAAU;QACV,QAAQ;QACR,SAAS,EAAE,aAAa;KACzB,CAAC;AACJ,CAAC","sourcesContent":["import type {\n Quote as RampsQuote,\n RampsOrder,\n RampsOrderCryptoCurrency,\n} from '@metamask/ramps-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger.js';\nimport type { TransactionPayControllerMessenger } from '../../types.js';\nimport {\n getFiatAssetPerTransactionType,\n getFiatEnabledTypes,\n} from '../../utils/feature-flags.js';\nimport { buildCaipAssetType, 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 quoteRequest = {\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 const quotes = await messenger.call(\n 'RampsController:getQuotes',\n quoteRequest,\n );\n\n log('Fetched ramps quotes', {\n quotesCount: quotes.success?.length ?? 0,\n });\n\n let quote = quotes.success?.[0];\n\n if (!quote) {\n throw new Error(errorMessage);\n }\n\n const isTransak = quote.provider\n .replace(/^\\/providers\\//u, '')\n .startsWith('transak');\n if (isTransak) {\n const feeOnTopQuotes = await messenger.call('RampsController:getQuotes', {\n ...quoteRequest,\n autoSelectProvider: false,\n providers: [quote.provider],\n isFeeExcludedFromFiat: true,\n forceRefresh: true,\n });\n quote = feeOnTopQuotes.success?.[0];\n if (!quote) {\n throw new Error(errorMessage);\n }\n if (quote.quote.feeMode?.effective !== 'fee-on-top') {\n throw new Error('Transak did not return a fee-on-top quote');\n }\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 * Coerces a quote fee field into a usable non-negative amount.\n *\n * Ramps quotes type their fee fields as `number | string | undefined`, and a\n * provider can report a value we cannot use (missing, `NaN`, or negative).\n * Treating those as zero matches how the rest of the ramps surface reads fee\n * fields (`partnerFees ?? 0` in the client analytics payloads, `extraFee ?? 0`\n * in the aggregator quote list), so quotes stay usable instead of being\n * discarded over a single bad field.\n *\n * @param value - Raw fee value from a ramps quote.\n * @returns The fee as a non-negative finite BigNumber, or zero.\n */\nexport function 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\nfunction getValidatedFee(\n value: BigNumber.Value | undefined,\n field: string,\n strict: boolean,\n): BigNumber {\n if (value === undefined) {\n return new BigNumber(0);\n }\n const fee = new BigNumber(value);\n if (fee.isFinite() && fee.isGreaterThanOrEqualTo(0)) {\n return fee;\n }\n if (strict) {\n throw new Error(`Malformed fee-on-top ${field}`);\n }\n return new BigNumber(0);\n}\n\n/**\n * Combined on-ramp provider fee for the `providerFiat` breakdown.\n *\n * Ramps providers handle network gas fees themselves but report them\n * separately as `networkFee` alongside their own `providerFee`. Both are the\n * on-ramp's cost, so they combine into a single bucket. The partner\n * (MetaMask) fee is deliberately excluded, so it cannot be counted twice.\n *\n * @param fiatQuote - The ramps quote containing provider and network fees.\n * @returns Combined on-ramp provider fee.\n */\nexport function getRampsProviderFiatFee(fiatQuote: RampsQuote): BigNumber {\n return getSafeFee(fiatQuote.quote.providerFee).plus(\n getSafeFee(fiatQuote.quote.networkFee),\n );\n}\n\n/**\n * Normalized on-ramp fee composition. A valid provider-reported total wins;\n * otherwise the total is derived from the safe component values.\n *\n * @param fiatQuote - Ramps quote containing fee fields.\n * @returns Safe component and total fee values.\n */\nexport function getRampsFeeComposition(fiatQuote: RampsQuote): {\n providerFee: BigNumber;\n networkFee: BigNumber;\n extraFee: BigNumber;\n totalFees: BigNumber;\n} {\n const strict = fiatQuote.quote.feeMode?.effective === 'fee-on-top';\n const providerFee = getValidatedFee(\n fiatQuote.quote.providerFee,\n 'providerFee',\n strict,\n );\n const networkFee = getValidatedFee(\n fiatQuote.quote.networkFee,\n 'networkFee',\n strict,\n );\n const extraFee = getValidatedFee(\n fiatQuote.quote.extraFee,\n 'extraFee',\n strict,\n );\n const componentTotal = providerFee.plus(networkFee).plus(extraFee);\n const rawReportedTotal =\n fiatQuote.quote.totalFees === undefined\n ? undefined\n : new BigNumber(fiatQuote.quote.totalFees);\n let reportedTotal = componentTotal;\n if (\n rawReportedTotal?.isFinite() &&\n rawReportedTotal.isGreaterThanOrEqualTo(0)\n ) {\n reportedTotal = rawReportedTotal;\n } else if (fiatQuote.quote.totalFees !== undefined && strict) {\n reportedTotal = getValidatedFee(\n fiatQuote.quote.totalFees,\n 'totalFees',\n true,\n );\n }\n\n if (\n strict &&\n !reportedTotal\n .shiftedBy(2)\n .integerValue()\n .isEqualTo(componentTotal.shiftedBy(2).integerValue())\n ) {\n throw new Error('Malformed fee-on-top fee total');\n }\n\n return {\n providerFee,\n networkFee,\n extraFee,\n totalFees: reportedTotal,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"utils.mjs","sourceRoot":"","sources":["../../../src/strategy/fiat/utils.ts"],"names":[],"mappings":"AAMA,OAAO,EAAE,eAAe,EAAE,yCAAyC;AAEnE,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AACrD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EAAE,aAAa,EAAE,yBAAwB;AAEhD,OAAO,EACL,8BAA8B,EAC9B,mBAAmB,EACpB,sCAAqC;AACtC,OAAO,EAAE,kBAAkB,EAAE,YAAY,EAAE,8BAA6B;AACxE,OAAO,EAAE,8BAA8B,EAAE,oCAAmC;AAG5E,OAAO,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,wBAAuB;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;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,sBAAsB,CACpC,WAA4B,EAC5B,YAA+B;IAE/B,IAAI,WAAW,CAAC,IAAI,KAA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GAQV;IACC,MAAM,YAAY,GAAG,mBAAmB,CAAC,SAAS,CAAC,QAAQ,CAAC,CAAC;IAE7D,IAAI,CAAC,YAAY,IAAI,CAAC,6BAA6B,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE,CAAC;QAC3E,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,CAAC;QACH,MAAM,OAAO,GAAG,kBAAkB,CAAC,SAAS,CAAC,OAAO,EAAE,SAAS,CAAC,OAAO,CAAC,CAAC;QACzE,MAAM,OAAO,GAAG,OAAO,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QAEtC,MAAM,WAAW,GAAG,MAAM,SAAS,CAAC,IAAI,CACtC,oCAAoC,EACpC,qBAAqB,EACrB,OAAO,EACP,OAAO,EACP,iBAAiB,EACjB,MAAM,CAAC,cAAc,CAAC,EACtB,qBAAqB,CACtB,CAAC;QAEF,MAAM,GAAG,GAAG,IAAI,SAAS,CAAC,WAAW,CAAC,QAAQ,IAAI,GAAG,CAAC,CAAC;QAEvD,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,IAAI,GAAG,CAAC,UAAU,CAAC,CAAC,CAAC,EAAE,CAAC;YACzC,GAAG,CAAC,qEAAqE,EAAE;gBACzE,QAAQ,EAAE,WAAW,CAAC,QAAQ;aAC/B,CAAC,CAAC;YACH,OAAO,IAAI,CAAC;QACd,CAAC;QAED,OAAO,GAAG,CAAC;IACb,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,GAAG,CAAC,uDAAuD,EAAE,EAAE,KAAK,EAAE,CAAC,CAAC;QACxE,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC","sourcesContent":["import type {\n Quote as RampsQuote,\n RampsOrder,\n RampsOrderCryptoCurrency,\n} from '@metamask/ramps-controller';\nimport type { TransactionMeta } from '@metamask/transaction-controller';\nimport { TransactionType } from '@metamask/transaction-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport { projectLogger } from '../../logger.js';\nimport type { TransactionPayControllerMessenger } from '../../types.js';\nimport {\n getFiatAssetPerTransactionType,\n getFiatEnabledTypes,\n} from '../../utils/feature-flags.js';\nimport { buildCaipAssetType, 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 = ['transak-native', 'transak-native-staging'];\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 'RampsController:transakGetBuyQuote',\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('Native Transak quote returned an unusable fee; using aggregator fee', {\n totalFee: nativeQuote.totalFee,\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.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AA4QA;;;GAGG;AACU,QAAA,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.cjs","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":";;;AA8QA;;;GAGG;AACU,QAAA,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} 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 | 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"]}
|
package/dist/types.d.cts
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 } 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.cjs";
|
|
24
24
|
import type { TransactionPayControllerMethodActions } from "./TransactionPayController-method-action-types.cjs";
|
|
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 | 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. */
|