felix-mcp 2.0.110 → 2.0.128

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.
@@ -6,8 +6,18 @@ export const OPERATIONS_GUIDE = `# Felix agent operations and recovery
6
6
 
7
7
  Start with get_situation. It returns agents, positions, marked PnL,
8
8
  canonical money, active risk blocks, recent decisions, and pending operations.
9
- Every source is independently marked available or unavailable. Never interpret
10
- an unavailable source as zero, flat, or complete.
9
+ Every source is independently marked available, partial, or unavailable.
10
+ \`partial_sources\` identifies successful reads whose nested completeness or
11
+ freshness is limited; inspect the nested reason before deciding whether the
12
+ known fields are usable. \`unavailable\` identifies sources that cannot support the
13
+ snapshot's normal decision contract. Never interpret partial or unavailable
14
+ data as zero, flat, spendable, or complete.
15
+
16
+ Use get_account_statement for a stable, owner-scoped reconciliation ledger.
17
+ Follow next_cursor until it is null. Every row labels live, paper, or live-mock
18
+ activity explicitly and reports whether historical fee and realized-PnL fields
19
+ are complete. It is an operational trade ledger, not tax advice or a tax
20
+ statement, and it never signs, submits orders, updates agents, or moves money.
11
21
 
12
22
  ## Events instead of polling
13
23
 
@@ -27,6 +37,42 @@ to recover the local encrypted money journal.
27
37
  4. Follow recovery_tool and its exact arguments when returned.
28
38
  5. Treat money_moved: null as unknown and reconcile before resuming.
29
39
  6. Use get_agent_log to distinguish executed, blocked, skipped, and errored decisions.
40
+ 7. Respect retryable:false. Retry-After or error.retry_after is a minimum wait,
41
+ not a reason to start a different workflow. If the wait is too long for one
42
+ call, retain the operation/key and resume after the delay.
43
+
44
+ ## Prepaid execution fees
45
+
46
+ Use get_fee_balance to read fee credit. Available credit can cover new execution;
47
+ reserved credit is held for pending execution, not charged yet. Only captured
48
+ credit is consumed. Fee credit is not withdrawable wallet cash or venue collateral.
49
+ The money map reports it separately, outside the wallet/venue total.
50
+
51
+ When exact counters are present, use those integer strings with six decimals for
52
+ accounting; numeric USD fields are display values. These counters cover prepaid
53
+ execution fees only, not gas, bridges, venue fees or Hyperliquid builder fees.
54
+ They do not provide historical timestamps or a full-account PnL calculation.
55
+
56
+ fund_market network fees are prepaid separately from execution-fee credit. The
57
+ exact treasury transfer must confirm before any venue funding or bridge value
58
+ leg is authorized. A failed fee payment starts no venue transfer. If a later
59
+ stage is interrupted, resume the exact original operation and idempotency key;
60
+ the durable paid proof is reused and must not be paid again. Funding never
61
+ creates an outstanding fee balance.
62
+
63
+ fee_credit_state_unavailable: retry get_fee_balance after retry_after.
64
+ fee_credit_state_invalid: use report_feedback with the request ID; do not retry
65
+ automatically. Neither error authorizes another top-up. Unknown is not zero.
66
+
67
+ ## Owner withdrawals
68
+
69
+ get_capital_operation and cancel_withdrawal are unavailable and refuse without
70
+ signing or moving anything. A broadcast withdrawal cannot be cancelled. For a
71
+ sent or uncertain withdrawal, retry withdraw with its original idempotency key
72
+ to confirm the saved hash; expiry does not authorize another transfer. Check
73
+ the result with get_money_map, get_balances and list_recent_operations. If
74
+ the owner nonce appears stuck, keep every hash and contact support. Never
75
+ submit a replacement transfer at a fresh nonce.
30
76
 
31
77
  ## Policy tuning
32
78
 
@@ -37,6 +83,130 @@ bounded by the active owner-authorized key caps. A stop loss is optional; when
37
83
  one is requested, Felix must confirm that the venue supports the selected exit
38
84
  mechanism before relying on it.
39
85
 
86
+ To replace strategy logic in place, stop the agent and close or explicitly
87
+ transfer responsibility for every open position. Call update_agent with the
88
+ reviewed Felix-generated strategy_id and resume:false. User-supplied code is
89
+ refused. Before that mutation, call review_agent_strategy_revision with the saved
90
+ agent UUID, candidate_strategy_id, realistic fees and slippage, and one stable
91
+ idempotency key. It compares
92
+ current and candidate logic on one shared dataset and a chronological cold-state
93
+ holdout without revealing the current source or changing the agent. A candidate
94
+ that outperforms historically is not auto-promoted and is not guaranteed to work
95
+ live.
96
+
97
+ Felix validates
98
+ the safe language subset, proves the owned position book is flat, preserves the
99
+ venue, authorized markets, portfolio intent, and risk envelope, and returns the
100
+ previous and new strategy SHA-256 values plus a monotonic strategy revision.
101
+ Review that receipt, then make a separate update_agent call with resume:true.
102
+ Strategy replacement and resume are intentionally never one atomic action.
103
+
104
+ ## Walk-forward validation
105
+
106
+ Use backtest_sensitivity before walk-forward validation to hold strategy code
107
+ fixed and test two to eight explicit history, capital, fee, and slippage
108
+ assumptions on one shared price dataset. Its overlapping windows are diagnostics,
109
+ not independent evidence. Incomplete history, unreplayed live-only inputs,
110
+ degraded or short execution, too few trades, or any non-positive scenario force
111
+ robust:false.
112
+
113
+ Use walk_forward_backtest to compare two to four explicit strategy variants on
114
+ one immutable historical dataset. Each fold selects using only its anchored
115
+ training window, then evaluates that exact variant on the next untouched
116
+ cold-start holdout. Always provide realistic fee_bps_per_side and
117
+ slippage_bps_per_side. Preserve and reuse the required idempotency key after a
118
+ timeout; a replacement key starts a separate study and consumes another quota.
119
+
120
+ This is computation only: it never deploys, signs, funds, or trades. A selected
121
+ variant is still not evidence of future returns. Treat robust:false as binding.
122
+ A robust verdict requires exact source and fold coverage, healthy full-length
123
+ zero-error execution, nonnegative integer counters, historically replayable
124
+ inputs, enough holdout trades, and positive return in every holdout. Reject
125
+ studies with degraded historical validity or costs that do not match the intended
126
+ venue.
127
+
128
+ Use portfolio_backtest after single-strategy validation to replay two to six
129
+ caller-owned saved agents with weights totaling exactly 10,000 basis points.
130
+ It returns combined full-period and chronological cold-state holdout equity,
131
+ costs, attribution, correlation, covariance, and explicit criteria. Capital is
132
+ modeled as independent fixed sleeves. Felix does not assume shared margin,
133
+ cross-venue netting, capital reuse, or market impact. The holdout is independently
134
+ out-of-sample only if every strategy was frozen before that window was inspected.
135
+ An incomplete evidence result is not a portfolio result. This tool never changes
136
+ an agent, signs, funds, submits an order, or moves money.
137
+
138
+ ## Execution-route selection
139
+
140
+ Use preview_execution_route with one explicit objective, canonical instrument,
141
+ side, and size before choosing a venue. Directional long exposure may compare
142
+ spot and perpetual execution; shorts use perpetuals. Event and option objectives
143
+ preserve the exact contract and are never treated as interchangeable with linear
144
+ exposure.
145
+
146
+ A selected route has verified venue binding, liquidity, collateral, portfolio
147
+ headroom, and complete immediate entry costs. Unknown fees or funding costs are
148
+ never zero and make a candidate ineligible. The comparison intentionally excludes
149
+ future funding or borrow, liquidation risk, nonlinear payoff risk, tax treatment,
150
+ and future exit cost or liquidity. Refresh preview_order immediately before any
151
+ separately authorized order. This selector never signs, funds, bridges, or trades.
152
+
153
+ For a Derive option, inspect preview_order.estimated_order_greeks and the
154
+ portfolio-risk derive_greek_impact before execution. They use the exact
155
+ venue-rounded contract count and current quote. Treat incomplete fields as
156
+ unavailable, and keep their Derive-native units separate from dollar P&L or
157
+ cross-venue risk. Owners may configure per-underlying absolute-net and gross
158
+ gamma, theta, and vega ceilings through update_portfolio_mandate. Direct orders,
159
+ autonomous opens, and cumulative batch legs enforce those limits on exact quote
160
+ projections while permitting risk-reducing trades. The projection itself is
161
+ decision evidence, not an authorization or automatic hedge instruction.
162
+
163
+ ## Portfolio and fleet risk
164
+
165
+ Use get_portfolio_risk as the authoritative combined-book snapshot before sizing,
166
+ hedging, rebalancing, or changing an agent fleet. It reports verified capital,
167
+ gross exposure, linear net exposure, concentration, venue allocation, daily loss,
168
+ and data-completeness state. Reconciled Derive positions also include signed net
169
+ and gross venue-native gamma, theta, and vega. Gross values preserve offsetting
170
+ option sensitivity. Do not interpret those higher-order values as dollar P&L,
171
+ cross-venue normalization, an enforced limit, or an automatic hedge instruction.
172
+ Unknown or incomplete sources are never zero.
173
+
174
+ Use preview_portfolio_hedge for one verified linear asset delta. The result combines
175
+ portfolio headroom with current Hyperliquid venue checks; it does not infer an
176
+ option or event-market hedge. Use preview_derive_greek_hedge for one verified
177
+ Derive net gamma, theta, or vega objective. It considers no more than four liquid
178
+ buy-to-open options with the opposite signed quote Greek, runs exact venue,
179
+ collateral, mandate, and cost previews with bounded concurrency, and ranks only
180
+ candidates that reduce the selected net sensitivity. Omit target_abs_net to use
181
+ the matching owner limit. It does not optimize gross exposure, several Greeks,
182
+ future volatility, or exit liquidity, and it cannot execute the selected trade.
183
+ Use preview_portfolio_stress for one to eight explicit
184
+ deterministic scenarios. Supply nonlinear P&L adjustments for every nonlinear
185
+ position before treating stressed equity as decision-usable.
186
+
187
+ Use preview_historical_portfolio_risk only with 20-500 unique, non-future daily
188
+ observations containing every current verified linear delta asset. Its VaR and
189
+ expected shortfall describe that supplied sample; they are not forecasts. Use
190
+ preview_covariance_risk_trim with the same complete observations to plan one
191
+ existing linear-exposure reduction toward the owner volatility mandate. An
192
+ explicit target may only tighten the mandate. The result is an exact read-only
193
+ Hyperliquid preview; it cannot create new exposure, cross zero, add leverage,
194
+ fund, sign, submit, or move money. Use
195
+ preview_fleet_capacity before allocating capital across autonomous agents, and
196
+ preview_fleet_reallocation to sequence an explicit owner-selected fleet target
197
+ through reductions, dependent-limit review, and separate budget changes. It
198
+ never infers live weights from historical returns or mutates the fleet. Pause
199
+ every agent whose budget will change, then use apply_fleet_reallocation with the
200
+ reviewed policy version, exact target and weights, and a stable idempotency key.
201
+ That mutation is atomic across the eligible fleet and changes policy ceilings
202
+ only: it never resumes an agent, moves/reserves capital, funds, or trades. Use
203
+ get_execution_quality for bounded decision, outcome, and runtime-latency evidence.
204
+ Only a decision-compatible terminal status plus a durable position identity is
205
+ confirmed; pending, reconciliation, missing, or unknown outcomes remain unresolved.
206
+ None of these tools reserves capital, updates an agent, signs, funds, bridges, or
207
+ trades. Continue to call preview_order and preview_portfolio_order immediately
208
+ before separately authorized execution.
209
+
40
210
  ## Autonomous Polymarket wallets
41
211
 
42
212
  Interactive Polymarket orders use the client-owned wallet and a local signer.
@@ -0,0 +1,366 @@
1
+ // Production ports for the HL -> Arc home return driver (arc-hl-return.ts).
2
+ //
3
+ // ARC_HL_RETURN_PORTS_2026_09_23. Every port is a thin, bounded client; all
4
+ // decisions stay in the driver.
5
+ //
6
+ // hyperliquid public /exchange (the one signed withdraw3 post) and /info
7
+ // (userNonFundingLedgerUpdates) -- the endpoints funding.ts uses.
8
+ // arbitrum READS only (nonce, fees, USDC balance, receipts) through the
9
+ // same Arbitrum RPC funding.ts reads from.
10
+ // arbitrumBroadcast WRITES only through Felix: POST
11
+ // /v1/arc-home/operations/{op}/source-authorize seals an intent
12
+ // for the row's exact approve + GatewayWallet.deposit, and the
13
+ // raw transaction is sent to /v1/wallet/funding/rpc/arbitrum with
14
+ // that intent. The transaction is checked here against the
15
+ // authorized calls before it leaves the process. There is no
16
+ // direct-RPC fallback for writes.
17
+ // arc DEFAULT: Felix's read-only GET /v1/arc-home/operations/{op}/
18
+ // arc-credit (strict-majority Arc reads of the row's OWN mint
19
+ // receipt and the home Safe's balance at the mint block and the
20
+ // block before). No client Arc RPC is needed. Optional hardening:
21
+ // FELIX_ARC_RPC_URL switches to an independent client Arc reader.
22
+ // signer settlementSignerPort(): the Arc settlement tools' owner key.
23
+ // journal the encrypted money-workflow journal context, unchanged.
24
+ import { keccak256, parseTransaction, encodeFunctionData, decodeEventLog } from "viem";
25
+ import { HL_ARC_ARBITRUM_BROADCAST_SCOPE, HL_ARC_CHAIN, settlementSignerPort, } from "./arc-hl-return.js";
26
+ import { requirePrivateRpcUrl } from "./rpc-endpoints.js";
27
+ export const HL_API_DEFAULT = "https://api.hyperliquid.xyz";
28
+ // NO_PUBLIC_RPC_2026_09_25: there is no Arbitrum RPC default. The owner-address
29
+ // reads (nonce, balance, receipts) require FELIX_ARBITRUM_RPC_URL and refuse a
30
+ // public host; resolveHlArcEndpoints is called at use (productionHlArcPorts),
31
+ // so an unset variable surfaces as hl_return_endpoint_invalid, never at import.
32
+ const MAX_RESPONSE_BYTES = 1_000_000;
33
+ const TIMEOUT_MS = 20_000;
34
+ const ARC_NATIVE_USDC_EMITTER = "0xfffffffffffffffffffffffffffffffffffffffe";
35
+ const LOOPBACK = new Set(["127.0.0.1", "localhost", "[::1]"]);
36
+ const ERC20_ABI = [
37
+ { type: "function", name: "balanceOf", stateMutability: "view", inputs: [{ name: "a", type: "address" }], outputs: [{ type: "uint256" }] },
38
+ { type: "event", name: "Transfer", inputs: [
39
+ { name: "from", type: "address", indexed: true }, { name: "to", type: "address", indexed: true },
40
+ { name: "value", type: "uint256", indexed: false }
41
+ ] },
42
+ ];
43
+ const isRecord = (v) => !!v && typeof v === "object" && !Array.isArray(v);
44
+ function endpoint(value, fallback, { allowRemoteOverride }) {
45
+ const raw = (value || "").trim();
46
+ if (!raw)
47
+ return fallback;
48
+ let url;
49
+ try {
50
+ url = new URL(raw);
51
+ }
52
+ catch {
53
+ throw new Error("A configured Hyperliquid/Arbitrum/Arc endpoint is not a URL.");
54
+ }
55
+ const loopback = LOOPBACK.has(url.hostname);
56
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && loopback)) {
57
+ throw new Error("Endpoints must use HTTPS (plain HTTP is allowed only on loopback).");
58
+ }
59
+ if (!allowRemoteOverride && !loopback) {
60
+ throw new Error("The Hyperliquid endpoint may only be overridden with a loopback test server.");
61
+ }
62
+ return url.toString().replace(/\/$/, "");
63
+ }
64
+ /**
65
+ * Only Hyperliquid's own API: the HL -> Arbitrum -> Relay route needs no client
66
+ * Arbitrum or Arc RPC (Felix proves the payout and the credit with quorum reads).
67
+ * Same rule as below: a remote override is refused so a mis-set variable cannot
68
+ * redirect a signed withdraw3.
69
+ */
70
+ export function resolveHyperliquidEndpoint(env = process.env) {
71
+ return endpoint(env.FELIX_HYPERLIQUID_API_URL, HL_API_DEFAULT, { allowRemoteOverride: false });
72
+ }
73
+ export function resolveHlArcEndpoints(env = process.env) {
74
+ return {
75
+ // The signed withdraw3 only ever goes to Hyperliquid's own API; a remote
76
+ // override is refused so a mis-set variable cannot redirect a signature.
77
+ hyperliquid: endpoint(env.FELIX_HYPERLIQUID_API_URL, HL_API_DEFAULT, { allowRemoteOverride: false }),
78
+ arbitrumRpc: requirePrivateRpcUrl("arbitrum", endpoint(env.FELIX_ARBITRUM_RPC_URL, null, { allowRemoteOverride: true })),
79
+ arcRpc: endpoint(env.FELIX_ARC_RPC_URL, null, { allowRemoteOverride: true }),
80
+ };
81
+ }
82
+ // ------------------------------------------------------------------ transport
83
+ async function postJson(fetchImpl, url, body, headers = {}) {
84
+ const controller = new AbortController();
85
+ const timer = setTimeout(() => controller.abort(), TIMEOUT_MS);
86
+ try {
87
+ const response = await fetchImpl(url, {
88
+ method: "POST",
89
+ headers: { "content-type": "application/json", accept: "application/json", ...headers },
90
+ body: JSON.stringify(body),
91
+ signal: controller.signal,
92
+ redirect: "error",
93
+ });
94
+ const text = await response.text();
95
+ if (text.length > MAX_RESPONSE_BYTES)
96
+ throw new Error("response too large");
97
+ let json;
98
+ try {
99
+ json = JSON.parse(text);
100
+ }
101
+ catch {
102
+ throw new Error("response is not JSON");
103
+ }
104
+ return { status: response.status, json };
105
+ }
106
+ finally {
107
+ clearTimeout(timer);
108
+ }
109
+ }
110
+ let rpcId = 0;
111
+ async function jsonRpc(fetchImpl, url, method, params, headers) {
112
+ const { status, json } = await postJson(fetchImpl, url, { jsonrpc: "2.0", id: ++rpcId, method, params }, headers);
113
+ if (status < 200 || status >= 300 || !isRecord(json))
114
+ throw new Error(`${method} failed (HTTP ${status})`);
115
+ if (json.error !== undefined)
116
+ throw new Error(`${method} returned an error`);
117
+ return json.result;
118
+ }
119
+ const quantity = (v, what) => {
120
+ if (typeof v !== "string" || !/^0x[0-9a-fA-F]+$/.test(v))
121
+ throw new Error(`${what} is not a quantity`);
122
+ return BigInt(v);
123
+ };
124
+ const toHex = (n) => `0x${BigInt(n).toString(16)}`;
125
+ // ---------------------------------------------------------------- hyperliquid
126
+ export function hyperliquidPort(base, fetchImpl = fetch) {
127
+ return {
128
+ // Resolves with the venue's JSON answer, including a definitive refusal;
129
+ // rejects only when no answer was received (the driver treats that as
130
+ // "outcome unknown" and lets the ledger decide).
131
+ async submitWithdraw(body) {
132
+ const { json } = await postJson(fetchImpl, `${base}/exchange`, body);
133
+ if (!isRecord(json))
134
+ throw new Error("Hyperliquid answered without a JSON object");
135
+ return json;
136
+ },
137
+ async ledger(owner, startTimeMs, endTimeMs) {
138
+ const { status, json } = await postJson(fetchImpl, `${base}/info`, {
139
+ type: "userNonFundingLedgerUpdates", user: owner, startTime: startTimeMs, endTime: endTimeMs,
140
+ });
141
+ if (status !== 200 || !Array.isArray(json) || json.length > 2_000)
142
+ throw new Error("Hyperliquid ledger unavailable");
143
+ return json;
144
+ },
145
+ };
146
+ }
147
+ // ------------------------------------------------------------ arbitrum reads
148
+ export function arbitrumReadPort(url, fetchImpl = fetch) {
149
+ const nonce = async (address, tag) => {
150
+ const n = quantity(await jsonRpc(fetchImpl, url, "eth_getTransactionCount", [address, tag]), "nonce");
151
+ if (n > BigInt(Number.MAX_SAFE_INTEGER))
152
+ throw new Error("nonce out of range");
153
+ return Number(n);
154
+ };
155
+ return {
156
+ pendingNonce: (a) => nonce(a, "pending"),
157
+ latestNonce: (a) => nonce(a, "latest"),
158
+ async fees() {
159
+ const gasPrice = quantity(await jsonRpc(fetchImpl, url, "eth_gasPrice", []), "gas price");
160
+ const priority = quantity(await jsonRpc(fetchImpl, url, "eth_maxPriorityFeePerGas", []), "priority fee");
161
+ const maxFeePerGas = gasPrice * 2n + priority;
162
+ return { maxFeePerGas, maxPriorityFeePerGas: priority > maxFeePerGas ? maxFeePerGas : priority };
163
+ },
164
+ async usdcBalance(address) {
165
+ const data = encodeFunctionData({ abi: ERC20_ABI, functionName: "balanceOf", args: [address] });
166
+ return quantity(await jsonRpc(fetchImpl, url, "eth_call", [{ to: HL_ARC_CHAIN.ARB_USDC, data }, "latest"]), "balance");
167
+ },
168
+ async receipt(hash) {
169
+ const r = await jsonRpc(fetchImpl, url, "eth_getTransactionReceipt", [hash]);
170
+ if (r === null)
171
+ return null;
172
+ if (!isRecord(r))
173
+ throw new Error("receipt malformed");
174
+ return { success: r.status === "0x1", block_number: Number(quantity(r.blockNumber, "block")) };
175
+ },
176
+ };
177
+ }
178
+ export function arbitrumBroadcastPort(access, fetchImpl = fetch) {
179
+ const base = access.api_url.replace(/\/$/, "");
180
+ const cache = new Map();
181
+ const auth = { Authorization: `Bearer ${access.api_key}` };
182
+ const query = `account_id=${encodeURIComponent(access.account_id)}`;
183
+ async function authorize(operationId) {
184
+ const cached = cache.get(operationId);
185
+ if (cached && cached.expiresAtMs - 30_000 > Date.now())
186
+ return cached;
187
+ const { status, json } = await postJson(fetchImpl, `${base}/v1/arc-home/operations/${encodeURIComponent(operationId)}/source-authorize?${query}`, { account_id: access.account_id }, auth);
188
+ const sb = isRecord(json) ? json.source_broadcast : undefined;
189
+ if (status !== 200 || !isRecord(sb) || sb.rpc_path !== "/v1/wallet/funding/rpc/arbitrum"
190
+ || sb.chain_id !== HL_ARC_CHAIN.ARB_CHAIN_ID || sb.operation_id !== operationId
191
+ || typeof sb.intent_token !== "string" || !Array.isArray(sb.calls)) {
192
+ throw new Error("Felix did not authorize this deposit's source calls");
193
+ }
194
+ const calls = sb.calls.map((c) => {
195
+ if (!isRecord(c) || typeof c.to !== "string" || typeof c.data !== "string" || String(c.value) !== "0") {
196
+ throw new Error("Felix authorized a malformed source call");
197
+ }
198
+ return { to: c.to.toLowerCase(), data: c.data.toLowerCase() };
199
+ });
200
+ const expiresAtMs = Date.parse(String(sb.expires_at));
201
+ const entry = { token: sb.intent_token, calls, expiresAtMs: Number.isFinite(expiresAtMs) ? expiresAtMs : 0 };
202
+ cache.set(operationId, entry);
203
+ return entry;
204
+ }
205
+ return {
206
+ scope: HL_ARC_ARBITRUM_BROADCAST_SCOPE,
207
+ async sendRawTransaction(raw, operationId) {
208
+ const tx = parseTransaction(raw);
209
+ const authorized = await authorize(operationId);
210
+ const to = String(tx.to || "").toLowerCase();
211
+ const data = String(tx.data || "0x").toLowerCase();
212
+ if (tx.chainId !== HL_ARC_CHAIN.ARB_CHAIN_ID || (tx.value ?? 0n) !== 0n
213
+ || !authorized.calls.some((c) => c.to === to && c.data === data)) {
214
+ // Never handed to the relay: the driver signed exactly what the plan
215
+ // said, so a mismatch here means the authorization changed under it.
216
+ throw new Error("the signed transaction is not one of this row's authorized source calls");
217
+ }
218
+ const { status, json } = await postJson(fetchImpl, `${base}/v1/wallet/funding/rpc/arbitrum?${query}`, { jsonrpc: "2.0", id: ++rpcId, method: "eth_sendRawTransaction", params: [raw] }, { ...auth, "X-Felix-Funding-Intent": authorized.token });
219
+ if (status === 401 || status === 403)
220
+ cache.delete(operationId);
221
+ if (status !== 200 || !isRecord(json) || typeof json.result !== "string") {
222
+ throw new Error("Felix relay did not acknowledge the transaction");
223
+ }
224
+ if (json.result.toLowerCase() !== keccak256(raw).toLowerCase()) {
225
+ throw new Error("Felix relay acknowledged a different transaction hash");
226
+ }
227
+ return json.result;
228
+ },
229
+ };
230
+ }
231
+ // ------------------------------------------------------------------ arc reads
232
+ export function arcReadPort(url, fetchImpl = fetch) {
233
+ const finalizedBlock = async () => {
234
+ const block = await jsonRpc(fetchImpl, url, "eth_getBlockByNumber", ["finalized", false]);
235
+ if (!isRecord(block))
236
+ throw new Error("finalized block unavailable");
237
+ return Number(quantity(block.number, "finalized block"));
238
+ };
239
+ return {
240
+ finalizedBlock,
241
+ async usdcBalance(address, block) {
242
+ const data = encodeFunctionData({ abi: ERC20_ABI, functionName: "balanceOf", args: [address] });
243
+ return quantity(await jsonRpc(fetchImpl, url, "eth_call", [{ to: HL_ARC_CHAIN.ARC_USDC, data }, toHex(block)]), "balance");
244
+ },
245
+ async mintReceipt(hash) {
246
+ const r = await jsonRpc(fetchImpl, url, "eth_getTransactionReceipt", [hash]);
247
+ if (r === null)
248
+ return null;
249
+ if (!isRecord(r) || !Array.isArray(r.logs))
250
+ throw new Error("receipt malformed");
251
+ const blockNumber = Number(quantity(r.blockNumber, "block"));
252
+ const head = await finalizedBlock();
253
+ const transfers = [];
254
+ const nativeTransfers = [];
255
+ for (const log of r.logs) {
256
+ if (!isRecord(log))
257
+ continue;
258
+ const emitter = String(log.address).toLowerCase();
259
+ if (emitter !== HL_ARC_CHAIN.ARC_USDC.toLowerCase() && emitter !== ARC_NATIVE_USDC_EMITTER)
260
+ continue;
261
+ try {
262
+ const ev = decodeEventLog({ abi: ERC20_ABI, data: log.data, topics: log.topics });
263
+ if (ev.eventName !== "Transfer")
264
+ continue;
265
+ const args = ev.args;
266
+ (emitter === ARC_NATIVE_USDC_EMITTER ? nativeTransfers : transfers).push({
267
+ token: emitter === ARC_NATIVE_USDC_EMITTER ? ARC_NATIVE_USDC_EMITTER : HL_ARC_CHAIN.ARC_USDC,
268
+ from: args.from, to: args.to, value: args.value,
269
+ });
270
+ }
271
+ catch { /* not a Transfer */ }
272
+ }
273
+ return { success: r.status === "0x1", finalized: blockNumber <= head, block_number: blockNumber,
274
+ usdc_transfers: transfers, native_usdc_transfers: nativeTransfers };
275
+ },
276
+ };
277
+ }
278
+ // ------------------------------------------------- arc reads through Felix
279
+ export function felixArcCreditPort(api, accountId) {
280
+ const read = async (operationId) => {
281
+ const out = await api("GET", `/v1/arc-home/operations/${encodeURIComponent(operationId)}/arc-credit?account_id=${encodeURIComponent(accountId)}`);
282
+ const meta = isRecord(out._meta) ? out._meta : {};
283
+ if (out.ok === false || meta.http_status !== 200 || out.operation_id !== operationId
284
+ || out.source !== "felix_arc_strict_majority_read") {
285
+ throw new Error("Felix Arc credit read unavailable");
286
+ }
287
+ return out;
288
+ };
289
+ const int = (v, what) => {
290
+ if (typeof v !== "number" || !Number.isSafeInteger(v) || v < 0)
291
+ throw new Error(`${what} invalid`);
292
+ return v;
293
+ };
294
+ const units = (v, what) => {
295
+ if (typeof v !== "string" || !/^\d+$/.test(v))
296
+ throw new Error(`${what} invalid`);
297
+ return BigInt(v);
298
+ };
299
+ return {
300
+ finalizedBlock: async (operationId) => int((await read(operationId)).finalized_block, "finalized block"),
301
+ async mintReceipt(hash, operationId) {
302
+ const view = await read(operationId);
303
+ // Only the row's own recorded mint is ever served; any other hash is a
304
+ // mismatch, never a lookup.
305
+ if (String(view.mint_tx_hash || "").toLowerCase() !== hash.toLowerCase()) {
306
+ throw new Error("Felix reports a different mint for this row");
307
+ }
308
+ const r = view.mint_receipt;
309
+ if (r === null)
310
+ return null;
311
+ if (!isRecord(r) || typeof r.success !== "boolean" || typeof r.finalized !== "boolean"
312
+ || !Array.isArray(r.usdc_transfers) || !Array.isArray(r.native_usdc_transfers)) {
313
+ throw new Error("Felix Arc receipt malformed");
314
+ }
315
+ return {
316
+ success: r.success, finalized: r.finalized, block_number: int(r.block_number, "mint block"),
317
+ usdc_transfers: r.usdc_transfers.map((t) => {
318
+ if (!isRecord(t))
319
+ throw new Error("Felix Arc transfer malformed");
320
+ return { token: String(t.token), from: String(t.from), to: String(t.to), value: units(t.value, "transfer value") };
321
+ }),
322
+ native_usdc_transfers: r.native_usdc_transfers.map((t) => {
323
+ if (!isRecord(t) || String(t.token).toLowerCase() !== ARC_NATIVE_USDC_EMITTER) {
324
+ throw new Error("Felix Arc native transfer malformed");
325
+ }
326
+ return { token: ARC_NATIVE_USDC_EMITTER, from: String(t.from), to: String(t.to),
327
+ value: units(t.value, "native transfer value") };
328
+ }),
329
+ };
330
+ },
331
+ async usdcBalance(address, block, operationId) {
332
+ const view = await read(operationId);
333
+ const bal = view.safe_usdc_balance;
334
+ if (!isRecord(bal) || String(view.safe || "").toLowerCase() !== address.toLowerCase()) {
335
+ throw new Error("Felix serves only the home Safe's balance around a finalized mint");
336
+ }
337
+ if (block === bal.before_block)
338
+ return units(bal.before_units, "balance");
339
+ if (block === bal.at_block)
340
+ return units(bal.at_units, "balance");
341
+ throw new Error("Felix did not read this block");
342
+ },
343
+ };
344
+ }
345
+ export function productionHlArcPorts(input) {
346
+ const signer = settlementSignerPort();
347
+ if (!signer)
348
+ return { error: "hl_return_local_signer_unavailable" };
349
+ let endpoints;
350
+ try {
351
+ endpoints = resolveHlArcEndpoints(input.env);
352
+ }
353
+ catch (error) {
354
+ return { error: `hl_return_endpoint_invalid: ${error.message}` };
355
+ }
356
+ const fetchImpl = input.fetchImpl ?? fetch;
357
+ return {
358
+ api: input.api,
359
+ signer,
360
+ hyperliquid: hyperliquidPort(endpoints.hyperliquid, fetchImpl),
361
+ arbitrum: arbitrumReadPort(endpoints.arbitrumRpc, fetchImpl),
362
+ arbitrumBroadcast: input.access ? arbitrumBroadcastPort(input.access, fetchImpl) : null,
363
+ arc: endpoints.arcRpc ? arcReadPort(endpoints.arcRpc, fetchImpl) : felixArcCreditPort(input.api, input.accountId),
364
+ journal: input.journal,
365
+ };
366
+ }