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.
@@ -0,0 +1,30 @@
1
+ import { RELAY_FILL_EXTRA_DATA } from "./arc-hypercore-return.js";
2
+ import { RELAY_TRUSTED_SOLVERS } from "./arc-pm-return.js";
3
+ /** Operator acceptance of the Arc Relay depository runtime (A4_ENABLEMENT 2026-09-27). */
4
+ export const ARC_DEPOSITORY_TRUST_ACCEPTED = true;
5
+ /** The Relay EVM fill word on the Arc refund leg (engine RELAY_ARC_REFUND_EXTRA_DATA). */
6
+ export const ARC_REFUND_EXTRA_DATA = RELAY_FILL_EXTRA_DATA;
7
+ export function hypercoreAppPolicy() {
8
+ return Object.freeze({
9
+ trustedSolvers: Object.freeze([...RELAY_TRUSTED_SOLVERS]),
10
+ arcRefundExtraData: ARC_REFUND_EXTRA_DATA,
11
+ verifyDepositoryRuntime: async () => ARC_DEPOSITORY_TRUST_ACCEPTED,
12
+ // Felix's prepared SafeTx carries the nonce its quorum read; the Safe itself refuses
13
+ // any other nonce on chain, and the driver signs one SafeTx per journaled key.
14
+ verifySafeState: async () => true,
15
+ verifyExecutionFailure: null,
16
+ });
17
+ }
18
+ export function hypercoreReturnAppPolicy() {
19
+ return Object.freeze({
20
+ trustedSolvers: Object.freeze([...RELAY_TRUSTED_SOLVERS]),
21
+ relayExtraData: RELAY_FILL_EXTRA_DATA,
22
+ // Called only with a claim the driver has already bound to this order, its solver
23
+ // and the signed credit bounds; completion reporting only, never a money decision.
24
+ verifyHomeCredit: async () => true,
25
+ });
26
+ }
27
+ // invalidate_safe_nonce is deliberately NOT on the app model (Astra BLOCK 2026-11-15): a
28
+ // Felix-attested "no-op executed" could let a stuck SafeTx and its replacement both run.
29
+ // It keeps the empty shipped policy and refuses before any request until a verified chain
30
+ // check exists; stuck Safe nonces are released in the Felix app meanwhile.
package/dist/funding.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { requireRpc } from "./rpc-endpoints.js";
1
2
  import { redactOutput } from "./redact-output.js";
2
3
  import { createPublicClient, createWalletClient, decodeEventLog, decodeFunctionData, defineChain, encodeFunctionData, getAddress, hashTypedData, http, keccak256, parseSignature, parseAbi, } from "viem";
3
4
  import { privateKeyToAccount } from "viem/accounts";
@@ -38,6 +39,19 @@ const DERIVE_WITHDRAW_MIN_UNITS = 500000n;
38
39
  // or misconfigured connector can never turn a bridge into an unbounded spend.
39
40
  const MAX_DERIVE_BRIDGE_FEE_WEI = 1000000000000000n;
40
41
  const FELIX_TREASURY_POLYGON = getAddress("0xDC9C35bF585fba2a39bcd17bDfE343277B595CaD");
42
+ // Engine 118d533: arc_fee_treasury and _prepare_arc_fee_credit_topup.
43
+ const ARC_FEE_CHAIN_ID = 5042;
44
+ const ARC_FEE_USDC = getAddress("0x3600000000000000000000000000000000000000");
45
+ const ARC_FEE_TREASURY = FELIX_TREASURY_POLYGON;
46
+ const ARC_FEE_MAX_GAS = 100000n;
47
+ const ARC_FEE_MAX_FEE_PER_GAS = 200000000000n;
48
+ const ARC_FEE_TTL_MS = 10 * 60_000;
49
+ const arcFeeChain = defineChain({
50
+ id: ARC_FEE_CHAIN_ID,
51
+ name: "Arc",
52
+ nativeCurrency: { name: "USDC", symbol: "USDC", decimals: 18 },
53
+ rpcUrls: { default: { http: [] } },
54
+ });
41
55
  const GAS_FEE_WALLET = getAddress("0x50BcAF3C79860B9BB2DFb2e8c4097180B00159a5");
42
56
  // FEE_RECIPIENT_ALIGNMENT_2026_09_22. The server's fee recipient moved to the
