@metamask-previews/transaction-pay-controller 26.4.1-preview-fa46676 → 26.4.1-preview-7cfd8be
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 +0 -6
- package/dist/TransactionPayController.cjs +6 -6
- package/dist/TransactionPayController.cjs.map +1 -1
- package/dist/TransactionPayController.d.cts +1 -1
- package/dist/TransactionPayController.d.cts.map +1 -1
- package/dist/TransactionPayController.d.mts +1 -1
- package/dist/TransactionPayController.d.mts.map +1 -1
- package/dist/TransactionPayController.mjs +6 -6
- package/dist/TransactionPayController.mjs.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.cts.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +26 -20
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +26 -20
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/source-amounts.cjs +37 -28
- package/dist/utils/source-amounts.cjs.map +1 -1
- package/dist/utils/source-amounts.d.cts +3 -5
- package/dist/utils/source-amounts.d.cts.map +1 -1
- package/dist/utils/source-amounts.d.mts +3 -5
- package/dist/utils/source-amounts.d.mts.map +1 -1
- package/dist/utils/source-amounts.mjs +38 -29
- package/dist/utils/source-amounts.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -15,36 +15,28 @@ const log = (0, utils_1.createModuleLogger)(logger_js_1.projectLogger, 'source-a
|
|
|
15
15
|
* @param transactionId - ID of the transaction to update.
|
|
16
16
|
* @param transactionData - Existing transaction data.
|
|
17
17
|
* @param messenger - Controller messenger.
|
|
18
|
-
* @param
|
|
19
|
-
* calculation. Called only when `isMaxAmount` is true. Return `undefined` to fall back to
|
|
20
|
-
* the built-in token balance.
|
|
18
|
+
* @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.
|
|
21
19
|
*/
|
|
22
|
-
function updateSourceAmounts(transactionId, transactionData, messenger,
|
|
20
|
+
function updateSourceAmounts(transactionId, transactionData, messenger, resolveSourceAmount) {
|
|
23
21
|
if (!transactionData) {
|
|
24
22
|
return;
|
|
25
23
|
}
|
|
26
|
-
const { isMaxAmount, isPostQuote, paymentToken, tokens } = transactionData;
|
|
24
|
+
const { isMaxAmount, isPostQuote, paymentOverride, paymentToken, tokens } = transactionData;
|
|
27
25
|
if (!tokens.length || !paymentToken) {
|
|
28
26
|
return;
|
|
29
27
|
}
|
|
30
|
-
const transaction = getBalance && isMaxAmount
|
|
31
|
-
? (0, transaction_js_1.getTransaction)(transactionId, messenger)
|
|
32
|
-
: undefined;
|
|
33
|
-
const balanceOverride = getBalance && transaction
|
|
34
|
-
? getBalance({ transaction, transactionData })
|
|
35
|
-
: undefined;
|
|
36
28
|
// For post-quote flows, source amounts are calculated differently
|
|
37
29
|
// The source is the transaction's required token, not the selected token
|
|
38
30
|
if (isPostQuote) {
|
|
39
31
|
const { isHyperliquidSource, isPolymarketDepositWallet } = transactionData;
|
|
40
|
-
const sourceAmounts = calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount ?? false, isHyperliquidSource, isPolymarketDepositWallet
|
|
32
|
+
const sourceAmounts = calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount ?? false, isHyperliquidSource, isPolymarketDepositWallet);
|
|
41
33
|
log('Updated post-quote source amounts', { transactionId, sourceAmounts });
|
|
42
34
|
transactionData.sourceAmounts = sourceAmounts;
|
|
43
35
|
return;
|
|
44
36
|
}
|
|
45
37
|
const { isQuoteRequired } = transactionData;
|
|
46
38
|
const sourceAmounts = tokens
|
|
47
|
-
.map((singleToken) => calculateSourceAmount(paymentToken, singleToken, messenger, transactionId, isMaxAmount ?? false, isQuoteRequired,
|
|
39
|
+
.map((singleToken) => calculateSourceAmount(paymentToken, singleToken, messenger, transactionId, isMaxAmount ?? false, isQuoteRequired, paymentOverride, resolveSourceAmount))
|
|
48
40
|
.filter(Boolean);
|
|
49
41
|
log('Updated source amounts', { transactionId, sourceAmounts });
|
|
50
42
|
transactionData.sourceAmounts = sourceAmounts;
|
|
@@ -60,10 +52,9 @@ exports.updateSourceAmounts = updateSourceAmounts;
|
|
|
60
52
|
* @param isMaxAmount - Whether the transaction is a maximum amount transaction.
|
|
61
53
|
* @param isHyperliquidSource - Whether the source is HyperLiquid (perps withdrawal).
|
|
62
54
|
* @param isPolymarketDepositWallet - Whether the source is a Polymarket deposit wallet.
|
|
63
|
-
* @param balanceOverride - Optional balance override from the `getBalance` callback.
|
|
64
55
|
* @returns Array of source amounts.
|
|
65
56
|
*/
|
|
66
|
-
function calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount, isHyperliquidSource, isPolymarketDepositWallet
|
|
57
|
+
function calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount, isHyperliquidSource, isPolymarketDepositWallet) {
|
|
67
58
|
return tokens
|
|
68
59
|
.filter((token) => {
|
|
69
60
|
if (token.skipIfBalance) {
|
|
@@ -87,10 +78,8 @@ function calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount, isHy
|
|
|
87
78
|
})
|
|
88
79
|
.map((token) => ({
|
|
89
80
|
sourceAmountHuman: isMaxAmount ? token.balanceHuman : token.amountHuman,
|
|
90
|
-
sourceAmountRaw: isMaxAmount
|
|
91
|
-
|
|
92
|
-
: token.amountRaw,
|
|
93
|
-
sourceBalanceRaw: balanceOverride?.balanceRaw ?? token.balanceRaw,
|
|
81
|
+
sourceAmountRaw: isMaxAmount ? token.balanceRaw : token.amountRaw,
|
|
82
|
+
sourceBalanceRaw: token.balanceRaw,
|
|
94
83
|
sourceChainId: token.chainId,
|
|
95
84
|
sourceTokenAddress: token.address,
|
|
96
85
|
targetTokenAddress: paymentToken.address,
|
|
@@ -105,10 +94,11 @@ function calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount, isHy
|
|
|
105
94
|
* @param transactionId - ID of the transaction.
|
|
106
95
|
* @param isMaxAmount - Whether the transaction is a maximum amount transaction.
|
|
107
96
|
* @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.
|
|
108
|
-
* @param
|
|
97
|
+
* @param paymentOverride - Optional payment source override for the transaction.
|
|
98
|
+
* @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.
|
|
109
99
|
* @returns The source amount or undefined if calculation failed.
|
|
110
100
|
*/
|
|
111
|
-
function calculateSourceAmount(paymentToken, token, messenger, transactionId, isMaxAmount, isQuoteRequired,
|
|
101
|
+
function calculateSourceAmount(paymentToken, token, messenger, transactionId, isMaxAmount, isQuoteRequired, paymentOverride, resolveSourceAmount) {
|
|
112
102
|
const paymentTokenFiatRate = (0, token_js_1.getTokenFiatRate)(messenger, paymentToken.address, paymentToken.chainId);
|
|
113
103
|
if (!paymentTokenFiatRate) {
|
|
114
104
|
return undefined;
|
|
@@ -130,20 +120,39 @@ function calculateSourceAmount(paymentToken, token, messenger, transactionId, is
|
|
|
130
120
|
log('Skipping token as zero amount', { tokenAddress: token.address });
|
|
131
121
|
return undefined;
|
|
132
122
|
}
|
|
123
|
+
const resolvedSourceAmount = resolveSourceAmount?.({
|
|
124
|
+
isMaxAmount,
|
|
125
|
+
paymentOverride,
|
|
126
|
+
});
|
|
127
|
+
if (resolvedSourceAmount) {
|
|
128
|
+
const { sourceAmountRaw } = resolvedSourceAmount;
|
|
129
|
+
const sourceAmountHuman = new bignumber_js_1.BigNumber(sourceAmountRaw)
|
|
130
|
+
.shiftedBy(-paymentToken.decimals)
|
|
131
|
+
.toString(10);
|
|
132
|
+
log('Resolved source amount from callback', {
|
|
133
|
+
tokenAddress: token.address,
|
|
134
|
+
sourceAmountRaw,
|
|
135
|
+
});
|
|
136
|
+
return {
|
|
137
|
+
sourceAmountHuman,
|
|
138
|
+
sourceAmountRaw,
|
|
139
|
+
targetTokenAddress: token.address,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
133
142
|
const sourceAmountHumanValue = new bignumber_js_1.BigNumber(token.amountUsd).div(paymentTokenFiatRate.usdRate);
|
|
134
143
|
const sourceAmountHuman = sourceAmountHumanValue.toString(10);
|
|
135
144
|
const sourceAmountRaw = sourceAmountHumanValue
|
|
136
145
|
.shiftedBy(paymentToken.decimals)
|
|
137
146
|
.toFixed(0);
|
|
138
|
-
//
|
|
139
|
-
//
|
|
140
|
-
//
|
|
141
|
-
//
|
|
142
|
-
//
|
|
143
|
-
if (isMaxAmount) {
|
|
147
|
+
// Money account Max must not use the pay token's on-chain balance. That
|
|
148
|
+
// balance is only un-vaulted mUSD, while the typed required amount already
|
|
149
|
+
// reflects the full withdrawable total (mUSD + vmUSD). Using the typed
|
|
150
|
+
// fiat-derived source keeps isMaxAmount=true (EXACT_INPUT) correct for
|
|
151
|
+
// deposits funded from the money account (e.g. Send to Perps).
|
|
152
|
+
if (isMaxAmount && paymentOverride !== constants_js_1.PaymentOverride.MoneyAccount) {
|
|
144
153
|
return {
|
|
145
154
|
sourceAmountHuman: paymentToken.balanceHuman,
|
|
146
|
-
sourceAmountRaw:
|
|
155
|
+
sourceAmountRaw: paymentToken.balanceRaw,
|
|
147
156
|
targetTokenAddress: token.address,
|
|
148
157
|
};
|
|
149
158
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source-amounts.cjs","sourceRoot":"","sources":["../../src/utils/source-amounts.ts"],"names":[],"mappings":";;;AAIA,2CAAqD;AACrD,+CAAyC;AAEzC,mDAIyB;AAKzB,2CAAqD;AACrD,6CAA6C;AAQ7C,0CAA2D;AAC3D,sDAAkD;AAElD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,yBAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE;;;;;;;;;GASG;AACH,SAAgB,mBAAmB,CACjC,aAAqB,EACrB,eAA4C,EAC5C,SAA4C,EAC5C,UAA+B;IAE/B,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,OAAO;IACT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,WAAW,GAAG,IAAA,+BAAc,EAChC,aAAa,EACb,SAAS,CACS,CAAC;IAErB,OAAO;QACL,qBAAqB,EAAE,WAAW,CAAC,IAAI;QACvC,QAAQ,EAAE,SAAS,CAAC,IAAI,CACtB,sCAAsC,EACtC,WAAW,CACZ;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n TransactionMeta,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ARBITRUM_USDC_ADDRESS,\n CHAIN_ID_ARBITRUM,\n PERPS_DEPOSIT_TYPES,\n} from '../constants.js';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPaymentToken,\n} from '../index.js';\nimport { TransactionPayStrategy } from '../index.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n GetBalanceCallback,\n GetBalanceResponse,\n TransactionPaySourceAmount,\n TransactionData,\n TransactionPayRequiredToken,\n} from '../types.js';\nimport { getTokenFiatRate, isSameToken } from './token.js';\nimport { getTransaction } from './transaction.js';\n\nconst log = createModuleLogger(projectLogger, 'source-amounts');\n\n/**\n * Update the source amounts for a transaction.\n *\n * @param transactionId - ID of the transaction to update.\n * @param transactionData - Existing transaction data.\n * @param messenger - Controller messenger.\n * @param getBalance - Optional callback to override the source balance used for max-amount\n * calculation. Called only when `isMaxAmount` is true. Return `undefined` to fall back to\n * the built-in token balance.\n */\nexport function updateSourceAmounts(\n transactionId: string,\n transactionData: TransactionData | undefined,\n messenger: TransactionPayControllerMessenger,\n getBalance?: GetBalanceCallback,\n): void {\n if (!transactionData) {\n return;\n }\n\n const { isMaxAmount, isPostQuote, paymentToken, tokens } = transactionData;\n\n if (!tokens.length || !paymentToken) {\n return;\n }\n\n const transaction =\n getBalance && isMaxAmount\n ? getTransaction(transactionId, messenger)\n : undefined;\n const balanceOverride =\n getBalance && transaction\n ? getBalance({ transaction, transactionData })\n : undefined;\n\n // For post-quote flows, source amounts are calculated differently\n // The source is the transaction's required token, not the selected token\n if (isPostQuote) {\n const { isHyperliquidSource, isPolymarketDepositWallet } = transactionData;\n const sourceAmounts = calculatePostQuoteSourceAmounts(\n tokens,\n paymentToken,\n isMaxAmount ?? false,\n isHyperliquidSource,\n isPolymarketDepositWallet,\n balanceOverride,\n );\n log('Updated post-quote source amounts', { transactionId, sourceAmounts });\n transactionData.sourceAmounts = sourceAmounts;\n return;\n }\n\n const { isQuoteRequired } = transactionData;\n\n const sourceAmounts = tokens\n .map((singleToken) =>\n calculateSourceAmount(\n paymentToken,\n singleToken,\n messenger,\n transactionId,\n isMaxAmount ?? false,\n isQuoteRequired,\n balanceOverride,\n ),\n )\n .filter(Boolean) as TransactionPaySourceAmount[];\n\n log('Updated source amounts', { transactionId, sourceAmounts });\n\n transactionData.sourceAmounts = sourceAmounts;\n}\n\n/**\n * Calculate source amounts for post-quote flows.\n * In this flow, the required tokens ARE the source tokens,\n * and the payment token is the target (destination).\n *\n * @param tokens - Required tokens from the transaction.\n * @param paymentToken - Selected payment/destination token.\n * @param isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param isHyperliquidSource - Whether the source is HyperLiquid (perps withdrawal).\n * @param isPolymarketDepositWallet - Whether the source is a Polymarket deposit wallet.\n * @param balanceOverride - Optional balance override from the `getBalance` callback.\n * @returns Array of source amounts.\n */\nfunction calculatePostQuoteSourceAmounts(\n tokens: TransactionPayRequiredToken[],\n paymentToken: TransactionPaymentToken,\n isMaxAmount: boolean,\n isHyperliquidSource?: boolean,\n isPolymarketDepositWallet?: boolean,\n balanceOverride?: GetBalanceResponse,\n): TransactionPaySourceAmount[] {\n return tokens\n .filter((token) => {\n if (token.skipIfBalance) {\n return false;\n }\n\n // Skip zero amounts (unless max amount, where we use balance)\n if (token.amountRaw === '0' && !isMaxAmount) {\n log('Skipping token as zero amount', { tokenAddress: token.address });\n return false;\n }\n\n // Skip same token on same chain, unless the source is a synthetic\n // upstream (HyperLiquid HyperCore or Polymarket deposit wallet) that\n // the strategy renormalizes to a different effective source.\n if (\n isSameToken(token, paymentToken) &&\n !isHyperliquidSource &&\n !isPolymarketDepositWallet\n ) {\n log('Skipping token as same as destination token');\n return false;\n }\n\n return true;\n })\n .map((token) => ({\n sourceAmountHuman: isMaxAmount ? token.balanceHuman : token.amountHuman,\n sourceAmountRaw: isMaxAmount\n ? (balanceOverride?.balanceRaw ?? token.balanceRaw)\n : token.amountRaw,\n sourceBalanceRaw: balanceOverride?.balanceRaw ?? token.balanceRaw,\n sourceChainId: token.chainId,\n sourceTokenAddress: token.address,\n targetTokenAddress: paymentToken.address,\n }));\n}\n\n/**\n * Calculate the required source amount for a payment token to cover a target token.\n *\n * @param paymentToken - Selected payment token.\n * @param token - Target token to cover.\n * @param messenger - Controller messenger.\n * @param transactionId - ID of the transaction.\n * @param isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.\n * @param balanceOverride - Optional balance override from the `getBalance` callback.\n * @returns The source amount or undefined if calculation failed.\n */\nfunction calculateSourceAmount(\n paymentToken: TransactionPaymentToken,\n token: TransactionPayRequiredToken,\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n isMaxAmount: boolean,\n isQuoteRequired?: boolean,\n balanceOverride?: GetBalanceResponse,\n): TransactionPaySourceAmount | undefined {\n const paymentTokenFiatRate = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!paymentTokenFiatRate) {\n return undefined;\n }\n\n const hasBalance = new BigNumber(token.balanceRaw).gte(token.amountRaw);\n\n if (token.skipIfBalance && hasBalance) {\n log('Skipping token as sufficient balance', {\n tokenAddress: token.address,\n });\n return undefined;\n }\n\n const { parentTransactionType, strategy } = getStrategyContext(\n transactionId,\n messenger,\n );\n const isAlwaysRequired = isQuoteAlwaysRequired(\n token,\n strategy,\n parentTransactionType,\n isQuoteRequired,\n );\n\n if (isSameToken(token, paymentToken) && !isAlwaysRequired) {\n log('Skipping token as same as payment token');\n return undefined;\n }\n\n if (token.amountRaw === '0') {\n log('Skipping token as zero amount', { tokenAddress: token.address });\n return undefined;\n }\n\n const sourceAmountHumanValue = new BigNumber(token.amountUsd).div(\n paymentTokenFiatRate.usdRate,\n );\n\n const sourceAmountHuman = sourceAmountHumanValue.toString(10);\n\n const sourceAmountRaw = sourceAmountHumanValue\n .shiftedBy(paymentToken.decimals)\n .toFixed(0);\n\n // On Max, use the exact source balance. The client `getBalance` callback is\n // authoritative and owns all balance complexity (perps, predict, money\n // account, payment overrides): when it returns a `balanceOverride`, use it;\n // when it returns `undefined`, that is a deliberate signal to use the pay\n // token's on-chain balance. This path is payment-override agnostic.\n if (isMaxAmount) {\n return {\n sourceAmountHuman: paymentToken.balanceHuman,\n sourceAmountRaw: balanceOverride?.balanceRaw ?? paymentToken.balanceRaw,\n targetTokenAddress: token.address,\n };\n }\n\n return {\n sourceAmountHuman,\n sourceAmountRaw,\n targetTokenAddress: token.address,\n };\n}\n\n/**\n * Determine if a quote is always required for a token and strategy.\n *\n * @param token - Target token.\n * @param strategy - Payment strategy.\n * @param parentTransactionType - Parent transaction type, if available.\n * @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.\n * @returns True if a quote is always required, false otherwise.\n */\nfunction isQuoteAlwaysRequired(\n token: TransactionPayRequiredToken,\n strategy: TransactionPayStrategy,\n parentTransactionType?: TransactionType,\n isQuoteRequired?: boolean,\n): boolean {\n if (isQuoteRequired) {\n return true;\n }\n\n const isHyperliquidDeposit =\n token.chainId === CHAIN_ID_ARBITRUM &&\n token.address.toLowerCase() === ARBITRUM_USDC_ADDRESS.toLowerCase();\n\n return (\n isHyperliquidDeposit &&\n (strategy === TransactionPayStrategy.Relay ||\n (strategy === TransactionPayStrategy.Across &&\n parentTransactionType !== undefined &&\n PERPS_DEPOSIT_TYPES.includes(parentTransactionType)))\n );\n}\n\nfunction getStrategyContext(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): {\n parentTransactionType?: TransactionType;\n strategy: TransactionPayStrategy;\n} {\n const transaction = getTransaction(\n transactionId,\n messenger,\n ) as TransactionMeta;\n\n return {\n parentTransactionType: transaction.type,\n strategy: messenger.call(\n 'TransactionPayController:getStrategy',\n transaction,\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"source-amounts.cjs","sourceRoot":"","sources":["../../src/utils/source-amounts.ts"],"names":[],"mappings":";;;AAIA,2CAAqD;AACrD,+CAAyC;AAEzC,mDAKyB;AAKzB,2CAAqD;AACrD,6CAA6C;AAO7C,0CAA2D;AAC3D,sDAAkD;AAElD,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,yBAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE;;;;;;;GAOG;AACH,SAAgB,mBAAmB,CACjC,aAAqB,EACrB,eAA4C,EAC5C,SAA4C,EAC5C,mBAAiD;IAEjD,IAAI,CAAC,eAAe,EAAE,CAAC;QACrB,OAAO;IACT,CAAC;IAED,MAAM,EAAE,WAAW,EAAE,WAAW,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,EAAE,GACvE,eAAe,CAAC;IAElB,IAAI,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,YAAY,EAAE,CAAC;QACpC,OAAO;IACT,CAAC;IAED,kEAAkE;IAClE,yEAAyE;IACzE,IAAI,WAAW,EAAE,CAAC;QAChB,MAAM,EAAE,mBAAmB,EAAE,yBAAyB,EAAE,GAAG,eAAe,CAAC;QAC3E,MAAM,aAAa,GAAG,+BAA+B,CACnD,MAAM,EACN,YAAY,EACZ,WAAW,IAAI,KAAK,EACpB,mBAAmB,EACnB,yBAAyB,CAC1B,CAAC;QACF,GAAG,CAAC,mCAAmC,EAAE,EAAE,aAAa,EAAE,aAAa,EAAE,CAAC,CAAC;QAC3E,eAAe,CAAC,aAAa,GAAG,aAAa,CAAC;QAC9C,OAAO;IACT,CAAC;IAED,MAAM,EAAE,eAAe,EAAE,GAAG,eAAe,CAAC;IAE5C,MAAM,aAAa,GAAG,MAAM;SAC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eAAe,EAAE,YAAY,CAAC,UAAU;YACxC,kBAAkB,EAAE,KAAK,CAAC,OAAO;SAClC,CAAC;IACJ,CAAC;IAED,OAAO;QACL,iBAAiB;QACjB,eAAe;QACf,kBAAkB,EAAE,KAAK,CAAC,OAAO;KAClC,CAAC;AACJ,CAAC;AAED;;;;;;;;GAQG;AACH,SAAS,qBAAqB,CAC5B,KAAkC,EAClC,QAAgC,EAChC,qBAAuC,EACvC,eAAyB;IAEzB,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,KAAK,gCAAiB;QACnC,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,KAAK,oCAAqB,CAAC,WAAW,EAAE,CAAC;IAEtE,OAAO,CACL,oBAAoB;QACpB,CAAC,QAAQ,KAAK,iCAAsB,CAAC,KAAK;YACxC,CAAC,QAAQ,KAAK,iCAAsB,CAAC,MAAM;gBACzC,qBAAqB,KAAK,SAAS;gBACnC,kCAAmB,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,aAAqB,EACrB,SAA4C;IAK5C,MAAM,WAAW,GAAG,IAAA,+BAAc,EAChC,aAAa,EACb,SAAS,CACS,CAAC;IAErB,OAAO;QACL,qBAAqB,EAAE,WAAW,CAAC,IAAI;QACvC,QAAQ,EAAE,SAAS,CAAC,IAAI,CACtB,sCAAsC,EACtC,WAAW,CACZ;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n TransactionMeta,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ARBITRUM_USDC_ADDRESS,\n CHAIN_ID_ARBITRUM,\n PaymentOverride,\n PERPS_DEPOSIT_TYPES,\n} from '../constants.js';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPaymentToken,\n} from '../index.js';\nimport { TransactionPayStrategy } from '../index.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n TransactionPaySourceAmount,\n TransactionData,\n TransactionPayRequiredToken,\n ResolveSourceAmountCallback,\n} from '../types.js';\nimport { getTokenFiatRate, isSameToken } from './token.js';\nimport { getTransaction } from './transaction.js';\n\nconst log = createModuleLogger(projectLogger, 'source-amounts');\n\n/**\n * Update the source amounts for a transaction.\n *\n * @param transactionId - ID of the transaction to update.\n * @param transactionData - Existing transaction data.\n * @param messenger - Controller messenger.\n * @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.\n */\nexport function updateSourceAmounts(\n transactionId: string,\n transactionData: TransactionData | undefined,\n messenger: TransactionPayControllerMessenger,\n resolveSourceAmount?: ResolveSourceAmountCallback,\n): void {\n if (!transactionData) {\n return;\n }\n\n const { isMaxAmount, isPostQuote, paymentOverride, paymentToken, tokens } =\n transactionData;\n\n if (!tokens.length || !paymentToken) {\n return;\n }\n\n // For post-quote flows, source amounts are calculated differently\n // The source is the transaction's required token, not the selected token\n if (isPostQuote) {\n const { isHyperliquidSource, isPolymarketDepositWallet } = transactionData;\n const sourceAmounts = calculatePostQuoteSourceAmounts(\n tokens,\n paymentToken,\n isMaxAmount ?? false,\n isHyperliquidSource,\n isPolymarketDepositWallet,\n );\n log('Updated post-quote source amounts', { transactionId, sourceAmounts });\n transactionData.sourceAmounts = sourceAmounts;\n return;\n }\n\n const { isQuoteRequired } = transactionData;\n\n const sourceAmounts = tokens\n .map((singleToken) =>\n calculateSourceAmount(\n paymentToken,\n singleToken,\n messenger,\n transactionId,\n isMaxAmount ?? false,\n isQuoteRequired,\n paymentOverride,\n resolveSourceAmount,\n ),\n )\n .filter(Boolean) as TransactionPaySourceAmount[];\n\n log('Updated source amounts', { transactionId, sourceAmounts });\n\n transactionData.sourceAmounts = sourceAmounts;\n}\n\n/**\n * Calculate source amounts for post-quote flows.\n * In this flow, the required tokens ARE the source tokens,\n * and the payment token is the target (destination).\n *\n * @param tokens - Required tokens from the transaction.\n * @param paymentToken - Selected payment/destination token.\n * @param isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param isHyperliquidSource - Whether the source is HyperLiquid (perps withdrawal).\n * @param isPolymarketDepositWallet - Whether the source is a Polymarket deposit wallet.\n * @returns Array of source amounts.\n */\nfunction calculatePostQuoteSourceAmounts(\n tokens: TransactionPayRequiredToken[],\n paymentToken: TransactionPaymentToken,\n isMaxAmount: boolean,\n isHyperliquidSource?: boolean,\n isPolymarketDepositWallet?: boolean,\n): TransactionPaySourceAmount[] {\n return tokens\n .filter((token) => {\n if (token.skipIfBalance) {\n return false;\n }\n\n // Skip zero amounts (unless max amount, where we use balance)\n if (token.amountRaw === '0' && !isMaxAmount) {\n log('Skipping token as zero amount', { tokenAddress: token.address });\n return false;\n }\n\n // Skip same token on same chain, unless the source is a synthetic\n // upstream (HyperLiquid HyperCore or Polymarket deposit wallet) that\n // the strategy renormalizes to a different effective source.\n if (\n isSameToken(token, paymentToken) &&\n !isHyperliquidSource &&\n !isPolymarketDepositWallet\n ) {\n log('Skipping token as same as destination token');\n return false;\n }\n\n return true;\n })\n .map((token) => ({\n sourceAmountHuman: isMaxAmount ? token.balanceHuman : token.amountHuman,\n sourceAmountRaw: isMaxAmount ? token.balanceRaw : token.amountRaw,\n sourceBalanceRaw: token.balanceRaw,\n sourceChainId: token.chainId,\n sourceTokenAddress: token.address,\n targetTokenAddress: paymentToken.address,\n }));\n}\n\n/**\n * Calculate the required source amount for a payment token to cover a target token.\n *\n * @param paymentToken - Selected payment token.\n * @param token - Target token to cover.\n * @param messenger - Controller messenger.\n * @param transactionId - ID of the transaction.\n * @param isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.\n * @param paymentOverride - Optional payment source override for the transaction.\n * @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.\n * @returns The source amount or undefined if calculation failed.\n */\nfunction calculateSourceAmount(\n paymentToken: TransactionPaymentToken,\n token: TransactionPayRequiredToken,\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n isMaxAmount: boolean,\n isQuoteRequired?: boolean,\n paymentOverride?: PaymentOverride,\n resolveSourceAmount?: ResolveSourceAmountCallback,\n): TransactionPaySourceAmount | undefined {\n const paymentTokenFiatRate = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!paymentTokenFiatRate) {\n return undefined;\n }\n\n const hasBalance = new BigNumber(token.balanceRaw).gte(token.amountRaw);\n\n if (token.skipIfBalance && hasBalance) {\n log('Skipping token as sufficient balance', {\n tokenAddress: token.address,\n });\n return undefined;\n }\n\n const { parentTransactionType, strategy } = getStrategyContext(\n transactionId,\n messenger,\n );\n const isAlwaysRequired = isQuoteAlwaysRequired(\n token,\n strategy,\n parentTransactionType,\n isQuoteRequired,\n );\n\n if (isSameToken(token, paymentToken) && !isAlwaysRequired) {\n log('Skipping token as same as payment token');\n return undefined;\n }\n\n if (token.amountRaw === '0') {\n log('Skipping token as zero amount', { tokenAddress: token.address });\n return undefined;\n }\n\n const resolvedSourceAmount = resolveSourceAmount?.({\n isMaxAmount,\n paymentOverride,\n });\n\n if (resolvedSourceAmount) {\n const { sourceAmountRaw } = resolvedSourceAmount;\n const sourceAmountHuman = new BigNumber(sourceAmountRaw)\n .shiftedBy(-paymentToken.decimals)\n .toString(10);\n\n log('Resolved source amount from callback', {\n tokenAddress: token.address,\n sourceAmountRaw,\n });\n\n return {\n sourceAmountHuman,\n sourceAmountRaw,\n targetTokenAddress: token.address,\n };\n }\n\n const sourceAmountHumanValue = new BigNumber(token.amountUsd).div(\n paymentTokenFiatRate.usdRate,\n );\n\n const sourceAmountHuman = sourceAmountHumanValue.toString(10);\n\n const sourceAmountRaw = sourceAmountHumanValue\n .shiftedBy(paymentToken.decimals)\n .toFixed(0);\n\n // Money account Max must not use the pay token's on-chain balance. That\n // balance is only un-vaulted mUSD, while the typed required amount already\n // reflects the full withdrawable total (mUSD + vmUSD). Using the typed\n // fiat-derived source keeps isMaxAmount=true (EXACT_INPUT) correct for\n // deposits funded from the money account (e.g. Send to Perps).\n if (isMaxAmount && paymentOverride !== PaymentOverride.MoneyAccount) {\n return {\n sourceAmountHuman: paymentToken.balanceHuman,\n sourceAmountRaw: paymentToken.balanceRaw,\n targetTokenAddress: token.address,\n };\n }\n\n return {\n sourceAmountHuman,\n sourceAmountRaw,\n targetTokenAddress: token.address,\n };\n}\n\n/**\n * Determine if a quote is always required for a token and strategy.\n *\n * @param token - Target token.\n * @param strategy - Payment strategy.\n * @param parentTransactionType - Parent transaction type, if available.\n * @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.\n * @returns True if a quote is always required, false otherwise.\n */\nfunction isQuoteAlwaysRequired(\n token: TransactionPayRequiredToken,\n strategy: TransactionPayStrategy,\n parentTransactionType?: TransactionType,\n isQuoteRequired?: boolean,\n): boolean {\n if (isQuoteRequired) {\n return true;\n }\n\n const isHyperliquidDeposit =\n token.chainId === CHAIN_ID_ARBITRUM &&\n token.address.toLowerCase() === ARBITRUM_USDC_ADDRESS.toLowerCase();\n\n return (\n isHyperliquidDeposit &&\n (strategy === TransactionPayStrategy.Relay ||\n (strategy === TransactionPayStrategy.Across &&\n parentTransactionType !== undefined &&\n PERPS_DEPOSIT_TYPES.includes(parentTransactionType)))\n );\n}\n\nfunction getStrategyContext(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): {\n parentTransactionType?: TransactionType;\n strategy: TransactionPayStrategy;\n} {\n const transaction = getTransaction(\n transactionId,\n messenger,\n ) as TransactionMeta;\n\n return {\n parentTransactionType: transaction.type,\n strategy: messenger.call(\n 'TransactionPayController:getStrategy',\n transaction,\n ),\n };\n}\n"]}
|
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
import type { TransactionPayControllerMessenger } from "../index.cjs";
|
|
2
|
-
import type {
|
|
2
|
+
import type { TransactionData, ResolveSourceAmountCallback } from "../types.cjs";
|
|
3
3
|
/**
|
|
4
4
|
* Update the source amounts for a transaction.
|
|
5
5
|
*
|
|
6
6
|
* @param transactionId - ID of the transaction to update.
|
|
7
7
|
* @param transactionData - Existing transaction data.
|
|
8
8
|
* @param messenger - Controller messenger.
|
|
9
|
-
* @param
|
|
10
|
-
* calculation. Called only when `isMaxAmount` is true. Return `undefined` to fall back to
|
|
11
|
-
* the built-in token balance.
|
|
9
|
+
* @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.
|
|
12
10
|
*/
|
|
13
|
-
export declare function updateSourceAmounts(transactionId: string, transactionData: TransactionData | undefined, messenger: TransactionPayControllerMessenger,
|
|
11
|
+
export declare function updateSourceAmounts(transactionId: string, transactionData: TransactionData | undefined, messenger: TransactionPayControllerMessenger, resolveSourceAmount?: ResolveSourceAmountCallback): void;
|
|
14
12
|
//# sourceMappingURL=source-amounts.d.cts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source-amounts.d.cts","sourceRoot":"","sources":["../../src/utils/source-amounts.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"source-amounts.d.cts","sourceRoot":"","sources":["../../src/utils/source-amounts.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,iCAAiC,EAElC,qBAAoB;AAGrB,OAAO,KAAK,EAEV,eAAe,EAEf,2BAA2B,EAC5B,qBAAoB;AAMrB;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,aAAa,EAAE,MAAM,EACrB,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,SAAS,EAAE,iCAAiC,EAC5C,mBAAmB,CAAC,EAAE,2BAA2B,GAChD,IAAI,CAgDN"}
|
|
@@ -1,14 +1,12 @@
|
|
|
1
1
|
import type { TransactionPayControllerMessenger } from "../index.mjs";
|
|
2
|
-
import type {
|
|
2
|
+
import type { TransactionData, ResolveSourceAmountCallback } from "../types.mjs";
|
|
3
3
|
/**
|
|
4
4
|
* Update the source amounts for a transaction.
|
|
5
5
|
*
|
|
6
6
|
* @param transactionId - ID of the transaction to update.
|
|
7
7
|
* @param transactionData - Existing transaction data.
|
|
8
8
|
* @param messenger - Controller messenger.
|
|
9
|
-
* @param
|
|
10
|
-
* calculation. Called only when `isMaxAmount` is true. Return `undefined` to fall back to
|
|
11
|
-
* the built-in token balance.
|
|
9
|
+
* @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.
|
|
12
10
|
*/
|
|
13
|
-
export declare function updateSourceAmounts(transactionId: string, transactionData: TransactionData | undefined, messenger: TransactionPayControllerMessenger,
|
|
11
|
+
export declare function updateSourceAmounts(transactionId: string, transactionData: TransactionData | undefined, messenger: TransactionPayControllerMessenger, resolveSourceAmount?: ResolveSourceAmountCallback): void;
|
|
14
12
|
//# sourceMappingURL=source-amounts.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source-amounts.d.mts","sourceRoot":"","sources":["../../src/utils/source-amounts.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"source-amounts.d.mts","sourceRoot":"","sources":["../../src/utils/source-amounts.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EACV,iCAAiC,EAElC,qBAAoB;AAGrB,OAAO,KAAK,EAEV,eAAe,EAEf,2BAA2B,EAC5B,qBAAoB;AAMrB;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,aAAa,EAAE,MAAM,EACrB,eAAe,EAAE,eAAe,GAAG,SAAS,EAC5C,SAAS,EAAE,iCAAiC,EAC5C,mBAAmB,CAAC,EAAE,2BAA2B,GAChD,IAAI,CAgDN"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createModuleLogger } from "@metamask/utils";
|
|
2
2
|
import { BigNumber } from "bignumber.js";
|
|
3
|
-
import { ARBITRUM_USDC_ADDRESS, CHAIN_ID_ARBITRUM, PERPS_DEPOSIT_TYPES } from "../constants.mjs";
|
|
3
|
+
import { ARBITRUM_USDC_ADDRESS, CHAIN_ID_ARBITRUM, PaymentOverride, PERPS_DEPOSIT_TYPES } from "../constants.mjs";
|
|
4
4
|
import { TransactionPayStrategy } from "../index.mjs";
|
|
5
5
|
import { projectLogger } from "../logger.mjs";
|
|
6
6
|
import { getTokenFiatRate, isSameToken } from "./token.mjs";
|
|
@@ -12,36 +12,28 @@ const log = createModuleLogger(projectLogger, 'source-amounts');
|
|
|
12
12
|
* @param transactionId - ID of the transaction to update.
|
|
13
13
|
* @param transactionData - Existing transaction data.
|
|
14
14
|
* @param messenger - Controller messenger.
|
|
15
|
-
* @param
|
|
16
|
-
* calculation. Called only when `isMaxAmount` is true. Return `undefined` to fall back to
|
|
17
|
-
* the built-in token balance.
|
|
15
|
+
* @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.
|
|
18
16
|
*/
|
|
19
|
-
export function updateSourceAmounts(transactionId, transactionData, messenger,
|
|
17
|
+
export function updateSourceAmounts(transactionId, transactionData, messenger, resolveSourceAmount) {
|
|
20
18
|
if (!transactionData) {
|
|
21
19
|
return;
|
|
22
20
|
}
|
|
23
|
-
const { isMaxAmount, isPostQuote, paymentToken, tokens } = transactionData;
|
|
21
|
+
const { isMaxAmount, isPostQuote, paymentOverride, paymentToken, tokens } = transactionData;
|
|
24
22
|
if (!tokens.length || !paymentToken) {
|
|
25
23
|
return;
|
|
26
24
|
}
|
|
27
|
-
const transaction = getBalance && isMaxAmount
|
|
28
|
-
? getTransaction(transactionId, messenger)
|
|
29
|
-
: undefined;
|
|
30
|
-
const balanceOverride = getBalance && transaction
|
|
31
|
-
? getBalance({ transaction, transactionData })
|
|
32
|
-
: undefined;
|
|
33
25
|
// For post-quote flows, source amounts are calculated differently
|
|
34
26
|
// The source is the transaction's required token, not the selected token
|
|
35
27
|
if (isPostQuote) {
|
|
36
28
|
const { isHyperliquidSource, isPolymarketDepositWallet } = transactionData;
|
|
37
|
-
const sourceAmounts = calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount ?? false, isHyperliquidSource, isPolymarketDepositWallet
|
|
29
|
+
const sourceAmounts = calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount ?? false, isHyperliquidSource, isPolymarketDepositWallet);
|
|
38
30
|
log('Updated post-quote source amounts', { transactionId, sourceAmounts });
|
|
39
31
|
transactionData.sourceAmounts = sourceAmounts;
|
|
40
32
|
return;
|
|
41
33
|
}
|
|
42
34
|
const { isQuoteRequired } = transactionData;
|
|
43
35
|
const sourceAmounts = tokens
|
|
44
|
-
.map((singleToken) => calculateSourceAmount(paymentToken, singleToken, messenger, transactionId, isMaxAmount ?? false, isQuoteRequired,
|
|
36
|
+
.map((singleToken) => calculateSourceAmount(paymentToken, singleToken, messenger, transactionId, isMaxAmount ?? false, isQuoteRequired, paymentOverride, resolveSourceAmount))
|
|
45
37
|
.filter(Boolean);
|
|
46
38
|
log('Updated source amounts', { transactionId, sourceAmounts });
|
|
47
39
|
transactionData.sourceAmounts = sourceAmounts;
|
|
@@ -56,10 +48,9 @@ export function updateSourceAmounts(transactionId, transactionData, messenger, g
|
|
|
56
48
|
* @param isMaxAmount - Whether the transaction is a maximum amount transaction.
|
|
57
49
|
* @param isHyperliquidSource - Whether the source is HyperLiquid (perps withdrawal).
|
|
58
50
|
* @param isPolymarketDepositWallet - Whether the source is a Polymarket deposit wallet.
|
|
59
|
-
* @param balanceOverride - Optional balance override from the `getBalance` callback.
|
|
60
51
|
* @returns Array of source amounts.
|
|
61
52
|
*/
|
|
62
|
-
function calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount, isHyperliquidSource, isPolymarketDepositWallet
|
|
53
|
+
function calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount, isHyperliquidSource, isPolymarketDepositWallet) {
|
|
63
54
|
return tokens
|
|
64
55
|
.filter((token) => {
|
|
65
56
|
if (token.skipIfBalance) {
|
|
@@ -83,10 +74,8 @@ function calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount, isHy
|
|
|
83
74
|
})
|
|
84
75
|
.map((token) => ({
|
|
85
76
|
sourceAmountHuman: isMaxAmount ? token.balanceHuman : token.amountHuman,
|
|
86
|
-
sourceAmountRaw: isMaxAmount
|
|
87
|
-
|
|
88
|
-
: token.amountRaw,
|
|
89
|
-
sourceBalanceRaw: balanceOverride?.balanceRaw ?? token.balanceRaw,
|
|
77
|
+
sourceAmountRaw: isMaxAmount ? token.balanceRaw : token.amountRaw,
|
|
78
|
+
sourceBalanceRaw: token.balanceRaw,
|
|
90
79
|
sourceChainId: token.chainId,
|
|
91
80
|
sourceTokenAddress: token.address,
|
|
92
81
|
targetTokenAddress: paymentToken.address,
|
|
@@ -101,10 +90,11 @@ function calculatePostQuoteSourceAmounts(tokens, paymentToken, isMaxAmount, isHy
|
|
|
101
90
|
* @param transactionId - ID of the transaction.
|
|
102
91
|
* @param isMaxAmount - Whether the transaction is a maximum amount transaction.
|
|
103
92
|
* @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.
|
|
104
|
-
* @param
|
|
93
|
+
* @param paymentOverride - Optional payment source override for the transaction.
|
|
94
|
+
* @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.
|
|
105
95
|
* @returns The source amount or undefined if calculation failed.
|
|
106
96
|
*/
|
|
107
|
-
function calculateSourceAmount(paymentToken, token, messenger, transactionId, isMaxAmount, isQuoteRequired,
|
|
97
|
+
function calculateSourceAmount(paymentToken, token, messenger, transactionId, isMaxAmount, isQuoteRequired, paymentOverride, resolveSourceAmount) {
|
|
108
98
|
const paymentTokenFiatRate = getTokenFiatRate(messenger, paymentToken.address, paymentToken.chainId);
|
|
109
99
|
if (!paymentTokenFiatRate) {
|
|
110
100
|
return undefined;
|
|
@@ -126,20 +116,39 @@ function calculateSourceAmount(paymentToken, token, messenger, transactionId, is
|
|
|
126
116
|
log('Skipping token as zero amount', { tokenAddress: token.address });
|
|
127
117
|
return undefined;
|
|
128
118
|
}
|
|
119
|
+
const resolvedSourceAmount = resolveSourceAmount?.({
|
|
120
|
+
isMaxAmount,
|
|
121
|
+
paymentOverride,
|
|
122
|
+
});
|
|
123
|
+
if (resolvedSourceAmount) {
|
|
124
|
+
const { sourceAmountRaw } = resolvedSourceAmount;
|
|
125
|
+
const sourceAmountHuman = new BigNumber(sourceAmountRaw)
|
|
126
|
+
.shiftedBy(-paymentToken.decimals)
|
|
127
|
+
.toString(10);
|
|
128
|
+
log('Resolved source amount from callback', {
|
|
129
|
+
tokenAddress: token.address,
|
|
130
|
+
sourceAmountRaw,
|
|
131
|
+
});
|
|
132
|
+
return {
|
|
133
|
+
sourceAmountHuman,
|
|
134
|
+
sourceAmountRaw,
|
|
135
|
+
targetTokenAddress: token.address,
|
|
136
|
+
};
|
|
137
|
+
}
|
|
129
138
|
const sourceAmountHumanValue = new BigNumber(token.amountUsd).div(paymentTokenFiatRate.usdRate);
|
|
130
139
|
const sourceAmountHuman = sourceAmountHumanValue.toString(10);
|
|
131
140
|
const sourceAmountRaw = sourceAmountHumanValue
|
|
132
141
|
.shiftedBy(paymentToken.decimals)
|
|
133
142
|
.toFixed(0);
|
|
134
|
-
//
|
|
135
|
-
//
|
|
136
|
-
//
|
|
137
|
-
//
|
|
138
|
-
//
|
|
139
|
-
if (isMaxAmount) {
|
|
143
|
+
// Money account Max must not use the pay token's on-chain balance. That
|
|
144
|
+
// balance is only un-vaulted mUSD, while the typed required amount already
|
|
145
|
+
// reflects the full withdrawable total (mUSD + vmUSD). Using the typed
|
|
146
|
+
// fiat-derived source keeps isMaxAmount=true (EXACT_INPUT) correct for
|
|
147
|
+
// deposits funded from the money account (e.g. Send to Perps).
|
|
148
|
+
if (isMaxAmount && paymentOverride !== PaymentOverride.MoneyAccount) {
|
|
140
149
|
return {
|
|
141
150
|
sourceAmountHuman: paymentToken.balanceHuman,
|
|
142
|
-
sourceAmountRaw:
|
|
151
|
+
sourceAmountRaw: paymentToken.balanceRaw,
|
|
143
152
|
targetTokenAddress: token.address,
|
|
144
153
|
};
|
|
145
154
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source-amounts.mjs","source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,CAC5B,KAAkC,EAClC,QAAgC,EAChC,qBAAuC,EACvC,eAAyB;IAEzB,IAAI,eAAe,EAAE,CAAC;QACpB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,oBAAoB,GACxB,KAAK,CAAC,OAAO,KAAK,iBAAiB;QACnC,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,KAAK,qBAAqB,CAAC,WAAW,EAAE,CAAC;IAEtE,OAAO,CACL,oBAAoB;QACpB,CAAC,QAAQ,KAAK,sBAAsB,CAAC,KAAK;YACxC,CAAC,QAAQ,KAAK,sBAAsB,CAAC,MAAM;gBACzC,qBAAqB,KAAK,SAAS;gBACnC,mBAAmB,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,aAAqB,EACrB,SAA4C;IAK5C,MAAM,WAAW,GAAG,cAAc,CAChC,aAAa,EACb,SAAS,CACS,CAAC;IAErB,OAAO;QACL,qBAAqB,EAAE,WAAW,CAAC,IAAI;QACvC,QAAQ,EAAE,SAAS,CAAC,IAAI,CACtB,sCAAsC,EACtC,WAAW,CACZ;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n TransactionMeta,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ARBITRUM_USDC_ADDRESS,\n CHAIN_ID_ARBITRUM,\n PERPS_DEPOSIT_TYPES,\n} from '../constants.js';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPaymentToken,\n} from '../index.js';\nimport { TransactionPayStrategy } from '../index.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n GetBalanceCallback,\n GetBalanceResponse,\n TransactionPaySourceAmount,\n TransactionData,\n TransactionPayRequiredToken,\n} from '../types.js';\nimport { getTokenFiatRate, isSameToken } from './token.js';\nimport { getTransaction } from './transaction.js';\n\nconst log = createModuleLogger(projectLogger, 'source-amounts');\n\n/**\n * Update the source amounts for a transaction.\n *\n * @param transactionId - ID of the transaction to update.\n * @param transactionData - Existing transaction data.\n * @param messenger - Controller messenger.\n * @param getBalance - Optional callback to override the source balance used for max-amount\n * calculation. Called only when `isMaxAmount` is true. Return `undefined` to fall back to\n * the built-in token balance.\n */\nexport function updateSourceAmounts(\n transactionId: string,\n transactionData: TransactionData | undefined,\n messenger: TransactionPayControllerMessenger,\n getBalance?: GetBalanceCallback,\n): void {\n if (!transactionData) {\n return;\n }\n\n const { isMaxAmount, isPostQuote, paymentToken, tokens } = transactionData;\n\n if (!tokens.length || !paymentToken) {\n return;\n }\n\n const transaction =\n getBalance && isMaxAmount\n ? getTransaction(transactionId, messenger)\n : undefined;\n const balanceOverride =\n getBalance && transaction\n ? getBalance({ transaction, transactionData })\n : undefined;\n\n // For post-quote flows, source amounts are calculated differently\n // The source is the transaction's required token, not the selected token\n if (isPostQuote) {\n const { isHyperliquidSource, isPolymarketDepositWallet } = transactionData;\n const sourceAmounts = calculatePostQuoteSourceAmounts(\n tokens,\n paymentToken,\n isMaxAmount ?? false,\n isHyperliquidSource,\n isPolymarketDepositWallet,\n balanceOverride,\n );\n log('Updated post-quote source amounts', { transactionId, sourceAmounts });\n transactionData.sourceAmounts = sourceAmounts;\n return;\n }\n\n const { isQuoteRequired } = transactionData;\n\n const sourceAmounts = tokens\n .map((singleToken) =>\n calculateSourceAmount(\n paymentToken,\n singleToken,\n messenger,\n transactionId,\n isMaxAmount ?? false,\n isQuoteRequired,\n balanceOverride,\n ),\n )\n .filter(Boolean) as TransactionPaySourceAmount[];\n\n log('Updated source amounts', { transactionId, sourceAmounts });\n\n transactionData.sourceAmounts = sourceAmounts;\n}\n\n/**\n * Calculate source amounts for post-quote flows.\n * In this flow, the required tokens ARE the source tokens,\n * and the payment token is the target (destination).\n *\n * @param tokens - Required tokens from the transaction.\n * @param paymentToken - Selected payment/destination token.\n * @param isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param isHyperliquidSource - Whether the source is HyperLiquid (perps withdrawal).\n * @param isPolymarketDepositWallet - Whether the source is a Polymarket deposit wallet.\n * @param balanceOverride - Optional balance override from the `getBalance` callback.\n * @returns Array of source amounts.\n */\nfunction calculatePostQuoteSourceAmounts(\n tokens: TransactionPayRequiredToken[],\n paymentToken: TransactionPaymentToken,\n isMaxAmount: boolean,\n isHyperliquidSource?: boolean,\n isPolymarketDepositWallet?: boolean,\n balanceOverride?: GetBalanceResponse,\n): TransactionPaySourceAmount[] {\n return tokens\n .filter((token) => {\n if (token.skipIfBalance) {\n return false;\n }\n\n // Skip zero amounts (unless max amount, where we use balance)\n if (token.amountRaw === '0' && !isMaxAmount) {\n log('Skipping token as zero amount', { tokenAddress: token.address });\n return false;\n }\n\n // Skip same token on same chain, unless the source is a synthetic\n // upstream (HyperLiquid HyperCore or Polymarket deposit wallet) that\n // the strategy renormalizes to a different effective source.\n if (\n isSameToken(token, paymentToken) &&\n !isHyperliquidSource &&\n !isPolymarketDepositWallet\n ) {\n log('Skipping token as same as destination token');\n return false;\n }\n\n return true;\n })\n .map((token) => ({\n sourceAmountHuman: isMaxAmount ? token.balanceHuman : token.amountHuman,\n sourceAmountRaw: isMaxAmount\n ? (balanceOverride?.balanceRaw ?? token.balanceRaw)\n : token.amountRaw,\n sourceBalanceRaw: balanceOverride?.balanceRaw ?? token.balanceRaw,\n sourceChainId: token.chainId,\n sourceTokenAddress: token.address,\n targetTokenAddress: paymentToken.address,\n }));\n}\n\n/**\n * Calculate the required source amount for a payment token to cover a target token.\n *\n * @param paymentToken - Selected payment token.\n * @param token - Target token to cover.\n * @param messenger - Controller messenger.\n * @param transactionId - ID of the transaction.\n * @param isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.\n * @param balanceOverride - Optional balance override from the `getBalance` callback.\n * @returns The source amount or undefined if calculation failed.\n */\nfunction calculateSourceAmount(\n paymentToken: TransactionPaymentToken,\n token: TransactionPayRequiredToken,\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n isMaxAmount: boolean,\n isQuoteRequired?: boolean,\n balanceOverride?: GetBalanceResponse,\n): TransactionPaySourceAmount | undefined {\n const paymentTokenFiatRate = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!paymentTokenFiatRate) {\n return undefined;\n }\n\n const hasBalance = new BigNumber(token.balanceRaw).gte(token.amountRaw);\n\n if (token.skipIfBalance && hasBalance) {\n log('Skipping token as sufficient balance', {\n tokenAddress: token.address,\n });\n return undefined;\n }\n\n const { parentTransactionType, strategy } = getStrategyContext(\n transactionId,\n messenger,\n );\n const isAlwaysRequired = isQuoteAlwaysRequired(\n token,\n strategy,\n parentTransactionType,\n isQuoteRequired,\n );\n\n if (isSameToken(token, paymentToken) && !isAlwaysRequired) {\n log('Skipping token as same as payment token');\n return undefined;\n }\n\n if (token.amountRaw === '0') {\n log('Skipping token as zero amount', { tokenAddress: token.address });\n return undefined;\n }\n\n const sourceAmountHumanValue = new BigNumber(token.amountUsd).div(\n paymentTokenFiatRate.usdRate,\n );\n\n const sourceAmountHuman = sourceAmountHumanValue.toString(10);\n\n const sourceAmountRaw = sourceAmountHumanValue\n .shiftedBy(paymentToken.decimals)\n .toFixed(0);\n\n // On Max, use the exact source balance. The client `getBalance` callback is\n // authoritative and owns all balance complexity (perps, predict, money\n // account, payment overrides): when it returns a `balanceOverride`, use it;\n // when it returns `undefined`, that is a deliberate signal to use the pay\n // token's on-chain balance. This path is payment-override agnostic.\n if (isMaxAmount) {\n return {\n sourceAmountHuman: paymentToken.balanceHuman,\n sourceAmountRaw: balanceOverride?.balanceRaw ?? paymentToken.balanceRaw,\n targetTokenAddress: token.address,\n };\n }\n\n return {\n sourceAmountHuman,\n sourceAmountRaw,\n targetTokenAddress: token.address,\n };\n}\n\n/**\n * Determine if a quote is always required for a token and strategy.\n *\n * @param token - Target token.\n * @param strategy - Payment strategy.\n * @param parentTransactionType - Parent transaction type, if available.\n * @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.\n * @returns True if a quote is always required, false otherwise.\n */\nfunction isQuoteAlwaysRequired(\n token: TransactionPayRequiredToken,\n strategy: TransactionPayStrategy,\n parentTransactionType?: TransactionType,\n isQuoteRequired?: boolean,\n): boolean {\n if (isQuoteRequired) {\n return true;\n }\n\n const isHyperliquidDeposit =\n token.chainId === CHAIN_ID_ARBITRUM &&\n token.address.toLowerCase() === ARBITRUM_USDC_ADDRESS.toLowerCase();\n\n return (\n isHyperliquidDeposit &&\n (strategy === TransactionPayStrategy.Relay ||\n (strategy === TransactionPayStrategy.Across &&\n parentTransactionType !== undefined &&\n PERPS_DEPOSIT_TYPES.includes(parentTransactionType)))\n );\n}\n\nfunction getStrategyContext(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): {\n parentTransactionType?: TransactionType;\n strategy: TransactionPayStrategy;\n} {\n const transaction = getTransaction(\n transactionId,\n messenger,\n ) as TransactionMeta;\n\n return {\n parentTransactionType: transaction.type,\n strategy: messenger.call(\n 'TransactionPayController:getStrategy',\n transaction,\n ),\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"source-amounts.mjs","sourceRoot":"","sources":["../../src/utils/source-amounts.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AACrD,OAAO,EAAE,SAAS,EAAE,qBAAqB;AAEzC,OAAO,EACL,qBAAqB,EACrB,iBAAiB,EACjB,eAAe,EACf,mBAAmB,EACpB,yBAAwB;AAKzB,OAAO,EAAE,sBAAsB,EAAE,qBAAoB;AACrD,OAAO,EAAE,aAAa,EAAE,sBAAqB;AAO7C,OAAO,EAAE,gBAAgB,EAAE,WAAW,EAAE,oBAAmB;AAC3D,OAAO,EAAE,cAAc,EAAE,0BAAyB;AAElD,MAAM,GAAG,GAAG,kBAAkB,CAAC,aAAa,EAAE,gBAAgB,CAAC,CAAC;AAEhE;;;;;;;GAOG;AACH,MAAM,UAAU,mBAAmB,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L,oBAAoB;QACpB,CAAC,QAAQ,KAAK,sBAAsB,CAAC,KAAK;YACxC,CAAC,QAAQ,KAAK,sBAAsB,CAAC,MAAM;gBACzC,qBAAqB,KAAK,SAAS;gBACnC,mBAAmB,CAAC,QAAQ,CAAC,qBAAqB,CAAC,CAAC,CAAC,CAC1D,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CACzB,aAAqB,EACrB,SAA4C;IAK5C,MAAM,WAAW,GAAG,cAAc,CAChC,aAAa,EACb,SAAS,CACS,CAAC;IAErB,OAAO;QACL,qBAAqB,EAAE,WAAW,CAAC,IAAI;QACvC,QAAQ,EAAE,SAAS,CAAC,IAAI,CACtB,sCAAsC,EACtC,WAAW,CACZ;KACF,CAAC;AACJ,CAAC","sourcesContent":["import type {\n TransactionMeta,\n TransactionType,\n} from '@metamask/transaction-controller';\nimport { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n ARBITRUM_USDC_ADDRESS,\n CHAIN_ID_ARBITRUM,\n PaymentOverride,\n PERPS_DEPOSIT_TYPES,\n} from '../constants.js';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPaymentToken,\n} from '../index.js';\nimport { TransactionPayStrategy } from '../index.js';\nimport { projectLogger } from '../logger.js';\nimport type {\n TransactionPaySourceAmount,\n TransactionData,\n TransactionPayRequiredToken,\n ResolveSourceAmountCallback,\n} from '../types.js';\nimport { getTokenFiatRate, isSameToken } from './token.js';\nimport { getTransaction } from './transaction.js';\n\nconst log = createModuleLogger(projectLogger, 'source-amounts');\n\n/**\n * Update the source amounts for a transaction.\n *\n * @param transactionId - ID of the transaction to update.\n * @param transactionData - Existing transaction data.\n * @param messenger - Controller messenger.\n * @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.\n */\nexport function updateSourceAmounts(\n transactionId: string,\n transactionData: TransactionData | undefined,\n messenger: TransactionPayControllerMessenger,\n resolveSourceAmount?: ResolveSourceAmountCallback,\n): void {\n if (!transactionData) {\n return;\n }\n\n const { isMaxAmount, isPostQuote, paymentOverride, paymentToken, tokens } =\n transactionData;\n\n if (!tokens.length || !paymentToken) {\n return;\n }\n\n // For post-quote flows, source amounts are calculated differently\n // The source is the transaction's required token, not the selected token\n if (isPostQuote) {\n const { isHyperliquidSource, isPolymarketDepositWallet } = transactionData;\n const sourceAmounts = calculatePostQuoteSourceAmounts(\n tokens,\n paymentToken,\n isMaxAmount ?? false,\n isHyperliquidSource,\n isPolymarketDepositWallet,\n );\n log('Updated post-quote source amounts', { transactionId, sourceAmounts });\n transactionData.sourceAmounts = sourceAmounts;\n return;\n }\n\n const { isQuoteRequired } = transactionData;\n\n const sourceAmounts = tokens\n .map((singleToken) =>\n calculateSourceAmount(\n paymentToken,\n singleToken,\n messenger,\n transactionId,\n isMaxAmount ?? false,\n isQuoteRequired,\n paymentOverride,\n resolveSourceAmount,\n ),\n )\n .filter(Boolean) as TransactionPaySourceAmount[];\n\n log('Updated source amounts', { transactionId, sourceAmounts });\n\n transactionData.sourceAmounts = sourceAmounts;\n}\n\n/**\n * Calculate source amounts for post-quote flows.\n * In this flow, the required tokens ARE the source tokens,\n * and the payment token is the target (destination).\n *\n * @param tokens - Required tokens from the transaction.\n * @param paymentToken - Selected payment/destination token.\n * @param isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param isHyperliquidSource - Whether the source is HyperLiquid (perps withdrawal).\n * @param isPolymarketDepositWallet - Whether the source is a Polymarket deposit wallet.\n * @returns Array of source amounts.\n */\nfunction calculatePostQuoteSourceAmounts(\n tokens: TransactionPayRequiredToken[],\n paymentToken: TransactionPaymentToken,\n isMaxAmount: boolean,\n isHyperliquidSource?: boolean,\n isPolymarketDepositWallet?: boolean,\n): TransactionPaySourceAmount[] {\n return tokens\n .filter((token) => {\n if (token.skipIfBalance) {\n return false;\n }\n\n // Skip zero amounts (unless max amount, where we use balance)\n if (token.amountRaw === '0' && !isMaxAmount) {\n log('Skipping token as zero amount', { tokenAddress: token.address });\n return false;\n }\n\n // Skip same token on same chain, unless the source is a synthetic\n // upstream (HyperLiquid HyperCore or Polymarket deposit wallet) that\n // the strategy renormalizes to a different effective source.\n if (\n isSameToken(token, paymentToken) &&\n !isHyperliquidSource &&\n !isPolymarketDepositWallet\n ) {\n log('Skipping token as same as destination token');\n return false;\n }\n\n return true;\n })\n .map((token) => ({\n sourceAmountHuman: isMaxAmount ? token.balanceHuman : token.amountHuman,\n sourceAmountRaw: isMaxAmount ? token.balanceRaw : token.amountRaw,\n sourceBalanceRaw: token.balanceRaw,\n sourceChainId: token.chainId,\n sourceTokenAddress: token.address,\n targetTokenAddress: paymentToken.address,\n }));\n}\n\n/**\n * Calculate the required source amount for a payment token to cover a target token.\n *\n * @param paymentToken - Selected payment token.\n * @param token - Target token to cover.\n * @param messenger - Controller messenger.\n * @param transactionId - ID of the transaction.\n * @param isMaxAmount - Whether the transaction is a maximum amount transaction.\n * @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.\n * @param paymentOverride - Optional payment source override for the transaction.\n * @param resolveSourceAmount - Optional callback supplying an exact atomic source amount.\n * @returns The source amount or undefined if calculation failed.\n */\nfunction calculateSourceAmount(\n paymentToken: TransactionPaymentToken,\n token: TransactionPayRequiredToken,\n messenger: TransactionPayControllerMessenger,\n transactionId: string,\n isMaxAmount: boolean,\n isQuoteRequired?: boolean,\n paymentOverride?: PaymentOverride,\n resolveSourceAmount?: ResolveSourceAmountCallback,\n): TransactionPaySourceAmount | undefined {\n const paymentTokenFiatRate = getTokenFiatRate(\n messenger,\n paymentToken.address,\n paymentToken.chainId,\n );\n\n if (!paymentTokenFiatRate) {\n return undefined;\n }\n\n const hasBalance = new BigNumber(token.balanceRaw).gte(token.amountRaw);\n\n if (token.skipIfBalance && hasBalance) {\n log('Skipping token as sufficient balance', {\n tokenAddress: token.address,\n });\n return undefined;\n }\n\n const { parentTransactionType, strategy } = getStrategyContext(\n transactionId,\n messenger,\n );\n const isAlwaysRequired = isQuoteAlwaysRequired(\n token,\n strategy,\n parentTransactionType,\n isQuoteRequired,\n );\n\n if (isSameToken(token, paymentToken) && !isAlwaysRequired) {\n log('Skipping token as same as payment token');\n return undefined;\n }\n\n if (token.amountRaw === '0') {\n log('Skipping token as zero amount', { tokenAddress: token.address });\n return undefined;\n }\n\n const resolvedSourceAmount = resolveSourceAmount?.({\n isMaxAmount,\n paymentOverride,\n });\n\n if (resolvedSourceAmount) {\n const { sourceAmountRaw } = resolvedSourceAmount;\n const sourceAmountHuman = new BigNumber(sourceAmountRaw)\n .shiftedBy(-paymentToken.decimals)\n .toString(10);\n\n log('Resolved source amount from callback', {\n tokenAddress: token.address,\n sourceAmountRaw,\n });\n\n return {\n sourceAmountHuman,\n sourceAmountRaw,\n targetTokenAddress: token.address,\n };\n }\n\n const sourceAmountHumanValue = new BigNumber(token.amountUsd).div(\n paymentTokenFiatRate.usdRate,\n );\n\n const sourceAmountHuman = sourceAmountHumanValue.toString(10);\n\n const sourceAmountRaw = sourceAmountHumanValue\n .shiftedBy(paymentToken.decimals)\n .toFixed(0);\n\n // Money account Max must not use the pay token's on-chain balance. That\n // balance is only un-vaulted mUSD, while the typed required amount already\n // reflects the full withdrawable total (mUSD + vmUSD). Using the typed\n // fiat-derived source keeps isMaxAmount=true (EXACT_INPUT) correct for\n // deposits funded from the money account (e.g. Send to Perps).\n if (isMaxAmount && paymentOverride !== PaymentOverride.MoneyAccount) {\n return {\n sourceAmountHuman: paymentToken.balanceHuman,\n sourceAmountRaw: paymentToken.balanceRaw,\n targetTokenAddress: token.address,\n };\n }\n\n return {\n sourceAmountHuman,\n sourceAmountRaw,\n targetTokenAddress: token.address,\n };\n}\n\n/**\n * Determine if a quote is always required for a token and strategy.\n *\n * @param token - Target token.\n * @param strategy - Payment strategy.\n * @param parentTransactionType - Parent transaction type, if available.\n * @param isQuoteRequired - When true, a quote is always fetched even when source and target tokens are identical.\n * @returns True if a quote is always required, false otherwise.\n */\nfunction isQuoteAlwaysRequired(\n token: TransactionPayRequiredToken,\n strategy: TransactionPayStrategy,\n parentTransactionType?: TransactionType,\n isQuoteRequired?: boolean,\n): boolean {\n if (isQuoteRequired) {\n return true;\n }\n\n const isHyperliquidDeposit =\n token.chainId === CHAIN_ID_ARBITRUM &&\n token.address.toLowerCase() === ARBITRUM_USDC_ADDRESS.toLowerCase();\n\n return (\n isHyperliquidDeposit &&\n (strategy === TransactionPayStrategy.Relay ||\n (strategy === TransactionPayStrategy.Across &&\n parentTransactionType !== undefined &&\n PERPS_DEPOSIT_TYPES.includes(parentTransactionType)))\n );\n}\n\nfunction getStrategyContext(\n transactionId: string,\n messenger: TransactionPayControllerMessenger,\n): {\n parentTransactionType?: TransactionType;\n strategy: TransactionPayStrategy;\n} {\n const transaction = getTransaction(\n transactionId,\n messenger,\n ) as TransactionMeta;\n\n return {\n parentTransactionType: transaction.type,\n strategy: messenger.call(\n 'TransactionPayController:getStrategy',\n transaction,\n ),\n };\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@metamask-previews/transaction-pay-controller",
|
|
3
|
-
"version": "26.4.1-preview-
|
|
3
|
+
"version": "26.4.1-preview-7cfd8be",
|
|
4
4
|
"description": "Manages alternate payment strategies to provide required funds for transactions in MetaMask",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"Ethereum",
|