felix-mcp 2.0.123 → 2.0.129
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/README.md +26 -3
- package/dist/arc-hl-return-ports.js +15 -2
- package/dist/arc-hl-return.js +4 -2
- package/dist/arc-home.js +3 -10
- package/dist/arc-hypercore-funding.js +1076 -0
- package/dist/arc-hypercore-return.js +826 -0
- package/dist/arc-pm-return.js +28 -3
- package/dist/arc-safe-invalidation-hints.js +209 -0
- package/dist/arc-safe-invalidation.js +672 -0
- package/dist/arc-venue-app-policy.js +30 -0
- package/dist/funding.js +192 -25
- package/dist/getting-started-guide.js +12 -2
- package/dist/http-server.js +25 -8
- package/dist/index.js +821 -202
- package/dist/key-backup.js +15 -4
- package/dist/polymarket.js +5 -3
- package/dist/public-venue.js +35 -0
- package/dist/rpc-endpoints.js +133 -0
- package/dist/safe-migration.js +7 -3
- package/dist/safe-onboarding.js +58 -49
- package/dist/safe-policy.js +39 -28
- package/package.json +14 -2
- package/server.json +2 -2
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
// ARC_HYPERCORE_RETURN_CLIENT_2026_09_27: the owner's HyperCore PERPS USDC ->
|
|
2
|
+
// this account's Arc home Safe, DIRECT via Relay (no Arbitrum, no withdraw3,
|
|
3
|
+
// no HyperEVM). Relay's HyperCore origin takes an owner-signed nonce mapping
|
|
4
|
+
// (RelayNonceMapping, POST /authorize) plus an owner-signed HyperCore
|
|
5
|
+
// sendAsset of the perps USDC to Relay's HyperCore depository with the SAME
|
|
6
|
+
// nonce; Relay's solver then pays the Safe on Arc.
|
|
7
|
+
//
|
|
8
|
+
// Engine journey (contract v1: FELIX_HL_DIRECT_RETURN_CONTRACT_2026_09_27.md, engine
|
|
9
|
+
// branch claude/hl-direct-return-engine-20260927, services/arc_home_hypercore_return.py):
|
|
10
|
+
// POST {ROUTE_PREFIX}/prepare Idempotency-Key; the unsigned plan
|
|
11
|
+
// GET {ROUTE_PREFIX}/{id}?account_id= a passive read
|
|
12
|
+
// POST {ROUTE_PREFIX}/{id}/submit the two owner signatures, journaled by the engine
|
|
13
|
+
// BEFORE it posts /authorize then HyperCore /exchange
|
|
14
|
+
// POST {ROUTE_PREFIX}/{id}/reconcile advance / read
|
|
15
|
+
//
|
|
16
|
+
// DISABLED BY DEFAULT, twice over:
|
|
17
|
+
// * HYPERCORE_RETURN_CLIENT_ENABLED = false keeps the tool unlisted and refused;
|
|
18
|
+
// * SHIPPED_HYPERCORE_RETURN_POLICY is EMPTY: no trusted solver, no reviewed
|
|
19
|
+
// Relay extraData word and no Arc credit proof, so nothing is ever signed.
|
|
20
|
+
//
|
|
21
|
+
// Before either signature the client re-derives, from pins and the policy
|
|
22
|
+
// (never server authority): the Relay order id and the trusted solver it
|
|
23
|
+
// recovers to; input exactly the amount (8-decimal perps units) of HyperCore
|
|
24
|
+
// perps USDC; exactly one output on Arc in Arc USDC to THIS account's verified
|
|
25
|
+
// Safe with a minimum >= the client's floor and any requested minimum; refunds
|
|
26
|
+
// only to the owner on HyperCore and the owner or Safe on Arc; the reviewed
|
|
27
|
+
// extraData. It then BUILDS both typed-data payloads itself and requires the
|
|
28
|
+
// server's payloads to be byte-identical: NonceMapping(chainId "hyperliquid",
|
|
29
|
+
// wallet = depositor = owner, id = order, nonce) and HyperCore SendAsset
|
|
30
|
+
// (Mainnet, destination = the pinned Relay HyperCore depository, perps -> perps
|
|
31
|
+
// "" / "", USDC, the exact amount, no subaccount, the same nonce). It signs the
|
|
32
|
+
// mapping, journals it, signs the send, journals both BEFORE submitting, submits
|
|
33
|
+
// them at most once per invocation, and on every resume re-offers the SAME
|
|
34
|
+
// signatures, never re-signing.
|
|
35
|
+
//
|
|
36
|
+
// money_moved: false only before any signature; "unknown" after signing until
|
|
37
|
+
// completion is proven; true once proven. Completion (home_usable) needs the
|
|
38
|
+
// engine's completion bound to this order and nonce, the client's own HyperCore
|
|
39
|
+
// ledger read of the owner -> depository send, and an independent Arc read of
|
|
40
|
+
// the solver's fill to the Safe (policy.verifyHomeCredit).
|
|
41
|
+
import { getAddress, hashStruct, hashTypedData, recoverMessageAddress } from "viem";
|
|
42
|
+
import { RELAY_ORDER_TYPES, relayOrderMessage } from "./arc-pm-return.js";
|
|
43
|
+
import { namesVenue } from "./public-venue.js";
|
|
44
|
+
import { describeOpenJourney, openJourneyId } from "./arc-safe-invalidation-hints.js";
|
|
45
|
+
// Enabled 2026-09-27 (A4_ENABLEMENT, operator accepted Relay attribution); the
|
|
46
|
+
// launch policy (hypercoreReturnLaunchPolicy) still refuses without a private
|
|
47
|
+
// Arc proof quorum, and the engine gates on FELIX_ARC_HYPERCORE_RETURN_ENABLED.
|
|
48
|
+
export const HYPERCORE_RETURN_CLIENT_ENABLED = true;
|
|
49
|
+
export const HYPERCORE_RETURN_TOOL = "arc_home_hypercore_return";
|
|
50
|
+
export const ROUTE_PREFIX = "/v1/arc-home/hypercore-returns";
|
|
51
|
+
export const ARC_CHAIN_ID = 5042;
|
|
52
|
+
export const ARC_USDC = "0x3600000000000000000000000000000000000000";
|
|
53
|
+
export const HYPERCORE_CHAIN_ID = 1337;
|
|
54
|
+
export const HYPERCORE_PERPS_USDC = "0x00000000000000000000000000000000";
|
|
55
|
+
export const HYPERCORE_UNITS_PER_USDC_UNIT = 100n; // HyperCore USDC is 8 decimals
|
|
56
|
+
export const RELAY_HL_DEPOSITORY = "0x66cf0aace1b4e562593bec10ec7868fba9932224";
|
|
57
|
+
export const HL_USDC_TOKEN = "USDC:0x6d1e7cde53ba9467b783cb7c530ce054";
|
|
58
|
+
export const HL_SIGNATURE_CHAIN_ID = 421614; // 0x66eee, HyperCore user-signed action domain
|
|
59
|
+
const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
|
|
60
|
+
export const MIN_AMOUNT_UNITS = 5000000n;
|
|
61
|
+
export const MAX_AMOUNT_UNITS = 25000000n;
|
|
62
|
+
// All-in client floor, the engine's own (contract v1: minimum_credit >= ceil(amount * 0.99));
|
|
63
|
+
// the engine requests Relay's slippage so the signed provider minimum clears it.
|
|
64
|
+
export const MAX_ALL_IN_COST_BPS = 100n;
|
|
65
|
+
export const RELAY_FILL_EXTRA_DATA = "0x000000000000000000000000b92fe925dc43a0ecde6c8b1a2709c170ec4fff4f";
|
|
66
|
+
const ORDER_DEADLINE_MARGIN_S = 60;
|
|
67
|
+
const QUOTE_SIGNING_MARGIN_S = 45;
|
|
68
|
+
// HyperCore accepts a user-signed nonce only near its own clock (roughly
|
|
69
|
+
// T - 2 days .. T + 1 day); the client refuses to sign one further than this.
|
|
70
|
+
const NONCE_WINDOW_MS = 10 * 60_000;
|
|
71
|
+
const DEFAULT_MAX_POLLS = 60;
|
|
72
|
+
const MIN_POLL_MS = 2_000;
|
|
73
|
+
const MAX_POLL_MS = 30_000;
|
|
74
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
75
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
76
|
+
const HASH = /^0x[0-9a-fA-F]{64}$/;
|
|
77
|
+
const SIGNATURE = /^0x[0-9a-fA-F]{130}$/;
|
|
78
|
+
const UINT = /^(0|[1-9][0-9]{0,30})$/;
|
|
79
|
+
const PHASES = new Set(["prepared", "source_submitted", "source_confirmed", "completed", "reconciliation_required",
|
|
80
|
+
"expired", "source_dropped", "refunded", "closed"]);
|
|
81
|
+
// HyperCore refuses a user-signed nonce after ~2 days; the engine closes a row as
|
|
82
|
+
// source_dropped only after this window (contract v1 section 3).
|
|
83
|
+
export const HL_NONCE_WINDOW_CLOSED_MS = 2 * 86_400_000 + 3_600_000;
|
|
84
|
+
export const CP = {
|
|
85
|
+
scope: "hcret:scope",
|
|
86
|
+
prepared: "hcret:prepared",
|
|
87
|
+
signedMapping: "hcret:signed-mapping",
|
|
88
|
+
signed: "hcret:signed",
|
|
89
|
+
closed: "hcret:closed-unsigned",
|
|
90
|
+
submission: "hcret:submission-started",
|
|
91
|
+
completed: "hcret:completed",
|
|
92
|
+
};
|
|
93
|
+
// ------------------------------------------------------------------ typed data (client-built)
|
|
94
|
+
export const NONCE_MAPPING_TYPES = Object.freeze([
|
|
95
|
+
{ name: "chainId", type: "string" }, { name: "wallet", type: "address" }, { name: "depositor", type: "address" },
|
|
96
|
+
{ name: "id", type: "bytes32" }, { name: "nonce", type: "uint256" },
|
|
97
|
+
]);
|
|
98
|
+
export const SEND_ASSET_TYPES = Object.freeze([
|
|
99
|
+
{ name: "hyperliquidChain", type: "string" }, { name: "destination", type: "string" },
|
|
100
|
+
{ name: "sourceDex", type: "string" }, { name: "destinationDex", type: "string" }, { name: "token", type: "string" },
|
|
101
|
+
{ name: "amount", type: "string" }, { name: "fromSubAccount", type: "string" }, { name: "nonce", type: "uint64" },
|
|
102
|
+
]);
|
|
103
|
+
/** Exactly six decimals, as HyperCore's sendAsset and Relay's quote spell it ("5.000000"). */
|
|
104
|
+
export function sendAmountText(amount) {
|
|
105
|
+
return `${amount / 1000000n}.${(amount % 1000000n).toString().padStart(6, "0")}`;
|
|
106
|
+
}
|
|
107
|
+
export function buildNonceMapping(owner, orderId, nonce) {
|
|
108
|
+
const wallet = owner.toLowerCase();
|
|
109
|
+
return {
|
|
110
|
+
typedData: {
|
|
111
|
+
domain: { name: "RelayNonceMapping", version: "2", chainId: 1, verifyingContract: ZERO_ADDRESS },
|
|
112
|
+
types: { NonceMapping: NONCE_MAPPING_TYPES.map((f) => ({ ...f })) },
|
|
113
|
+
primaryType: "NonceMapping",
|
|
114
|
+
message: { chainId: "hyperliquid", wallet, depositor: wallet, id: orderId.toLowerCase(), nonce },
|
|
115
|
+
},
|
|
116
|
+
postBody: { type: "nonce-mapping", walletChainId: HYPERCORE_CHAIN_ID, wallet, nonce, id: orderId.toLowerCase(),
|
|
117
|
+
depositor: wallet, signatureChainId: 1 },
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
export function buildSendAsset(amount, nonce) {
|
|
121
|
+
const message = { hyperliquidChain: "Mainnet", destination: RELAY_HL_DEPOSITORY, sourceDex: "", destinationDex: "",
|
|
122
|
+
token: HL_USDC_TOKEN, amount: sendAmountText(amount), fromSubAccount: "", nonce };
|
|
123
|
+
return {
|
|
124
|
+
typedData: {
|
|
125
|
+
domain: { name: "HyperliquidSignTransaction", version: "1", chainId: HL_SIGNATURE_CHAIN_ID, verifyingContract: ZERO_ADDRESS },
|
|
126
|
+
types: { "HyperliquidTransaction:SendAsset": SEND_ASSET_TYPES.map((f) => ({ ...f })) },
|
|
127
|
+
primaryType: "HyperliquidTransaction:SendAsset",
|
|
128
|
+
message,
|
|
129
|
+
},
|
|
130
|
+
action: { type: "sendAsset", ...message, signatureChainId: `0x${HL_SIGNATURE_CHAIN_ID.toString(16)}` },
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function canonical(value) {
|
|
134
|
+
if (Array.isArray(value))
|
|
135
|
+
return `[${value.map(canonical).join(",")}]`;
|
|
136
|
+
if (value && typeof value === "object") {
|
|
137
|
+
return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`).join(",")}}`;
|
|
138
|
+
}
|
|
139
|
+
if (typeof value === "string")
|
|
140
|
+
return JSON.stringify(value.toLowerCase());
|
|
141
|
+
if (typeof value === "bigint")
|
|
142
|
+
return value.toString();
|
|
143
|
+
return JSON.stringify(value);
|
|
144
|
+
}
|
|
145
|
+
export function typedDataDigest(t) {
|
|
146
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
147
|
+
return hashTypedData({ domain: t.domain, types: t.types, primaryType: t.primaryType, message: t.message }).toLowerCase();
|
|
148
|
+
}
|
|
149
|
+
export const SHIPPED_HYPERCORE_RETURN_POLICY = Object.freeze({
|
|
150
|
+
trustedSolvers: Object.freeze([]),
|
|
151
|
+
relayExtraData: null,
|
|
152
|
+
verifyHomeCredit: null,
|
|
153
|
+
});
|
|
154
|
+
export function policyGaps(policy) {
|
|
155
|
+
const gaps = [];
|
|
156
|
+
const solvers = policy?.trustedSolvers;
|
|
157
|
+
if (!Array.isArray(solvers) || !solvers.length || !solvers.every((s) => typeof s === "string" && ADDRESS.test(s))) {
|
|
158
|
+
gaps.push("hypercore_return_solver_unverified");
|
|
159
|
+
}
|
|
160
|
+
if (typeof policy?.relayExtraData !== "string" || !HASH.test(policy.relayExtraData))
|
|
161
|
+
gaps.push("hypercore_return_extra_data_unverified");
|
|
162
|
+
if (typeof policy?.verifyHomeCredit !== "function")
|
|
163
|
+
gaps.push("hypercore_return_home_credit_read_unverified");
|
|
164
|
+
return gaps;
|
|
165
|
+
}
|
|
166
|
+
export class HypercoreReturnHostileServer extends Error {
|
|
167
|
+
constructor(message) {
|
|
168
|
+
super(message);
|
|
169
|
+
this.name = "HypercoreReturnHostileServer";
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
function hostile(message) {
|
|
173
|
+
throw new HypercoreReturnHostileServer(message);
|
|
174
|
+
}
|
|
175
|
+
function isRecord(value) {
|
|
176
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
177
|
+
}
|
|
178
|
+
function lower(value, name) {
|
|
179
|
+
if (typeof value !== "string" || !ADDRESS.test(value))
|
|
180
|
+
hostile(`${name} is not an address`);
|
|
181
|
+
return value.toLowerCase();
|
|
182
|
+
}
|
|
183
|
+
function units(value, name) {
|
|
184
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
|
|
185
|
+
return BigInt(value);
|
|
186
|
+
if (typeof value !== "string" || !UINT.test(value))
|
|
187
|
+
hostile(`${name} is not exact integer units`);
|
|
188
|
+
return BigInt(value);
|
|
189
|
+
}
|
|
190
|
+
/** A HyperCore decimal USDC string to exact 6-decimal units; anything finer or malformed is null. */
|
|
191
|
+
export function usdToUnits(value) {
|
|
192
|
+
if (typeof value !== "string" || !/^[0-9]{1,12}(\.[0-9]{1,8})?$/.test(value))
|
|
193
|
+
return null;
|
|
194
|
+
const [whole, fraction = ""] = value.split(".");
|
|
195
|
+
const padded = fraction.padEnd(8, "0");
|
|
196
|
+
if (!padded.endsWith("00"))
|
|
197
|
+
return null;
|
|
198
|
+
return BigInt(whole) * 1000000n + BigInt(padded.slice(0, 6));
|
|
199
|
+
}
|
|
200
|
+
export const floorUnits = (amount) => (amount * (10000n - MAX_ALL_IN_COST_BPS) + 9999n) / 10000n;
|
|
201
|
+
function usd(unitsValue) {
|
|
202
|
+
const whole = unitsValue / 1000000n;
|
|
203
|
+
const fraction = (unitsValue % 1000000n).toString().padStart(6, "0").replace(/0+$/, "");
|
|
204
|
+
return fraction ? `${whole}.${fraction}` : whole.toString();
|
|
205
|
+
}
|
|
206
|
+
/** Every view: this journey's owner, Safe, amount and HyperCore perps source; never venue-sourced. */
|
|
207
|
+
export function assertView(view, expect) {
|
|
208
|
+
if (!isRecord(view))
|
|
209
|
+
hostile("the HyperCore return view is not an object");
|
|
210
|
+
const v = view;
|
|
211
|
+
if (v.kind !== "arc_hypercore_return" || v.provider !== "relay" || !PHASES.has(String(v.phase))) {
|
|
212
|
+
hostile("the view is not an Arc HyperCore return");
|
|
213
|
+
}
|
|
214
|
+
if (typeof v.id !== "string" || !UUID.test(v.id) || (expect.id !== undefined && v.id !== expect.id)) {
|
|
215
|
+
hostile("the server answered for another HyperCore return");
|
|
216
|
+
}
|
|
217
|
+
// The public API renders venue names as asset classes ("hyperliquid" ->
|
|
218
|
+
// "crypto"; found by the 2.0.221 A6 canary). The binding facts are the chain
|
|
219
|
+
// id, the main dex and the exact perps token; the name is either spelling.
|
|
220
|
+
if (!namesVenue(v.source_chain, "hyperliquid")
|
|
221
|
+
|| v.source_chain_id !== HYPERCORE_CHAIN_ID || v.source_dex !== ""
|
|
222
|
+
|| String(v.source_token || "").toLowerCase() !== HYPERCORE_PERPS_USDC) {
|
|
223
|
+
hostile("the return is not sourced from HyperCore main-dex perps USDC");
|
|
224
|
+
}
|
|
225
|
+
if (v.destination_chain_id !== ARC_CHAIN_ID || lower(v.destination_token, "destination_token") !== ARC_USDC) {
|
|
226
|
+
hostile("the return does not credit Arc USDC");
|
|
227
|
+
}
|
|
228
|
+
if (lower(v.owner, "owner") !== expect.owner || lower(v.recipient, "recipient") !== expect.safe) {
|
|
229
|
+
hostile("the return is not from this owner to this account's Arc home Safe");
|
|
230
|
+
}
|
|
231
|
+
if (units(v.amount_units, "amount_units") !== expect.amount)
|
|
232
|
+
hostile("the return moves another amount");
|
|
233
|
+
const minimum = units(v.minimum_credit_units, "minimum_credit_units");
|
|
234
|
+
if (minimum < floorUnits(expect.amount) || minimum > expect.amount
|
|
235
|
+
|| (expect.requestedMinimum !== null && minimum < expect.requestedMinimum)) {
|
|
236
|
+
hostile("the return's minimum credit is below the client's floor or request");
|
|
237
|
+
}
|
|
238
|
+
if (v.home_usable === true && v.phase !== "completed")
|
|
239
|
+
hostile("home_usable claimed before completion");
|
|
240
|
+
if (v.money_moved === true && ["prepared", "expired", "source_dropped"].includes(String(v.phase))) {
|
|
241
|
+
hostile("money_moved claimed in a phase where nothing can have moved");
|
|
242
|
+
}
|
|
243
|
+
return v;
|
|
244
|
+
}
|
|
245
|
+
/** The solver-signed order, bound to HyperCore perps input, this Safe, this owner and the reviewed extraData. */
|
|
246
|
+
export async function assertOrder(view, expect, policy, nowS) {
|
|
247
|
+
const relay = view.relay_order;
|
|
248
|
+
if (!isRecord(relay))
|
|
249
|
+
hostile("relay_order is missing");
|
|
250
|
+
const r = relay;
|
|
251
|
+
const orderId = String(r.order_id || "").toLowerCase();
|
|
252
|
+
if (!HASH.test(orderId))
|
|
253
|
+
hostile("relay_order.order_id is not 32 bytes");
|
|
254
|
+
const signature = String(r.order_signature || "");
|
|
255
|
+
if (!SIGNATURE.test(signature))
|
|
256
|
+
hostile("relay_order.order_signature is not 65 bytes");
|
|
257
|
+
let message;
|
|
258
|
+
try {
|
|
259
|
+
message = relayOrderMessage(r.order_data);
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
hostile(`relay_order is malformed: ${error.message}`);
|
|
263
|
+
}
|
|
264
|
+
let recomputed;
|
|
265
|
+
try {
|
|
266
|
+
recomputed = hashStruct({ types: RELAY_ORDER_TYPES, primaryType: "Order", data: message }).toLowerCase();
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
hostile("relay_order does not hash as a Relay v1 order");
|
|
270
|
+
}
|
|
271
|
+
if (recomputed !== orderId || String(view.order_id || "").toLowerCase() !== orderId) {
|
|
272
|
+
hostile("the signed order is not the order the view names");
|
|
273
|
+
}
|
|
274
|
+
let recovered;
|
|
275
|
+
try {
|
|
276
|
+
recovered = (await recoverMessageAddress({ message: { raw: orderId }, signature: signature })).toLowerCase();
|
|
277
|
+
}
|
|
278
|
+
catch {
|
|
279
|
+
hostile("the order signature does not recover");
|
|
280
|
+
}
|
|
281
|
+
const trusted = new Set(policy.trustedSolvers.map((s) => s.toLowerCase()));
|
|
282
|
+
if (recovered !== message.solver.toLowerCase() || recovered !== lower(r.solver, "relay_order.solver") || !trusted.has(recovered)) {
|
|
283
|
+
hostile("the order is not signed by a Relay solver the reviewed policy trusts");
|
|
284
|
+
}
|
|
285
|
+
if (message.version !== "v1" || message.solverChainId !== "base" || message.inputs.length !== 1) {
|
|
286
|
+
hostile("the order is not a single-input Relay v1 order");
|
|
287
|
+
}
|
|
288
|
+
const payment = message.inputs[0].payment;
|
|
289
|
+
if (payment.chainId !== "hyperliquid" || payment.currency !== HYPERCORE_PERPS_USDC
|
|
290
|
+
|| payment.amount !== expect.amount * HYPERCORE_UNITS_PER_USDC_UNIT || payment.weight !== 1n) {
|
|
291
|
+
hostile("the order does not take exactly the amount of HyperCore perps USDC");
|
|
292
|
+
}
|
|
293
|
+
const output = message.output;
|
|
294
|
+
if (output.chainId !== "arc" || output.payments.length !== 1)
|
|
295
|
+
hostile("the signed order does not pay once on Arc");
|
|
296
|
+
const paid = output.payments[0];
|
|
297
|
+
if (paid.recipient !== expect.safe || paid.currency !== ARC_USDC) {
|
|
298
|
+
hostile("the signed order does not pay this account's Arc home Safe in Arc USDC");
|
|
299
|
+
}
|
|
300
|
+
// Signing refuses an order whose own minimum is under the caller's request:
|
|
301
|
+
// Relay could then fill between the two and strand the return.
|
|
302
|
+
if (paid.minimumAmount < floorUnits(expect.amount) || paid.minimumAmount < (expect.requestedMinimum ?? 0n)
|
|
303
|
+
|| paid.minimumAmount > paid.expectedAmount || paid.expectedAmount > expect.amount
|
|
304
|
+
|| units(view.provider_minimum_credit_units, "provider_minimum_credit_units") !== paid.minimumAmount
|
|
305
|
+
|| units(view.expected_credit_units, "expected_credit_units") !== paid.expectedAmount
|
|
306
|
+
|| units(view.minimum_credit_units, "minimum_credit_units") > paid.minimumAmount && expect.requestedMinimum === null) {
|
|
307
|
+
hostile("the signed order's minimum is below the client's floor or request, or not the minimum the view states");
|
|
308
|
+
}
|
|
309
|
+
const extra = String(policy.relayExtraData).toLowerCase();
|
|
310
|
+
if (output.calls.length !== 0 || output.extraData !== extra || message.fees.length !== 0) {
|
|
311
|
+
hostile("the signed order carries calls, fees or an unreviewed fill extraData");
|
|
312
|
+
}
|
|
313
|
+
if (output.deadline < nowS + ORDER_DEADLINE_MARGIN_S)
|
|
314
|
+
hostile("the signed order is expired or about to");
|
|
315
|
+
const refunds = new Map();
|
|
316
|
+
for (const refund of message.inputs[0].refunds) {
|
|
317
|
+
if (refund.minimumAmount !== 0n || refund.deadline !== output.deadline || refunds.has(refund.chainId)) {
|
|
318
|
+
hostile("an order refund is not the reviewed owner refund");
|
|
319
|
+
}
|
|
320
|
+
refunds.set(refund.chainId, { recipient: refund.recipient, currency: refund.currency, extraData: refund.extraData });
|
|
321
|
+
}
|
|
322
|
+
const source = refunds.get("hyperliquid");
|
|
323
|
+
const arc = refunds.get("arc");
|
|
324
|
+
if (refunds.size !== 2 || !source || !arc || source.recipient !== expect.owner || source.currency !== HYPERCORE_PERPS_USDC
|
|
325
|
+
|| source.extraData !== "0x" || arc.recipient !== expect.safe || arc.currency !== ARC_USDC || arc.extraData !== extra) {
|
|
326
|
+
hostile("the order refunds someone other than the owner on HyperCore and the Safe on Arc");
|
|
327
|
+
}
|
|
328
|
+
return { orderId, solver: recovered, signedMinimum: paid.minimumAmount, deadline: output.deadline };
|
|
329
|
+
}
|
|
330
|
+
/** The server's two payloads must equal what this client builds from the verified order and nonce. */
|
|
331
|
+
export function assertSigning(view, expect, orderId, nowMs) {
|
|
332
|
+
const expires = Number(view.quote_expires_at);
|
|
333
|
+
if (!Number.isSafeInteger(expires) || expires <= 0)
|
|
334
|
+
hostile("the quote expiry is invalid");
|
|
335
|
+
const requestId = String(view.request_id || "").toLowerCase();
|
|
336
|
+
if (!HASH.test(requestId))
|
|
337
|
+
hostile("request_id is not 32 bytes");
|
|
338
|
+
const nonce = view.nonce;
|
|
339
|
+
if (typeof nonce !== "number" || !Number.isSafeInteger(nonce) || nonce <= 0 || Math.abs(nonce - nowMs) > NONCE_WINDOW_MS) {
|
|
340
|
+
hostile("the relay nonce is not a current HyperCore nonce");
|
|
341
|
+
}
|
|
342
|
+
const signing = view.signing;
|
|
343
|
+
if (!isRecord(signing) || lower(signing.signer, "signing.signer") !== expect.owner)
|
|
344
|
+
hostile("the signing plan is not for this owner");
|
|
345
|
+
const s = signing;
|
|
346
|
+
const mapping = buildNonceMapping(expect.owner, orderId, nonce);
|
|
347
|
+
const send = buildSendAsset(expect.amount, nonce);
|
|
348
|
+
const served = (value, name) => (isRecord(value) ? value : hostile(`${name} is missing`));
|
|
349
|
+
const m = served(s.nonce_mapping, "signing.nonce_mapping");
|
|
350
|
+
const a = served(s.send_asset, "signing.send_asset");
|
|
351
|
+
if (canonical(m.typed_data) !== canonical(mapping.typedData)) {
|
|
352
|
+
hostile("the nonce mapping is not exactly the owner's mapping of this order at this nonce");
|
|
353
|
+
}
|
|
354
|
+
if (canonical(a.typed_data) !== canonical(send.typedData)) {
|
|
355
|
+
hostile("the sendAsset is not exactly the amount of perps USDC to the pinned Relay depository at this nonce");
|
|
356
|
+
}
|
|
357
|
+
const mappingDigest = typedDataDigest(mapping.typedData);
|
|
358
|
+
const sendDigest = typedDataDigest(send.typedData);
|
|
359
|
+
if (String(m.typed_data_hash || "").toLowerCase() !== mappingDigest || String(a.typed_data_hash || "").toLowerCase() !== sendDigest) {
|
|
360
|
+
hostile("a served typed-data digest does not match its payload");
|
|
361
|
+
}
|
|
362
|
+
return { nonce: nonce, quoteExpiresAt: expires, requestId,
|
|
363
|
+
mapping: { typedData: mapping.typedData, digest: mappingDigest }, send: { typedData: send.typedData, digest: sendDigest } };
|
|
364
|
+
}
|
|
365
|
+
/** The owner's own ledger shows exactly one perps send of the amount to the depository at the signed nonce. */
|
|
366
|
+
export function ledgerShowsSource(rows, owner, amount, nonce) {
|
|
367
|
+
const matching = rows.filter((row) => isRecord(row) && isRecord(row.delta) && row.delta.nonce === nonce);
|
|
368
|
+
if (!matching.length)
|
|
369
|
+
return "none";
|
|
370
|
+
if (matching.length !== 1)
|
|
371
|
+
return "mismatch";
|
|
372
|
+
const d = matching[0].delta;
|
|
373
|
+
const ok = d.type === "send" && String(d.user || "").toLowerCase() === owner
|
|
374
|
+
&& String(d.destination || "").toLowerCase() === RELAY_HL_DEPOSITORY && d.sourceDex === "" && d.destinationDex === ""
|
|
375
|
+
&& d.token === "USDC" && usdToUnits(d.amount) === amount;
|
|
376
|
+
return ok ? "one" : "mismatch";
|
|
377
|
+
}
|
|
378
|
+
/** The engine completion, bound to what THIS client signed: order, nonce, amount and credit evidence. */
|
|
379
|
+
export function assertCompletion(view, signed, safe, amount) {
|
|
380
|
+
if (view.home_usable !== true || view.money_moved !== true
|
|
381
|
+
|| String(view.order_id || "").toLowerCase() !== signed.order_id
|
|
382
|
+
|| String(view.solver || "").toLowerCase() !== signed.solver) {
|
|
383
|
+
hostile("the completion is not bound to the order this client signed");
|
|
384
|
+
}
|
|
385
|
+
const source = view.source_proof;
|
|
386
|
+
if (!isRecord(source) || Number(source.nonce) !== signed.nonce
|
|
387
|
+
|| units(source.amount_units, "source_proof.amount_units") !== amount
|
|
388
|
+
|| lower(source.depository, "source_proof.depository") !== RELAY_HL_DEPOSITORY
|
|
389
|
+
|| !HASH.test(String(source.ledger_hash || ""))
|
|
390
|
+
|| (view.source_hash !== undefined && String(view.source_hash).toLowerCase() !== String(source.ledger_hash).toLowerCase())) {
|
|
391
|
+
hostile("the completion has no HyperCore source proof for the signed send");
|
|
392
|
+
}
|
|
393
|
+
const credit = view.credit;
|
|
394
|
+
if (!isRecord(credit))
|
|
395
|
+
hostile("the completion carries no credit evidence");
|
|
396
|
+
const c = credit;
|
|
397
|
+
const binding = c.order_binding;
|
|
398
|
+
if (!isRecord(binding))
|
|
399
|
+
hostile("the credit carries no order binding");
|
|
400
|
+
const b = binding;
|
|
401
|
+
const creditUnits = units(c.amount_units, "credit.amount_units");
|
|
402
|
+
const minimum = [BigInt(String(signed.signed_minimum_units)), units(view.minimum_credit_units, "minimum_credit_units")]
|
|
403
|
+
.reduce((x, y) => (x > y ? x : y));
|
|
404
|
+
const blockNumber = Number(c.block_number);
|
|
405
|
+
if ((c.recipient !== undefined && lower(c.recipient, "credit.recipient") !== safe)
|
|
406
|
+
|| (c.order_id !== undefined && String(c.order_id).toLowerCase() !== signed.order_id)
|
|
407
|
+
|| (c.tx_hash !== undefined && String(c.tx_hash).toLowerCase() !== String(b.tx_hash || "").toLowerCase())
|
|
408
|
+
|| creditUnits < minimum || creditUnits > amount
|
|
409
|
+
|| String(b.kind) !== "relay_evm_order_suffix_v1" || String(b.order_id || "").toLowerCase() !== signed.order_id
|
|
410
|
+
|| lower(b.solver, "order_binding.solver") !== signed.solver
|
|
411
|
+
|| !HASH.test(String(b.tx_hash || "")) || !HASH.test(String(b.block_hash || ""))
|
|
412
|
+
|| !Number.isSafeInteger(blockNumber) || blockNumber <= 0 || Number(b.block_number) !== blockNumber
|
|
413
|
+
|| Number(b.block_timestamp) > Number(signed.order_deadline)) {
|
|
414
|
+
hostile("the credit evidence is not this order's fill of the signed bounds to this Safe");
|
|
415
|
+
}
|
|
416
|
+
return { safe, orderId: String(signed.order_id), solver: String(signed.solver), fillTxHash: String(b.tx_hash).toLowerCase(),
|
|
417
|
+
blockNumber, blockHash: String(b.block_hash).toLowerCase(), amountUnits: creditUnits, minimumUnits: minimum,
|
|
418
|
+
maximumUnits: amount, orderDeadline: Number(signed.order_deadline) };
|
|
419
|
+
}
|
|
420
|
+
// ------------------------------------------------------------------ driver
|
|
421
|
+
function httpStatus(response) {
|
|
422
|
+
const meta = isRecord(response._meta) ? response._meta : {};
|
|
423
|
+
const status = Number(meta.http_status);
|
|
424
|
+
return Number.isInteger(status) ? status : undefined;
|
|
425
|
+
}
|
|
426
|
+
function errorOf(response) {
|
|
427
|
+
if (isRecord(response.error))
|
|
428
|
+
return response.error;
|
|
429
|
+
const detail = isRecord(response.detail) ? response.detail.error : undefined;
|
|
430
|
+
return isRecord(detail) ? detail : {};
|
|
431
|
+
}
|
|
432
|
+
const definitiveRefusal = (response) => {
|
|
433
|
+
const status = httpStatus(response);
|
|
434
|
+
return status !== undefined && [400, 401, 403, 404, 409, 422].includes(status);
|
|
435
|
+
};
|
|
436
|
+
const failed = (response) => response.ok === false || (httpStatus(response) ?? 0) >= 400;
|
|
437
|
+
/** The owner's perps withdrawable (6-decimal units) from a raw clearinghouseState answer; null when unreadable. */
|
|
438
|
+
export function perpsWithdrawableUnits(answer) {
|
|
439
|
+
if (!isRecord(answer))
|
|
440
|
+
return null;
|
|
441
|
+
return usdToUnits(answer.withdrawable);
|
|
442
|
+
}
|
|
443
|
+
export async function driveHypercoreReturn(request, deps) {
|
|
444
|
+
const signedAnything = () => Boolean(deps.getCheckpoint(CP.signed) || deps.getCheckpoint(CP.signedMapping));
|
|
445
|
+
const movement = (view) => {
|
|
446
|
+
if (deps.getCheckpoint(CP.completed))
|
|
447
|
+
return true;
|
|
448
|
+
if (view && view.money_moved === true)
|
|
449
|
+
return true;
|
|
450
|
+
// Only the pair (or the send) can move money; a lone journaled mapping cannot.
|
|
451
|
+
return deps.getCheckpoint(CP.signed) ? "unknown" : false;
|
|
452
|
+
};
|
|
453
|
+
const result = (ok, status, fields) => ({
|
|
454
|
+
ok, status, route: "arc_hypercore_return", account_id: deps.accountId,
|
|
455
|
+
source: "hypercore_perps", destination_chain_id: ARC_CHAIN_ID,
|
|
456
|
+
hypercore_return_id: deps.getCheckpoint(CP.prepared)?.id ?? null,
|
|
457
|
+
home_usable: false, ...fields,
|
|
458
|
+
money_moved: fields.money_moved ?? movement(), user_funds_moved: fields.money_moved ?? movement(),
|
|
459
|
+
});
|
|
460
|
+
const refuse = (code, message, extra = {}) => result(false, "refused", { error: { code, message }, money_moved: movement(), ...extra });
|
|
461
|
+
const hold = (code, message, view, extra = {}) => result(false, "reconciliation_required", { error: { code, message }, money_moved: movement(view),
|
|
462
|
+
reconciliation_required: true, next_action: "reconcile_do_not_resign", server_reason: view?.reason ?? null, ...extra });
|
|
463
|
+
const amount = request.amount_units;
|
|
464
|
+
const requestedMinimum = request.minimum_credit_units;
|
|
465
|
+
if (amount < MIN_AMOUNT_UNITS || amount > MAX_AMOUNT_UNITS)
|
|
466
|
+
return refuse("hypercore_return_amount_invalid", "amount must be 5 to 25 USDC.");
|
|
467
|
+
if (requestedMinimum !== null && (requestedMinimum <= 0n || requestedMinimum > amount)) {
|
|
468
|
+
return refuse("hypercore_return_minimum_invalid", "minimum_credit must be positive and no more than the amount.");
|
|
469
|
+
}
|
|
470
|
+
const accountId = typeof deps.accountId === "string" ? deps.accountId.toLowerCase() : "";
|
|
471
|
+
if (!UUID.test(accountId))
|
|
472
|
+
return refuse("child_account_required", "Select the account with use_child_account first.");
|
|
473
|
+
const owner = typeof deps.owner === "string" && ADDRESS.test(deps.owner) ? deps.owner.toLowerCase() : "";
|
|
474
|
+
if (!owner)
|
|
475
|
+
return refuse("client_signature_required", "A local owner key is required.");
|
|
476
|
+
const gaps = policyGaps(deps.policy);
|
|
477
|
+
if (gaps.length) {
|
|
478
|
+
return refuse("hypercore_return_policy_unverified", "This client has no reviewed evidence for every release gate of the HyperCore -> Arc route; nothing was prepared or signed.", { policy_gaps: gaps });
|
|
479
|
+
}
|
|
480
|
+
const api = async (method, path, body, opts) => {
|
|
481
|
+
try {
|
|
482
|
+
const out = await deps.call(method, path, body, opts);
|
|
483
|
+
return isRecord(out) ? out : { ok: false, error: { code: "invalid_response", outcome_unknown: true } };
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
return { ok: false, error: { code: "transport_lost", outcome_unknown: true, message: String(error?.message || error).slice(0, 200) } };
|
|
487
|
+
}
|
|
488
|
+
};
|
|
489
|
+
const startedAt = deps.now();
|
|
490
|
+
const budget = deps.pollBudgetMs ?? 45_000;
|
|
491
|
+
const maxPolls = deps.maxPolls ?? DEFAULT_MAX_POLLS;
|
|
492
|
+
let polls = 0;
|
|
493
|
+
let delay = MIN_POLL_MS;
|
|
494
|
+
const pause = async () => { await deps.sleep(delay); delay = Math.min(MAX_POLL_MS, delay * 2); };
|
|
495
|
+
try {
|
|
496
|
+
const safe = lower(await deps.expectedSafe(), "verified Arc home Safe");
|
|
497
|
+
const scope = { account_id: accountId, owner, safe, source: "hypercore_perps", amount_units: amount.toString(),
|
|
498
|
+
minimum_credit_units: requestedMinimum === null ? null : requestedMinimum.toString() };
|
|
499
|
+
const saved = deps.getCheckpoint(CP.scope);
|
|
500
|
+
if (saved && JSON.stringify(saved) !== JSON.stringify(scope)) {
|
|
501
|
+
return refuse("hypercore_return_scope_conflict", "This idempotency key belongs to a different account, owner, Safe or amount; nothing was signed.");
|
|
502
|
+
}
|
|
503
|
+
if (!saved)
|
|
504
|
+
deps.saveCheckpoint(CP.scope, scope);
|
|
505
|
+
const done = deps.getCheckpoint(CP.completed) ?? deps.getCheckpoint(CP.closed);
|
|
506
|
+
if (done && isRecord(done.result))
|
|
507
|
+
return done.result;
|
|
508
|
+
const expect = { owner, safe, amount, requestedMinimum };
|
|
509
|
+
// Venue preconditions, read by this client before anything is prepared or signed.
|
|
510
|
+
const venueGate = async () => {
|
|
511
|
+
let mode;
|
|
512
|
+
let state;
|
|
513
|
+
try {
|
|
514
|
+
[mode, state] = await Promise.all([deps.hyperliquid.abstraction(owner), deps.hyperliquid.clearinghouse(owner)]);
|
|
515
|
+
}
|
|
516
|
+
catch {
|
|
517
|
+
return "hypercore_account_unreadable";
|
|
518
|
+
}
|
|
519
|
+
if (mode !== "default")
|
|
520
|
+
return "hypercore_account_mode_unsupported";
|
|
521
|
+
const withdrawable = perpsWithdrawableUnits(state);
|
|
522
|
+
if (withdrawable === null)
|
|
523
|
+
return "hypercore_account_unreadable";
|
|
524
|
+
return withdrawable < amount ? "hypercore_withdrawable_insufficient" : null;
|
|
525
|
+
};
|
|
526
|
+
// -------- prepare (idempotent by key), verified before it is journaled
|
|
527
|
+
const prepareBody = { account_id: accountId, amount: usd(amount),
|
|
528
|
+
...(requestedMinimum === null ? {} : { minimum_credit: usd(requestedMinimum) }) };
|
|
529
|
+
const prepareKey = deps.stageKey("hcret-prepare");
|
|
530
|
+
let prepared = deps.getCheckpoint(CP.prepared);
|
|
531
|
+
if (!prepared) {
|
|
532
|
+
const gate = await venueGate();
|
|
533
|
+
if (gate) {
|
|
534
|
+
return refuse(gate, "The owner's HyperCore perps account is not in default mode or does not hold the amount "
|
|
535
|
+
+ "as withdrawable; nothing was prepared or signed.");
|
|
536
|
+
}
|
|
537
|
+
const response = await api("POST", `${ROUTE_PREFIX}/prepare`, prepareBody, { idempotencyKey: prepareKey });
|
|
538
|
+
if (failed(response)) {
|
|
539
|
+
if (definitiveRefusal(response) || (httpStatus(response) ?? 0) >= 500) {
|
|
540
|
+
// B5: an in_progress refusal names this account's own open return.
|
|
541
|
+
const open = openJourneyId(response);
|
|
542
|
+
const guidance = open
|
|
543
|
+
? await describeOpenJourney(api, { id: open, readPath: `${ROUTE_PREFIX}/${open}`, accountId,
|
|
544
|
+
resumeTool: HYPERCORE_RETURN_TOOL })
|
|
545
|
+
: {};
|
|
546
|
+
return refuse(String(errorOf(response).reason || errorOf(response).code || "hypercore_return_prepare_refused"), "Felix did not prepare the HyperCore return; nothing was signed.", { server_error: errorOf(response), ...guidance });
|
|
547
|
+
}
|
|
548
|
+
return result(false, "in_progress", { money_moved: false, next_action: "resume_with_same_idempotency_key",
|
|
549
|
+
error: { code: "hypercore_return_prepare_outcome_unknown", message: "Retry with the same key; nothing was signed." } });
|
|
550
|
+
}
|
|
551
|
+
const view = assertView(response, expect);
|
|
552
|
+
if (view.phase !== "prepared") {
|
|
553
|
+
return result(false, String(view.phase), { money_moved: view.money_moved === true ? true : "unknown",
|
|
554
|
+
next_action: "reconcile", error: { code: "hypercore_return_unsigned_advanced",
|
|
555
|
+
message: "The return under this key advanced before this client signed it; do not prepare a new one." } });
|
|
556
|
+
}
|
|
557
|
+
prepared = { id: view.id };
|
|
558
|
+
deps.saveCheckpoint(CP.prepared, prepared);
|
|
559
|
+
}
|
|
560
|
+
const id = String(prepared.id);
|
|
561
|
+
const base = `${ROUTE_PREFIX}/${id}`;
|
|
562
|
+
// -------- sign once: fresh read, full verification, journal the signatures
|
|
563
|
+
if (!deps.getCheckpoint(CP.signed)) {
|
|
564
|
+
const read = await api("GET", `${base}?account_id=${encodeURIComponent(accountId)}`);
|
|
565
|
+
if (failed(read)) {
|
|
566
|
+
if (definitiveRefusal(read))
|
|
567
|
+
return hold(String(errorOf(read).reason || "hypercore_return_read_refused"), "Felix would not read the return.");
|
|
568
|
+
return result(false, "in_progress", { money_moved: movement(), error: { code: "hypercore_return_read_unavailable", message: "Retry with the same key." } });
|
|
569
|
+
}
|
|
570
|
+
const view = assertView(read, { ...expect, id });
|
|
571
|
+
if (view.phase !== "prepared") {
|
|
572
|
+
return result(false, String(view.phase), { money_moved: view.money_moved === true ? true : "unknown", next_action: "reconcile",
|
|
573
|
+
error: { code: "hypercore_return_unsigned_advanced", message: "The return advanced before this client signed it." } });
|
|
574
|
+
}
|
|
575
|
+
const nowS = Math.floor(deps.now() / 1000);
|
|
576
|
+
const order = await assertOrder(view, expect, deps.policy, nowS);
|
|
577
|
+
const plan = assertSigning(view, expect, order.orderId, deps.now());
|
|
578
|
+
// Nothing was ever SENT before both signatures are journaled, so an expiring
|
|
579
|
+
// quote here is closed passively (never a new key, never a signature).
|
|
580
|
+
const closeUnsigned = async () => {
|
|
581
|
+
const current = await api("POST", `${base}/reconcile`, { account_id: accountId }, { retryOnError: true });
|
|
582
|
+
if (!failed(current)) {
|
|
583
|
+
const v = assertView(current, { ...expect, id });
|
|
584
|
+
if (v.phase === "expired" && v.money_moved === false) {
|
|
585
|
+
const closed = result(false, "expired", { money_moved: false, next_action: "prepare_new_with_a_new_idempotency_key",
|
|
586
|
+
error: { code: "hypercore_return_quote_expired_unsigned",
|
|
587
|
+
message: "The Relay quote expired before this client signed the send; nothing was sent. This key is "
|
|
588
|
+
+ "closed; start a new return with a NEW idempotency key if you still want to return." } });
|
|
589
|
+
deps.saveCheckpoint(CP.closed, { result: closed });
|
|
590
|
+
return closed;
|
|
591
|
+
}
|
|
592
|
+
if (v.phase !== "prepared") {
|
|
593
|
+
return result(false, String(v.phase), { money_moved: v.money_moved === true ? true : "unknown", next_action: "reconcile",
|
|
594
|
+
error: { code: "hypercore_return_unsigned_advanced", message: "The return advanced before this client signed it." } });
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
return result(false, "in_progress", { money_moved: false, next_action: "resume_with_same_idempotency_key",
|
|
598
|
+
error: { code: "hypercore_return_quote_expiring",
|
|
599
|
+
message: "The Relay quote is too close to expiry to sign; nothing was sent. Resume later to close it." } });
|
|
600
|
+
};
|
|
601
|
+
if (plan.quoteExpiresAt - nowS < QUOTE_SIGNING_MARGIN_S)
|
|
602
|
+
return closeUnsigned();
|
|
603
|
+
// The venue can change between prepare and signing (a trade, a transfer).
|
|
604
|
+
const gate = await venueGate();
|
|
605
|
+
if (gate) {
|
|
606
|
+
return refuse(gate, "The owner's HyperCore perps account no longer holds the amount as withdrawable (or left "
|
|
607
|
+
+ "default mode); nothing was signed.");
|
|
608
|
+
}
|
|
609
|
+
// Fresh admission immediately before signing: the same-key prepare replay
|
|
610
|
+
// runs the route's freeze, kill-switch and launch gates again and must hand
|
|
611
|
+
// back this exact plan. A passive read is not admission; refusal signs nothing.
|
|
612
|
+
const admitted = await api("POST", `${ROUTE_PREFIX}/prepare`, prepareBody, { idempotencyKey: prepareKey });
|
|
613
|
+
if (failed(admitted)) {
|
|
614
|
+
if (definitiveRefusal(admitted) || (httpStatus(admitted) ?? 0) >= 500) {
|
|
615
|
+
return refuse(String(errorOf(admitted).reason || errorOf(admitted).code || "hypercore_return_admission_refused"), "Felix did not re-admit this return at signing time; nothing was signed.", { server_error: errorOf(admitted) });
|
|
616
|
+
}
|
|
617
|
+
return result(false, "in_progress", { money_moved: false, error: { code: "hypercore_return_admission_unknown",
|
|
618
|
+
message: "The signing-time admission check did not answer; nothing was signed. Retry with the same key." } });
|
|
619
|
+
}
|
|
620
|
+
const again = assertView(admitted, { ...expect, id });
|
|
621
|
+
if (again.phase !== "prepared")
|
|
622
|
+
hostile("the signing-time admission answered with an advanced return");
|
|
623
|
+
const orderAgain = await assertOrder(again, expect, deps.policy, Math.floor(deps.now() / 1000));
|
|
624
|
+
const planAgain = assertSigning(again, expect, orderAgain.orderId, deps.now());
|
|
625
|
+
if (orderAgain.orderId !== order.orderId || orderAgain.solver !== order.solver || planAgain.nonce !== plan.nonce
|
|
626
|
+
|| planAgain.mapping.digest !== plan.mapping.digest || planAgain.send.digest !== plan.send.digest
|
|
627
|
+
|| planAgain.quoteExpiresAt !== plan.quoteExpiresAt || planAgain.requestId !== plan.requestId) {
|
|
628
|
+
hostile("the signing-time admission answered with another plan");
|
|
629
|
+
}
|
|
630
|
+
if (plan.quoteExpiresAt - Math.floor(deps.now() / 1000) < QUOTE_SIGNING_MARGIN_S)
|
|
631
|
+
return closeUnsigned();
|
|
632
|
+
// The mapping alone moves nothing; it is journaled first and reused on
|
|
633
|
+
// resume for exactly this plan, never re-signed.
|
|
634
|
+
let partial = deps.getCheckpoint(CP.signedMapping);
|
|
635
|
+
if (partial && (partial.id !== id || partial.mapping_digest !== plan.mapping.digest || partial.send_digest !== plan.send.digest)) {
|
|
636
|
+
hostile("the journaled nonce mapping was signed for another plan");
|
|
637
|
+
}
|
|
638
|
+
if (!partial) {
|
|
639
|
+
const signature = await deps.signTypedData(plan.mapping.typedData);
|
|
640
|
+
if (!SIGNATURE.test(signature))
|
|
641
|
+
return refuse("client_signing_failed", "The local nonce-mapping signature is malformed; nothing was sent.");
|
|
642
|
+
partial = { id, mapping_digest: plan.mapping.digest, send_digest: plan.send.digest, mapping_signature: signature.toLowerCase(),
|
|
643
|
+
signed_at_ms: deps.now() };
|
|
644
|
+
deps.saveCheckpoint(CP.signedMapping, partial);
|
|
645
|
+
}
|
|
646
|
+
const sendSignature = await deps.signTypedData(plan.send.typedData);
|
|
647
|
+
if (!SIGNATURE.test(sendSignature)) {
|
|
648
|
+
return refuse("client_signing_failed", "The local sendAsset signature is malformed; nothing was sent.");
|
|
649
|
+
}
|
|
650
|
+
deps.saveCheckpoint(CP.signed, {
|
|
651
|
+
id, nonce: plan.nonce, request_id: plan.requestId, order_id: order.orderId, solver: order.solver,
|
|
652
|
+
signed_minimum_units: order.signedMinimum.toString(), order_deadline: order.deadline,
|
|
653
|
+
mapping_digest: plan.mapping.digest, send_digest: plan.send.digest,
|
|
654
|
+
mapping_signature: String(partial.mapping_signature), send_signature: sendSignature.toLowerCase(),
|
|
655
|
+
signed_at_ms: deps.now(),
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
// -------- submit the SAME signatures at most once per invocation; reconcile resolves the rest
|
|
659
|
+
const signed = deps.getCheckpoint(CP.signed);
|
|
660
|
+
if (signed.id !== id)
|
|
661
|
+
hostile("the journaled signatures are for another return");
|
|
662
|
+
// B2: a definitive submit refusal, surfaced with the step that resolves it.
|
|
663
|
+
// Both signatures stay journaled; nothing is ever re-signed.
|
|
664
|
+
const submitRefusal = (response, view) => {
|
|
665
|
+
const error = errorOf(response);
|
|
666
|
+
const code = String(error.reason || error.code || "hypercore_return_submit_refused");
|
|
667
|
+
const expiresAt = Number(view.quote_expires_at);
|
|
668
|
+
const common = { money_moved: movement(), submit_refused: true, server_error: error,
|
|
669
|
+
quote_expires_at: Number.isSafeInteger(expiresAt) ? expiresAt : null };
|
|
670
|
+
if (code === "arc_hypercore_return_signature_invalid") {
|
|
671
|
+
return hold(code, "Felix did not accept this client's signatures as the owner's.", view, { server_error: error, next_action: "contact_support" });
|
|
672
|
+
}
|
|
673
|
+
const [next, message] = code === "arc_admission_frozen"
|
|
674
|
+
? ["resume_before_quote_expiry", "Felix paused new Arc money movement (for example during a deploy). Both "
|
|
675
|
+
+ "signatures are journaled; resume with the same idempotency_key before quote_expires_at."]
|
|
676
|
+
: code === "arc_hypercore_return_not_launch_enabled"
|
|
677
|
+
? ["resume_when_route_enabled", "Felix has not enabled this route; nothing was sent by Felix. Both "
|
|
678
|
+
+ "signatures stay journaled; resume with the same idempotency_key once it is enabled."]
|
|
679
|
+
: code === "arc_hypercore_return_quote_expired"
|
|
680
|
+
? ["resume_with_same_idempotency_key", "The Relay quote expired before Felix accepted the signatures, "
|
|
681
|
+
+ "which exist only in this client's journal. Resume with the same key to reconcile the expired "
|
|
682
|
+
+ "return; it is never re-signed."]
|
|
683
|
+
: ["resume_with_same_idempotency_key", "Felix refused the submission now. Both signatures are journaled; "
|
|
684
|
+
+ "resume with the same idempotency_key to reconcile and offer the SAME signatures again."];
|
|
685
|
+
return result(false, "submit_refused", { ...common, next_action: next, error: { code, message } });
|
|
686
|
+
};
|
|
687
|
+
let offered = false;
|
|
688
|
+
for (;;) {
|
|
689
|
+
if (polls >= maxPolls || deps.now() - startedAt > budget) {
|
|
690
|
+
return result(true, "in_progress", { money_moved: movement(), next_action: "resume_with_same_idempotency_key" });
|
|
691
|
+
}
|
|
692
|
+
polls += 1;
|
|
693
|
+
const current = await api("POST", `${base}/reconcile`, { account_id: accountId }, { retryOnError: true });
|
|
694
|
+
if (failed(current)) {
|
|
695
|
+
if (httpStatus(current) === 404)
|
|
696
|
+
hostile("the server lost the return");
|
|
697
|
+
if (definitiveRefusal(current)) {
|
|
698
|
+
return hold(String(errorOf(current).reason || "hypercore_return_reconcile_refused"), "Felix refused to advance the return.");
|
|
699
|
+
}
|
|
700
|
+
await pause();
|
|
701
|
+
continue;
|
|
702
|
+
}
|
|
703
|
+
const view = assertView(current, { ...expect, id });
|
|
704
|
+
const phase = String(view.phase);
|
|
705
|
+
// The engine never returns signatures; the plan it names must still be the signed one.
|
|
706
|
+
const differs = (value, mine) => value !== undefined && value !== null && String(value).toLowerCase() !== String(mine).toLowerCase();
|
|
707
|
+
if (differs(view.nonce, signed.nonce) || differs(view.order_id, signed.order_id) || differs(view.request_id, signed.request_id)) {
|
|
708
|
+
hostile("the return names another nonce, order or request than this client signed");
|
|
709
|
+
}
|
|
710
|
+
if (phase === "prepared" || phase === "source_submitted") {
|
|
711
|
+
// The engine journals the signatures BEFORE it posts them, so a
|
|
712
|
+
// source_submitted row may never have been sent (crash in between). Offer
|
|
713
|
+
// the SAME journaled signatures once per invocation; HyperCore refuses a
|
|
714
|
+
// reused nonce, so a re-post of an already-landed send moves nothing.
|
|
715
|
+
if (!offered) {
|
|
716
|
+
offered = true;
|
|
717
|
+
if (!deps.getCheckpoint(CP.submission))
|
|
718
|
+
deps.saveCheckpoint(CP.submission, { id });
|
|
719
|
+
const submitted = await api("POST", `${base}/submit`, { account_id: accountId, nonce_mapping_signature: signed.mapping_signature,
|
|
720
|
+
send_asset_signature: signed.send_signature }, { retryOnError: false });
|
|
721
|
+
// B2 (MCP-SWALLOWS-SUBMIT-REFUSAL): a DEFINITIVE refusal is surfaced now
|
|
722
|
+
// with its next step; a lost/5xx answer is resolved by reconcile.
|
|
723
|
+
if (failed(submitted) && definitiveRefusal(submitted))
|
|
724
|
+
return submitRefusal(submitted, view);
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
await pause();
|
|
728
|
+
continue;
|
|
729
|
+
}
|
|
730
|
+
if (phase === "completed") {
|
|
731
|
+
const claim = assertCompletion(view, signed, safe, amount);
|
|
732
|
+
// The client's own reads, never the engine's status: the send left the
|
|
733
|
+
// owner's perps at the signed nonce, and the solver's fill paid the Safe.
|
|
734
|
+
const signedAt = Number(signed.signed_at_ms);
|
|
735
|
+
let rows = [];
|
|
736
|
+
try {
|
|
737
|
+
rows = await deps.hyperliquid.ledger(owner, signedAt - 60_000, deps.now() + 60_000);
|
|
738
|
+
}
|
|
739
|
+
catch {
|
|
740
|
+
rows = [];
|
|
741
|
+
}
|
|
742
|
+
const source = ledgerShowsSource(rows, owner, amount, Number(signed.nonce));
|
|
743
|
+
if (source === "mismatch")
|
|
744
|
+
hostile("the owner's HyperCore ledger does not show exactly the signed send");
|
|
745
|
+
let proven = false;
|
|
746
|
+
if (source === "one") {
|
|
747
|
+
try {
|
|
748
|
+
proven = (await deps.policy.verifyHomeCredit(claim)) === true;
|
|
749
|
+
}
|
|
750
|
+
catch {
|
|
751
|
+
proven = false;
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
if (!proven) {
|
|
755
|
+
await pause();
|
|
756
|
+
continue;
|
|
757
|
+
}
|
|
758
|
+
const final = result(true, "completed", {
|
|
759
|
+
money_moved: true, home_usable: true, order_id: signed.order_id, relay_nonce: signed.nonce,
|
|
760
|
+
source_proof: { ledger_hash: String(view.source_proof.ledger_hash).toLowerCase(), nonce: signed.nonce,
|
|
761
|
+
amount_units: amount.toString(), destination: RELAY_HL_DEPOSITORY },
|
|
762
|
+
credit: { amount_units: claim.amountUnits.toString(), fill_tx_hash: claim.fillTxHash,
|
|
763
|
+
block_number: claim.blockNumber, block_hash: claim.blockHash },
|
|
764
|
+
destination: { chain_id: ARC_CHAIN_ID, token: ARC_USDC, safe },
|
|
765
|
+
home_usable_basis: {
|
|
766
|
+
felix: "engine completion bound to this client's order and nonce",
|
|
767
|
+
client_proof: ["own HyperCore ledger read of the signed perps send to the Relay depository",
|
|
768
|
+
"Felix's Arc credit evidence bound to this order, solver and the signed credit bounds (app model)"],
|
|
769
|
+
not_claimed: ["current_spendable_balance", "venue_funding"],
|
|
770
|
+
},
|
|
771
|
+
next_action: "none",
|
|
772
|
+
});
|
|
773
|
+
deps.saveCheckpoint(CP.completed, { result: final });
|
|
774
|
+
return final;
|
|
775
|
+
}
|
|
776
|
+
if (phase === "source_dropped") {
|
|
777
|
+
// Terminal only on this client's own evidence: the HyperCore nonce window
|
|
778
|
+
// is closed AND the owner's ledger over it shows no send at the nonce.
|
|
779
|
+
const nonceMs = Number(signed.nonce);
|
|
780
|
+
if (deps.now() > nonceMs + HL_NONCE_WINDOW_CLOSED_MS) {
|
|
781
|
+
let rows = null;
|
|
782
|
+
try {
|
|
783
|
+
rows = await deps.hyperliquid.ledger(owner, Number(signed.signed_at_ms) - 60_000, nonceMs + HL_NONCE_WINDOW_CLOSED_MS);
|
|
784
|
+
}
|
|
785
|
+
catch {
|
|
786
|
+
rows = null;
|
|
787
|
+
}
|
|
788
|
+
if (rows !== null && ledgerShowsSource(rows, owner, amount, nonceMs) === "none"
|
|
789
|
+
&& !rows.some((row) => isRecord(row) && isRecord(row.delta) && row.delta.nonce === nonceMs)) {
|
|
790
|
+
const closed = result(false, "source_dropped", { money_moved: false, verified: true,
|
|
791
|
+
next_action: "prepare_new_with_a_new_idempotency_key",
|
|
792
|
+
error: { code: "hypercore_return_source_dropped",
|
|
793
|
+
message: "The signed send can no longer execute (its HyperCore nonce window closed) and the owner's "
|
|
794
|
+
+ "ledger shows no send at that nonce; nothing moved. This key is closed." } });
|
|
795
|
+
deps.saveCheckpoint(CP.closed, { result: closed });
|
|
796
|
+
return closed;
|
|
797
|
+
}
|
|
798
|
+
}
|
|
799
|
+
return hold("hypercore_return_source_dropped_unverified", "Felix reports the signed send never executed. This client has not yet verified that on the owner's HyperCore "
|
|
800
|
+
+ "ledger; the same key is never re-signed. Resume after the nonce window closes.", view, { server_phase: phase, verified: false });
|
|
801
|
+
}
|
|
802
|
+
if (phase === "expired") {
|
|
803
|
+
return hold("hypercore_return_expired_reported", "Felix reports the signed return expired. This client has not verified that nothing left HyperCore; the same "
|
|
804
|
+
+ "key is never re-signed. Reconcile before any new return.", view, { server_phase: phase, verified: false });
|
|
805
|
+
}
|
|
806
|
+
if (phase === "refunded") {
|
|
807
|
+
return hold("hypercore_return_refund_reported_unverified", "Felix reports that Relay refunded this return. This client has not verified the refund; check balances.", view, { server_phase: "refunded", verified: false, refund: view.refund ?? null });
|
|
808
|
+
}
|
|
809
|
+
if (phase === "reconciliation_required" || phase === "closed") {
|
|
810
|
+
return hold(`hypercore_return_${phase}`, "Felix needs reconciliation before this return can continue.", view);
|
|
811
|
+
}
|
|
812
|
+
await pause(); // source_confirmed
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
catch (error) {
|
|
816
|
+
if (error instanceof HypercoreReturnHostileServer)
|
|
817
|
+
return hold("hypercore_return_server_untrusted", error.message);
|
|
818
|
+
if (signedAnything())
|
|
819
|
+
return hold("hypercore_return_client_failed_after_signing", String(error?.message || error).slice(0, 200));
|
|
820
|
+
return refuse("hypercore_return_client_failed", String(error?.message || error).slice(0, 200));
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
export const HYPERCORE_RETURN_PINS = Object.freeze({
|
|
824
|
+
relayHlDepository: getAddress(RELAY_HL_DEPOSITORY),
|
|
825
|
+
hlUsdcToken: HL_USDC_TOKEN,
|
|
826
|
+
});
|