43
57
  // configured treasury (TREASURY_ADDRESS), and its own allow-list is
@@ -110,14 +124,17 @@ const RELAY_HL_USDC_ASSET = "USDC:0x6d1e7cde53ba9467b783cb7c530ce054";
110
124
  const RELAY_AUTHORIZE_URL = "https://api.relay.link/authorize";
111
125
  const HYPERLIQUID_EXCHANGE_URL = "https://api.hyperliquid.xyz/exchange";
112
126
  const RELAY_MINIMUM_RECEIVE_BPS = 9000n;
113
- const POLYGON_RPC = process.env.FELIX_POLYGON_RPC_URL || "https://polygon-bor-rpc.publicnode.com";
114
- const ARBITRUM_RPC = process.env.FELIX_ARBITRUM_RPC_URL || "https://arbitrum-one-rpc.publicnode.com";
115
- const DERIVE_RPC = process.env.FELIX_DERIVE_RPC_URL || "https://rpc.derive.xyz/";
127
+ // NO_PUBLIC_RPC_20261115: funding goes through Felix's authenticated, intent-bound RPC
128
+ // relay (fundingTransport). A direct chain RPC is used only when there is no relay and
129
+ // then only the user's own FELIX_<CHAIN>_RPC_URL, resolved at the call; never a public RPC.
130
+ const POLYGON_RPC = () => requireRpc("polygon");
131
+ const ARBITRUM_RPC = () => requireRpc("arbitrum");
132
+ const DERIVE_RPC = () => requireRpc("derive");
116
133
  const derive = defineChain({
117
134
  id: DERIVE_CHAIN_ID,
118
135
  name: "Derive",
119
136
  nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
120
- rpcUrls: { default: { http: [DERIVE_RPC] } },
137
+ rpcUrls: { default: { http: [] } },
121
138
  });
122
139
  const ERC20 = parseAbi([
123
140
  "function balanceOf(address owner) view returns (uint256)",
@@ -430,6 +447,13 @@ export async function waitForRelayedFundingSubmission(prepared, transactionHash,
430
447
  }
431
448
  }
432
449
  export async function polygonFundingNonceUnchanged(prepared, expectedNonce, access, privateKey) {
450
+ if (prepared.operation === "fee_credit_topup"
451
+ && (prepared.settlement_home === "arc" || prepared.chain_id === ARC_FEE_CHAIN_ID)) {
452
+ // Arc checkpoints are evidence-only: never consult Polygon or sign a new nonce.
453
+ // Returning false sends ONLY the journaled hash to fees/confirm, whose
454
+ // sealed-intent finalized proof remains authoritative.
455
+ return false;
456
+ }
433
457
  assertPolygonFundingRecoveryIntent(prepared, privateKey);
434
458
  return relayedFundingNonceUnchanged(prepared, expectedNonce, access, privateKey);
435
459
  }
@@ -484,7 +508,7 @@ function fundingTransport(relay, directRpc, intentToken, access, retryCount = 0)
484
508
  throw new Error("Felix funding relay retry count is outside the bounded range.");
485
509
  }
486
510
  if (!access)
487
- return http(directRpc, { retryCount, timeout: 30_000 });
511
+ return http(directRpc(), { retryCount, timeout: 30_000 });
488
512
  const token = text(intentToken, "intent_token");
489
513
  if (token.length > 16_000
490
514
  || !API_KEY_RE.test(access.api_key)
@@ -787,6 +811,9 @@ export async function sendLocallyPreparedTransaction(publicClient, wallet, accou
787
811
  throw new Error("Owner nonce changed since withdrawal preparation. Reconcile or cancel the original operation.");
788
812
  }
789
813
  const { maxFeePerGas, maxPriorityFeePerGas } = polygonFeeCaps(baseFee);
814
+ if (options.maxFeePerGasCeiling !== undefined && maxFeePerGas > options.maxFeePerGasCeiling) {
815
+ throw new Error("The chain fee per gas is above this transaction's reviewed ceiling; nothing was signed.");
816
+ }
790
817
  if (nativeBalance < value + gas * maxFeePerGas) {
791
818
  throw new Error("Owner has insufficient Polygon gas for the locally prepared transaction.");
792
819
  }
@@ -814,6 +841,10 @@ export async function sendLocallyPreparedTransaction(publicClient, wallet, accou
814
841
  publicClient.getBalance({ address: account.address }),
815
842
  publicClient.estimateFeesPerGas(),
816
843
  ]);
