@oneie/cli 5.7.4 → 5.7.5

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
@@ -193,6 +193,20 @@ one wallet keygen # mint a self-host
193
193
  one wallet paper # reprint the 24 words for paper — terminal only, same refusals as `one key new`
194
194
  ```
195
195
 
196
+ ### Swap — any coin, or straight into Hyperliquid
197
+
198
+ ```bash
199
+ one swap 0.01 BTC hl # price BTC into your Hyperliquid perps balance (dry — nothing minted)
200
+ one swap 10 USDC@base to hl --live # a real deposit address, read back from 1Click and checked first
201
+ one swap 25 SUI ETH --slippage 50 # SUI to ETH on ethereum, 0.5% max slippage
202
+ one swap 100 USDC@base hl --exact-out # receive exactly 100 USDC on Hyperliquid
203
+ one swap status <depositAddress> --watch # PENDING_DEPOSIT → PROCESSING → SUCCESS, with tx links
204
+ one swap assets # every alias, chain, decimals and who can sign it
205
+ one hl balance 0x… # Hyperliquid perps + spot (never summed); no address = your EVM wallet
206
+ ```
207
+
208
+ `swap` never signs and ONE never holds the coins: you send from your own wallet to a NEAR Intents 1Click deposit address. Quotes are dry until `--live`; a live quote is read back from 1Click directly and checked against what you typed (assets, amount, slippage, fees, recipient, refund address) before the CLI prints `Send exactly … before …` — any mismatch prints `quote_mismatch` and nothing to send. Every answer says `network: mainnet`: 1Click has no testnet, so a live deposit is real money. Pass `--mine <your addresses>` to require that delivery and refunds go to them — off a terminal (scripts, agents, `--json`) a live quote needs it, or it stops at `mine_required` before anything is minted. `one swap status <addr> --mine … --amount …` prints the send line again only when 1Click's record passes the same check against the amount you name (add `--slippage` if you minted with one); without `--amount` it says `amount_not_given` and prints nothing to send. Every fee shown comes from the live quote.
209
+
196
210
  `register` reads a `wallet keygen` output but transmits only its four address fields — the map it sends is built key-by-key from a fixed chain whitelist, so a `mnemonic` or `privateKey` in that file has no route onto the wire. The write is first-write-wins per chain and cannot be corrected afterwards (`address_conflict`), so it prints the addresses and asks for confirmation; `--yes` skips the prompt for scripted provisioning (needed when the JSON arrives on stdin, which leaves no terminal to answer with).
197
211
 
198
212
  `send` never signs — sign and broadcast the transfer yourself first (`agent-wallet-client.ts` for an agent, `/w` for a human), then pass the resulting transaction hash. The private key never crosses this command. `faucet` talks to `pay.one.ie` directly (its own protocol, not the `/ask` gateway) and needs no credential — funding any address is public by design, funding ≠ ownership.
package/dist/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@oneie/cli",
3
- "version": "5.7.4",
3
+ "version": "5.7.5",
4
4
  "description": "ONE agent CLI",
5
5
  "type": "module",
6
6
  "bin": {
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "dependencies": {
22
22
  "commander": "^12.0.0",
23
- "@oneie/sdk": "^0.17.5"
23
+ "@oneie/sdk": "^0.17.6"
24
24
  },
25
25
  "devDependencies": {
26
26
  "@oneie/evals": "^0.2.0",
package/dist/src/index.js CHANGED
@@ -19,6 +19,7 @@ import { evalCmd } from './eval.js';
19
19
  import { setupCmd } from './setup.js';
20
20
  import { clientCmd } from './client.js';
21
21
  import { walletCmd } from './wallet.js';
22
+ import { swapCmd, hlCmd } from './swap.js';
22
23
  import { keyCmd } from './key.js';
23
24
  import { secretsCmd } from './secrets.js';
24
25
  import { runCmd } from './secrets-run.js';
@@ -75,6 +76,8 @@ program.addCommand(doctorCmd());
75
76
  program.addCommand(whoamiCmd());
76
77
  program.addCommand(buildLoginCommand());
77
78
  program.addCommand(walletCmd());
79
+ program.addCommand(swapCmd());
80
+ program.addCommand(hlCmd());
78
81
  program.addCommand(keyCmd());
79
82
  program.addCommand(secretsCmd());
80
83
  program.addCommand(runCmd());
@@ -0,0 +1,163 @@
1
+ /**
2
+ * swap-core — the pure half of `one swap` (text/swap-plan.md § CLI).
3
+ *
4
+ * The CLI cannot import one.ie/web code and must not import a new @oneie/sdk export
5
+ * (R2: packages/cli/node_modules resolves another tree's SDK, so a new subpath would pass
6
+ * hollow). So the four things the client check needs are ported here, verbatim in behaviour,
7
+ * and tests/swap-parity.test.ts runs them against the web originals so the copy cannot drift:
8
+ *
9
+ * SWAP_TABLE + resolveAlias ← one.ie/web/src/lib/swap/assets.ts (SWAP_ASSETS, resolveAsset)
10
+ * parseUnits + formatUnits ← one.ie/web/src/lib/units.ts
11
+ * checkQuote ← one.ie/web/src/lib/swap/core.ts (R16, incl. 3fef1b14c fields)
12
+ * sendUri ← one.ie/web/src/lib/swap/core.ts
13
+ *
14
+ * Nothing here touches the network, and nothing here ever signs. No Number cast touches an amount.
15
+ */
16
+ export type SwapChain = 'ethereum' | 'base' | 'arbitrum' | 'solana' | 'sui' | 'bitcoin' | 'hyperliquid';
17
+ export type SwapSigner = 'browser' | 'external' | 'none';
18
+ export interface SwapRow {
19
+ alias: string;
20
+ chain: SwapChain;
21
+ symbol: string;
22
+ assetId: string;
23
+ decimals: number;
24
+ contract: string | null;
25
+ signer: SwapSigner;
26
+ origin: boolean;
27
+ destination: boolean;
28
+ }
29
+ export declare const HL_USDC_ASSET_ID = "1cs_v1:hypercore:hip1:0x6d1e7cde53ba9467b783cb7c530ce054";
30
+ /** Copied from one.ie/web/src/lib/swap/assets.ts — tests/swap-parity.test.ts pins it row by row. */
31
+ export declare const SWAP_TABLE: readonly SwapRow[];
32
+ export type AliasResult = {
33
+ ok: true;
34
+ asset: SwapRow;
35
+ } | {
36
+ ok: false;
37
+ error: 'unknown_asset';
38
+ } | {
39
+ ok: false;
40
+ error: 'ambiguous_asset';
41
+ options: string[];
42
+ } | {
43
+ ok: false;
44
+ error: 'not_a_destination';
45
+ asset: SwapRow;
46
+ };
47
+ /** Same rules as the web resolveAsset — a parity test compares every alias both ways. */
48
+ export declare function resolveAlias(input: unknown, side: 'from' | 'to'): AliasResult;
49
+ export declare function rowById(assetId: unknown): SwapRow | undefined;
50
+ export declare function parseUnits(input: string, decimals: number): bigint | null;
51
+ export declare function formatUnits(value: bigint, decimals: number): string;
52
+ /** The one rule (plan § CLI): the amount is the token that looks like a plain decimal. */
53
+ export declare const AMOUNT_TOKEN: RegExp;
54
+ export type Words = {
55
+ ok: true;
56
+ amount: string;
57
+ from: string;
58
+ to: string;
59
+ } | {
60
+ ok: false;
61
+ error: 'bad_amount' | 'usage';
62
+ next: string;
63
+ };
64
+ /**
65
+ * `one swap 0.01 BTC hl` = `one swap 0.01 BTC to hl` = `one swap BTC hl 0.01`.
66
+ * Exactly one plain-decimal amount (nonzero), a literal `to` dropped, two asset words left
67
+ * in order (from, to). `1e3`, `0x10`, `-1`, `.5` and `0` are refused here, before any call.
68
+ */
69
+ export declare function parseSwapWords(words: readonly string[]): Words;
70
+ /** --slippage <bps>: an integer 1..500, read by regex and parseInt, never a Number cast. */
71
+ export declare function parseSlippage(s: string | undefined): {
72
+ ok: true;
73
+ bps?: number;
74
+ } | {
75
+ ok: false;
76
+ };
77
+ /** --mine a,b,c → the caller's own addresses, as typed. */
78
+ export declare function parseMine(s: string | undefined): string[];
79
+ export declare const ONECLICK = "https://1click.chaindefuser.com";
80
+ export declare const ONECLICK_PROTOCOL_RECIPIENT = "5880ad2b362620fadf759cbceb1cd5737ce8c6ed7fb8e9942881e6731f9247dd";
81
+ export declare const DEFAULT_SLIPPAGE_BPS = 100;
82
+ /** ONE's app fee, pinned in client code (null = none, so any non-1Click fee row fails). Same as core.ts. */
83
+ export declare const ONE_APP_FEE: {
84
+ recipient: string;
85
+ bps: number;
86
+ } | null;
87
+ /** Cap on summed 1Click protocol rows — measured 0/1/20 bps over 74 keyless routes (max 20), 25 = the documented no-key 0.25%. Same as core.ts. */
88
+ export declare const PROTOCOL_FEE_CAP_BPS = 25;
89
+ /** 1Click's own status URL for a deposit address — a fixed host, the address in URLSearchParams. */
90
+ export declare function oneClickStatusUrl(depositAddress: string): string;
91
+ export declare function depositAddressFits(addr: unknown): addr is string;
92
+ export declare const HL_ADDRESS: RegExp;
93
+ export interface MyQuoteValues {
94
+ depositAddress: string;
95
+ recipient: string;
96
+ refundTo: string;
97
+ originAsset: string;
98
+ destinationAsset: string;
99
+ exact: 'in' | 'out';
100
+ amountBase: string;
101
+ maxAmountInBase?: string;
102
+ slippageBps?: number;
103
+ appFeeCapBps?: number;
104
+ appFeeRecipient?: string;
105
+ protocolFeeCapBps?: number;
106
+ }
107
+ export type CheckField = 'stored' | 'depositAddress' | 'recipient' | 'refundTo' | 'originAsset' | 'destinationAsset' | 'depositType' | 'depositMode' | 'memo' | 'swapType' | 'amount' | 'amountIn' | 'refundType' | 'recipientType' | 'slippageTolerance' | 'appFees';
108
+ export type CheckResult = {
109
+ ok: true;
110
+ } | {
111
+ ok: false;
112
+ error: 'quote_mismatch';
113
+ field: CheckField;
114
+ };
115
+ type Obj = Record<string, unknown>;
116
+ export declare function sameAddress(a: unknown, b: unknown): boolean;
117
+ export declare function checkQuote(stored: unknown, mine: MyQuoteValues): CheckResult;
118
+ /** What 1Click itself recorded for a deposit address — read straight out of its status body. */
119
+ export interface StoredRecord {
120
+ recipient?: string;
121
+ refundTo?: string;
122
+ originAsset?: string;
123
+ destinationAsset?: string;
124
+ amountInBase?: string;
125
+ amountOutBase?: string;
126
+ minAmountOutBase?: string;
127
+ /** quoteRequest.swapType and quoteRequest.amount — what the status door re-checks (R16). */
128
+ swapType?: string;
129
+ amountBase?: string;
130
+ refundAfter?: string;
131
+ addressExpires?: string;
132
+ quotedAt?: string;
133
+ status?: string;
134
+ }
135
+ export declare function storedRecord(body: unknown): StoredRecord;
136
+ /** Never print a send line inside the last five minutes before refunds begin. */
137
+ export declare const SEND_MARGIN_MS: number;
138
+ /**
139
+ * Is there still time to send? `quotedAt` (1Click's clock) corrects this machine's skew:
140
+ * skew = localNowAtQuote − quotedAt; 1Click's now ≈ localNow − skew.
141
+ */
142
+ export declare function stillSendable(refundAfter: string | undefined, now: Date, skewMs?: number): boolean;
143
+ export declare function sendUri(asset: SwapRow, to: string, amountBase: bigint): string | undefined;
144
+ /**
145
+ * The page origin a link points at. The server's own link is only trusted for its ORIGIN, and
146
+ * only when that origin is https://one.ie or localhost — a gateway call can come back as
147
+ * https://api.one.ie/swap, which is no page. The query is always built here, never copied.
148
+ */
149
+ export declare function pageOrigin(serverLink: unknown): string;
150
+ export declare function swapLink(origin: string, q: {
151
+ from: string;
152
+ to: string;
153
+ amount: string;
154
+ exact?: 'in' | 'out';
155
+ }): string;
156
+ export declare function depositLink(origin: string, depositAddress: string): string;
157
+ /** The quote, one fact per line. `network: mainnet` is always the first line. */
158
+ export declare function quoteLines(r: Obj): string[];
159
+ export declare function statusLines(r: Obj): string[];
160
+ /** Perps and spot, side by side — never summed (unified accounts show everything in spot). */
161
+ export declare function hlLines(h: Obj): string[];
162
+ export declare function assetLines(assets: readonly Obj[]): string[];
163
+ export {};
@@ -0,0 +1,405 @@
1
+ /**
2
+ * swap-core — the pure half of `one swap` (text/swap-plan.md § CLI).
3
+ *
4
+ * The CLI cannot import one.ie/web code and must not import a new @oneie/sdk export
5
+ * (R2: packages/cli/node_modules resolves another tree's SDK, so a new subpath would pass
6
+ * hollow). So the four things the client check needs are ported here, verbatim in behaviour,
7
+ * and tests/swap-parity.test.ts runs them against the web originals so the copy cannot drift:
8
+ *
9
+ * SWAP_TABLE + resolveAlias ← one.ie/web/src/lib/swap/assets.ts (SWAP_ASSETS, resolveAsset)
10
+ * parseUnits + formatUnits ← one.ie/web/src/lib/units.ts
11
+ * checkQuote ← one.ie/web/src/lib/swap/core.ts (R16, incl. 3fef1b14c fields)
12
+ * sendUri ← one.ie/web/src/lib/swap/core.ts
13
+ *
14
+ * Nothing here touches the network, and nothing here ever signs. No Number cast touches an amount.
15
+ */
16
+ export const HL_USDC_ASSET_ID = '1cs_v1:hypercore:hip1:0x6d1e7cde53ba9467b783cb7c530ce054';
17
+ /** Copied from one.ie/web/src/lib/swap/assets.ts — tests/swap-parity.test.ts pins it row by row. */
18
+ export const SWAP_TABLE = [
19
+ { alias: 'BTC', chain: 'bitcoin', symbol: 'BTC', assetId: 'nep141:btc.omft.near', decimals: 8, contract: null, signer: 'external', origin: true, destination: true },
20
+ { alias: 'ETH@ethereum', chain: 'ethereum', symbol: 'ETH', assetId: 'nep141:eth.omft.near', decimals: 18, contract: null, signer: 'browser', origin: true, destination: true },
21
+ { alias: 'ETH@base', chain: 'base', symbol: 'ETH', assetId: 'nep141:base.omft.near', decimals: 18, contract: null, signer: 'browser', origin: true, destination: true },
22
+ { alias: 'ETH@arbitrum', chain: 'arbitrum', symbol: 'ETH', assetId: 'nep141:arb.omft.near', decimals: 18, contract: null, signer: 'external', origin: true, destination: true },
23
+ { alias: 'USDC@ethereum', chain: 'ethereum', symbol: 'USDC', assetId: 'nep141:eth-0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48.omft.near', decimals: 6, contract: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', signer: 'browser', origin: true, destination: true },
24
+ { alias: 'USDC@base', chain: 'base', symbol: 'USDC', assetId: 'nep141:base-0x833589fcd6edb6e08f4c7c32d4f71b54bda02913.omft.near', decimals: 6, contract: '0x833589fcd6edb6e08f4c7c32d4f71b54bda02913', signer: 'browser', origin: true, destination: true },
25
+ { alias: 'USDC@arbitrum', chain: 'arbitrum', symbol: 'USDC', assetId: 'nep141:arb-0xaf88d065e77c8cc2239327c5edb3a432268e5831.omft.near', decimals: 6, contract: '0xaf88d065e77c8cc2239327c5edb3a432268e5831', signer: 'external', origin: true, destination: true },
26
+ { alias: 'USDT@ethereum', chain: 'ethereum', symbol: 'USDT', assetId: 'nep141:eth-0xdac17f958d2ee523a2206206994597c13d831ec7.omft.near', decimals: 6, contract: '0xdac17f958d2ee523a2206206994597c13d831ec7', signer: 'external', origin: true, destination: true },
27
+ { alias: 'USDT0@arbitrum', chain: 'arbitrum', symbol: 'USDT0', assetId: 'nep141:arb-0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9.omft.near', decimals: 6, contract: '0xfd086bc7cd5c481dcc9c85ebe478a1c0b69fcbb9', signer: 'external', origin: true, destination: true },
28
+ { alias: 'SOL', chain: 'solana', symbol: 'SOL', assetId: 'nep141:sol.omft.near', decimals: 9, contract: null, signer: 'external', origin: true, destination: true },
29
+ { alias: 'USDC@solana', chain: 'solana', symbol: 'USDC', assetId: 'nep141:sol-5ce3bf3a31af18be40ba30f721101b4341690186.omft.near', decimals: 6, contract: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v', signer: 'external', origin: true, destination: true },
30
+ { alias: 'SUI', chain: 'sui', symbol: 'SUI', assetId: 'nep141:sui.omft.near', decimals: 9, contract: null, signer: 'browser', origin: true, destination: true },
31
+ { alias: 'USDC@sui', chain: 'sui', symbol: 'USDC', assetId: 'nep141:sui-c1b81ecaf27933252d31a963bc5e9458f13c18ce.omft.near', decimals: 6, contract: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC', signer: 'browser', origin: true, destination: true },
32
+ { alias: 'USDC@hyperliquid', chain: 'hyperliquid', symbol: 'USDC', assetId: HL_USDC_ASSET_ID, decimals: 8, contract: '0x6d1e7cde53ba9467b783cb7c530ce054', signer: 'none', origin: false, destination: true },
33
+ ];
34
+ const CHAIN_SYNONYMS = {
35
+ ethereum: 'ethereum', eth: 'ethereum', 'ethereum-mainnet': 'ethereum',
36
+ base: 'base',
37
+ arbitrum: 'arbitrum', arb: 'arbitrum',
38
+ solana: 'solana', sol: 'solana',
39
+ sui: 'sui',
40
+ bitcoin: 'bitcoin', btc: 'bitcoin',
41
+ hyperliquid: 'hyperliquid', hl: 'hyperliquid', hypercore: 'hyperliquid',
42
+ };
43
+ const DEST_DEFAULT = { ETH: 'ETH@ethereum', USDC: 'USDC@base', USDT: 'USDT@ethereum' };
44
+ const byAlias = new Map(SWAP_TABLE.map((a) => [a.alias.toLowerCase(), a]));
45
+ /** Same rules as the web resolveAsset — a parity test compares every alias both ways. */
46
+ export function resolveAlias(input, side) {
47
+ const raw = typeof input === 'string' ? input.trim() : '';
48
+ if (!raw)
49
+ return { ok: false, error: 'unknown_asset' };
50
+ const lower = raw.toLowerCase();
51
+ let asset;
52
+ if (lower === 'hl' || lower === 'hyperliquid' || lower === 'hypercore') {
53
+ asset = byAlias.get('usdc@hyperliquid');
54
+ }
55
+ else if (lower.includes('@')) {
56
+ const [sym, ch] = lower.split('@', 2);
57
+ const chain = CHAIN_SYNONYMS[ch];
58
+ if (!chain)
59
+ return { ok: false, error: 'unknown_asset' };
60
+ asset = SWAP_TABLE.find((a) => a.symbol.toLowerCase() === sym && a.chain === chain);
61
+ }
62
+ else {
63
+ const rows = SWAP_TABLE.filter((a) => a.symbol.toLowerCase() === lower);
64
+ if (rows.length === 1)
65
+ asset = rows[0];
66
+ else if (rows.length > 1) {
67
+ if (side === 'to')
68
+ asset = byAlias.get((DEST_DEFAULT[raw.toUpperCase()] ?? '').toLowerCase());
69
+ if (!asset)
70
+ return { ok: false, error: 'ambiguous_asset', options: rows.map((r) => r.alias) };
71
+ }
72
+ }
73
+ if (!asset)
74
+ return { ok: false, error: 'unknown_asset' };
75
+ if (side === 'to' && !asset.destination)
76
+ return { ok: false, error: 'not_a_destination', asset };
77
+ return { ok: true, asset };
78
+ }
79
+ export function rowById(assetId) {
80
+ return SWAP_TABLE.find((a) => a.assetId === assetId);
81
+ }
82
+ // ─── units (verbatim from one.ie/web/src/lib/units.ts) ─────────────────────────
83
+ export function parseUnits(input, decimals) {
84
+ const s = input.trim();
85
+ if (s !== input || !/^(\d+\.?\d*|\.\d+)$/.test(s))
86
+ return null;
87
+ const [whole, frac = ''] = s.split('.');
88
+ if (frac.length > decimals)
89
+ return null;
90
+ return BigInt(whole || '0') * 10n ** BigInt(decimals) + BigInt((frac + '0'.repeat(decimals)).slice(0, decimals) || '0');
91
+ }
92
+ export function formatUnits(value, decimals) {
93
+ const neg = value < 0n;
94
+ const v = neg ? -value : value;
95
+ const base = 10n ** BigInt(decimals);
96
+ const whole = v / base;
97
+ const frac = (v % base).toString().padStart(decimals, '0').replace(/0+$/, '');
98
+ return `${neg ? '-' : ''}${whole}${frac ? `.${frac}` : ''}`;
99
+ }
100
+ // ─── grammar ──────────────────────────────────────────────────────────────────
101
+ /** The one rule (plan § CLI): the amount is the token that looks like a plain decimal. */
102
+ export const AMOUNT_TOKEN = /^\d+(\.\d+)?$/;
103
+ const USAGE = 'one swap <amount> <from> [to] <to> — e.g. one swap 0.01 BTC hl · one swap 10 USDC@base to hl';
104
+ /**
105
+ * `one swap 0.01 BTC hl` = `one swap 0.01 BTC to hl` = `one swap BTC hl 0.01`.
106
+ * Exactly one plain-decimal amount (nonzero), a literal `to` dropped, two asset words left
107
+ * in order (from, to). `1e3`, `0x10`, `-1`, `.5` and `0` are refused here, before any call.
108
+ */
109
+ export function parseSwapWords(words) {
110
+ const kept = words.filter((w) => w.toLowerCase() !== 'to');
111
+ const amounts = kept.filter((w) => AMOUNT_TOKEN.test(w));
112
+ const rest = kept.filter((w) => !AMOUNT_TOKEN.test(w));
113
+ if (amounts.length === 0) {
114
+ return { ok: false, error: 'bad_amount', next: `No amount found — write it as a plain decimal like 10 or 0.01 (never 1e3, -1 or .5). ${USAGE}` };
115
+ }
116
+ if (amounts.length > 1)
117
+ return { ok: false, error: 'usage', next: `Two amounts given (${amounts.join(', ')}); give one. ${USAGE}` };
118
+ const amount = amounts[0];
119
+ if (!/[1-9]/.test(amount))
120
+ return { ok: false, error: 'bad_amount', next: 'The amount must be more than zero.' };
121
+ if (rest.length !== 2)
122
+ return { ok: false, error: 'usage', next: `Name exactly two assets, what you pay and what you get. ${USAGE}` };
123
+ return { ok: true, amount, from: rest[0], to: rest[1] };
124
+ }
125
+ /** --slippage <bps>: an integer 1..500, read by regex and parseInt, never a Number cast. */
126
+ export function parseSlippage(s) {
127
+ if (s === undefined)
128
+ return { ok: true };
129
+ if (!/^\d{1,3}$/.test(s))
130
+ return { ok: false };
131
+ const bps = Number.parseInt(s, 10);
132
+ return bps >= 1 && bps <= 500 ? { ok: true, bps } : { ok: false };
133
+ }
134
+ /** --mine a,b,c → the caller's own addresses, as typed. */
135
+ export function parseMine(s) {
136
+ if (!s)
137
+ return [];
138
+ return s.split(/[\s,]+/).map((x) => x.trim()).filter(Boolean);
139
+ }
140
+ // ─── the client check (R16) — verbatim from one.ie/web/src/lib/swap/core.ts ────
141
+ export const ONECLICK = 'https://1click.chaindefuser.com';
142
+ export const ONECLICK_PROTOCOL_RECIPIENT = '5880ad2b362620fadf759cbceb1cd5737ce8c6ed7fb8e9942881e6731f9247dd';
143
+ export const DEFAULT_SLIPPAGE_BPS = 100;
144
+ /** ONE's app fee, pinned in client code (null = none, so any non-1Click fee row fails). Same as core.ts. */
145
+ export const ONE_APP_FEE = null;
146
+ /** Cap on summed 1Click protocol rows — measured 0/1/20 bps over 74 keyless routes (max 20), 25 = the documented no-key 0.25%. Same as core.ts. */
147
+ export const PROTOCOL_FEE_CAP_BPS = 25;
148
+ /** 1Click's own status URL for a deposit address — a fixed host, the address in URLSearchParams. */
149
+ export function oneClickStatusUrl(depositAddress) {
150
+ return `${ONECLICK}/v0/status?${new URLSearchParams({ depositAddress }).toString()}`;
151
+ }
152
+ const DEPOSIT_RE = /^[A-Za-z0-9:._-]{20,128}$/;
153
+ export function depositAddressFits(addr) {
154
+ return typeof addr === 'string' && DEPOSIT_RE.test(addr);
155
+ }
156
+ export const HL_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
157
+ const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
158
+ function bigOf(s) {
159
+ if (typeof s === 'number' && Number.isInteger(s) && s >= 0)
160
+ return BigInt(s);
161
+ if (typeof s !== 'string' || !/^\d+$/.test(s))
162
+ return null;
163
+ return BigInt(s);
164
+ }
165
+ export function sameAddress(a, b) {
166
+ if (typeof a !== 'string' || typeof b !== 'string' || !a || !b)
167
+ return false;
168
+ if (a.startsWith('0x') && b.startsWith('0x'))
169
+ return a.toLowerCase() === b.toLowerCase();
170
+ return a === b;
171
+ }
172
+ export function checkQuote(stored, mine) {
173
+ const fail = (field) => ({ ok: false, error: 'quote_mismatch', field });
174
+ if (!isObj(stored))
175
+ return fail('stored');
176
+ const qr = isObj(stored['quoteResponse']) ? stored['quoteResponse'] : stored;
177
+ const req = isObj(qr['quoteRequest']) ? qr['quoteRequest'] : null;
178
+ const q = isObj(qr['quote']) ? qr['quote'] : null;
179
+ if (!req || !q)
180
+ return fail('stored');
181
+ if (!sameAddress(q['depositAddress'], mine.depositAddress))
182
+ return fail('depositAddress');
183
+ if (!sameAddress(req['recipient'], mine.recipient))
184
+ return fail('recipient');
185
+ if (!sameAddress(req['refundTo'], mine.refundTo))
186
+ return fail('refundTo');
187
+ if (req['originAsset'] !== mine.originAsset)
188
+ return fail('originAsset');
189
+ if (req['destinationAsset'] !== mine.destinationAsset)
190
+ return fail('destinationAsset');
191
+ if (req['depositType'] !== 'ORIGIN_CHAIN')
192
+ return fail('depositType');
193
+ if (req['refundType'] !== 'ORIGIN_CHAIN')
194
+ return fail('refundType');
195
+ if (req['recipientType'] !== 'DESTINATION_CHAIN')
196
+ return fail('recipientType');
197
+ if (req['slippageTolerance'] !== (mine.slippageBps ?? DEFAULT_SLIPPAGE_BPS))
198
+ return fail('slippageTolerance');
199
+ const fees = req['appFees'] === undefined || req['appFees'] === null ? [] : req['appFees'];
200
+ if (!Array.isArray(fees))
201
+ return fail('appFees');
202
+ const payee = mine.appFeeRecipient ?? ONE_APP_FEE?.recipient;
203
+ let other = 0;
204
+ let protocol = 0;
205
+ for (const f of fees) {
206
+ if (!isObj(f) || typeof f['fee'] !== 'number' || !Number.isFinite(f['fee']) || f['fee'] < 0)
207
+ return fail('appFees');
208
+ if (f['recipient'] === ONECLICK_PROTOCOL_RECIPIENT) {
209
+ protocol += f['fee'];
210
+ continue;
211
+ }
212
+ if (payee !== undefined && f['recipient'] !== payee)
213
+ return fail('appFees');
214
+ other += f['fee'];
215
+ }
216
+ if (protocol > (mine.protocolFeeCapBps ?? PROTOCOL_FEE_CAP_BPS))
217
+ return fail('appFees');
218
+ if (other > (mine.appFeeCapBps ?? ONE_APP_FEE?.bps ?? 0))
219
+ return fail('appFees');
220
+ if (req['depositMode'] !== undefined && req['depositMode'] !== 'SIMPLE')
221
+ return fail('depositMode');
222
+ if (q['depositMemo'] !== undefined && q['depositMemo'] !== null && q['depositMemo'] !== '')
223
+ return fail('memo');
224
+ const wantType = mine.exact === 'out' ? 'EXACT_OUTPUT' : 'EXACT_INPUT';
225
+ if (req['swapType'] !== wantType)
226
+ return fail('swapType');
227
+ if (String(req['amount'] ?? '') !== mine.amountBase)
228
+ return fail('amount');
229
+ if (mine.exact === 'in') {
230
+ if (String(q['amountIn'] ?? '') !== mine.amountBase)
231
+ return fail('amountIn');
232
+ }
233
+ else {
234
+ const cap = bigOf(mine.maxAmountInBase);
235
+ const got = bigOf(q['amountIn']);
236
+ if (cap === null || got === null || got > cap)
237
+ return fail('amountIn');
238
+ }
239
+ return { ok: true };
240
+ }
241
+ export function storedRecord(body) {
242
+ if (!isObj(body))
243
+ return {};
244
+ const qr = isObj(body['quoteResponse']) ? body['quoteResponse'] : body;
245
+ const req = isObj(qr['quoteRequest']) ? qr['quoteRequest'] : {};
246
+ const q = isObj(qr['quote']) ? qr['quote'] : {};
247
+ const s = (v) => (typeof v === 'string' && v ? v : undefined);
248
+ const amountIn = bigOf(q['amountIn']);
249
+ const amountOut = bigOf(q['amountOut']);
250
+ const minOut = bigOf(q['minAmountOut']);
251
+ return {
252
+ recipient: s(req['recipient']),
253
+ refundTo: s(req['refundTo']),
254
+ originAsset: s(req['originAsset']),
255
+ destinationAsset: s(req['destinationAsset']),
256
+ amountInBase: amountIn === null ? undefined : amountIn.toString(),
257
+ amountOutBase: amountOut === null ? undefined : amountOut.toString(),
258
+ minAmountOutBase: minOut === null ? undefined : minOut.toString(),
259
+ swapType: s(req['swapType']),
260
+ amountBase: bigOf(req['amount'])?.toString(),
261
+ // refundAfter is quoteRequest.deadline (1Click starts refunding), NOT quote.deadline (~72 h).
262
+ refundAfter: s(req['deadline']),
263
+ addressExpires: s(q['timeWhenInactive']) ?? s(q['deadline']),
264
+ quotedAt: s(qr['timestamp']),
265
+ status: s(body['status']),
266
+ };
267
+ }
268
+ /** Never print a send line inside the last five minutes before refunds begin. */
269
+ export const SEND_MARGIN_MS = 5 * 60_000;
270
+ /**
271
+ * Is there still time to send? `quotedAt` (1Click's clock) corrects this machine's skew:
272
+ * skew = localNowAtQuote − quotedAt; 1Click's now ≈ localNow − skew.
273
+ */
274
+ export function stillSendable(refundAfter, now, skewMs = 0) {
275
+ if (!refundAfter)
276
+ return false;
277
+ const t = Date.parse(refundAfter);
278
+ if (Number.isNaN(t))
279
+ return false;
280
+ return now.getTime() - skewMs < t - SEND_MARGIN_MS;
281
+ }
282
+ // ─── send instruction (verbatim from core.sendUri) ─────────────────────────────
283
+ const EVM_CHAIN_ID = { ethereum: 1, base: 8453, arbitrum: 42161 };
284
+ export function sendUri(asset, to, amountBase) {
285
+ const dec = formatUnits(amountBase, asset.decimals);
286
+ if (asset.chain === 'bitcoin')
287
+ return `bitcoin:${to}?amount=${dec}`;
288
+ if (asset.chain === 'solana')
289
+ return `solana:${to}?amount=${dec}${asset.contract ? `&spl-token=${asset.contract}` : ''}`;
290
+ const id = EVM_CHAIN_ID[asset.chain];
291
+ if (!id)
292
+ return undefined;
293
+ if (!asset.contract)
294
+ return `ethereum:${to}@${id}?value=${amountBase.toString()}`;
295
+ return `ethereum:${asset.contract}@${id}/transfer?address=${to}&uint256=${amountBase.toString()}`;
296
+ }
297
+ // ─── links ─────────────────────────────────────────────────────────────────────
298
+ const LOCAL_ORIGIN = /^http:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/;
299
+ /**
300
+ * The page origin a link points at. The server's own link is only trusted for its ORIGIN, and
301
+ * only when that origin is https://one.ie or localhost — a gateway call can come back as
302
+ * https://api.one.ie/swap, which is no page. The query is always built here, never copied.
303
+ */
304
+ export function pageOrigin(serverLink) {
305
+ if (typeof serverLink !== 'string')
306
+ return 'https://one.ie';
307
+ try {
308
+ const o = new URL(serverLink).origin;
309
+ return o === 'https://one.ie' || LOCAL_ORIGIN.test(o) ? o : 'https://one.ie';
310
+ }
311
+ catch {
312
+ return 'https://one.ie';
313
+ }
314
+ }
315
+ export function swapLink(origin, q) {
316
+ const p = new URLSearchParams({ from: q.from, to: q.to, amount: q.amount });
317
+ if (q.exact === 'out')
318
+ p.set('exact', 'out');
319
+ return `${origin}/swap?${p.toString()}`;
320
+ }
321
+ export function depositLink(origin, depositAddress) {
322
+ return `${origin}/swap?${new URLSearchParams({ deposit: depositAddress }).toString()}`;
323
+ }
324
+ // ─── human lines ───────────────────────────────────────────────────────────────
325
+ const pad = (k) => k.padEnd(10);
326
+ /** The quote, one fact per line. `network: mainnet` is always the first line. */
327
+ export function quoteLines(r) {
328
+ const from = isObj(r['from']) ? r['from'] : {};
329
+ const to = isObj(r['to']) ? r['to'] : {};
330
+ const lines = [];
331
+ lines.push(`${pad('network')}${r['dry'] === false ? 'mainnet — real funds' : 'mainnet (1Click has no testnet; this is a price only)'}`);
332
+ if (r['amountIn'] !== undefined)
333
+ lines.push(`${pad('you send')}${r['amountIn']} ${from['alias'] ?? ''}${from['chain'] ? ` on ${from['chain']}` : ''}${r['amountInUsd'] ? ` (~$${r['amountInUsd']})` : ''}`);
334
+ if (r['minAmountIn'] !== undefined && r['minAmountIn'] !== r['amountIn'])
335
+ lines.push(`${pad('min send')}${r['minAmountIn']} ${from['alias'] ?? ''}`);
336
+ if (r['amountOut'] !== undefined)
337
+ lines.push(`${pad('you get')}${r['amountOut']} ${to['alias'] ?? ''}${r['amountOutUsd'] ? ` (~$${r['amountOutUsd']})` : ''}`);
338
+ if (r['minAmountOut'] !== undefined)
339
+ lines.push(`${pad('min recv')}${r['minAmountOut']} ${to['alias'] ?? ''} (after slippage)`);
340
+ const fees = Array.isArray(r['fees']) ? r['fees'] : [];
341
+ for (const f of fees) {
342
+ const amt = f.amount ? `${f.amount} ${f.asset ?? ''}`.trim() : '';
343
+ const bps = typeof f.bps === 'number' ? `${f.bps} bps` : '';
344
+ lines.push(`${pad('fee')}${[f.kind, [amt, bps].filter(Boolean).join(' · '), f.note ? `— ${f.note}` : ''].filter(Boolean).join(' ')}`);
345
+ }
346
+ if (r['costUsd'] !== undefined)
347
+ lines.push(`${pad('cost')}$${r['costUsd']} (value in − value out, read from the live quote)`);
348
+ if (typeof r['timeEstimateSec'] === 'number')
349
+ lines.push(`${pad('eta')}~${r['timeEstimateSec']} s after the deposit confirms`);
350
+ const route = isObj(r['route']) ? r['route'] : {};
351
+ if (route['credits'] === 'perps')
352
+ lines.push(`${pad('lands in')}your Hyperliquid PERPS balance`);
353
+ const warnings = Array.isArray(r['warnings']) ? r['warnings'] : [];
354
+ for (const w of warnings)
355
+ lines.push(`${pad('warning')}${w}`);
356
+ return lines;
357
+ }
358
+ export function statusLines(r) {
359
+ const lines = [`${pad('network')}mainnet`];
360
+ if (r['status'] !== undefined)
361
+ lines.push(`${pad('status')}${r['status']}${r['terminal'] ? ' (final)' : ''}`);
362
+ if (r['explain'])
363
+ lines.push(`${pad('means')}${r['explain']}`);
364
+ if (r['from'] || r['to'])
365
+ lines.push(`${pad('swap')}${r['from'] ?? '?'} → ${r['to'] ?? '?'}`);
366
+ if (r['amountIn'] !== undefined)
367
+ lines.push(`${pad('deposited')}${r['amountIn']}`);
368
+ if (r['amountOut'] !== undefined)
369
+ lines.push(`${pad('delivered')}${r['amountOut']}${r['amountOutUsd'] ? ` (~$${r['amountOutUsd']})` : ''}`);
370
+ if (r['refundedAmount'] !== undefined && r['refundedAmount'] !== '0')
371
+ lines.push(`${pad('refunded')}${r['refundedAmount']}${r['refundReason'] ? ` — ${r['refundReason']}` : ''}`);
372
+ for (const key of ['originTxs', 'destinationTxs']) {
373
+ const txs = Array.isArray(r[key]) ? r[key] : [];
374
+ for (const t of txs)
375
+ lines.push(`${pad(key === 'originTxs' ? 'deposit tx' : 'deliver tx')}${t.explorerUrl ?? t.hash ?? ''}`);
376
+ }
377
+ if (r['submitted'] === true)
378
+ lines.push(`${pad('tx hash')}forwarded to 1Click to speed matching (not a verification)`);
379
+ if (r['refundAfter'])
380
+ lines.push(`${pad('refunds')}begin ${r['refundAfter']} if not filled`);
381
+ if (isObj(r['hyperliquid']))
382
+ lines.push(...hlLines(r['hyperliquid']));
383
+ return lines;
384
+ }
385
+ /** Perps and spot, side by side — never summed (unified accounts show everything in spot). */
386
+ export function hlLines(h) {
387
+ const perps = isObj(h['perps']) ? h['perps'] : {};
388
+ const spot = Array.isArray(h['spot']) ? h['spot'] : [];
389
+ const lines = [
390
+ `${pad('hl')}${h['address'] ?? ''} on ${h['network'] ?? 'mainnet'}`,
391
+ `${pad('perps')}account value $${perps['accountValue'] ?? '0'} · withdrawable $${perps['withdrawable'] ?? '0'}`,
392
+ ];
393
+ if (!spot.length)
394
+ lines.push(`${pad('spot')}(empty)`);
395
+ for (const s of spot)
396
+ lines.push(`${pad('spot')}${s.total ?? '0'} ${s.coin ?? ''}${s.hold && s.hold !== '0' && s.hold !== '0.0' ? ` (${s.hold} on hold)` : ''}`);
397
+ if (h['firstDeposit'] === true)
398
+ lines.push(`${pad('note')}empty account — Hyperliquid MAY take a one-time ~1 USDC activation (unverified)`);
399
+ lines.push(`${pad('note')}perps and spot are separate balances; they are not summed`);
400
+ return lines;
401
+ }
402
+ export function assetLines(assets) {
403
+ const head = `${'alias'.padEnd(18)}${'chain'.padEnd(13)}${'decimals'.padEnd(10)}${'signer'.padEnd(10)}from to`;
404
+ return [head, ...assets.map((a) => `${String(a['alias'] ?? '').padEnd(18)}${String(a['chain'] ?? '').padEnd(13)}${String(a['decimals'] ?? '').padEnd(10)}${String(a['signer'] ?? '').padEnd(10)}${a['origin'] ? 'yes ' : 'dry '} ${a['destination'] ? 'yes' : 'no'}`)];
405
+ }