felix-mcp 2.0.129 → 2.0.132

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 CHANGED
@@ -7,7 +7,7 @@
7
7
  Non-custodial trading tools for AI agents across Hyperliquid, Polymarket, and
8
8
  Derive. Live execution is the default; paper mode must be selected explicitly.
9
9
 
10
- Package version: `felix-mcp@2.0.129`. For prepublication review, use the local
10
+ Package version: `felix-mcp@2.0.132`. For prepublication review, use the local
11
11
  tarball below. Packaging checks do not certify live money workflows.
12
12
 
13
13
  ## Hosted (no install)
@@ -48,14 +48,14 @@ node --version
48
48
  npm ci
49
49
  candidate_dir="$(mktemp -d)"
50
50
  npm pack --pack-destination "$candidate_dir"
51
- npm install --global "$candidate_dir/felix-mcp-2.0.129.tgz"
51
+ npm install --global "$candidate_dir/felix-mcp-2.0.132.tgz"
52
52
  felix-keys --help
53
53
  ```
54
54
 
55
55
  After the operator publishes this version, the registry installation is:
56
56
 
57
57
  ```bash
58
- npm install --global felix-mcp@2.0.129
58
+ npm install --global felix-mcp@2.0.132
59
59
  ```
60
60
 
61
61
  ### 2. Set up keys locally
@@ -206,22 +206,25 @@ derive_api_key(paper=true, accept_terms=true, legal_version="2026-10-11")
206
206
  Felix can settle an account on Arc in its owner-controlled Arc home Safe. Read the
207
207
  account's reported home rather than assuming every account uses Arc.
208
208
 
209
- - `get_deposit_address` returns `home_chain` (`arc` or `polygon`). Its top-level
210
- `address` is the Polygon owner wallet. When Arc settlement is active, the
211
- `arc.address` is the verified Arc home Safe; before verification it is `null`
212
- with `onboarding_required: true`. Send Arc USDC only to that verified Safe.
213
- If `arc.admission_frozen` is true, do not start a new Arc deposit; the address
214
- stays visible only so existing transfers can be verified and recovered.
209
+ - Deposits work like the Felix app: every deposit settles as USDC in the
210
+ account's Arc home Safe, which the MCP re-derives from the account's own owner
211
+ key before showing anything. `get_deposit_address` shows the Arc home, the
212
+ deposit steps, accepted tokens (`list_currencies`), a price preview
213
+ (`from_currency` + `from_amount`) and a deposit's status (`request_id`).
214
+ `create_deposit` returns a one-time payment address for any accepted token on
215
+ its own network; `cancel_deposit` closes an unpaid one. USDC already on Arc may
216
+ go straight to `direct_arc_usdc.address`. The MCP never gives out a Polygon
217
+ owner address as a deposit address.
215
218
  - `get_money_map` reports `settlement_home.home_cash_location` as
216
219
  `arc_home_safe` or `owner_wallet_polygon`. Arc locations include
217
220
  `arc_home_safe`, `arc_home_safe_gateway_balance`, `owner_wallet_arc`, and
218
221
  `arc_settlement_in_transit`. The Arc owner wallet is not the Arc home Safe.
219
- - A new account's first `create_account` call uses a Polygon deposit address.
220
- The same workflow now completes owner-signed Arc-home onboarding before
221
- issuing a live key. Fresh-account Arc activation has not yet passed a live
222
- end-to-end canary, so this held release is not launch-certified. If
223
- `arc.onboarding_required` is true, do not send funds on Arc; retry the same
224
- account-creation key or contact support.
222
+ - A new account's first `create_account` call binds its owner and returns
223
+ `account_funding_required` with `deposit_flow` (the app's first deposit into
224
+ the account's not-yet-deployed Arc home Safe, at least $5). After
225
+ `get_deposit_address` reports `funded`, retry `create_account` with the same
226
+ idempotency key; it completes owner-signed Arc-home onboarding before issuing
227
+ a live key.
225
228
  - `fund_market` spends USDC from the Polygon owner wallet, not from the Arc
226
229
  home Safe; Polygon USDC deposits still count as spendable cash. Funding
227
230
  Polymarket or Hyperliquid from Arc home funds has not passed a live canary on
@@ -0,0 +1,366 @@
1
+ // ARC_FIRST_DEPOSIT_MCP_20261117: the app's deposit flow for the MCP.
2
+ //
3
+ // app.felix.trade funds a brand-new account like this: bind the device owner,
4
+ // create one Relay deposit instruction that settles as USDC into the account's
5
+ // counterfactual Arc home Safe, wait for the Arc funding read to report funded,
6
+ // then run Arc onboarding. Every deposit after that settles into the verified
7
+ // Arc home Safe. The MCP never hands out a Polygon owner address.
8
+ //
9
+ // The rule matches the app: the Arc home Safe is re-derived locally from the
10
+ // account's own owner key (CREATE2, predictArcHomeSafe) and every server answer
11
+ // that names it must match, or nothing is shown to the user.
12
+ import { getAddress, isAddress } from "viem";
13
+ import { predictArcHomeSafe } from "./arc-home.js";
14
+ export const ARC_DEPOSIT_CHAIN_ID = 5042;
15
+ export const ARC_FIRST_DEPOSIT_MIN_USD = 5;
16
+ export const RELAY_DEPOSIT_MAX_FROM_AMOUNT = 1e15;
17
+ const REQUEST_ID_RE = /^0x[0-9a-f]{64}$/;
18
+ const EVM_RE = /^0x[0-9a-fA-F]{40}$/;
19
+ const BTC_RE = /^(?:bc1|[13])[a-zA-HJ-NP-Z0-9]{20,90}$/;
20
+ const SOLANA_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
21
+ const CURRENCY_KEY_RE = /^[a-z0-9_.-]{2,80}$/;
22
+ const RELAY_STATUSES = new Set([
23
+ "waiting", "confirming", "exchanging", "sending", "finished", "failed", "refunded", "expired",
24
+ ]);
25
+ export class ArcDepositError extends Error {
26
+ code;
27
+ constructor(code, message) {
28
+ super(message);
29
+ this.code = code;
30
+ }
31
+ }
32
+ function fail(code, message) {
33
+ throw new ArcDepositError(code, message);
34
+ }
35
+ function isRecord(value) {
36
+ return typeof value === "object" && value !== null && !Array.isArray(value);
37
+ }
38
+ function money(value) {
39
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value < 1e12 ? value : undefined;
40
+ }
41
+ function sameAddress(left, right) {
42
+ return typeof left === "string" && EVM_RE.test(left) && left.toLowerCase() === right.toLowerCase();
43
+ }
44
+ /** The Arc home Safe this owner key controls (CREATE2, the same derivation as the app). */
45
+ export function expectedArcHomeSafe(owner) {
46
+ if (typeof owner !== "string" || !isAddress(owner))
47
+ fail("arc_deposit_owner_invalid", "The account owner address is unreadable.");
48
+ return predictArcHomeSafe(getAddress(owner));
49
+ }
50
+ /** GET /v1/arc-home/onboarding/funding, checked like the app's fetchArcOnboardingFunding. */
51
+ export function parseArcFunding(body, owner) {
52
+ const safe = expectedArcHomeSafe(owner);
53
+ if (!isRecord(body))
54
+ fail("arc_funding_response_invalid", "Felix returned an unreadable Arc funding answer.");
55
+ const observed = money(body.observed_balance_usd);
56
+ const minimum = money(body.minimum_deposit_usd);
57
+ const additional = money(body.additional_required_usd);
58
+ if (body.chain !== "arc" || typeof body.funded !== "boolean" || !sameAddress(body.owner, owner)
59
+ || body.deposit_address_role !== "arc_home_safe" || !Array.isArray(body.counts)
60
+ || body.counts.length !== 1 || body.counts[0] !== "arc_home_safe"
61
+ || observed === undefined || minimum === undefined || additional === undefined
62
+ || minimum < ARC_FIRST_DEPOSIT_MIN_USD
63
+ || Math.abs(additional - Math.max(0, minimum - observed)) > 0.000001
64
+ || body.funded !== (observed >= minimum)) {
65
+ fail("arc_funding_response_invalid", "Felix returned an Arc funding answer that does not add up.");
66
+ }
67
+ if (!sameAddress(body.deposit_address, safe)) {
68
+ fail("arc_home_safe_mismatch", "Felix named an Arc home that is not the Safe this account's owner key controls.");
69
+ }
70
+ return {
71
+ owner: getAddress(owner), safe, funded: body.funded,
72
+ minimum_deposit_usd: minimum, observed_balance_usd: observed, additional_required_usd: additional,
73
+ };
74
+ }
75
+ /** The engine's account_funding_required 409 under the Arc home (chain "arc", Arc home Safe). */
76
+ export function parseArcFundingGate(error, owner) {
77
+ return parseArcFunding({
78
+ chain: error.chain, owner: error.owner_address ?? owner,
79
+ funded: false, deposit_address: error.deposit_address,
80
+ deposit_address_role: error.deposit_address_role,
81
+ counts: ["arc_home_safe"],
82
+ observed_balance_usd: error.observed_balance_usd,
83
+ minimum_deposit_usd: error.minimum_deposit_usd,
84
+ additional_required_usd: error.additional_required_usd,
85
+ }, owner);
86
+ }
87
+ // services/relay_deposits.SUPPORTED_TOKENS (engine arcfirstdep), pinned: a deposit key always means this exact
88
+ // token on this exact network. The engine's currency list may only narrow it, never relabel it.
89
+ export const RELAY_TOKEN_IDENTITY = Object.freeze({
90
+ "eth": { ticker: "eth", chain: "Ethereum", network: "ethereum", chain_id: 1, vm: "evm" },
91
+ "eth_base": { ticker: "eth", chain: "Base", network: "base", chain_id: 8453, vm: "evm" },
92
+ "eth_arbitrum": { ticker: "eth", chain: "Arbitrum", network: "arbitrum", chain_id: 42161, vm: "evm" },
93
+ "eth_optimism": { ticker: "eth", chain: "Optimism", network: "optimism", chain_id: 10, vm: "evm" },
94
+ "btc": { ticker: "btc", chain: "Bitcoin", network: "bitcoin", chain_id: 8253038, vm: "bvm" },
95
+ "sol": { ticker: "sol", chain: "Solana", network: "solana", chain_id: 792703809, vm: "svm" },
96
+ "sol_base": { ticker: "sol", chain: "Base", network: "base", chain_id: 8453, vm: "evm" },
97
+ "bnb": { ticker: "bnb", chain: "BNB Chain", network: "bsc", chain_id: 56, vm: "evm" },
98
+ "hype": { ticker: "hype", chain: "HyperEVM", network: "hyperevm", chain_id: 999, vm: "evm" },
99
+ "weth_eth": { ticker: "weth", chain: "Ethereum", network: "ethereum", chain_id: 1, vm: "evm" },
100
+ "weth_base": { ticker: "weth", chain: "Base", network: "base", chain_id: 8453, vm: "evm" },
101
+ "weth_arbitrum": { ticker: "weth", chain: "Arbitrum", network: "arbitrum", chain_id: 42161, vm: "evm" },
102
+ "weth_optimism": { ticker: "weth", chain: "Optimism", network: "optimism", chain_id: 10, vm: "evm" },
103
+ "dai_eth": { ticker: "dai", chain: "Ethereum", network: "ethereum", chain_id: 1, vm: "evm" },
104
+ "usde_eth": { ticker: "usde", chain: "Ethereum", network: "ethereum", chain_id: 1, vm: "evm" },
105
+ "usde_bsc": { ticker: "usde", chain: "BNB Chain", network: "bsc", chain_id: 56, vm: "evm" },
106
+ "usde_avalanche": { ticker: "usde", chain: "Avalanche", network: "avalanche", chain_id: 43114, vm: "evm" },
107
+ "usde_hyperevm": { ticker: "usde", chain: "HyperEVM", network: "hyperevm", chain_id: 999, vm: "evm" },
108
+ "cbbtc_base": { ticker: "cbbtc", chain: "Base", network: "base", chain_id: 8453, vm: "evm" },
109
+ "pyusd_eth": { ticker: "pyusd", chain: "Ethereum", network: "ethereum", chain_id: 1, vm: "evm" },
110
+ "pyusd_sol": { ticker: "pyusd", chain: "Solana", network: "solana", chain_id: 792703809, vm: "svm" },
111
+ "pengu_sol": { ticker: "pengu", chain: "Solana", network: "solana", chain_id: 792703809, vm: "svm" },
112
+ "pengu_abstract": { ticker: "pengu", chain: "Abstract", network: "abstract", chain_id: 2741, vm: "evm" },
113
+ "ape_eth": { ticker: "ape", chain: "Ethereum", network: "ethereum", chain_id: 1, vm: "evm" },
114
+ "ape_arbitrum": { ticker: "ape", chain: "Arbitrum", network: "arbitrum", chain_id: 42161, vm: "evm" },
115
+ "ape_apechain": { ticker: "ape", chain: "ApeChain", network: "apechain", chain_id: 33139, vm: "evm" },
116
+ "usdc_eth": { ticker: "usdc", chain: "Ethereum", network: "ethereum", chain_id: 1, vm: "evm" },
117
+ "usdc_base": { ticker: "usdc", chain: "Base", network: "base", chain_id: 8453, vm: "evm" },
118
+ "usdc_arbitrum": { ticker: "usdc", chain: "Arbitrum", network: "arbitrum", chain_id: 42161, vm: "evm" },
119
+ "usdc_sol": { ticker: "usdc", chain: "Solana", network: "solana", chain_id: 792703809, vm: "svm" },
120
+ "usdc_celo": { ticker: "usdc", chain: "Celo", network: "celo", chain_id: 42220, vm: "evm" },
121
+ "usdc_cronos": { ticker: "usdc", chain: "Cronos", network: "cronos", chain_id: 25, vm: "evm" },
122
+ "usdc_hyperevm": { ticker: "usdc", chain: "HyperEVM", network: "hyperevm", chain_id: 999, vm: "evm" },
123
+ "usdc_ink": { ticker: "usdc", chain: "Ink", network: "ink", chain_id: 57073, vm: "evm" },
124
+ "usdc_linea": { ticker: "usdc", chain: "Linea", network: "linea", chain_id: 59144, vm: "evm" },
125
+ "usdc_monad": { ticker: "usdc", chain: "Monad", network: "monad", chain_id: 143, vm: "evm" },
126
+ "usdc_sonic": { ticker: "usdc", chain: "Sonic", network: "sonic", chain_id: 146, vm: "evm" },
127
+ "usdc_unichain": { ticker: "usdc", chain: "Unichain", network: "unichain", chain_id: 130, vm: "evm" },
128
+ "usdc_worldchain": { ticker: "usdc", chain: "World Chain", network: "worldchain", chain_id: 480, vm: "evm" },
129
+ "usdc_xlayer": { ticker: "usdc", chain: "X Layer", network: "xlayer", chain_id: 196, vm: "evm" },
130
+ "usdc_bsc": { ticker: "usdc", chain: "BNB Chain", network: "bsc", chain_id: 56, vm: "evm" },
131
+ "usdc_optimism": { ticker: "usdc", chain: "Optimism", network: "optimism", chain_id: 10, vm: "evm" },
132
+ "usdc_polygon": { ticker: "usdc", chain: "Polygon", network: "polygon", chain_id: 137, vm: "evm" },
133
+ "usdce_polygon": { ticker: "usdc.e", chain: "Polygon", network: "polygon", chain_id: 137, vm: "evm" },
134
+ "usdc_avalanche": { ticker: "usdc", chain: "Avalanche", network: "avalanche", chain_id: 43114, vm: "evm" },
135
+ "usdt_eth": { ticker: "usdt", chain: "Ethereum", network: "ethereum", chain_id: 1, vm: "evm" },
136
+ "usdt_arbitrum": { ticker: "usdt", chain: "Arbitrum", network: "arbitrum", chain_id: 42161, vm: "evm" },
137
+ "usdt_sol": { ticker: "usdt", chain: "Solana", network: "solana", chain_id: 792703809, vm: "svm" },
138
+ "usdt_bsc": { ticker: "usdt", chain: "BNB Chain", network: "bsc", chain_id: 56, vm: "evm" },
139
+ "usdt_base": { ticker: "usdt", chain: "Base", network: "base", chain_id: 8453, vm: "evm" },
140
+ "usdt_optimism": { ticker: "usdt", chain: "Optimism", network: "optimism", chain_id: 10, vm: "evm" },
141
+ "usdt_polygon": { ticker: "usdt", chain: "Polygon", network: "polygon", chain_id: 137, vm: "evm" },
142
+ });
143
+ export function parseRelayCurrencies(body) {
144
+ if (!isRecord(body) || body.provider !== "relay" || !Array.isArray(body.currencies)
145
+ || body.currencies.length === 0 || body.currencies.length > 200) {
146
+ fail("relay_currencies_invalid", "Felix returned an unreadable deposit token list.");
147
+ }
148
+ const seen = new Set();
149
+ return body.currencies.map((row) => {
150
+ if (!isRecord(row) || typeof row.key !== "string" || !CURRENCY_KEY_RE.test(row.key) || seen.has(row.key)
151
+ || [row.ticker, row.name, row.chain, row.network].some((v) => typeof v !== "string" || !v || v.length > 64)) {
152
+ fail("relay_currencies_invalid", "Felix returned an unreadable deposit token list.");
153
+ }
154
+ seen.add(row.key);
155
+ return row;
156
+ }).filter((row) => {
157
+ // Astra mcploop r3: a key is only ever its pinned token on its pinned network. Unknown keys are dropped and a
158
+ // relabelled one (other ticker, chain or network) is refused outright.
159
+ const pinned = RELAY_TOKEN_IDENTITY[String(row.key)];
160
+ if (!pinned)
161
+ return false;
162
+ if (String(row.ticker).toLowerCase() !== pinned.ticker || row.chain !== pinned.chain || row.network !== pinned.network) {
163
+ fail("relay_currencies_invalid", "Felix returned a deposit token that does not match its known network.");
164
+ }
165
+ return true;
166
+ }).map((row) => {
167
+ const pinned = RELAY_TOKEN_IDENTITY[String(row.key)];
168
+ return { key: String(row.key), ticker: pinned.ticker, name: String(row.name), chain: pinned.chain,
169
+ network: pinned.network };
170
+ });
171
+ }
172
+ export function normalizeCurrencyKey(value) {
173
+ if (typeof value !== "string")
174
+ return undefined;
175
+ const key = value.trim().toLowerCase();
176
+ return CURRENCY_KEY_RE.test(key) ? key : undefined;
177
+ }
178
+ // Placeholder and burn destinations Relay or a faulty proxy could echo back. Funds sent there are unrecoverable.
179
+ const UNUSABLE_PAYMENT_ADDRESSES = new Set([
180
+ "0x0000000000000000000000000000000000000000",
181
+ "0x000000000000000000000000000000000000dead",
182
+ "0xdead000000000000000042069420694206942069",
183
+ "0xffffffffffffffffffffffffffffffffffffffff",
184
+ "0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
185
+ "bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8",
186
+ "1111111111111111111114oLvT2",
187
+ "11111111111111111111111111111111",
188
+ ]);
189
+ function paymentAddressValid(network, value, avoid) {
190
+ if (typeof value !== "string")
191
+ return false;
192
+ const lower = value.toLowerCase();
193
+ if (UNUSABLE_PAYMENT_ADDRESSES.has(lower) || UNUSABLE_PAYMENT_ADDRESSES.has(value))
194
+ return false;
195
+ if (avoid.some((address) => address.toLowerCase() === lower))
196
+ return false;
197
+ if (network === "bitcoin")
198
+ return BTC_RE.test(value) && !/^bc1q+[0-9a-z]{0,6}$/.test(value.replace(/q{20,}/, "q"));
199
+ if (network === "solana")
200
+ return SOLANA_RE.test(value) && !/^1+$/.test(value);
201
+ if (!EVM_RE.test(value))
202
+ return false;
203
+ const body = lower.slice(2);
204
+ // Precompiles and system addresses (leading zero runs), and single-repeated-character addresses, are not payable.
205
+ return !/^0{30}/.test(body) && !/^(.)\1{39}$/.test(body);
206
+ }
207
+ export function parseRelayEstimate(body, fromAmount) {
208
+ if (!isRecord(body))
209
+ fail("relay_estimate_invalid", "Felix returned an unreadable deposit estimate.");
210
+ const from = money(body.from_amount);
211
+ const to = money(body.to_amount);
212
+ const minimum = money(body.minimum_to_amount);
213
+ const settles = isRecord(body.settles_to) ? body.settles_to : {};
214
+ if (from === undefined || to === undefined || minimum === undefined || minimum > to
215
+ || Math.abs(from - fromAmount) > Math.max(1e-9, fromAmount * 1e-9) || settles.chain !== "arc") {
216
+ fail("relay_estimate_invalid", "Felix returned a deposit estimate that does not match the request.");
217
+ }
218
+ const seconds = typeof body.estimated_seconds === "number" && Number.isInteger(body.estimated_seconds)
219
+ && body.estimated_seconds >= 0 && body.estimated_seconds <= 86_400 ? body.estimated_seconds : null;
220
+ return { from_amount: from, to_amount: to, minimum_to_amount: minimum, estimated_seconds: seconds };
221
+ }
222
+ /** POST /v1/arc-home/relay-deposits: show a payment address only if it settles into THIS owner's Arc home. */
223
+ export function parseRelayDeposit(body, expected) {
224
+ const safe = expectedArcHomeSafe(expected.owner);
225
+ const pinned = RELAY_TOKEN_IDENTITY[expected.currency.key];
226
+ if (!pinned || pinned.ticker !== expected.currency.ticker || pinned.network !== expected.currency.network
227
+ || pinned.chain !== expected.currency.chain) {
228
+ fail("relay_deposit_invalid", "This deposit token is not a known Felix deposit token. Do not send funds.");
229
+ }
230
+ if (!isRecord(body))
231
+ fail("relay_deposit_invalid", "Felix returned an unreadable deposit instruction.");
232
+ const destination = isRecord(body.destination) ? body.destination : {};
233
+ if (destination.chain !== "arc" || destination.token !== "USDC"
234
+ || !["arc_home_safe", "arc_home_safe_pending"].includes(String(destination.role))) {
235
+ fail("relay_deposit_not_arc_home", "Felix returned a deposit that does not settle into the Arc home. Do not send funds.");
236
+ }
237
+ if (!sameAddress(destination.address, safe) || !sameAddress(body.to_address, safe)) {
238
+ fail("arc_home_safe_mismatch", "The deposit settles somewhere other than the Arc home Safe this account's owner key controls. Do not send funds.");
239
+ }
240
+ const requestId = typeof body.exchange_id === "string" ? body.exchange_id.toLowerCase() : "";
241
+ if (!REQUEST_ID_RE.test(requestId) || (body.request_id !== undefined && body.request_id !== body.exchange_id)) {
242
+ fail("relay_deposit_invalid", "Felix returned a deposit without a valid request id. Do not send funds.");
243
+ }
244
+ if (normalizeCurrencyKey(body.from_currency) !== expected.currency.key) {
245
+ fail("relay_deposit_invalid", "The deposit token differs from the one requested. Do not send funds.");
246
+ }
247
+ const from = money(body.from_amount);
248
+ const to = money(body.to_amount);
249
+ const minimum = money(body.minimum_to_amount);
250
+ if (from === undefined || Math.abs(from - expected.fromAmount) > Math.max(1e-9, expected.fromAmount * 1e-9)
251
+ || to === undefined || minimum === undefined || minimum <= 0 || minimum > to) {
252
+ fail("relay_deposit_invalid", "The deposit amounts differ from the request. Do not send funds.");
253
+ }
254
+ if (expected.firstDeposit && minimum < ARC_FIRST_DEPOSIT_MIN_USD) {
255
+ fail("relay_deposit_below_minimum", `This first deposit would deliver less than $${ARC_FIRST_DEPOSIT_MIN_USD.toFixed(2)}. Choose a larger amount.`);
256
+ }
257
+ if (!paymentAddressValid(expected.currency.network, body.deposit_address, [safe, expected.owner])) {
258
+ fail("relay_deposit_invalid", "Felix returned an unreadable payment address. Do not send funds.");
259
+ }
260
+ if (body.deposit_memo !== undefined && body.deposit_memo !== null) {
261
+ fail("relay_deposit_invalid", "This deposit needs a memo the client cannot verify. Do not send funds.");
262
+ }
263
+ const expires = typeof body.payment_expires_at === "string" ? Date.parse(body.payment_expires_at) : NaN;
264
+ if (!Number.isFinite(expires))
265
+ fail("relay_deposit_invalid", "Felix returned a deposit without a payment window.");
266
+ // A replay flag that is present in any form (even malformed) means "this may be an older instruction".
267
+ const replayed = (body.workflow_replayed !== undefined && body.workflow_replayed !== false)
268
+ || (body.workflow_reconciled !== undefined && body.workflow_reconciled !== false);
269
+ if (paymentEvidence(body)) {
270
+ fail("relay_deposit_not_payable", "This deposit instruction already shows payment or is closed. Do not pay it.");
271
+ }
272
+ if (expires <= (expected.nowMs ?? Date.now()) + 60_000) {
273
+ fail("relay_deposit_expired", "This payment window already closed. Do not send funds; create a new deposit.");
274
+ }
275
+ const seconds = typeof body.estimated_seconds === "number" && Number.isInteger(body.estimated_seconds)
276
+ && body.estimated_seconds >= 0 && body.estimated_seconds <= 86_400 ? body.estimated_seconds : null;
277
+ return {
278
+ request_id: requestId,
279
+ pay_to: String(body.deposit_address),
280
+ from_currency: expected.currency.key,
281
+ from_amount: from,
282
+ ticker: expected.currency.ticker,
283
+ network: expected.currency.network,
284
+ chain_name: expected.currency.chain,
285
+ to_amount: to,
286
+ minimum_to_amount: minimum,
287
+ payment_expires_at: new Date(expires).toISOString(),
288
+ estimated_seconds: seconds,
289
+ settles_into: {
290
+ chain: "arc", chain_id: ARC_DEPOSIT_CHAIN_ID, token: "USDC", address: safe,
291
+ role: String(destination.role),
292
+ },
293
+ replayed,
294
+ };
295
+ }
296
+ /** Any sign of a payment means "not unpaid": pay-in or payout evidence (even malformed), any credited amount other
297
+ * than an exact 0, a credited status, a refund, money_moved, or a non-waiting status. Wrong types never mean absent. */
298
+ export function paymentEvidence(body) {
299
+ const present = (value) => value !== undefined && value !== null && value !== "";
300
+ const evidenceFields = ["payin_hash", "payout_hash", "refund", "payin_hashes", "payout_hashes", "credit_tx_hash",
301
+ "credited_units"];
302
+ return evidenceFields.some((field) => present(body[field]) && !(Array.isArray(body[field]) && body[field].length === 0))
303
+ || (present(body.credited_usd) && body.credited_usd !== 0)
304
+ || (present(body.credit_status) && body.credit_status !== "unproven")
305
+ || (body.money_moved !== undefined && body.money_moved !== false)
306
+ || (body.status !== undefined && body.status !== "waiting")
307
+ || (body.provider_status !== undefined && body.provider_status !== "waiting");
308
+ }
309
+ const TX_HASH_RE = /^(?:0x[0-9a-fA-F]{64}|[0-9a-fA-F]{64}|[1-9A-HJ-NP-Za-km-z]{64,88})$/;
310
+ export function parseRelayDepositStatus(body, requestId) {
311
+ if (!isRecord(body))
312
+ fail("relay_status_invalid", "Felix returned an unreadable deposit status.");
313
+ const status = typeof body.status === "string" ? body.status : "";
314
+ if (!RELAY_STATUSES.has(status) && status !== "status_unavailable") {
315
+ fail("relay_status_invalid", "Felix returned an unknown deposit status.");
316
+ }
317
+ if (body.exchange_id !== undefined && String(body.exchange_id).toLowerCase() !== requestId) {
318
+ fail("relay_status_invalid", "The status is for another deposit.");
319
+ }
320
+ // Only known, typed fields leave the client: free-form provider text never reaches the user.
321
+ const hash = (value) => typeof value === "string" && TX_HASH_RE.test(value) ? value : null;
322
+ const refund = isRecord(body.refund) ? body.refund : undefined;
323
+ const refundAmount = refund && typeof refund.amount === "string" && /^[0-9]{1,30}(\.[0-9]{1,30})?$/.test(refund.amount)
324
+ ? refund.amount : undefined;
325
+ const refundToken = refund && typeof refund.token === "string" && /^[A-Za-z0-9.]{1,16}$/.test(refund.token)
326
+ ? refund.token : undefined;
327
+ const refundChain = refund && typeof refund.chain_id === "number" && Number.isSafeInteger(refund.chain_id)
328
+ && refund.chain_id > 0 ? refund.chain_id : undefined;
329
+ const credited = money(body.credited_usd);
330
+ const paymentSeen = paymentEvidence(body);
331
+ return {
332
+ request_id: requestId,
333
+ status,
334
+ payment_seen: paymentSeen,
335
+ credited_usd: credited ?? null,
336
+ credit_status: body.credit_status === "credited" || body.credit_status === "unproven" ? body.credit_status : null,
337
+ payin_hash: hash(body.payin_hash),
338
+ payout_hash: hash(body.payout_hash),
339
+ refund: refundAmount && refundToken && refundChain
340
+ ? { amount: refundAmount, token: refundToken, chain_id: refundChain, tx_hash: hash(refund?.tx_hash) }
341
+ : null,
342
+ };
343
+ }
344
+ export function isRequestId(value) {
345
+ return typeof value === "string" && REQUEST_ID_RE.test(value.toLowerCase());
346
+ }
347
+ /** What create_account and get_deposit_address hand the user: the app's deposit steps, Arc only. */
348
+ export function arcDepositSteps(accountId, funding) {
349
+ const target = accountId ? { account_id: accountId } : {};
350
+ return {
351
+ settles_into: funding
352
+ ? { chain: "arc", chain_id: ARC_DEPOSIT_CHAIN_ID, token: "USDC", arc_home_safe: funding.safe,
353
+ note: "Your Arc home Safe. It is not a payment address on any other network." }
354
+ : { chain: "arc", chain_id: ARC_DEPOSIT_CHAIN_ID, token: "USDC" },
355
+ steps: [
356
+ { step: 1, tool: "get_deposit_address", arguments: { ...target, from_currency: "<key>", from_amount: "<amount>" },
357
+ does: "Preview what a deposit of that token and amount delivers. Creates nothing." },
358
+ { step: 2, tool: "create_deposit",
359
+ arguments: { ...target, from_currency: "<key>", from_amount: "<amount>", idempotency_key: "<new unique key>" },
360
+ does: "Get a one-time payment address on the token's own network. Send exactly that token and amount there before the payment window ends; Relay converts it to USDC in your Arc home. Unpaid instructions expire; refunds go to the original sender." },
361
+ { step: 3, tool: "get_deposit_address", arguments: { ...target, request_id: "<request_id from step 2>" },
362
+ does: "Track the deposit until status is finished and the credit is proven." },
363
+ ],
364
+ currencies_hint: "Call get_deposit_address with list_currencies:true for every accepted token key (for example usdc_base, usdc_arbitrum, usdc_eth, usdt_eth, eth, btc, sol).",
365
+ };
366
+ }