844
+ if (options.maxFeePerGasCeiling !== undefined
845
+ && !(feeQuote.maxFeePerGas !== undefined && feeQuote.maxFeePerGas <= options.maxFeePerGasCeiling)) {
846
+ throw new Error("The chain fee per gas is above this transaction's reviewed ceiling; nothing was signed.");
847
+ }
817
848
  if (feeQuote.maxFeePerGas && feeQuote.maxPriorityFeePerGas !== undefined) {
818
849
  if (nativeBalance < value + gas * feeQuote.maxFeePerGas) {
819
850
  throw new Error("Owner has insufficient native gas for the locally prepared transaction.");
@@ -2329,19 +2360,60 @@ export async function executeNativeUsdcSwap(prepared, expectedAmountUsd, access,
2329
2360
  hashes.push(swapHash);
2330
2361
  return { transaction_hashes: hashes };
2331
2362
  }
2332
- export function inspectFeeSettlementIntent(prepared, expectedAmountUsd) {
2333
- if (expectedAmountUsd !== undefined) {
2334
- assertExpectedAmount(prepared, expectedAmountUsd, "fee_credit_topup");
2363
+ function feeSettlementUnits(value, field) {
2364
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0
2365
+ || value > PRACTICAL_NO_CAP_USD) {
2366
+ throw new Error(`Felix execution-fee top-up has an invalid ${field}.`);
2335
2367
  }
2368
+ const units = Math.round(value * 1_000_000);
2369
+ if (!Number.isSafeInteger(units) || units / 1_000_000 !== value) {
2370
+ throw new Error(`Felix execution-fee top-up has a non-exact ${field}.`);
2371
+ }
2372
+ return BigInt(units);
2373
+ }
2374
+ export function inspectFeeSettlementIntent(prepared, expectedAmountUsd) {
2336
2375
  const { account } = assertOwner(prepared);
2337
2376
  const sourceToken = address(prepared.source_token, "source_token");
2338
2377
  const fixedRecipient = address(prepared.fixed_recipient, "fixed_recipient");
2339
- const chainId = Number(prepared.chain_id);
2340
- if (text(prepared.operation, "operation") !== "fee_credit_topup" || chainId !== polygon.id
2341
- || sourceToken !== USDC_E_POLYGON || fixedRecipient !== FELIX_TREASURY_POLYGON) {
2378
+ const chainId = prepared.chain_id;
2379
+ const isArc = chainId === ARC_FEE_CHAIN_ID && prepared.settlement_home === "arc";
2380
+ const isPolygon = chainId === polygon.id
2381
+ && (prepared.settlement_home === undefined || prepared.settlement_home === "polygon");
2382
+ if (prepared.operation !== "fee_credit_topup"
2383
+ || (!isArc && !isPolygon)
2384
+ || sourceToken !== (isArc ? ARC_FEE_USDC : USDC_E_POLYGON)
2385
+ || fixedRecipient !== (isArc ? ARC_FEE_TREASURY : FELIX_TREASURY_POLYGON)) {
2342
2386
  throw new Error("Felix returned an unexpected execution-fee top-up route.");
2343
2387
  }
2344
- const amount = amountUnits(prepared);
2388
+ const amount = feeSettlementUnits(prepared.amount_usd, "amount_usd");
2389
+ if (amount < 100000n
2390
+ || (prepared.amount_units !== undefined && prepared.amount_units !== amount.toString())
2391
+ || (expectedAmountUsd !== undefined
2392
+ && amount !== feeSettlementUnits(expectedAmountUsd, "requested amount"))) {
2393
+ throw new Error("Felix changed the requested execution-fee top-up amount.");
2394
+ }
2395
+ if (isArc) {
2396
+ const expiry = Date.parse(text(prepared.expires_at, "expires_at"));
2397
+ const before = feeSettlementUnits(prepared.source_balance_before_usd, "source balance");
2398
+ const after = feeSettlementUnits(prepared.source_balance_after_usd, "remaining balance");
2399
+ const reserve = feeSettlementUnits(prepared.minimum_gas_reserve_usd, "gas reserve");
2400
+ if (prepared.ok !== true || prepared.status !== undefined || prepared.executable === false
2401
+ || prepared.collection_model !== "prepaid_before_live_execution"
2402
+ || prepared.gas_token !== "USDC"
2403
+ || typeof prepared.intent_id !== "string" || !UUID_RE.test(prepared.intent_id)
2404
+ || typeof prepared.intent_token !== "string" || !prepared.intent_token.trim()
2405
+ || prepared.intent_token !== prepared.intent_token.trim() || prepared.intent_token.length > 16_000
2406
+ || !/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,6})?(?:Z|\+00:00)$/.test(String(prepared.expires_at))
2407
+ || expiry > Date.now() + ARC_FEE_TTL_MS + 60_000
2408
+ || before - amount !== after
2409
+ || reserve < ARC_FEE_MAX_GAS * ARC_FEE_MAX_FEE_PER_GAS / 1000000000000n
2410
+ || after < reserve || prepared.gas_reserve_shortfall_usd !== 0
2411
+ || typeof prepared.would_reduce_owner_trading_buffer !== "boolean"
2412
+ || typeof prepared.low_owner_buffer_override_used !== "boolean"
2413
+ || (prepared.would_reduce_owner_trading_buffer && !prepared.low_owner_buffer_override_used)) {
2414
+ throw new Error("Felix returned an invalid prepaid Arc execution-fee intent.");
2415
+ }
2416
+ }
2345
2417
  const configuredCap = Number(process.env.FELIX_MAX_FEE_SETTLEMENT_USD || "100");
2346
2418
  const feeCap = Number.isFinite(configuredCap) ? Math.min(1_000, Math.max(1, configuredCap)) : 100;
2347
2419
  if (amount > BigInt(Math.round(feeCap * 1_000_000))) {
@@ -2357,19 +2429,114 @@ export function inspectFeeSettlementIntent(prepared, expectedAmountUsd) {
2357
2429
  };
2358
2430
  }
2359
2431
  export async function executeFeeSettlement(prepared, callbacks = {}) {
2432
+ prepared = { ...prepared };
2360
2433
  const intent = inspectFeeSettlementIntent(prepared, callbacks.expectedAmountUsd);
2434
+ const isArc = intent.chain_id === ARC_FEE_CHAIN_ID;
2435
+ if (isArc && (callbacks.expectedAmountUsd === undefined
2436
+ || typeof callbacks.beforeBroadcast !== "function"
2437
+ || typeof callbacks.onSubmitted !== "function")) {
2438
+ throw new Error("Arc execution-fee signing requires the requested amount and durable journal callbacks.");
2439
+ }
2361
2440
  const account = privateKeyToAccount(ownerKey());
2362
- const amount = BigInt(Math.round(intent.amount_usd * 1_000_000));
2363
- const publicClient = createPublicClient({ chain: polygon, transport: http(POLYGON_RPC) });
2364
- const wallet = createWalletClient({ account, chain: polygon, transport: http(POLYGON_RPC) });
2441
+ const amount = feeSettlementUnits(intent.amount_usd, "amount_usd");
2442
+ const chain = isArc ? arcFeeChain : polygon;
2443
+ const transport = isArc
2444
+ ? fundingTransport("arc", () => requireRpc("arc"), prepared.intent_token, callbacks.access, 0)
2445
+ : http(POLYGON_RPC(), { retryCount: 0, timeout: 15_000 });
2446
+ const publicClient = createPublicClient({ chain, transport });
2447
+ const wallet = createWalletClient({ account, chain, transport });
2448
+ if (isArc) {
2449
+ if (await publicClient.getChainId() !== ARC_FEE_CHAIN_ID) {
2450
+ throw new Error("The execution-fee RPC is not Arc mainnet.");
2451
+ }
2452
+ // Arc's ERC20 USDC and 18-decimal native gas share the SAME balance.
2453
+ const native = await publicClient.getBalance({ address: account.address });
2454
+ if (native < amount * 1000000000000n + ARC_FEE_MAX_GAS * ARC_FEE_MAX_FEE_PER_GAS) {
2455
+ throw new Error("The Arc execution-fee top-up would spend its native USDC gas reserve.");
2456
+ }
2457
+ }
2365
2458
  await assertFreshOwnerSource(publicClient, account.address, intent.source_token, prepared);
2366
- const hash = await sendLocallyPreparedTransaction(publicClient, wallet, account, polygon, intent.source_token, encodeFunctionData({
2459
+ inspectFeeSettlementIntent(prepared, callbacks.expectedAmountUsd);
2460
+ const data = encodeFunctionData({
2367
2461
  abi: ERC20, functionName: "transfer", args: [intent.fixed_recipient, amount],
2368
- }), { maxGas: 200000n, expectedNonce: callbacks.expectedNonce, beforeBroadcast: callbacks.beforeBroadcast });
2462
+ });
2463
+ const hash = await sendLocallyPreparedTransaction(publicClient, wallet, account, chain, intent.source_token, data, {
2464
+ maxGas: isArc ? ARC_FEE_MAX_GAS : 200000n,
2465
+ expectedNonce: isArc ? undefined : callbacks.expectedNonce,
2466
+ ...(isArc ? { maxFeePerGasCeiling: ARC_FEE_MAX_FEE_PER_GAS } : {}),
2467
+ beforeBroadcast: (submission) => {
2468
+ inspectFeeSettlementIntent(prepared, callbacks.expectedAmountUsd);
2469
+ const saved = callbacks.beforeBroadcast?.(submission);
2470
+ if (isArc && saved && typeof saved.then === "function") {
2471
+ throw new Error("The Arc execution-fee journal checkpoint must complete synchronously.");
2472
+ }
2473
+ },
2474
+ });
2369
2475
  await callbacks.onSubmitted?.(hash);
2370
- await wait(publicClient, hash);
2476
+ if (isArc) {
2477
+ await waitArcFeeSettlement(publicClient, prepared, hash, data, amount);
2478
+ }
2479
+ else {
2480
+ await wait(publicClient, hash);
2481
+ }
2371
2482
  return hash;
2372
2483
  }
2484
+ async function waitArcFeeSettlement(client, prepared, hash, data, amount) {
2485
+ const receipt = await client.waitForTransactionReceipt({ hash, timeout: 180_000, pollingInterval: 1_000 });
2486
+ const tx = await client.getTransaction({ hash });
2487
+ const block = await client.getBlock({ blockNumber: receipt.blockNumber });
2488
+ const finalized = await client.getBlock({ blockTag: "finalized" });
2489
+ const same = (a, b) => typeof a === "string" && typeof b === "string"
2490
+ && a.toLowerCase() === b.toLowerCase();
2491
+ const expiry = Date.parse(String(prepared.expires_at));
2492
+ const minedMs = Number(block.timestamp) * 1_000;
2493
+ if (await client.getChainId() !== ARC_FEE_CHAIN_ID
2494
+ || receipt.status !== "success" || !same(receipt.transactionHash, hash)
2495
+ || typeof receipt.blockNumber !== "bigint" || receipt.blockNumber < 0n
2496
+ || !same(tx.hash, hash) || tx.chainId !== ARC_FEE_CHAIN_ID
2497
+ || !same(tx.from, prepared.owner_address) || !same(receipt.from, prepared.owner_address)
2498
+ || !same(tx.to, ARC_FEE_USDC) || !same(receipt.to, ARC_FEE_USDC)
2499
+ || tx.value !== 0n || !same(tx.input, data)
2500
+ || !/^0x[0-9a-f]{64}$/i.test(String(receipt.blockHash))
2501
+ || tx.blockNumber !== receipt.blockNumber || block.number !== receipt.blockNumber
2502
+ || !same(tx.blockHash, receipt.blockHash) || !same(block.hash, receipt.blockHash)
2503
+ || typeof finalized.number !== "bigint" || finalized.number < receipt.blockNumber
2504
+ || !/^0x[0-9a-f]{64}$/i.test(String(finalized.hash))
2505
+ || (finalized.number === receipt.blockNumber && !same(finalized.hash, receipt.blockHash))
2506
+ || !Number.isSafeInteger(minedMs) || minedMs > Date.now() || minedMs > expiry
2507
+ || minedMs < Math.floor((expiry - ARC_FEE_TTL_MS) / 1_000) * 1_000
2508
+ || !Array.isArray(receipt.logs) || receipt.logs.length > 1024) {
2509
+ throw new Error("Arc execution-fee receipt is not exact canonical finalized intent evidence; reconcile the saved hash.");
2510
+ }
2511
+ const indices = new Set();
2512
+ let transfers = 0;
2513
+ for (const log of receipt.logs) {
2514
+ if (log.logIndex === null || !Number.isSafeInteger(log.logIndex) || log.logIndex < 0
2515
+ || indices.has(log.logIndex) || log.removed !== false
2516
+ || !same(log.transactionHash, hash) || !same(log.blockHash, receipt.blockHash)
2517
+ || log.blockNumber !== receipt.blockNumber || log.topics.length > 4) {
2518
+ throw new Error("Arc execution-fee receipt has malformed or replayed logs.");
2519
+ }
2520
+ indices.add(log.logIndex);
2521
+ if (!same(log.address, ARC_FEE_USDC)
2522
+ || !same(log.topics[0], keccak256(new TextEncoder().encode("Transfer(address,address,uint256)"))))
2523
+ continue;
2524
+ const event = decodeEventLog({ abi: ERC20, eventName: "Transfer", data: log.data, topics: log.topics, strict: true });
2525
+ if (log.topics.length !== 3 || log.data.length !== 66
2526
+ || !same(log.topics[1], `0x${String(prepared.owner_address).slice(2).padStart(64, "0")}`)
2527
+ || !same(log.topics[2], `0x${ARC_FEE_TREASURY.slice(2).padStart(64, "0")}`)
2528
+ || !same(event.args.from, prepared.owner_address) || !same(event.args.to, ARC_FEE_TREASURY)
2529
+ || event.args.value !== amount) {
2530
+ throw new Error("Arc execution-fee transfer log does not match its fixed intent.");
2531
+ }
2532
+ transfers += 1;
2533
+ }
2534
+ if (transfers !== 1)
2535
+ throw new Error("Arc execution-fee receipt is missing one unambiguous transfer.");
2536
+ // This is local evidence only, never prepaid credit. The engine still binds
2537
+ // the sealed creation time and requires two agreeing finalized RPC origins
2538
+ // before its chain-scoped atomic receipt claim can credit this account.
2539
+ }
2373
2540
  // DERIVE_RETURN_BRIDGE_2026_08_06: the missing bridge leg for bring_home
2374
2541
  // (options). A Derive venue withdrawal lands USDC in the owner EOA on Derive's
2375
2542
  // chain; these helpers move it owner -> owner to Arbitrum over the same Socket
@@ -2382,7 +2549,7 @@ function localOwnerAccount() {
2382
2549
  }
2383
2550
  export async function readDeriveOwnerReturnState() {
2384
2551
  const owner = localOwnerAccount().address;
2385
- const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC) });
2552
+ const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC()) });
2386
2553
  const [usdcUnits, ethWei] = await Promise.all([
2387
2554
  publicClient.readContract({
2388
2555
  address: DERIVE_USDC, abi: ERC20, functionName: "balanceOf", args: [owner],
@@ -2392,7 +2559,7 @@ export async function readDeriveOwnerReturnState() {
2392
2559
  return { owner, usdcUnits, ethWei };
2393
2560
  }
2394
2561
  export async function readArbitrumOwnerUsdcUnits(owner) {
2395
- const publicClient = createPublicClient({ chain: arbitrum, transport: http(ARBITRUM_RPC) });
2562
+ const publicClient = createPublicClient({ chain: arbitrum, transport: http(ARBITRUM_RPC()) });
2396
2563
  return publicClient.readContract({
2397
2564
  address: USDC_ARBITRUM, abi: ERC20, functionName: "balanceOf", args: [owner],
2398
2565
  });
@@ -2413,7 +2580,7 @@ export function deriveBridgeFeeWithinSafetyBound(messageFeeWei) {
2413
2580
  }
2414
2581
  export async function readDeriveReturnGasState() {
2415
2582
  const owner = localOwnerAccount().address;
2416
- const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC) });
2583
+ const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC()) });
2417
2584
  const [nativeBalance, messageFee, gasPrice] = await Promise.all([
2418
2585
  publicClient.getBalance({ address: owner }),
2419
2586
  publicClient.readContract({
@@ -2442,7 +2609,7 @@ export async function deriveFundingNonceUnchanged(expectedNonce) {
2442
2609
  throw new Error("The Derive recovery nonce is invalid.");
2443
2610
  }
2444
2611
  const owner = localOwnerAccount().address;
2445
- const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC) });
2612
+ const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC()) });
2446
2613
  const [latestNonce, pendingNonce] = await Promise.all([
2447
2614
  publicClient.getTransactionCount({ address: owner, blockTag: "latest" }),
2448
2615
  publicClient.getTransactionCount({ address: owner, blockTag: "pending" }),
@@ -2453,7 +2620,7 @@ export async function waitForDeriveFundingSubmission(transactionHash, timeoutMs
2453
2620
  if (!/^0x[0-9a-f]{64}$/i.test(transactionHash)) {
2454
2621
  throw new Error("The Derive recovery transaction hash is invalid.");
2455
2622
  }
2456
- const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC) });
2623
+ const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC()) });
2457
2624
  try {
2458
2625
  const receipt = await publicClient.waitForTransactionReceipt({
2459
2626
  hash: transactionHash,
@@ -2469,8 +2636,8 @@ export async function waitForDeriveFundingSubmission(transactionHash, timeoutMs
2469
2636
  export async function executeDeriveChainWithdrawal(requestedUnits, callbacks = {}) {
2470
2637
  const account = localOwnerAccount();
2471
2638
  const owner = account.address;
2472
- const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC) });
2473
- const wallet = createWalletClient({ account, chain: derive, transport: http(DERIVE_RPC) });
2639
+ const publicClient = createPublicClient({ chain: derive, transport: http(DERIVE_RPC()) });
2640
+ const wallet = createWalletClient({ account, chain: derive, transport: http(DERIVE_RPC()) });
2474
2641
  const linkedToken = await publicClient.readContract({
2475
2642
  address: DERIVE_WITHDRAW_CONTROLLER, abi: DERIVE_WITHDRAW_CONTROLLER_ABI, functionName: "token__",
2476
2643
  });
@@ -10,10 +10,15 @@ the current legal bundle at https://felix.trade/legal before accepting it.
10
10
 
11
11
  ### New local MCP user: start here
12
12
 
13
- Let your AI agent run this single command:
13
+ Already connected to this MCP? Call the \`onboard\` tool. Felix asks the owner
14
+ to accept the terms (in the client's own question when it has one; otherwise
15
+ the agent asks in chat and macOS shows one confirmation the owner clicks),
16
+ then creates the identity and loads it into the session with no restart.
17
+
18
+ Or let your AI agent run this single command:
14
19
 
15
20
  ~~~bash
16
- npx -y --package felix-mcp@2.0.123 felix-keys onboard --accept-terms --client claude
21
+ npx -y --package felix-mcp@2.0.129 felix-keys onboard --accept-terms --client claude
17
22
  ~~~
18
23
 
19
24
  After the user reviews the terms and explicitly authorizes acceptance, the agent
@@ -124,6 +129,11 @@ To move money in or out of the Arc home Safe itself, use 'arc_home_withdraw',
124
129
  lands native USDC in the Polygon owner wallet, then call 'fund_market'). These
125
130
  are owner-signed, need an 'idempotency_key', and are not live-certified yet.
126
131
  Recover with 'get_arc_home_operation' and 'reconcile_arc_home_operation'.
132
+ Between the Arc home Safe and your own Hyperliquid perps (the moves the app
133
+ uses, 5 to 25 USDC each, Relay, owner-signed locally): 'fund_hypercore_from_arc'
134
+ (Home to perps; a separate 1.00 USDC Felix fee) and 'arc_home_hypercore_return'
135
+ (perps to Home; no Felix fee). Select the account with 'use_child_account'
136
+ first; reuse the same 'idempotency_key' after any timeout.
127
137
  Guided onboarding already created the encrypted recovery file; require
128
138
  'get_custody_recovery_status.ready: true' before depositing meaningful funds.
129
139
 
@@ -16,11 +16,12 @@
16
16
  * explicitly and unambiguously attributed (review B3).
17
17
  */
18
18
  import { createServer } from "node:http";
19
+ import { isIP } from "node:net";
19
20
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
20
21
  import { clientAddress, createRateLimiter, forwardingPolicy, rateSubjects } from "./http-rate-subject.js";
21
22
  // Must be set before importing index.ts so its stdio bin entry does not start.
22
23
  process.env.FELIX_MCP_TRANSPORT = "http";
23
- const { makeServer, keyStore, validatedApiBase } = await import("./index.js");
24
+ const { makeServer, keyStore, validatedApiBase, HOSTED_CLIENT_IP_HEADER } = await import("./index.js");
24
25
  const API = validatedApiBase();
25
26
  function boundedEnvInt(name, fallback, min, max) {
26
27
  const parsed = Number(process.env[name]);
@@ -78,11 +79,23 @@ function reject(res, status, code, headers = {}) {
78
79
  res.writeHead(status, { "content-type": "application/json", "connection": "close", ...headers });
79
80
  res.end(JSON.stringify({ error: code }));
80
81
  }
82
+ /** The caller address to forward to a loopback engine hop, if the proxy attributed one. */
83
+ function forwardableClientIp(req) {
84
+ if (!HOSTED_CLIENT_IP_HEADER)
85
+ return undefined;
86
+ const address = clientAddress(FORWARDING, req.socket.remoteAddress, req.headers);
87
+ if (!address.attributed || !isIP(address.ip))
88
+ return undefined;
89
+ return LOOPBACK_HOSTS.has(address.ip) || address.ip.startsWith("127.") ? undefined : address.ip;
90
+ }
81
91
  /** Validate with the same read used by local credential recovery; never cache revocations. */
82
- async function authenticate(key, signal) {
92
+ async function authenticate(key, signal, clientIp) {
83
93
  try {
94
+ const headers = { Authorization: `Bearer ${key}`, Accept: "application/json" };
95
+ if (clientIp)
96
+ headers[HOSTED_CLIENT_IP_HEADER] = clientIp;
84
97
  const response = await fetch(`${API}/v1/me/subscription`, {
85
- headers: { Authorization: `Bearer ${key}`, Accept: "application/json" },
98
+ headers,
86
99
  signal: AbortSignal.any([signal, AbortSignal.timeout(AUTH_TIMEOUT_MS)]),
87
100
  redirect: "error",
88
101
  });
@@ -100,9 +113,12 @@ async function authenticate(key, signal) {
100
113
  if (!response.ok)
101
114
  throw new RequestError(503, "auth_unavailable");
102
115
  const identity = await response.json();
103
- // routes_platform.my_subscription returns ok and key_access for both paper
104
- // and live keys. Never infer authentication from a proxy's 200 error page.
105
- if (identity?.ok !== true || typeof identity.key_access?.account_id !== "string"
116
+ // routes_platform.my_subscription returns key_access (account_id + scopes)
117
+ // for both paper and live keys; the live envelope carries no top-level ok.
118
+ // Require that identity, never a bare 200 (a proxy error page has none),
119
+ // and still honour an explicit ok:false.
120
+ if (!identity || typeof identity !== "object" || identity.ok === false
121
+ || typeof identity.key_access?.account_id !== "string"
106
122
  || !Array.isArray(identity.key_access?.scopes)
107
123
  || !identity.key_access.scopes.includes("read")) {
108
124
  throw new RequestError(503, "auth_unavailable");
@@ -247,7 +263,8 @@ const httpServer = createServer(async (req, res) => {
247
263
  if (String(req.headers["content-type"] || "").split(";", 1)[0].trim().toLowerCase() !== "application/json") {
248
264
  throw new RequestError(415, "content_type_must_be_application_json");
249
265
  }
250
- await authenticate(key, controller.signal);
266
+ const clientIp = forwardableClientIp(req);
267
+ await authenticate(key, controller.signal, clientIp);
251
268
  if (controller.signal.aborted)
252
269
  return;
253
270
  const bodyDeadline = setTimeout(() => {
@@ -278,7 +295,7 @@ const httpServer = createServer(async (req, res) => {
278
295
  sessionIdGenerator: undefined,
279
296
  enableJsonResponse: true,
280
297
  });
281
- await keyStore.run({ key, signal: controller.signal }, async () => {
298
+ await keyStore.run({ key, signal: controller.signal, clientIp }, async () => {
282
299
  await requestServer.connect(requestTransport);
283
300
  await requestTransport.handleRequest(req, res, body);
284
301
  });