@metamask/transaction-pay-controller 18.1.0 → 19.0.0
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 +32 -1
- package/dist/TransactionPayController.cjs +2 -0
- package/dist/TransactionPayController.cjs.map +1 -1
- package/dist/TransactionPayController.d.cts.map +1 -1
- package/dist/TransactionPayController.d.mts.map +1 -1
- package/dist/TransactionPayController.mjs +2 -0
- package/dist/TransactionPayController.mjs.map +1 -1
- package/dist/constants.cjs +5 -2
- package/dist/constants.cjs.map +1 -1
- package/dist/constants.d.cts +3 -0
- package/dist/constants.d.cts.map +1 -1
- package/dist/constants.d.mts +3 -0
- package/dist/constants.d.mts.map +1 -1
- package/dist/constants.mjs +4 -1
- package/dist/constants.mjs.map +1 -1
- package/dist/strategy/relay/constants.cjs +3 -1
- package/dist/strategy/relay/constants.cjs.map +1 -1
- package/dist/strategy/relay/constants.d.cts +2 -0
- package/dist/strategy/relay/constants.d.cts.map +1 -1
- package/dist/strategy/relay/constants.d.mts +2 -0
- package/dist/strategy/relay/constants.d.mts.map +1 -1
- package/dist/strategy/relay/constants.mjs +2 -0
- package/dist/strategy/relay/constants.mjs.map +1 -1
- package/dist/strategy/relay/hyperliquid-withdraw.cjs +194 -0
- package/dist/strategy/relay/hyperliquid-withdraw.cjs.map +1 -0
- package/dist/strategy/relay/hyperliquid-withdraw.d.cts +18 -0
- package/dist/strategy/relay/hyperliquid-withdraw.d.cts.map +1 -0
- package/dist/strategy/relay/hyperliquid-withdraw.d.mts +18 -0
- package/dist/strategy/relay/hyperliquid-withdraw.d.mts.map +1 -0
- package/dist/strategy/relay/hyperliquid-withdraw.mjs +190 -0
- package/dist/strategy/relay/hyperliquid-withdraw.mjs.map +1 -0
- package/dist/strategy/relay/relay-max-gas-station.cjs +2 -1
- package/dist/strategy/relay/relay-max-gas-station.cjs.map +1 -1
- package/dist/strategy/relay/relay-max-gas-station.d.cts.map +1 -1
- package/dist/strategy/relay/relay-max-gas-station.d.mts.map +1 -1
- package/dist/strategy/relay/relay-max-gas-station.mjs +2 -1
- package/dist/strategy/relay/relay-max-gas-station.mjs.map +1 -1
- package/dist/strategy/relay/relay-quotes.cjs +35 -4
- package/dist/strategy/relay/relay-quotes.cjs.map +1 -1
- package/dist/strategy/relay/relay-quotes.d.cts.map +1 -1
- package/dist/strategy/relay/relay-quotes.d.mts.map +1 -1
- package/dist/strategy/relay/relay-quotes.mjs +36 -5
- package/dist/strategy/relay/relay-quotes.mjs.map +1 -1
- package/dist/strategy/relay/relay-submit.cjs +12 -3
- package/dist/strategy/relay/relay-submit.cjs.map +1 -1
- package/dist/strategy/relay/relay-submit.d.cts.map +1 -1
- package/dist/strategy/relay/relay-submit.d.mts.map +1 -1
- package/dist/strategy/relay/relay-submit.mjs +12 -3
- package/dist/strategy/relay/relay-submit.mjs.map +1 -1
- package/dist/strategy/relay/types.cjs.map +1 -1
- package/dist/strategy/relay/types.d.cts +66 -18
- package/dist/strategy/relay/types.d.cts.map +1 -1
- package/dist/strategy/relay/types.d.mts +66 -18
- package/dist/strategy/relay/types.d.mts.map +1 -1
- package/dist/strategy/relay/types.mjs.map +1 -1
- package/dist/types.cjs.map +1 -1
- package/dist/types.d.cts +12 -1
- package/dist/types.d.cts.map +1 -1
- package/dist/types.d.mts +12 -1
- package/dist/types.d.mts.map +1 -1
- package/dist/types.mjs.map +1 -1
- package/dist/utils/quotes.cjs +8 -7
- package/dist/utils/quotes.cjs.map +1 -1
- package/dist/utils/quotes.d.cts.map +1 -1
- package/dist/utils/quotes.d.mts.map +1 -1
- package/dist/utils/quotes.mjs +8 -7
- package/dist/utils/quotes.mjs.map +1 -1
- package/package.json +12 -12
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.submitHyperliquidWithdraw = void 0;
|
|
4
|
+
const controller_utils_1 = require("@metamask/controller-utils");
|
|
5
|
+
const keyring_controller_1 = require("@metamask/keyring-controller");
|
|
6
|
+
const utils_1 = require("@metamask/utils");
|
|
7
|
+
const constants_1 = require("./constants.cjs");
|
|
8
|
+
const constants_2 = require("../../constants.cjs");
|
|
9
|
+
const logger_1 = require("../../logger.cjs");
|
|
10
|
+
const log = (0, utils_1.createModuleLogger)(logger_1.projectLogger, 'hyperliquid-withdraw');
|
|
11
|
+
const DOMAIN_FIELD_MAP = {
|
|
12
|
+
name: { name: 'name', type: 'string' },
|
|
13
|
+
version: { name: 'version', type: 'string' },
|
|
14
|
+
chainId: { name: 'chainId', type: 'uint256' },
|
|
15
|
+
verifyingContract: { name: 'verifyingContract', type: 'address' },
|
|
16
|
+
salt: { name: 'salt', type: 'bytes32' },
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Submit a HyperLiquid 2-step withdrawal via Relay.
|
|
20
|
+
*
|
|
21
|
+
* Step 1 (authorize): Sign an EIP-712 nonce-mapping message, POST to Relay /authorize.
|
|
22
|
+
* Step 2 (deposit): Sign an EIP-712 HyperliquidSignTransaction, POST to HyperLiquid exchange.
|
|
23
|
+
*
|
|
24
|
+
* Both signatures are silent (no user confirmation). Both steps share the same nonce
|
|
25
|
+
* from the Relay quote response.
|
|
26
|
+
*
|
|
27
|
+
* @param quote - Relay quote containing the 2-step flow.
|
|
28
|
+
* @param from - User's account address.
|
|
29
|
+
* @param messenger - Controller messenger (for KeyringController:signTypedMessage).
|
|
30
|
+
*/
|
|
31
|
+
async function submitHyperliquidWithdraw(quote, from, messenger) {
|
|
32
|
+
const { steps } = quote.original;
|
|
33
|
+
log('Starting HyperLiquid withdrawal', {
|
|
34
|
+
stepCount: steps.length,
|
|
35
|
+
stepIds: steps.map((step) => step.id),
|
|
36
|
+
});
|
|
37
|
+
const authorizeStep = steps.find((step) => step.kind === 'signature' && step.id === 'authorize');
|
|
38
|
+
const depositStep = steps.find((step) => step.id === 'deposit');
|
|
39
|
+
if (!authorizeStep || !depositStep) {
|
|
40
|
+
throw new Error(`Expected authorize and deposit steps for HyperLiquid withdrawal, got: ${steps.map((step) => `${step.id}(${step.kind})`).join(', ')}`);
|
|
41
|
+
}
|
|
42
|
+
// Step 1: Authorize (nonce-mapping signature -> POST to Relay /authorize)
|
|
43
|
+
await executeAuthorizeStep(authorizeStep, from, messenger);
|
|
44
|
+
// Step 2: Deposit (HyperLiquid sendAsset -> POST to HyperLiquid exchange)
|
|
45
|
+
await executeDepositStep(depositStep, from, messenger);
|
|
46
|
+
log('HyperLiquid withdrawal submitted successfully');
|
|
47
|
+
}
|
|
48
|
+
exports.submitHyperliquidWithdraw = submitHyperliquidWithdraw;
|
|
49
|
+
/**
|
|
50
|
+
* Derive the EIP712Domain type array from a domain object.
|
|
51
|
+
* eth-sig-util defaults to EIP712Domain: [] when absent, breaking
|
|
52
|
+
* the domain separator hash. This ensures it matches ethers.js behavior.
|
|
53
|
+
*
|
|
54
|
+
* @param domain - The EIP-712 domain object.
|
|
55
|
+
* @returns The EIP712Domain type array in canonical order.
|
|
56
|
+
*/
|
|
57
|
+
function deriveEIP712DomainType(domain) {
|
|
58
|
+
return Object.keys(DOMAIN_FIELD_MAP)
|
|
59
|
+
.filter((key) => key in domain)
|
|
60
|
+
.map((key) => DOMAIN_FIELD_MAP[key]);
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Execute the authorize step: sign EIP-712 nonce-mapping and POST to Relay.
|
|
64
|
+
*
|
|
65
|
+
* @param step - The authorize signature step from the Relay quote.
|
|
66
|
+
* @param from - User's account address.
|
|
67
|
+
* @param messenger - Controller messenger for signing.
|
|
68
|
+
*/
|
|
69
|
+
async function executeAuthorizeStep(step, from, messenger) {
|
|
70
|
+
if (step.items.length !== 1) {
|
|
71
|
+
throw new Error(`Expected exactly 1 authorize item, got ${step.items.length}`);
|
|
72
|
+
}
|
|
73
|
+
const item = step.items[0];
|
|
74
|
+
if (!item) {
|
|
75
|
+
throw new Error('Authorize step has no items');
|
|
76
|
+
}
|
|
77
|
+
const { sign, post } = item.data;
|
|
78
|
+
const typedData = {
|
|
79
|
+
domain: sign.domain,
|
|
80
|
+
types: {
|
|
81
|
+
...sign.types,
|
|
82
|
+
EIP712Domain: deriveEIP712DomainType(sign.domain),
|
|
83
|
+
},
|
|
84
|
+
primaryType: sign.primaryType,
|
|
85
|
+
message: sign.value,
|
|
86
|
+
};
|
|
87
|
+
log('Signing authorize (nonce-mapping)', { domain: sign.domain });
|
|
88
|
+
const signature = await messenger.call('KeyringController:signTypedMessage', {
|
|
89
|
+
from,
|
|
90
|
+
data: JSON.stringify(typedData),
|
|
91
|
+
}, keyring_controller_1.SignTypedDataVersion.V4);
|
|
92
|
+
log('Posting authorize signature to Relay');
|
|
93
|
+
const authorizeUrl = `${constants_1.RELAY_AUTHORIZE_URL}?signature=${signature}`;
|
|
94
|
+
try {
|
|
95
|
+
const response = await (0, controller_utils_1.successfulFetch)(authorizeUrl, {
|
|
96
|
+
method: post.method,
|
|
97
|
+
headers: { 'Content-Type': 'application/json' },
|
|
98
|
+
body: JSON.stringify(post.body),
|
|
99
|
+
});
|
|
100
|
+
const result = await response.json();
|
|
101
|
+
log('Authorize response', result);
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
throw new Error(`HyperLiquid authorize failed: ${error.message}`);
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Execute the deposit step: sign HyperLiquid sendAsset and POST to HL exchange.
|
|
109
|
+
*
|
|
110
|
+
* The signature data must be constructed from the step's eip712Types and action
|
|
111
|
+
* parameters, following the Relay HyperLiquid integration spec.
|
|
112
|
+
*
|
|
113
|
+
* @param step - The deposit step from the Relay quote.
|
|
114
|
+
* @param from - User's account address.
|
|
115
|
+
* @param messenger - Controller messenger for signing.
|
|
116
|
+
*/
|
|
117
|
+
async function executeDepositStep(step, from, messenger) {
|
|
118
|
+
const items = step.items;
|
|
119
|
+
if (items.length !== 1) {
|
|
120
|
+
throw new Error(`Expected exactly 1 deposit item, got ${items.length}`);
|
|
121
|
+
}
|
|
122
|
+
const item = items[0];
|
|
123
|
+
if (!item) {
|
|
124
|
+
throw new Error('Deposit step has no items');
|
|
125
|
+
}
|
|
126
|
+
const { data } = item;
|
|
127
|
+
const action = data.action;
|
|
128
|
+
const nonce = data.nonce;
|
|
129
|
+
const eip712Types = data.eip712Types;
|
|
130
|
+
const eip712PrimaryType = data.eip712PrimaryType;
|
|
131
|
+
// HyperLiquid's EIP-712 signing spec requires Arbitrum's chain ID in the
|
|
132
|
+
// domain and message. This does not affect which chain the withdrawal
|
|
133
|
+
// targets — the destination chain is determined by the Relay quote.
|
|
134
|
+
const chainId = Number(constants_2.CHAIN_ID_ARBITRUM);
|
|
135
|
+
const domain = {
|
|
136
|
+
name: 'HyperliquidSignTransaction',
|
|
137
|
+
version: '1',
|
|
138
|
+
chainId,
|
|
139
|
+
verifyingContract: '0x0000000000000000000000000000000000000000',
|
|
140
|
+
};
|
|
141
|
+
const signatureData = {
|
|
142
|
+
domain,
|
|
143
|
+
types: {
|
|
144
|
+
...eip712Types,
|
|
145
|
+
EIP712Domain: deriveEIP712DomainType(domain),
|
|
146
|
+
},
|
|
147
|
+
primaryType: eip712PrimaryType,
|
|
148
|
+
message: {
|
|
149
|
+
...action.parameters,
|
|
150
|
+
type: action.type,
|
|
151
|
+
signatureChainId: `0x${chainId.toString(16)}`,
|
|
152
|
+
},
|
|
153
|
+
};
|
|
154
|
+
log('Signing HyperLiquid deposit (sendAsset)', {
|
|
155
|
+
nonce,
|
|
156
|
+
action: action.type,
|
|
157
|
+
});
|
|
158
|
+
const signature = await messenger.call('KeyringController:signTypedMessage', {
|
|
159
|
+
from,
|
|
160
|
+
data: JSON.stringify(signatureData),
|
|
161
|
+
}, keyring_controller_1.SignTypedDataVersion.V4);
|
|
162
|
+
// eslint-disable-next-line id-length
|
|
163
|
+
const r = signature.slice(0, 66);
|
|
164
|
+
// eslint-disable-next-line id-length
|
|
165
|
+
const s = `0x${signature.slice(66, 130)}`;
|
|
166
|
+
// eslint-disable-next-line id-length
|
|
167
|
+
const v = parseInt(signature.slice(130, 132), 16);
|
|
168
|
+
log('Posting deposit to HyperLiquid exchange');
|
|
169
|
+
let result;
|
|
170
|
+
try {
|
|
171
|
+
const response = await (0, controller_utils_1.successfulFetch)(constants_1.HYPERLIQUID_EXCHANGE_URL, {
|
|
172
|
+
method: 'POST',
|
|
173
|
+
headers: { 'Content-Type': 'application/json' },
|
|
174
|
+
body: JSON.stringify({
|
|
175
|
+
action: {
|
|
176
|
+
...action.parameters,
|
|
177
|
+
type: action.type,
|
|
178
|
+
signatureChainId: `0x${chainId.toString(16)}`,
|
|
179
|
+
},
|
|
180
|
+
nonce,
|
|
181
|
+
signature: { r, s, v },
|
|
182
|
+
}),
|
|
183
|
+
});
|
|
184
|
+
result = await response.json();
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
throw new Error(`HyperLiquid deposit failed: ${error.message}`);
|
|
188
|
+
}
|
|
189
|
+
if (result?.status !== 'ok') {
|
|
190
|
+
throw new Error(`HyperLiquid deposit failed: ${JSON.stringify(result)}`);
|
|
191
|
+
}
|
|
192
|
+
log('HyperLiquid deposit response', result);
|
|
193
|
+
}
|
|
194
|
+
//# sourceMappingURL=hyperliquid-withdraw.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hyperliquid-withdraw.cjs","sourceRoot":"","sources":["../../../src/strategy/relay/hyperliquid-withdraw.ts"],"names":[],"mappings":";;;AAAA,iEAA6D;AAC7D,qEAAoE;AAEpE,2CAAqD;AAErD,+CAA4E;AAE5E,mDAAoD;AACpD,6CAA6C;AAM7C,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,sBAAsB,CAAC,CAAC;AAItE,MAAM,gBAAgB,GAAsC;IAC1D,IAAI,EAAE,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,QAAQ,EAAE;IACtC,OAAO,EAAE,EAAE,I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AK,CAAC,EAAE,EAAE,GAAG,CAAC,EAAE,CAAC;IAC1C,qCAAqC;IACrC,MAAM,CAAC,GAAG,QAAQ,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IAElD,GAAG,CAAC,yCAAyC,CAAC,CAAC;IAE/C,IAAI,MAAe,CAAC;IAEpB,IAAI,CAAC;QACH,MAAM,QAAQ,GAAG,MAAM,IAAA,kCAAe,EAAC,oCAAwB,EAAE;YAC/D,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;YAC/C,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC;gBACnB,MAAM,EAAE;oBACN,GAAG,MAAM,CAAC,UAAU;oBACpB,IAAI,EAAE,MAAM,CAAC,IAAI;oBACjB,gBAAgB,EAAE,KAAK,OAAO,CAAC,QAAQ,CAAC,EAAE,CAAC,EAAE;iBAC9C;gBACD,KAAK;gBACL,SAAS,EAAE,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE;aACvB,CAAC;SACH,CAAC,CAAC;QAEH,MAAM,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IACjC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,+BAAgC,KAAe,CAAC,OAAO,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,IAAK,MAA8B,EAAE,MAAM,KAAK,IAAI,EAAE,CAAC;QACrD,MAAM,IAAI,KAAK,CAAC,+BAA+B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import { successfulFetch } from '@metamask/controller-utils';\nimport { SignTypedDataVersion } from '@metamask/keyring-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { RELAY_AUTHORIZE_URL, HYPERLIQUID_EXCHANGE_URL } from './constants';\nimport type { RelayQuote, RelaySignatureStep } from './types';\nimport { CHAIN_ID_ARBITRUM } from '../../constants';\nimport { projectLogger } from '../../logger';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types';\n\nconst log = createModuleLogger(projectLogger, 'hyperliquid-withdraw');\n\ntype EIP712DomainField = { name: string; type: string };\n\nconst DOMAIN_FIELD_MAP: Record<string, EIP712DomainField> = {\n name: { name: 'name', type: 'string' },\n version: { name: 'version', type: 'string' },\n chainId: { name: 'chainId', type: 'uint256' },\n verifyingContract: { name: 'verifyingContract', type: 'address' },\n salt: { name: 'salt', type: 'bytes32' },\n};\n\n/**\n * Submit a HyperLiquid 2-step withdrawal via Relay.\n *\n * Step 1 (authorize): Sign an EIP-712 nonce-mapping message, POST to Relay /authorize.\n * Step 2 (deposit): Sign an EIP-712 HyperliquidSignTransaction, POST to HyperLiquid exchange.\n *\n * Both signatures are silent (no user confirmation). Both steps share the same nonce\n * from the Relay quote response.\n *\n * @param quote - Relay quote containing the 2-step flow.\n * @param from - User's account address.\n * @param messenger - Controller messenger (for KeyringController:signTypedMessage).\n */\nexport async function submitHyperliquidWithdraw(\n quote: TransactionPayQuote<RelayQuote>,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const { steps } = quote.original;\n\n log('Starting HyperLiquid withdrawal', {\n stepCount: steps.length,\n stepIds: steps.map((step) => step.id),\n });\n\n const authorizeStep = steps.find(\n (step) => step.kind === 'signature' && step.id === 'authorize',\n ) as RelaySignatureStep | undefined;\n\n const depositStep = steps.find((step) => step.id === 'deposit');\n\n if (!authorizeStep || !depositStep) {\n throw new Error(\n `Expected authorize and deposit steps for HyperLiquid withdrawal, got: ${steps.map((step) => `${step.id}(${step.kind})`).join(', ')}`,\n );\n }\n\n // Step 1: Authorize (nonce-mapping signature -> POST to Relay /authorize)\n await executeAuthorizeStep(authorizeStep, from, messenger);\n\n // Step 2: Deposit (HyperLiquid sendAsset -> POST to HyperLiquid exchange)\n await executeDepositStep(depositStep, from, messenger);\n\n log('HyperLiquid withdrawal submitted successfully');\n}\n\n/**\n * Derive the EIP712Domain type array from a domain object.\n * eth-sig-util defaults to EIP712Domain: [] when absent, breaking\n * the domain separator hash. This ensures it matches ethers.js behavior.\n *\n * @param domain - The EIP-712 domain object.\n * @returns The EIP712Domain type array in canonical order.\n */\nfunction deriveEIP712DomainType(\n domain: Record<string, unknown>,\n): EIP712DomainField[] {\n return Object.keys(DOMAIN_FIELD_MAP)\n .filter((key) => key in domain)\n .map((key) => DOMAIN_FIELD_MAP[key]);\n}\n\n/**\n * Execute the authorize step: sign EIP-712 nonce-mapping and POST to Relay.\n *\n * @param step - The authorize signature step from the Relay quote.\n * @param from - User's account address.\n * @param messenger - Controller messenger for signing.\n */\nasync function executeAuthorizeStep(\n step: RelaySignatureStep,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n if (step.items.length !== 1) {\n throw new Error(\n `Expected exactly 1 authorize item, got ${step.items.length}`,\n );\n }\n\n const item = step.items[0];\n if (!item) {\n throw new Error('Authorize step has no items');\n }\n\n const { sign, post } = item.data;\n\n const typedData = {\n domain: sign.domain,\n types: {\n ...sign.types,\n EIP712Domain: deriveEIP712DomainType(sign.domain),\n },\n primaryType: sign.primaryType,\n message: sign.value,\n };\n\n log('Signing authorize (nonce-mapping)', { domain: sign.domain });\n\n const signature = await messenger.call(\n 'KeyringController:signTypedMessage',\n {\n from,\n data: JSON.stringify(typedData),\n },\n SignTypedDataVersion.V4,\n );\n\n log('Posting authorize signature to Relay');\n\n const authorizeUrl = `${RELAY_AUTHORIZE_URL}?signature=${signature}`;\n\n try {\n const response = await successfulFetch(authorizeUrl, {\n method: post.method,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(post.body),\n });\n\n const result = await response.json();\n\n log('Authorize response', result);\n } catch (error) {\n throw new Error(\n `HyperLiquid authorize failed: ${(error as Error).message}`,\n );\n }\n}\n\n/**\n * Execute the deposit step: sign HyperLiquid sendAsset and POST to HL exchange.\n *\n * The signature data must be constructed from the step's eip712Types and action\n * parameters, following the Relay HyperLiquid integration spec.\n *\n * @param step - The deposit step from the Relay quote.\n * @param from - User's account address.\n * @param messenger - Controller messenger for signing.\n */\nasync function executeDepositStep(\n step: RelaySignatureStep | { id: string; kind: string; items: unknown[] },\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const items = step.items as { data: Record<string, unknown> }[];\n\n if (items.length !== 1) {\n throw new Error(`Expected exactly 1 deposit item, got ${items.length}`);\n }\n\n const item = items[0];\n if (!item) {\n throw new Error('Deposit step has no items');\n }\n\n const { data } = item;\n\n const action = data.action as {\n type: string;\n parameters: Record<string, unknown>;\n };\n const nonce = data.nonce as number;\n const eip712Types = data.eip712Types as Record<string, unknown>;\n const eip712PrimaryType = data.eip712PrimaryType as string;\n\n // HyperLiquid's EIP-712 signing spec requires Arbitrum's chain ID in the\n // domain and message. This does not affect which chain the withdrawal\n // targets — the destination chain is determined by the Relay quote.\n const chainId = Number(CHAIN_ID_ARBITRUM);\n\n const domain = {\n name: 'HyperliquidSignTransaction',\n version: '1',\n chainId,\n verifyingContract: '0x0000000000000000000000000000000000000000',\n };\n\n const signatureData = {\n domain,\n types: {\n ...eip712Types,\n EIP712Domain: deriveEIP712DomainType(domain),\n },\n primaryType: eip712PrimaryType,\n message: {\n ...action.parameters,\n type: action.type,\n signatureChainId: `0x${chainId.toString(16)}`,\n },\n };\n\n log('Signing HyperLiquid deposit (sendAsset)', {\n nonce,\n action: action.type,\n });\n\n const signature = await messenger.call(\n 'KeyringController:signTypedMessage',\n {\n from,\n data: JSON.stringify(signatureData),\n },\n SignTypedDataVersion.V4,\n );\n\n // eslint-disable-next-line id-length\n const r = signature.slice(0, 66);\n // eslint-disable-next-line id-length\n const s = `0x${signature.slice(66, 130)}`;\n // eslint-disable-next-line id-length\n const v = parseInt(signature.slice(130, 132), 16);\n\n log('Posting deposit to HyperLiquid exchange');\n\n let result: unknown;\n\n try {\n const response = await successfulFetch(HYPERLIQUID_EXCHANGE_URL, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n action: {\n ...action.parameters,\n type: action.type,\n signatureChainId: `0x${chainId.toString(16)}`,\n },\n nonce,\n signature: { r, s, v },\n }),\n });\n\n result = await response.json();\n } catch (error) {\n throw new Error(`HyperLiquid deposit failed: ${(error as Error).message}`);\n }\n\n if ((result as { status?: string })?.status !== 'ok') {\n throw new Error(`HyperLiquid deposit failed: ${JSON.stringify(result)}`);\n }\n\n log('HyperLiquid deposit response', result);\n}\n"]}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Hex } from "@metamask/utils";
|
|
2
|
+
import type { RelayQuote } from "./types.cjs";
|
|
3
|
+
import type { TransactionPayControllerMessenger, TransactionPayQuote } from "../../types.cjs";
|
|
4
|
+
/**
|
|
5
|
+
* Submit a HyperLiquid 2-step withdrawal via Relay.
|
|
6
|
+
*
|
|
7
|
+
* Step 1 (authorize): Sign an EIP-712 nonce-mapping message, POST to Relay /authorize.
|
|
8
|
+
* Step 2 (deposit): Sign an EIP-712 HyperliquidSignTransaction, POST to HyperLiquid exchange.
|
|
9
|
+
*
|
|
10
|
+
* Both signatures are silent (no user confirmation). Both steps share the same nonce
|
|
11
|
+
* from the Relay quote response.
|
|
12
|
+
*
|
|
13
|
+
* @param quote - Relay quote containing the 2-step flow.
|
|
14
|
+
* @param from - User's account address.
|
|
15
|
+
* @param messenger - Controller messenger (for KeyringController:signTypedMessage).
|
|
16
|
+
*/
|
|
17
|
+
export declare function submitHyperliquidWithdraw(quote: TransactionPayQuote<RelayQuote>, from: Hex, messenger: TransactionPayControllerMessenger): Promise<void>;
|
|
18
|
+
//# sourceMappingURL=hyperliquid-withdraw.d.cts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hyperliquid-withdraw.d.cts","sourceRoot":"","sources":["../../../src/strategy/relay/hyperliquid-withdraw.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAE,UAAU,EAAsB,oBAAgB;AAG9D,OAAO,KAAK,EACV,iCAAiC,EACjC,mBAAmB,EACpB,wBAAoB;AAcrB;;;;;;;;;;;;GAYG;AACH,wBAAsB,yBAAyB,CAC7C,KAAK,EAAE,mBAAmB,CAAC,UAAU,CAAC,EACtC,IAAI,EAAE,GAAG,EACT,SAAS,EAAE,iCAAiC,GAC3C,OAAO,CAAC,IAAI,CAAC,CA2Bf"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Hex } from "@metamask/utils";
|
|
2
|
+
import type { RelayQuote } from "./types.mjs";
|
|
3
|
+
import type { TransactionPayControllerMessenger, TransactionPayQuote } from "../../types.mjs";
|
|
4
|
+
/**
|
|
5
|
+
* Submit a HyperLiquid 2-step withdrawal via Relay.
|
|
6
|
+
*
|
|
7
|
+
* Step 1 (authorize): Sign an EIP-712 nonce-mapping message, POST to Relay /authorize.
|
|
8
|
+
* Step 2 (deposit): Sign an EIP-712 HyperliquidSignTransaction, POST to HyperLiquid exchange.
|
|
9
|
+
*
|
|
10
|
+
* Both signatures are silent (no user confirmation). Both steps share the same nonce
|
|
11
|
+
* from the Relay quote response.
|
|
12
|
+
*
|
|
13
|
+
* @param quote - Relay quote containing the 2-step flow.
|
|
14
|
+
* @param from - User's account address.
|
|
15
|
+
* @param messenger - Controller messenger (for KeyringController:signTypedMessage).
|
|
16
|
+
*/
|
|
17
|
+
export declare function submitHyperliquidWithdraw(quote: TransactionPayQuote<RelayQuote>, from: Hex, messenger: TransactionPayControllerMessenger): Promise<void>;
|
|
18
|
+
//# sourceMappingURL=hyperliquid-withdraw.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hyperliquid-withdraw.d.mts","sourceRoot":"","sources":["../../../src/strategy/relay/hyperliquid-withdraw.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,GAAG,EAAE,wBAAwB;AAI3C,OAAO,KAAK,EAAE,UAAU,EAAsB,oBAAgB;AAG9D,OAAO,KAAK,EACV,iCAAiC,EACjC,mBAAmB,EACpB,wBAAoB;AAcrB;;;;;;;;;;;;GAYG;AACH,wBAAsB,yBAAyB,CAC7C,KAAK,EAAE,mBAAmB,CAAC,UAAU,CAAC,EACtC,IAAI,EAAE,GAAG,EACT,SAAS,EAAE,iCAAiC,GAC3C,OAAO,CAAC,IAAI,CAAC,CA2Bf"}
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import { successfulFetch } from "@metamask/controller-utils";
|
|
2
|
+
import { SignTypedDataVersion } from "@metamask/keyring-controller";
|
|
3
|
+
import { createModuleLogger } from "@metamask/utils";
|
|
4
|
+
import { RELAY_AUTHORIZE_URL, HYPERLIQUID_EXCHANGE_URL } from "./constants.mjs";
|
|
5
|
+
import { CHAIN_ID_ARBITRUM } from "../../constants.mjs";
|
|
6
|
+
import { projectLogger } from "../../logger.mjs";
|
|
7
|
+
const log = createModuleLogger(projectLogger, 'hyperliquid-withdraw');
|
|
8
|
+
const DOMAIN_FIELD_MAP = {
|
|
9
|
+
name: { name: 'name', type: 'string' },
|
|
10
|
+
version: { name: 'version', type: 'string' },
|
|
11
|
+
chainId: { name: 'chainId', type: 'uint256' },
|
|
12
|
+
verifyingContract: { name: 'verifyingContract', type: 'address' },
|
|
13
|
+
salt: { name: 'salt', type: 'bytes32' },
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* Submit a HyperLiquid 2-step withdrawal via Relay.
|
|
17
|
+
*
|
|
18
|
+
* Step 1 (authorize): Sign an EIP-712 nonce-mapping message, POST to Relay /authorize.
|
|
19
|
+
* Step 2 (deposit): Sign an EIP-712 HyperliquidSignTransaction, POST to HyperLiquid exchange.
|
|
20
|
+
*
|
|
21
|
+
* Both signatures are silent (no user confirmation). Both steps share the same nonce
|
|
22
|
+
* from the Relay quote response.
|
|
23
|
+
*
|
|
24
|
+
* @param quote - Relay quote containing the 2-step flow.
|
|
25
|
+
* @param from - User's account address.
|
|
26
|
+
* @param messenger - Controller messenger (for KeyringController:signTypedMessage).
|
|
27
|
+
*/
|
|
28
|
+
export async function submitHyperliquidWithdraw(quote, from, messenger) {
|
|
29
|
+
const { steps } = quote.original;
|
|
30
|
+
log('Starting HyperLiquid withdrawal', {
|
|
31
|
+
stepCount: steps.length,
|
|
32
|
+
stepIds: steps.map((step) => step.id),
|
|
33
|
+
});
|
|
34
|
+
const authorizeStep = steps.find((step) => step.kind === 'signature' && step.id === 'authorize');
|
|
35
|
+
const depositStep = steps.find((step) => step.id === 'deposit');
|
|
36
|
+
if (!authorizeStep || !depositStep) {
|
|
37
|
+
throw new Error(`Expected authorize and deposit steps for HyperLiquid withdrawal, got: ${steps.map((step) => `${step.id}(${step.kind})`).join(', ')}`);
|
|
38
|
+
}
|
|
39
|
+
// Step 1: Authorize (nonce-mapping signature -> POST to Relay /authorize)
|
|
40
|
+
await executeAuthorizeStep(authorizeStep, from, messenger);
|
|
41
|
+
// Step 2: Deposit (HyperLiquid sendAsset -> POST to HyperLiquid exchange)
|
|
42
|
+
await executeDepositStep(depositStep, from, messenger);
|
|
43
|
+
log('HyperLiquid withdrawal submitted successfully');
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Derive the EIP712Domain type array from a domain object.
|
|
47
|
+
* eth-sig-util defaults to EIP712Domain: [] when absent, breaking
|
|
48
|
+
* the domain separator hash. This ensures it matches ethers.js behavior.
|
|
49
|
+
*
|
|
50
|
+
* @param domain - The EIP-712 domain object.
|
|
51
|
+
* @returns The EIP712Domain type array in canonical order.
|
|
52
|
+
*/
|
|
53
|
+
function deriveEIP712DomainType(domain) {
|
|
54
|
+
return Object.keys(DOMAIN_FIELD_MAP)
|
|
55
|
+
.filter((key) => key in domain)
|
|
56
|
+
.map((key) => DOMAIN_FIELD_MAP[key]);
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Execute the authorize step: sign EIP-712 nonce-mapping and POST to Relay.
|
|
60
|
+
*
|
|
61
|
+
* @param step - The authorize signature step from the Relay quote.
|
|
62
|
+
* @param from - User's account address.
|
|
63
|
+
* @param messenger - Controller messenger for signing.
|
|
64
|
+
*/
|
|
65
|
+
async function executeAuthorizeStep(step, from, messenger) {
|
|
66
|
+
if (step.items.length !== 1) {
|
|
67
|
+
throw new Error(`Expected exactly 1 authorize item, got ${step.items.length}`);
|
|
68
|
+
}
|
|
69
|
+
const item = step.items[0];
|
|
70
|
+
if (!item) {
|
|
71
|
+
throw new Error('Authorize step has no items');
|
|
72
|
+
}
|
|
73
|
+
const { sign, post } = item.data;
|
|
74
|
+
const typedData = {
|
|
75
|
+
domain: sign.domain,
|
|
76
|
+
types: {
|
|
77
|
+
...sign.types,
|
|
78
|
+
EIP712Domain: deriveEIP712DomainType(sign.domain),
|
|
79
|
+
},
|
|
80
|
+
primaryType: sign.primaryType,
|
|
81
|
+
message: sign.value,
|
|
82
|
+
};
|
|
83
|
+
log('Signing authorize (nonce-mapping)', { domain: sign.domain });
|
|
84
|
+
const signature = await messenger.call('KeyringController:signTypedMessage', {
|
|
85
|
+
from,
|
|
86
|
+
data: JSON.stringify(typedData),
|
|
87
|
+
}, SignTypedDataVersion.V4);
|
|
88
|
+
log('Posting authorize signature to Relay');
|
|
89
|
+
const authorizeUrl = `${RELAY_AUTHORIZE_URL}?signature=${signature}`;
|
|
90
|
+
try {
|
|
91
|
+
const response = await successfulFetch(authorizeUrl, {
|
|
92
|
+
method: post.method,
|
|
93
|
+
headers: { 'Content-Type': 'application/json' },
|
|
94
|
+
body: JSON.stringify(post.body),
|
|
95
|
+
});
|
|
96
|
+
const result = await response.json();
|
|
97
|
+
log('Authorize response', result);
|
|
98
|
+
}
|
|
99
|
+
catch (error) {
|
|
100
|
+
throw new Error(`HyperLiquid authorize failed: ${error.message}`);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Execute the deposit step: sign HyperLiquid sendAsset and POST to HL exchange.
|
|
105
|
+
*
|
|
106
|
+
* The signature data must be constructed from the step's eip712Types and action
|
|
107
|
+
* parameters, following the Relay HyperLiquid integration spec.
|
|
108
|
+
*
|
|
109
|
+
* @param step - The deposit step from the Relay quote.
|
|
110
|
+
* @param from - User's account address.
|
|
111
|
+
* @param messenger - Controller messenger for signing.
|
|
112
|
+
*/
|
|
113
|
+
async function executeDepositStep(step, from, messenger) {
|
|
114
|
+
const items = step.items;
|
|
115
|
+
if (items.length !== 1) {
|
|
116
|
+
throw new Error(`Expected exactly 1 deposit item, got ${items.length}`);
|
|
117
|
+
}
|
|
118
|
+
const item = items[0];
|
|
119
|
+
if (!item) {
|
|
120
|
+
throw new Error('Deposit step has no items');
|
|
121
|
+
}
|
|
122
|
+
const { data } = item;
|
|
123
|
+
const action = data.action;
|
|
124
|
+
const nonce = data.nonce;
|
|
125
|
+
const eip712Types = data.eip712Types;
|
|
126
|
+
const eip712PrimaryType = data.eip712PrimaryType;
|
|
127
|
+
// HyperLiquid's EIP-712 signing spec requires Arbitrum's chain ID in the
|
|
128
|
+
// domain and message. This does not affect which chain the withdrawal
|
|
129
|
+
// targets — the destination chain is determined by the Relay quote.
|
|
130
|
+
const chainId = Number(CHAIN_ID_ARBITRUM);
|
|
131
|
+
const domain = {
|
|
132
|
+
name: 'HyperliquidSignTransaction',
|
|
133
|
+
version: '1',
|
|
134
|
+
chainId,
|
|
135
|
+
verifyingContract: '0x0000000000000000000000000000000000000000',
|
|
136
|
+
};
|
|
137
|
+
const signatureData = {
|
|
138
|
+
domain,
|
|
139
|
+
types: {
|
|
140
|
+
...eip712Types,
|
|
141
|
+
EIP712Domain: deriveEIP712DomainType(domain),
|
|
142
|
+
},
|
|
143
|
+
primaryType: eip712PrimaryType,
|
|
144
|
+
message: {
|
|
145
|
+
...action.parameters,
|
|
146
|
+
type: action.type,
|
|
147
|
+
signatureChainId: `0x${chainId.toString(16)}`,
|
|
148
|
+
},
|
|
149
|
+
};
|
|
150
|
+
log('Signing HyperLiquid deposit (sendAsset)', {
|
|
151
|
+
nonce,
|
|
152
|
+
action: action.type,
|
|
153
|
+
});
|
|
154
|
+
const signature = await messenger.call('KeyringController:signTypedMessage', {
|
|
155
|
+
from,
|
|
156
|
+
data: JSON.stringify(signatureData),
|
|
157
|
+
}, SignTypedDataVersion.V4);
|
|
158
|
+
// eslint-disable-next-line id-length
|
|
159
|
+
const r = signature.slice(0, 66);
|
|
160
|
+
// eslint-disable-next-line id-length
|
|
161
|
+
const s = `0x${signature.slice(66, 130)}`;
|
|
162
|
+
// eslint-disable-next-line id-length
|
|
163
|
+
const v = parseInt(signature.slice(130, 132), 16);
|
|
164
|
+
log('Posting deposit to HyperLiquid exchange');
|
|
165
|
+
let result;
|
|
166
|
+
try {
|
|
167
|
+
const response = await successfulFetch(HYPERLIQUID_EXCHANGE_URL, {
|
|
168
|
+
method: 'POST',
|
|
169
|
+
headers: { 'Content-Type': 'application/json' },
|
|
170
|
+
body: JSON.stringify({
|
|
171
|
+
action: {
|
|
172
|
+
...action.parameters,
|
|
173
|
+
type: action.type,
|
|
174
|
+
signatureChainId: `0x${chainId.toString(16)}`,
|
|
175
|
+
},
|
|
176
|
+
nonce,
|
|
177
|
+
signature: { r, s, v },
|
|
178
|
+
}),
|
|
179
|
+
});
|
|
180
|
+
result = await response.json();
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
throw new Error(`HyperLiquid deposit failed: ${error.message}`);
|
|
184
|
+
}
|
|
185
|
+
if (result?.status !== 'ok') {
|
|
186
|
+
throw new Error(`HyperLiquid deposit failed: ${JSON.stringify(result)}`);
|
|
187
|
+
}
|
|
188
|
+
log('HyperLiquid deposit response', result);
|
|
189
|
+
}
|
|
190
|
+
//# sourceMappingURL=hyperliquid-withdraw.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hyperli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GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;IACjC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,MAAM,IAAI,KAAK,CAAC,+BAAgC,KAAe,CAAC,OAAO,EAAE,CAAC,CAAC;IAC7E,CAAC;IAED,IAAK,MAA8B,EAAE,MAAM,KAAK,IAAI,EAAE,CAAC;QACrD,MAAM,IAAI,KAAK,CAAC,+BAA+B,IAAI,CAAC,SAAS,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC3E,CAAC;IAED,GAAG,CAAC,8BAA8B,EAAE,MAAM,CAAC,CAAC;AAC9C,CAAC","sourcesContent":["import { successfulFetch } from '@metamask/controller-utils';\nimport { SignTypedDataVersion } from '@metamask/keyring-controller';\nimport type { Hex } from '@metamask/utils';\nimport { createModuleLogger } from '@metamask/utils';\n\nimport { RELAY_AUTHORIZE_URL, HYPERLIQUID_EXCHANGE_URL } from './constants';\nimport type { RelayQuote, RelaySignatureStep } from './types';\nimport { CHAIN_ID_ARBITRUM } from '../../constants';\nimport { projectLogger } from '../../logger';\nimport type {\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types';\n\nconst log = createModuleLogger(projectLogger, 'hyperliquid-withdraw');\n\ntype EIP712DomainField = { name: string; type: string };\n\nconst DOMAIN_FIELD_MAP: Record<string, EIP712DomainField> = {\n name: { name: 'name', type: 'string' },\n version: { name: 'version', type: 'string' },\n chainId: { name: 'chainId', type: 'uint256' },\n verifyingContract: { name: 'verifyingContract', type: 'address' },\n salt: { name: 'salt', type: 'bytes32' },\n};\n\n/**\n * Submit a HyperLiquid 2-step withdrawal via Relay.\n *\n * Step 1 (authorize): Sign an EIP-712 nonce-mapping message, POST to Relay /authorize.\n * Step 2 (deposit): Sign an EIP-712 HyperliquidSignTransaction, POST to HyperLiquid exchange.\n *\n * Both signatures are silent (no user confirmation). Both steps share the same nonce\n * from the Relay quote response.\n *\n * @param quote - Relay quote containing the 2-step flow.\n * @param from - User's account address.\n * @param messenger - Controller messenger (for KeyringController:signTypedMessage).\n */\nexport async function submitHyperliquidWithdraw(\n quote: TransactionPayQuote<RelayQuote>,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const { steps } = quote.original;\n\n log('Starting HyperLiquid withdrawal', {\n stepCount: steps.length,\n stepIds: steps.map((step) => step.id),\n });\n\n const authorizeStep = steps.find(\n (step) => step.kind === 'signature' && step.id === 'authorize',\n ) as RelaySignatureStep | undefined;\n\n const depositStep = steps.find((step) => step.id === 'deposit');\n\n if (!authorizeStep || !depositStep) {\n throw new Error(\n `Expected authorize and deposit steps for HyperLiquid withdrawal, got: ${steps.map((step) => `${step.id}(${step.kind})`).join(', ')}`,\n );\n }\n\n // Step 1: Authorize (nonce-mapping signature -> POST to Relay /authorize)\n await executeAuthorizeStep(authorizeStep, from, messenger);\n\n // Step 2: Deposit (HyperLiquid sendAsset -> POST to HyperLiquid exchange)\n await executeDepositStep(depositStep, from, messenger);\n\n log('HyperLiquid withdrawal submitted successfully');\n}\n\n/**\n * Derive the EIP712Domain type array from a domain object.\n * eth-sig-util defaults to EIP712Domain: [] when absent, breaking\n * the domain separator hash. This ensures it matches ethers.js behavior.\n *\n * @param domain - The EIP-712 domain object.\n * @returns The EIP712Domain type array in canonical order.\n */\nfunction deriveEIP712DomainType(\n domain: Record<string, unknown>,\n): EIP712DomainField[] {\n return Object.keys(DOMAIN_FIELD_MAP)\n .filter((key) => key in domain)\n .map((key) => DOMAIN_FIELD_MAP[key]);\n}\n\n/**\n * Execute the authorize step: sign EIP-712 nonce-mapping and POST to Relay.\n *\n * @param step - The authorize signature step from the Relay quote.\n * @param from - User's account address.\n * @param messenger - Controller messenger for signing.\n */\nasync function executeAuthorizeStep(\n step: RelaySignatureStep,\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n if (step.items.length !== 1) {\n throw new Error(\n `Expected exactly 1 authorize item, got ${step.items.length}`,\n );\n }\n\n const item = step.items[0];\n if (!item) {\n throw new Error('Authorize step has no items');\n }\n\n const { sign, post } = item.data;\n\n const typedData = {\n domain: sign.domain,\n types: {\n ...sign.types,\n EIP712Domain: deriveEIP712DomainType(sign.domain),\n },\n primaryType: sign.primaryType,\n message: sign.value,\n };\n\n log('Signing authorize (nonce-mapping)', { domain: sign.domain });\n\n const signature = await messenger.call(\n 'KeyringController:signTypedMessage',\n {\n from,\n data: JSON.stringify(typedData),\n },\n SignTypedDataVersion.V4,\n );\n\n log('Posting authorize signature to Relay');\n\n const authorizeUrl = `${RELAY_AUTHORIZE_URL}?signature=${signature}`;\n\n try {\n const response = await successfulFetch(authorizeUrl, {\n method: post.method,\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify(post.body),\n });\n\n const result = await response.json();\n\n log('Authorize response', result);\n } catch (error) {\n throw new Error(\n `HyperLiquid authorize failed: ${(error as Error).message}`,\n );\n }\n}\n\n/**\n * Execute the deposit step: sign HyperLiquid sendAsset and POST to HL exchange.\n *\n * The signature data must be constructed from the step's eip712Types and action\n * parameters, following the Relay HyperLiquid integration spec.\n *\n * @param step - The deposit step from the Relay quote.\n * @param from - User's account address.\n * @param messenger - Controller messenger for signing.\n */\nasync function executeDepositStep(\n step: RelaySignatureStep | { id: string; kind: string; items: unknown[] },\n from: Hex,\n messenger: TransactionPayControllerMessenger,\n): Promise<void> {\n const items = step.items as { data: Record<string, unknown> }[];\n\n if (items.length !== 1) {\n throw new Error(`Expected exactly 1 deposit item, got ${items.length}`);\n }\n\n const item = items[0];\n if (!item) {\n throw new Error('Deposit step has no items');\n }\n\n const { data } = item;\n\n const action = data.action as {\n type: string;\n parameters: Record<string, unknown>;\n };\n const nonce = data.nonce as number;\n const eip712Types = data.eip712Types as Record<string, unknown>;\n const eip712PrimaryType = data.eip712PrimaryType as string;\n\n // HyperLiquid's EIP-712 signing spec requires Arbitrum's chain ID in the\n // domain and message. This does not affect which chain the withdrawal\n // targets — the destination chain is determined by the Relay quote.\n const chainId = Number(CHAIN_ID_ARBITRUM);\n\n const domain = {\n name: 'HyperliquidSignTransaction',\n version: '1',\n chainId,\n verifyingContract: '0x0000000000000000000000000000000000000000',\n };\n\n const signatureData = {\n domain,\n types: {\n ...eip712Types,\n EIP712Domain: deriveEIP712DomainType(domain),\n },\n primaryType: eip712PrimaryType,\n message: {\n ...action.parameters,\n type: action.type,\n signatureChainId: `0x${chainId.toString(16)}`,\n },\n };\n\n log('Signing HyperLiquid deposit (sendAsset)', {\n nonce,\n action: action.type,\n });\n\n const signature = await messenger.call(\n 'KeyringController:signTypedMessage',\n {\n from,\n data: JSON.stringify(signatureData),\n },\n SignTypedDataVersion.V4,\n );\n\n // eslint-disable-next-line id-length\n const r = signature.slice(0, 66);\n // eslint-disable-next-line id-length\n const s = `0x${signature.slice(66, 130)}`;\n // eslint-disable-next-line id-length\n const v = parseInt(signature.slice(130, 132), 16);\n\n log('Posting deposit to HyperLiquid exchange');\n\n let result: unknown;\n\n try {\n const response = await successfulFetch(HYPERLIQUID_EXCHANGE_URL, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({\n action: {\n ...action.parameters,\n type: action.type,\n signatureChainId: `0x${chainId.toString(16)}`,\n },\n nonce,\n signature: { r, s, v },\n }),\n });\n\n result = await response.json();\n } catch (error) {\n throw new Error(`HyperLiquid deposit failed: ${(error as Error).message}`);\n }\n\n if ((result as { status?: string })?.status !== 'ok') {\n throw new Error(`HyperLiquid deposit failed: ${JSON.stringify(result)}`);\n }\n\n log('HyperLiquid deposit response', result);\n}\n"]}
|
|
@@ -150,7 +150,8 @@ async function getGasCostFromQuoteOrGasStation(quote, messenger, request) {
|
|
|
150
150
|
source: GasCostEstimateSource.Quote,
|
|
151
151
|
};
|
|
152
152
|
}
|
|
153
|
-
const
|
|
153
|
+
const firstTxStep = quote.original.steps.find((step) => step.kind === 'transaction');
|
|
154
|
+
const firstStepData = firstTxStep?.items[0]?.data;
|
|
154
155
|
if (!firstStepData) {
|
|
155
156
|
return undefined;
|
|
156
157
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relay-max-gas-station.cjs","sourceRoot":"","sources":["../../../src/strategy/relay/relay-max-gas-station.ts"],"names":[],"mappings":";;;AAAA,2CAAqD;AACrD,+CAAyC;AAEzC,mDAGuB;AAEvB,6CAA6C;AAO7C,iDAI2B;AAE3B,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,uBAAuB,CAAC,CAAC;AAEvE,MAAM,uBAAuB,GAAG,IAAI,CAAC;AAErC,IAAK,qBAIJ;AAJD,WAAK,qBAAqB;IACxB,mDAA0B,CAAA;IAC1B,wCAAe,CAAA;IACf,wCAAe,CAAA;AACjB,CAAC,EAJI,qBAAqB,KAArB,qBAAqB,QAIzB;AAyBD;;;;;;;;;;;;;;;GAeG;AACI,KAAK,UAAU,0BAA0B,CAC9C,OAAqB,EACrB,WAAwC,EACxC,cAAgC;IAEhC,MAAM,EAAE,SAAS,EAAE,GAAG,WAAW,CAAC;IAClC,MAAM,EAAE,aAAa,EAAE,iBAAiB,EAAE,GAAG,OAAO,CAAC;IACrD,MAAM,OAAO,GAA0B;QACrC,WAAW;QACX,cAAc;QACd,SAAS;QACT,OAAO;KACR,CAAC;IAEF,MAAM,WAAW,GAAG,MAAM,cAAc,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;IAE/D,MAAM,kBAAkB,GAAG,kDAAkD,CAC3E,WAAW,EACX,SAAS,EACT,OAAO,CACR,CAAC;IAEF,IAAI,kBAAkB,CAAC,sBAAsB,EAAE,CAAC;QAC9C,OAAO,gBAAgB,CACrB,WAAW,EACX,sCAAsC,EACtC;YACE,aAAa,EAAE,kBAAkB,CAAC,aAAa;YAC/C,aAAa,EAAE,kBAAkB,CAAC,gBAAgB;SACnD,CACF,CAAC;IACJ,CAAC;IAED,MAAM,qBAAqB,GAAG,IAAA,sCAAwB,EACpD,SAAS,EACT,aAAa,CACd,CAAC;IAEF,IAAI,CAAC,qBAAqB,CAAC,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AAmB;IAC3C,OAAO,SAAS,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE,CAAC,KAAK,GAAG,QAAQ,EAAE,CAAC,CAAC,CAAC;AACpE,CAAC;AAED,SAAS,wBAAwB,CAC/B,KAAsC;IAEtC,KAAK,CAAC,QAAQ,CAAC,QAAQ,GAAG;QACxB,GAAG,KAAK,CAAC,QAAQ,CAAC,QAAQ;QAC1B,eAAe,EAAE,IAAI;KACtB,CAAC;AACJ,CAAC","sourcesContent":["import { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n getGasStationEligibility,\n getGasStationCostInSourceTokenRaw,\n} from './gas-station';\nimport type { RelayQuote } from './types';\nimport { projectLogger } from '../../logger';\nimport type {\n PayStrategyGetQuotesRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types';\nimport {\n getNativeToken,\n getTokenBalance,\n getTokenInfo,\n} from '../../utils/token';\n\nconst log = createModuleLogger(projectLogger, 'relay-max-gas-station');\n\nconst PROBE_AMOUNT_PERCENTAGE = 0.25;\n\nenum GasCostEstimateSource {\n GasStation = 'gas-station',\n Probe = 'probe',\n Quote = 'quote',\n}\n\ntype GasCostEstimate = {\n amount: BigNumber;\n source: GasCostEstimateSource;\n};\n\ntype NativeBalanceCheckResult = {\n hasEnoughNativeBalance: boolean;\n nativeBalance?: string;\n nativeGasCostRaw?: string;\n};\n\ntype GetSingleQuoteFn = (\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n) => Promise<TransactionPayQuote<RelayQuote>>;\n\ntype MaxAmountQuoteContext = {\n fullRequest: PayStrategyGetQuotesRequest;\n getSingleQuote: GetSingleQuoteFn;\n messenger: TransactionPayControllerMessenger;\n request: QuoteRequest;\n};\n\n/**\n * Returns a Relay max-amount quote using a two-phase gas-station fallback.\n *\n * It first requests a standard max quote (phase 1), then when needed estimates\n * gas in source-token units (directly or via a probe quote), requests an\n * adjusted max quote (phase 2), and accepts phase 2 only if validation passes\n * (source gas fee token selected, gas-limit checks, affordability).\n *\n * If any step fails or validation is unsafe, it safely falls back to phase 1.\n * Successful phase-2 quotes are tagged with `metamask.isMaxGasStation = true`.\n *\n * @param request - Relay quote request for a max-amount flow.\n * @param fullRequest - Full quote request context including messenger and transaction.\n * @param getSingleQuote - Quote fetcher used for phase-1, phase-2, and probe quotes.\n * @returns The validated adjusted phase-2 quote, or the original phase-1 quote on fallback.\n */\nexport async function getRelayMaxGasStationQuote(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n getSingleQuote: GetSingleQuoteFn,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const { messenger } = fullRequest;\n const { sourceChainId, sourceTokenAmount } = request;\n const context: MaxAmountQuoteContext = {\n fullRequest,\n getSingleQuote,\n messenger,\n request,\n };\n\n const phase1Quote = await getSingleQuote(request, fullRequest);\n\n const nativeBalanceCheck = checkEnoughNativeBalanceIfSourceGasFeeTokenNotUsed(\n phase1Quote,\n messenger,\n request,\n );\n\n if (nativeBalanceCheck.hasEnoughNativeBalance) {\n return fallbackToPhase1(\n phase1Quote,\n 'Native balance is sufficient for gas',\n {\n nativeBalance: nativeBalanceCheck.nativeBalance,\n nativeGasCost: nativeBalanceCheck.nativeGasCostRaw,\n },\n );\n }\n\n const gasStationEligibility = getGasStationEligibility(\n messenger,\n sourceChainId,\n );\n\n if (!gasStationEligibility.isEligible) {\n return fallbackToPhase1(\n phase1Quote,\n 'Gas station is disabled or unsupported',\n );\n }\n\n const sourceAmountBN = new BigNumber(sourceTokenAmount);\n const probeCost = await getProbeGasCostInSourceTokenRaw(context);\n\n if (!probeCost) {\n return fallbackToPhase1(\n phase1Quote,\n 'Unable to estimate gas-station source token cost',\n );\n }\n\n const initialGasEstimate: GasCostEstimate = {\n amount: probeCost,\n source: GasCostEstimateSource.Probe,\n };\n\n const adjustedSourceAmount = getAdjustedSourceAmount(\n sourceAmountBN,\n initialGasEstimate.amount,\n );\n\n if (!adjustedSourceAmount.isGreaterThan(0)) {\n return fallbackToPhase1(\n phase1Quote,\n 'Insufficient balance for gas station after max adjustment',\n );\n }\n\n const phase2Quote = await getAdjustedPhase2Quote(\n adjustedSourceAmount,\n initialGasEstimate,\n context,\n );\n\n if (!phase2Quote) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted phase-2 quote request failed',\n );\n }\n\n if (!phase2Quote.fees.isSourceGasFeeToken) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted quote did not return source gas fee token pricing',\n );\n }\n\n const phase1GasLimits = phase1Quote.original.metamask.gasLimits ?? [];\n const phase2GasLimits = phase2Quote.original.metamask.gasLimits ?? [];\n\n if (!hasMatchingGasLimitShape(phase1GasLimits, phase2GasLimits)) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted quote gas limit shape changed between phases',\n {\n phase1GasLimits,\n phase2GasLimits,\n },\n );\n }\n\n const phase1TotalGasLimit = getTotalGasLimit(phase1GasLimits);\n const phase2TotalGasLimit = getTotalGasLimit(phase2GasLimits);\n\n if (phase2TotalGasLimit > phase1TotalGasLimit) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted quote total gas limit increased between phases',\n {\n phase1TotalGasLimit,\n phase2TotalGasLimit,\n },\n );\n }\n\n const validationGasEstimate = new BigNumber(\n phase2Quote.fees.sourceNetwork.max.raw,\n );\n\n if (\n !isAdjustedAmountAffordable(\n adjustedSourceAmount,\n validationGasEstimate,\n sourceAmountBN,\n )\n ) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted quote fails affordability validation',\n {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n validationGasCost: validationGasEstimate.toString(10),\n },\n );\n }\n\n markQuoteAsMaxGasStation(phase2Quote);\n\n return phase2Quote;\n}\n\nfunction checkEnoughNativeBalanceIfSourceGasFeeTokenNotUsed(\n quote: TransactionPayQuote<RelayQuote>,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n): NativeBalanceCheckResult {\n if (quote.fees.isSourceGasFeeToken) {\n return { hasEnoughNativeBalance: false };\n }\n\n const nativeGasCostRaw = quote.fees.sourceNetwork.max.raw;\n const nativeBalance = getTokenBalance(\n messenger,\n request.from,\n request.sourceChainId,\n getNativeToken(request.sourceChainId),\n );\n\n return {\n hasEnoughNativeBalance: new BigNumber(nativeBalance).isGreaterThanOrEqualTo(\n nativeGasCostRaw,\n ),\n nativeBalance,\n nativeGasCostRaw,\n };\n}\n\nfunction getAdjustedSourceAmount(\n sourceAmount: BigNumber,\n estimatedGasCost: BigNumber,\n): BigNumber {\n return sourceAmount\n .minus(estimatedGasCost)\n .integerValue(BigNumber.ROUND_DOWN);\n}\n\nfunction isAdjustedAmountAffordable(\n adjustedSourceAmount: BigNumber,\n gasCost: BigNumber,\n originalSourceAmount: BigNumber,\n): boolean {\n return adjustedSourceAmount\n .plus(gasCost)\n .isLessThanOrEqualTo(originalSourceAmount);\n}\n\nasync function getAdjustedPhase2Quote(\n adjustedSourceAmount: BigNumber,\n initialGasEstimate: GasCostEstimate,\n context: MaxAmountQuoteContext,\n): Promise<TransactionPayQuote<RelayQuote> | undefined> {\n const { fullRequest, getSingleQuote, request } = context;\n\n log('Requesting adjusted max quote', {\n adjustedAmount: adjustedSourceAmount.toString(10),\n gasCostInSourceToken: initialGasEstimate.amount.toString(10),\n gasEstimateSource: initialGasEstimate.source,\n originalAmount: request.sourceTokenAmount,\n });\n\n try {\n return await getSingleQuote(\n {\n ...request,\n sourceTokenAmount: adjustedSourceAmount.toFixed(\n 0,\n BigNumber.ROUND_DOWN,\n ),\n },\n fullRequest,\n );\n } catch (error) {\n log('Adjusted quote request failed, falling back to phase-1 quote', {\n error,\n });\n return undefined;\n }\n}\n\nasync function getGasCostFromQuoteOrGasStation(\n quote: TransactionPayQuote<RelayQuote>,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n): Promise<GasCostEstimate | undefined> {\n const gasCost = quote.fees.sourceNetwork.max;\n\n if (quote.fees.isSourceGasFeeToken) {\n log('Gas cost already in source token units', { raw: gasCost.raw });\n return {\n amount: new BigNumber(gasCost.raw),\n source: GasCostEstimateSource.Quote,\n };\n }\n\n const firstStepData = quote.original.steps[0]?.items[0]?.data;\n\n if (!firstStepData) {\n return undefined;\n }\n\n const totalItemCount = quote.original.steps.reduce(\n (count, step) => count + step.items.length,\n 0,\n );\n\n const totalGasEstimate = (quote.original.metamask.gasLimits ?? []).reduce(\n (acc, gasLimit) => acc + gasLimit,\n 0,\n );\n\n const gasStationCost = await getGasStationCostInSourceTokenRaw({\n firstStepData,\n messenger,\n request: {\n from: request.from,\n sourceChainId: request.sourceChainId,\n sourceTokenAddress: request.sourceTokenAddress,\n },\n totalGasEstimate,\n totalItemCount,\n });\n\n if (!gasStationCost) {\n return undefined;\n }\n\n return {\n amount: new BigNumber(gasStationCost.raw),\n source: GasCostEstimateSource.GasStation,\n };\n}\n\nasync function getProbeGasCostInSourceTokenRaw(\n context: MaxAmountQuoteContext,\n): Promise<BigNumber | undefined> {\n const { fullRequest, getSingleQuote, messenger, request } = context;\n\n const sourceTokenInfo = getTokenInfo(\n messenger,\n request.sourceTokenAddress,\n request.sourceChainId,\n );\n\n if (!sourceTokenInfo) {\n return undefined;\n }\n\n const probeAmount = getProbeSourceAmountRaw(\n request.sourceTokenAmount,\n sourceTokenInfo.decimals,\n );\n\n if (!probeAmount || probeAmount === request.sourceTokenAmount) {\n return undefined;\n }\n\n log('Requesting probe quote for gas station estimation', {\n originalSourceAmount: request.sourceTokenAmount,\n probeAmount,\n });\n\n let probeQuote: TransactionPayQuote<RelayQuote> | undefined;\n\n try {\n probeQuote = await getSingleQuote(\n {\n ...request,\n sourceTokenAmount: probeAmount,\n },\n fullRequest,\n );\n } catch (error) {\n log('Probe quote request failed', { error });\n return undefined;\n }\n\n if (!probeQuote) {\n return undefined;\n }\n\n const probeEstimate = await getGasCostFromQuoteOrGasStation(\n probeQuote,\n messenger,\n request,\n );\n\n return probeEstimate?.amount;\n}\n\nfunction getProbeSourceAmountRaw(\n sourceAmountRaw: string,\n sourceDecimals: number,\n): string | undefined {\n const sourceAmount = new BigNumber(sourceAmountRaw);\n\n if (sourceAmount.isLessThanOrEqualTo(0)) {\n return undefined;\n }\n\n const probeRawAmount = sourceAmount\n .multipliedBy(PROBE_AMOUNT_PERCENTAGE)\n .integerValue(BigNumber.ROUND_FLOOR);\n\n // Minimum probe size: ~0.01 token for tokens with >=2 decimals,\n // otherwise one raw unit for low-decimal tokens.\n const minimumProbeRaw = new BigNumber(1).shiftedBy(\n Math.max(sourceDecimals - 2, 0),\n );\n\n const probeRaw = BigNumber.minimum(\n sourceAmount,\n BigNumber.maximum(probeRawAmount, minimumProbeRaw),\n ).integerValue(BigNumber.ROUND_FLOOR);\n\n if (probeRaw.isLessThanOrEqualTo(0)) {\n return undefined;\n }\n\n return probeRaw.toFixed(0);\n}\n\nfunction fallbackToPhase1(\n phase1Quote: TransactionPayQuote<RelayQuote>,\n message: string,\n paramsToLog?: Record<string, unknown>,\n): TransactionPayQuote<RelayQuote> {\n log(message, paramsToLog);\n return phase1Quote;\n}\n\nfunction hasMatchingGasLimitShape(phase1: number[], phase2: number[]): boolean {\n return phase1.length === phase2.length;\n}\n\nfunction getTotalGasLimit(gasLimits: number[]): number {\n return gasLimits.reduce((total, gasLimit) => total + gasLimit, 0);\n}\n\nfunction markQuoteAsMaxGasStation(\n quote: TransactionPayQuote<RelayQuote>,\n): void {\n quote.original.metamask = {\n ...quote.original.metamask,\n isMaxGasStation: true,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"file":"relay-max-gas-station.cjs","sourceRoot":"","sources":["../../../src/strategy/relay/relay-max-gas-station.ts"],"names":[],"mappings":";;;AAAA,2CAAqD;AACrD,+CAAyC;AAEzC,mDAGuB;AAEvB,6CAA6C;AAO7C,iDAI2B;AAE3B,MAAM,GAAG,GAAG,IAAA,0BAAkB,EAAC,sBAAa,EAAE,uBAAuB,CAAC,CAAC;AAEvE,MAAM,uB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,CAAC,QAAQ,GAAG;QACxB,GAAG,KAAK,CAAC,QAAQ,CAAC,QAAQ;QAC1B,eAAe,EAAE,IAAI;KACtB,CAAC;AACJ,CAAC","sourcesContent":["import { createModuleLogger } from '@metamask/utils';\nimport { BigNumber } from 'bignumber.js';\n\nimport {\n getGasStationEligibility,\n getGasStationCostInSourceTokenRaw,\n} from './gas-station';\nimport type { RelayQuote, RelayTransactionStep } from './types';\nimport { projectLogger } from '../../logger';\nimport type {\n PayStrategyGetQuotesRequest,\n QuoteRequest,\n TransactionPayControllerMessenger,\n TransactionPayQuote,\n} from '../../types';\nimport {\n getNativeToken,\n getTokenBalance,\n getTokenInfo,\n} from '../../utils/token';\n\nconst log = createModuleLogger(projectLogger, 'relay-max-gas-station');\n\nconst PROBE_AMOUNT_PERCENTAGE = 0.25;\n\nenum GasCostEstimateSource {\n GasStation = 'gas-station',\n Probe = 'probe',\n Quote = 'quote',\n}\n\ntype GasCostEstimate = {\n amount: BigNumber;\n source: GasCostEstimateSource;\n};\n\ntype NativeBalanceCheckResult = {\n hasEnoughNativeBalance: boolean;\n nativeBalance?: string;\n nativeGasCostRaw?: string;\n};\n\ntype GetSingleQuoteFn = (\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n) => Promise<TransactionPayQuote<RelayQuote>>;\n\ntype MaxAmountQuoteContext = {\n fullRequest: PayStrategyGetQuotesRequest;\n getSingleQuote: GetSingleQuoteFn;\n messenger: TransactionPayControllerMessenger;\n request: QuoteRequest;\n};\n\n/**\n * Returns a Relay max-amount quote using a two-phase gas-station fallback.\n *\n * It first requests a standard max quote (phase 1), then when needed estimates\n * gas in source-token units (directly or via a probe quote), requests an\n * adjusted max quote (phase 2), and accepts phase 2 only if validation passes\n * (source gas fee token selected, gas-limit checks, affordability).\n *\n * If any step fails or validation is unsafe, it safely falls back to phase 1.\n * Successful phase-2 quotes are tagged with `metamask.isMaxGasStation = true`.\n *\n * @param request - Relay quote request for a max-amount flow.\n * @param fullRequest - Full quote request context including messenger and transaction.\n * @param getSingleQuote - Quote fetcher used for phase-1, phase-2, and probe quotes.\n * @returns The validated adjusted phase-2 quote, or the original phase-1 quote on fallback.\n */\nexport async function getRelayMaxGasStationQuote(\n request: QuoteRequest,\n fullRequest: PayStrategyGetQuotesRequest,\n getSingleQuote: GetSingleQuoteFn,\n): Promise<TransactionPayQuote<RelayQuote>> {\n const { messenger } = fullRequest;\n const { sourceChainId, sourceTokenAmount } = request;\n const context: MaxAmountQuoteContext = {\n fullRequest,\n getSingleQuote,\n messenger,\n request,\n };\n\n const phase1Quote = await getSingleQuote(request, fullRequest);\n\n const nativeBalanceCheck = checkEnoughNativeBalanceIfSourceGasFeeTokenNotUsed(\n phase1Quote,\n messenger,\n request,\n );\n\n if (nativeBalanceCheck.hasEnoughNativeBalance) {\n return fallbackToPhase1(\n phase1Quote,\n 'Native balance is sufficient for gas',\n {\n nativeBalance: nativeBalanceCheck.nativeBalance,\n nativeGasCost: nativeBalanceCheck.nativeGasCostRaw,\n },\n );\n }\n\n const gasStationEligibility = getGasStationEligibility(\n messenger,\n sourceChainId,\n );\n\n if (!gasStationEligibility.isEligible) {\n return fallbackToPhase1(\n phase1Quote,\n 'Gas station is disabled or unsupported',\n );\n }\n\n const sourceAmountBN = new BigNumber(sourceTokenAmount);\n const probeCost = await getProbeGasCostInSourceTokenRaw(context);\n\n if (!probeCost) {\n return fallbackToPhase1(\n phase1Quote,\n 'Unable to estimate gas-station source token cost',\n );\n }\n\n const initialGasEstimate: GasCostEstimate = {\n amount: probeCost,\n source: GasCostEstimateSource.Probe,\n };\n\n const adjustedSourceAmount = getAdjustedSourceAmount(\n sourceAmountBN,\n initialGasEstimate.amount,\n );\n\n if (!adjustedSourceAmount.isGreaterThan(0)) {\n return fallbackToPhase1(\n phase1Quote,\n 'Insufficient balance for gas station after max adjustment',\n );\n }\n\n const phase2Quote = await getAdjustedPhase2Quote(\n adjustedSourceAmount,\n initialGasEstimate,\n context,\n );\n\n if (!phase2Quote) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted phase-2 quote request failed',\n );\n }\n\n if (!phase2Quote.fees.isSourceGasFeeToken) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted quote did not return source gas fee token pricing',\n );\n }\n\n const phase1GasLimits = phase1Quote.original.metamask.gasLimits ?? [];\n const phase2GasLimits = phase2Quote.original.metamask.gasLimits ?? [];\n\n if (!hasMatchingGasLimitShape(phase1GasLimits, phase2GasLimits)) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted quote gas limit shape changed between phases',\n {\n phase1GasLimits,\n phase2GasLimits,\n },\n );\n }\n\n const phase1TotalGasLimit = getTotalGasLimit(phase1GasLimits);\n const phase2TotalGasLimit = getTotalGasLimit(phase2GasLimits);\n\n if (phase2TotalGasLimit > phase1TotalGasLimit) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted quote total gas limit increased between phases',\n {\n phase1TotalGasLimit,\n phase2TotalGasLimit,\n },\n );\n }\n\n const validationGasEstimate = new BigNumber(\n phase2Quote.fees.sourceNetwork.max.raw,\n );\n\n if (\n !isAdjustedAmountAffordable(\n adjustedSourceAmount,\n validationGasEstimate,\n sourceAmountBN,\n )\n ) {\n return fallbackToPhase1(\n phase1Quote,\n 'Adjusted quote fails affordability validation',\n {\n adjustedSourceAmount: adjustedSourceAmount.toString(10),\n validationGasCost: validationGasEstimate.toString(10),\n },\n );\n }\n\n markQuoteAsMaxGasStation(phase2Quote);\n\n return phase2Quote;\n}\n\nfunction checkEnoughNativeBalanceIfSourceGasFeeTokenNotUsed(\n quote: TransactionPayQuote<RelayQuote>,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n): NativeBalanceCheckResult {\n if (quote.fees.isSourceGasFeeToken) {\n return { hasEnoughNativeBalance: false };\n }\n\n const nativeGasCostRaw = quote.fees.sourceNetwork.max.raw;\n const nativeBalance = getTokenBalance(\n messenger,\n request.from,\n request.sourceChainId,\n getNativeToken(request.sourceChainId),\n );\n\n return {\n hasEnoughNativeBalance: new BigNumber(nativeBalance).isGreaterThanOrEqualTo(\n nativeGasCostRaw,\n ),\n nativeBalance,\n nativeGasCostRaw,\n };\n}\n\nfunction getAdjustedSourceAmount(\n sourceAmount: BigNumber,\n estimatedGasCost: BigNumber,\n): BigNumber {\n return sourceAmount\n .minus(estimatedGasCost)\n .integerValue(BigNumber.ROUND_DOWN);\n}\n\nfunction isAdjustedAmountAffordable(\n adjustedSourceAmount: BigNumber,\n gasCost: BigNumber,\n originalSourceAmount: BigNumber,\n): boolean {\n return adjustedSourceAmount\n .plus(gasCost)\n .isLessThanOrEqualTo(originalSourceAmount);\n}\n\nasync function getAdjustedPhase2Quote(\n adjustedSourceAmount: BigNumber,\n initialGasEstimate: GasCostEstimate,\n context: MaxAmountQuoteContext,\n): Promise<TransactionPayQuote<RelayQuote> | undefined> {\n const { fullRequest, getSingleQuote, request } = context;\n\n log('Requesting adjusted max quote', {\n adjustedAmount: adjustedSourceAmount.toString(10),\n gasCostInSourceToken: initialGasEstimate.amount.toString(10),\n gasEstimateSource: initialGasEstimate.source,\n originalAmount: request.sourceTokenAmount,\n });\n\n try {\n return await getSingleQuote(\n {\n ...request,\n sourceTokenAmount: adjustedSourceAmount.toFixed(\n 0,\n BigNumber.ROUND_DOWN,\n ),\n },\n fullRequest,\n );\n } catch (error) {\n log('Adjusted quote request failed, falling back to phase-1 quote', {\n error,\n });\n return undefined;\n }\n}\n\nasync function getGasCostFromQuoteOrGasStation(\n quote: TransactionPayQuote<RelayQuote>,\n messenger: TransactionPayControllerMessenger,\n request: QuoteRequest,\n): Promise<GasCostEstimate | undefined> {\n const gasCost = quote.fees.sourceNetwork.max;\n\n if (quote.fees.isSourceGasFeeToken) {\n log('Gas cost already in source token units', { raw: gasCost.raw });\n return {\n amount: new BigNumber(gasCost.raw),\n source: GasCostEstimateSource.Quote,\n };\n }\n\n const firstTxStep = quote.original.steps.find(\n (step): step is RelayTransactionStep => step.kind === 'transaction',\n );\n const firstStepData = firstTxStep?.items[0]?.data;\n\n if (!firstStepData) {\n return undefined;\n }\n\n const totalItemCount = quote.original.steps.reduce(\n (count, step) => count + step.items.length,\n 0,\n );\n\n const totalGasEstimate = (quote.original.metamask.gasLimits ?? []).reduce(\n (acc, gasLimit) => acc + gasLimit,\n 0,\n );\n\n const gasStationCost = await getGasStationCostInSourceTokenRaw({\n firstStepData,\n messenger,\n request: {\n from: request.from,\n sourceChainId: request.sourceChainId,\n sourceTokenAddress: request.sourceTokenAddress,\n },\n totalGasEstimate,\n totalItemCount,\n });\n\n if (!gasStationCost) {\n return undefined;\n }\n\n return {\n amount: new BigNumber(gasStationCost.raw),\n source: GasCostEstimateSource.GasStation,\n };\n}\n\nasync function getProbeGasCostInSourceTokenRaw(\n context: MaxAmountQuoteContext,\n): Promise<BigNumber | undefined> {\n const { fullRequest, getSingleQuote, messenger, request } = context;\n\n const sourceTokenInfo = getTokenInfo(\n messenger,\n request.sourceTokenAddress,\n request.sourceChainId,\n );\n\n if (!sourceTokenInfo) {\n return undefined;\n }\n\n const probeAmount = getProbeSourceAmountRaw(\n request.sourceTokenAmount,\n sourceTokenInfo.decimals,\n );\n\n if (!probeAmount || probeAmount === request.sourceTokenAmount) {\n return undefined;\n }\n\n log('Requesting probe quote for gas station estimation', {\n originalSourceAmount: request.sourceTokenAmount,\n probeAmount,\n });\n\n let probeQuote: TransactionPayQuote<RelayQuote> | undefined;\n\n try {\n probeQuote = await getSingleQuote(\n {\n ...request,\n sourceTokenAmount: probeAmount,\n },\n fullRequest,\n );\n } catch (error) {\n log('Probe quote request failed', { error });\n return undefined;\n }\n\n if (!probeQuote) {\n return undefined;\n }\n\n const probeEstimate = await getGasCostFromQuoteOrGasStation(\n probeQuote,\n messenger,\n request,\n );\n\n return probeEstimate?.amount;\n}\n\nfunction getProbeSourceAmountRaw(\n sourceAmountRaw: string,\n sourceDecimals: number,\n): string | undefined {\n const sourceAmount = new BigNumber(sourceAmountRaw);\n\n if (sourceAmount.isLessThanOrEqualTo(0)) {\n return undefined;\n }\n\n const probeRawAmount = sourceAmount\n .multipliedBy(PROBE_AMOUNT_PERCENTAGE)\n .integerValue(BigNumber.ROUND_FLOOR);\n\n // Minimum probe size: ~0.01 token for tokens with >=2 decimals,\n // otherwise one raw unit for low-decimal tokens.\n const minimumProbeRaw = new BigNumber(1).shiftedBy(\n Math.max(sourceDecimals - 2, 0),\n );\n\n const probeRaw = BigNumber.minimum(\n sourceAmount,\n BigNumber.maximum(probeRawAmount, minimumProbeRaw),\n ).integerValue(BigNumber.ROUND_FLOOR);\n\n if (probeRaw.isLessThanOrEqualTo(0)) {\n return undefined;\n }\n\n return probeRaw.toFixed(0);\n}\n\nfunction fallbackToPhase1(\n phase1Quote: TransactionPayQuote<RelayQuote>,\n message: string,\n paramsToLog?: Record<string, unknown>,\n): TransactionPayQuote<RelayQuote> {\n log(message, paramsToLog);\n return phase1Quote;\n}\n\nfunction hasMatchingGasLimitShape(phase1: number[], phase2: number[]): boolean {\n return phase1.length === phase2.length;\n}\n\nfunction getTotalGasLimit(gasLimits: number[]): number {\n return gasLimits.reduce((total, gasLimit) => total + gasLimit, 0);\n}\n\nfunction markQuoteAsMaxGasStation(\n quote: TransactionPayQuote<RelayQuote>,\n): void {\n quote.original.metamask = {\n ...quote.original.metamask,\n isMaxGasStation: true,\n };\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relay-max-gas-station.d.cts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-max-gas-station.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,
|
|
1
|
+
{"version":3,"file":"relay-max-gas-station.d.cts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-max-gas-station.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAwB,oBAAgB;AAEhE,OAAO,KAAK,EACV,2BAA2B,EAC3B,YAAY,EAEZ,mBAAmB,EACpB,wBAAoB;AA4BrB,KAAK,gBAAgB,GAAG,CACtB,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,2BAA2B,KACrC,OAAO,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CAAC;AAS9C;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,0BAA0B,CAC9C,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,2BAA2B,EACxC,cAAc,EAAE,gBAAgB,GAC/B,OAAO,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CA4I1C"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"relay-max-gas-station.d.mts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-max-gas-station.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,
|
|
1
|
+
{"version":3,"file":"relay-max-gas-station.d.mts","sourceRoot":"","sources":["../../../src/strategy/relay/relay-max-gas-station.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,UAAU,EAAwB,oBAAgB;AAEhE,OAAO,KAAK,EACV,2BAA2B,EAC3B,YAAY,EAEZ,mBAAmB,EACpB,wBAAoB;AA4BrB,KAAK,gBAAgB,GAAG,CACtB,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,2BAA2B,KACrC,OAAO,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CAAC;AAS9C;;;;;;;;;;;;;;;GAeG;AACH,wBAAsB,0BAA0B,CAC9C,OAAO,EAAE,YAAY,EACrB,WAAW,EAAE,2BAA2B,EACxC,cAAc,EAAE,gBAAgB,GAC/B,OAAO,CAAC,mBAAmB,CAAC,UAAU,CAAC,CAAC,CA4I1C"}
|
|
@@ -146,7 +146,8 @@ async function getGasCostFromQuoteOrGasStation(quote, messenger, request) {
|
|
|
146
146
|
source: GasCostEstimateSource.Quote,
|
|
147
147
|
};
|
|
148
148
|
}
|
|
149
|
-
const
|
|
149
|
+
const firstTxStep = quote.original.steps.find((step) => step.kind === 'transaction');
|
|
150
|
+
const firstStepData = firstTxStep?.items[0]?.data;
|
|
150
151
|
if (!firstStepData) {
|
|
151
152
|
return undefined;
|
|
152
153
|
}
|