oneie 5.7.5 → 5.7.6
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 +1 -0
- package/dist/package.json +5 -2
- package/dist/src/balances.d.ts +89 -0
- package/dist/src/balances.js +202 -0
- package/dist/src/hl-run.d.ts +119 -0
- package/dist/src/hl-run.js +480 -0
- package/dist/src/hl.d.ts +17 -0
- package/dist/src/hl.js +148 -0
- package/dist/src/index.js +2 -1
- package/dist/src/key-sweep.d.ts +19 -3
- package/dist/src/key-sweep.js +63 -20
- package/dist/src/lib/hl-core/actions.d.ts +99 -0
- package/dist/src/lib/hl-core/actions.js +69 -0
- package/dist/src/lib/hl-core/eip712.d.ts +33 -0
- package/dist/src/lib/hl-core/eip712.js +107 -0
- package/dist/src/lib/hl-core/errors.d.ts +10 -0
- package/dist/src/lib/hl-core/errors.js +15 -0
- package/dist/src/lib/hl-core/exchange.d.ts +24 -0
- package/dist/src/lib/hl-core/exchange.js +47 -0
- package/dist/src/lib/hl-core/index.d.ts +13 -0
- package/dist/src/lib/hl-core/index.js +14 -0
- package/dist/src/lib/hl-core/meta.d.ts +57 -0
- package/dist/src/lib/hl-core/meta.js +110 -0
- package/dist/src/lib/hl-core/msgpack.d.ts +18 -0
- package/dist/src/lib/hl-core/msgpack.js +136 -0
- package/dist/src/lib/hl-core/net.d.ts +2 -0
- package/dist/src/lib/hl-core/net.js +7 -0
- package/dist/src/lib/hl-core/signing.d.ts +103 -0
- package/dist/src/lib/hl-core/signing.js +295 -0
- package/dist/src/lib/hl-core/wire.d.ts +34 -0
- package/dist/src/lib/hl-core/wire.js +81 -0
- package/dist/src/lib/journey-words.d.ts +54 -3
- package/dist/src/lib/journey-words.js +159 -20
- package/dist/src/lib/journey.js +1 -1
- package/dist/src/lib/key-source.d.ts +9 -0
- package/dist/src/lib/key-source.js +33 -0
- package/dist/src/lib/network.d.ts +15 -0
- package/dist/src/lib/network.js +41 -0
- package/dist/src/lib/qr.d.ts +21 -0
- package/dist/src/lib/qr.js +402 -0
- package/dist/src/lib/sale-card.d.ts +117 -0
- package/dist/src/lib/sale-card.js +261 -0
- package/dist/src/lib/sui-grpc-send.d.ts +50 -0
- package/dist/src/lib/sui-grpc-send.js +89 -0
- package/dist/src/lib/wallet-money.d.ts +222 -0
- package/dist/src/lib/wallet-money.js +578 -0
- package/dist/src/lib/wallet-request.d.ts +50 -0
- package/dist/src/lib/wallet-request.js +86 -0
- package/dist/src/onboard.js +4 -3
- package/dist/src/shop.js +38 -1
- package/dist/src/staff.js +10 -0
- package/dist/src/start.js +14 -6
- package/dist/src/wallet-money.d.ts +152 -0
- package/dist/src/wallet-money.js +564 -0
- package/dist/src/wallet.js +169 -24
- package/package.json +5 -2
package/dist/src/key-sweep.d.ts
CHANGED
|
@@ -26,6 +26,8 @@
|
|
|
26
26
|
import { Command } from 'commander';
|
|
27
27
|
import type { SweepOrderChain } from '@oneie/sdk/sweep-order';
|
|
28
28
|
import type { SweepAsk, SweepTransfer } from '@oneie/sdk/sweep-runner';
|
|
29
|
+
import { type SuiSendDone, type SuiSendReq } from './lib/sui-grpc-send.js';
|
|
30
|
+
import { type Net } from './lib/wallet-money.js';
|
|
29
31
|
/** The order lives 10 minutes: inside the server's 15-minute cap, with room for the agent's 2-minute floor. */
|
|
30
32
|
export declare const ORDER_LIFETIME_MS: number;
|
|
31
33
|
type VaultKey = {
|
|
@@ -47,8 +49,22 @@ export interface SweepDeps {
|
|
|
47
49
|
}
|
|
48
50
|
/** One receiver call through the ask door; answers the receiver's own result. */
|
|
49
51
|
export declare function askVia(base: string, fetchImpl?: typeof fetch): SweepAsk;
|
|
50
|
-
/**
|
|
51
|
-
|
|
52
|
+
/**
|
|
53
|
+
* Sui balance in mist over gRPC — Sui JSON-RPC is switched off on every public fullnode.
|
|
54
|
+
* `core.getBalance` answers `balance.balance` (coin + address balance), already base units.
|
|
55
|
+
* `rpc` overrides the gRPC base URL; the default is Mysten's public fullnode for `net`.
|
|
56
|
+
*/
|
|
57
|
+
export declare function suiBalanceReader(opts: {
|
|
58
|
+
net: Net;
|
|
59
|
+
rpc?: string;
|
|
60
|
+
}, load?: (spec: string) => Promise<Record<string, unknown>>, deadlineMs?: number): (address: string) => Promise<string | null>;
|
|
61
|
+
/** The sweep's Sui signer over gRPC: one SUI transfer through suiSendGrpc; resolves to the digest. */
|
|
62
|
+
export declare function suiTransferGrpc(opts: {
|
|
63
|
+
net: Net;
|
|
64
|
+
rpc?: string;
|
|
65
|
+
}, send?: (r: SuiSendReq) => Promise<SuiSendDone>): SweepTransfer;
|
|
66
|
+
/** --network wins; else an --rpc URL that names mainnet or testnet; else null. */
|
|
67
|
+
export declare function sweepNet(network?: string, rpc?: string): Net | null;
|
|
52
68
|
export declare function ownerSweepRule(args: {
|
|
53
69
|
agent: string;
|
|
54
70
|
workspace: string;
|
|
@@ -68,7 +84,7 @@ export declare function agentSweepRun(args: {
|
|
|
68
84
|
workspace: string;
|
|
69
85
|
chain: SweepOrderChain;
|
|
70
86
|
rpc?: string;
|
|
71
|
-
network?:
|
|
87
|
+
network?: Net;
|
|
72
88
|
ownerAddress?: string;
|
|
73
89
|
}, deps: SweepDeps & {
|
|
74
90
|
transfer?: Partial<Record<SweepOrderChain, SweepTransfer>>;
|
package/dist/src/key-sweep.js
CHANGED
|
@@ -27,6 +27,8 @@ import { Command } from 'commander';
|
|
|
27
27
|
import { addressProofMessage, signAddressProof } from '@oneie/sdk/address-proof';
|
|
28
28
|
import { authHeaders, out, resolveBase } from './lib/client.js';
|
|
29
29
|
import { askPath } from './lib/api-path.js';
|
|
30
|
+
import { SUI_GRPC, SuiSendError, loadSpec, suiSendGrpc } from './lib/sui-grpc-send.js';
|
|
31
|
+
import { SUI_NATIVE, parseNet } from './lib/wallet-money.js';
|
|
30
32
|
import { unlock } from './wallet.js';
|
|
31
33
|
/** The vault's chain spelling for each sweep chain. */
|
|
32
34
|
const VAULT_CHAIN = { sui: 'sui', evm: 'evm', solana: 'sol', btc: 'btc' };
|
|
@@ -52,23 +54,57 @@ export function askVia(base, fetchImpl = fetch) {
|
|
|
52
54
|
}
|
|
53
55
|
};
|
|
54
56
|
}
|
|
55
|
-
/**
|
|
56
|
-
|
|
57
|
+
/**
|
|
58
|
+
* Sui balance in mist over gRPC — Sui JSON-RPC is switched off on every public fullnode.
|
|
59
|
+
* `core.getBalance` answers `balance.balance` (coin + address balance), already base units.
|
|
60
|
+
* `rpc` overrides the gRPC base URL; the default is Mysten's public fullnode for `net`.
|
|
61
|
+
*/
|
|
62
|
+
export function suiBalanceReader(opts, load = loadSpec, deadlineMs = 15_000) {
|
|
57
63
|
return async (address) => {
|
|
64
|
+
let timer;
|
|
58
65
|
try {
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
});
|
|
63
|
-
const
|
|
64
|
-
const v = json.result?.totalBalance;
|
|
66
|
+
const grpc = (await load('@mysten/sui/grpc'));
|
|
67
|
+
const client = new grpc.SuiGrpcClient({ network: opts.net, baseUrl: (opts.rpc ?? SUI_GRPC[opts.net]).replace(/\/$/, '') });
|
|
68
|
+
const deadline = new Promise((resolve) => { timer = setTimeout(() => resolve(null), deadlineMs); });
|
|
69
|
+
const res = await Promise.race([client.core.getBalance({ owner: address, coinType: SUI_NATIVE }), deadline]);
|
|
70
|
+
const v = res?.balance?.balance;
|
|
65
71
|
return digits(v) ? v : null;
|
|
66
72
|
}
|
|
67
73
|
catch {
|
|
68
74
|
return null;
|
|
69
75
|
}
|
|
76
|
+
finally {
|
|
77
|
+
if (timer)
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
}
|
|
70
80
|
};
|
|
71
81
|
}
|
|
82
|
+
/** The sweep's Sui signer over gRPC: one SUI transfer through suiSendGrpc; resolves to the digest. */
|
|
83
|
+
export function suiTransferGrpc(opts, send = (r) => suiSendGrpc(r)) {
|
|
84
|
+
return async (t) => {
|
|
85
|
+
if (t.chain !== 'sui')
|
|
86
|
+
throw new Error(`no_signer:${t.chain}`);
|
|
87
|
+
try {
|
|
88
|
+
const done = await send({ asset: 'SUI', coinType: SUI_NATIVE, from: t.from, to: t.to, amountUnits: t.amountUnits, privateKeyHex: t.privateKeyHex, rpc: opts.rpc, net: opts.net });
|
|
89
|
+
return done.digest;
|
|
90
|
+
}
|
|
91
|
+
catch (e) {
|
|
92
|
+
// Keep the code and, when one exists, the digest of a transfer that may still land.
|
|
93
|
+
if (e instanceof SuiSendError)
|
|
94
|
+
throw new Error(`${e.code}: ${e.message}${e.digest ? ` (digest ${e.digest})` : ''}`);
|
|
95
|
+
throw e;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/** --network wins; else an --rpc URL that names mainnet or testnet; else null. */
|
|
100
|
+
export function sweepNet(network, rpc) {
|
|
101
|
+
const n = parseNet(network);
|
|
102
|
+
if (n)
|
|
103
|
+
return n;
|
|
104
|
+
if (network === undefined && rpc)
|
|
105
|
+
return /mainnet/i.test(rpc) ? 'mainnet' : /testnet/i.test(rpc) ? 'testnet' : null;
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
72
108
|
function keyFor(keys, chain, address) {
|
|
73
109
|
const want = VAULT_CHAIN[chain];
|
|
74
110
|
const k = keys.find((x) => x.chain === want && (address === undefined || x.address.toLowerCase() === address.toLowerCase()));
|
|
@@ -112,7 +148,7 @@ export async function ownerSweep(args, deps) {
|
|
|
112
148
|
let balance = args.balance;
|
|
113
149
|
if (balance === undefined) {
|
|
114
150
|
if (!deps.readBalance)
|
|
115
|
-
return { ok: false, error: 'pass --balance <base units>, or --
|
|
151
|
+
return { ok: false, error: 'pass --balance <base units>, or --network mainnet|testnet to read it (sui only)' };
|
|
116
152
|
const read = await deps.readBalance(agentAddress);
|
|
117
153
|
if (read === null)
|
|
118
154
|
return { ok: false, error: 'could not read the agent balance — pass --balance' };
|
|
@@ -154,7 +190,7 @@ export async function ownerSweep(args, deps) {
|
|
|
154
190
|
}
|
|
155
191
|
// ── agent: perform and settle ──────────────────────────────────────────────
|
|
156
192
|
export async function agentSweepRun(args, deps) {
|
|
157
|
-
const { runSweepOrders
|
|
193
|
+
const { runSweepOrders } = await runnerModule();
|
|
158
194
|
const opened = await deps.unlock();
|
|
159
195
|
if ('error' in opened)
|
|
160
196
|
return { ok: false, error: opened.error };
|
|
@@ -163,9 +199,9 @@ export async function agentSweepRun(args, deps) {
|
|
|
163
199
|
return { ok: false, error: `the vault holds no ${args.chain} key` };
|
|
164
200
|
let transfer = deps.transfer;
|
|
165
201
|
if (!transfer && args.chain === 'sui') {
|
|
166
|
-
if (!args.
|
|
167
|
-
return { ok: false, error: 'pass --rpc <
|
|
168
|
-
transfer = { sui:
|
|
202
|
+
if (!args.network)
|
|
203
|
+
return { ok: false, error: 'pass --network mainnet|testnet (--rpc <gRPC base URL> optionally overrides the public fullnode)' };
|
|
204
|
+
transfer = { sui: suiTransferGrpc({ net: args.network, rpc: args.rpc }) };
|
|
169
205
|
}
|
|
170
206
|
const res = await runSweepOrders({ workspace: args.workspace, actor: args.agent, chain: args.chain, agentKey: { address: key.address, privateKeyHex: key.privateKeyHex }, ownerAddress: args.ownerAddress }, { ask: deps.ask, transfer, now: deps.now });
|
|
171
207
|
return { ok: res.ok, ...(res.error ? { error: res.error } : {}), agent: args.agent, chain: args.chain, results: res.results };
|
|
@@ -194,27 +230,34 @@ export function keySweepCommands() {
|
|
|
194
230
|
const sweep = common(new Command('sweep'))
|
|
195
231
|
.description("OWNER — sign a sweep order for what is due and submit it; the agent's runtime performs it")
|
|
196
232
|
.option('--amount <units>', 'Base units to sweep (default: everything above the float)')
|
|
197
|
-
.option('--balance <units>', "The agent's balance in base units (else read via --
|
|
198
|
-
.option('--
|
|
233
|
+
.option('--balance <units>', "The agent's balance in base units (else read from Sui over gRPC via --network, sui only)")
|
|
234
|
+
.option('--network <n>', 'mainnet | testnet — the Sui network to read the balance on')
|
|
235
|
+
.option('--rpc <url>', 'Sui gRPC base URL override (default: the public fullnode for --network)')
|
|
199
236
|
.action(async (o, c) => {
|
|
200
237
|
if (!isSweepChain(o.chain))
|
|
201
238
|
return out(c, { ok: false, error: '--chain must be sui, evm, solana or btc' });
|
|
239
|
+
if (o.network !== undefined && !parseNet(o.network))
|
|
240
|
+
return out(c, { ok: false, error: '--network must be mainnet or testnet' });
|
|
202
241
|
const deps = depsFor(o);
|
|
203
|
-
if (o.
|
|
204
|
-
|
|
242
|
+
if (o.chain === 'sui' && (o.network !== undefined || o.rpc)) {
|
|
243
|
+
const net = sweepNet(o.network, o.rpc);
|
|
244
|
+
if (!net)
|
|
245
|
+
return out(c, { ok: false, error: 'pass --network mainnet|testnet with --rpc' });
|
|
246
|
+
deps.readBalance = suiBalanceReader({ net, rpc: o.rpc });
|
|
247
|
+
}
|
|
205
248
|
out(c, await ownerSweep({ agent: o.agent, workspace: o.workspace ?? o.agent, chain: o.chain, amount: o.amount, balance: o.balance }, deps));
|
|
206
249
|
});
|
|
207
250
|
const run = common(new Command('sweep-run'))
|
|
208
251
|
.description("AGENT — perform and settle the owner's open sweep orders with this agent's own key (sui)")
|
|
209
|
-
.option('--rpc <url>', 'Sui
|
|
210
|
-
.option('--network <n>', 'mainnet | testnet')
|
|
252
|
+
.option('--rpc <url>', 'Sui gRPC base URL override (default: the public fullnode for --network)')
|
|
253
|
+
.option('--network <n>', 'mainnet | testnet — picks the Sui fullnode the transfer goes through')
|
|
211
254
|
.option('--owner-address <addr>', "Pin the owner's address; any other is refused")
|
|
212
255
|
.action(async (o, c) => {
|
|
213
256
|
if (!isSweepChain(o.chain))
|
|
214
257
|
return out(c, { ok: false, error: '--chain must be sui, evm, solana or btc' });
|
|
215
258
|
if (o.network !== undefined && o.network !== 'mainnet' && o.network !== 'testnet')
|
|
216
259
|
return out(c, { ok: false, error: '--network must be mainnet or testnet' });
|
|
217
|
-
out(c, await agentSweepRun({ agent: o.agent, workspace: o.workspace ?? o.agent, chain: o.chain, rpc: o.rpc, network: o.network, ownerAddress: o.ownerAddress }, depsFor(o)));
|
|
260
|
+
out(c, await agentSweepRun({ agent: o.agent, workspace: o.workspace ?? o.agent, chain: o.chain, rpc: o.rpc, network: sweepNet(o.network, o.rpc) ?? undefined, ownerAddress: o.ownerAddress }, depsFor(o)));
|
|
218
261
|
});
|
|
219
262
|
return [rule, sweep, run];
|
|
220
263
|
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hyperliquid/actions — builders for the four actions ONE prepares (text/hyperliquid-plan.md H2):
|
|
3
|
+
*
|
|
4
|
+
* L1 (msgpack-hashed, phantom-agent signed) order · cancel
|
|
5
|
+
* user-signed (own EIP-712 domain) usdClassTransfer · withdraw3
|
|
6
|
+
*
|
|
7
|
+
* KEY ORDER IS PART OF THE HASH for L1 actions: msgpack keeps insertion order, so each literal
|
|
8
|
+
* below is written in exactly the python SDK's order (`order_request_to_order_wire`,
|
|
9
|
+
* `order_wires_to_order_action`, `bulk_cancel`). Do not "tidy" them.
|
|
10
|
+
*
|
|
11
|
+
* Every builder validates against the asset's tick rules and throws `HlRefusal` before an action
|
|
12
|
+
* exists. Nothing here reads the network or the clock: nonce and mid come in as arguments.
|
|
13
|
+
*/
|
|
14
|
+
import { type AssetInfo } from './meta.js';
|
|
15
|
+
export type Tif = 'Gtc' | 'Ioc' | 'Alo';
|
|
16
|
+
export interface OrderWire {
|
|
17
|
+
a: number;
|
|
18
|
+
b: boolean;
|
|
19
|
+
p: string;
|
|
20
|
+
s: string;
|
|
21
|
+
r: boolean;
|
|
22
|
+
t: {
|
|
23
|
+
limit: {
|
|
24
|
+
tif: Tif;
|
|
25
|
+
};
|
|
26
|
+
};
|
|
27
|
+
c?: string;
|
|
28
|
+
}
|
|
29
|
+
export interface OrderAction {
|
|
30
|
+
type: 'order';
|
|
31
|
+
orders: OrderWire[];
|
|
32
|
+
grouping: 'na';
|
|
33
|
+
}
|
|
34
|
+
export interface CancelAction {
|
|
35
|
+
type: 'cancel';
|
|
36
|
+
cancels: Array<{
|
|
37
|
+
a: number;
|
|
38
|
+
o: number;
|
|
39
|
+
}>;
|
|
40
|
+
}
|
|
41
|
+
export interface UsdClassTransferAction {
|
|
42
|
+
type: 'usdClassTransfer';
|
|
43
|
+
amount: string;
|
|
44
|
+
toPerp: boolean;
|
|
45
|
+
nonce: number;
|
|
46
|
+
}
|
|
47
|
+
export interface Withdraw3Action {
|
|
48
|
+
type: 'withdraw3';
|
|
49
|
+
destination: string;
|
|
50
|
+
amount: string;
|
|
51
|
+
time: number;
|
|
52
|
+
}
|
|
53
|
+
export type L1Action = OrderAction | CancelAction;
|
|
54
|
+
export type UserAction = UsdClassTransferAction | Withdraw3Action;
|
|
55
|
+
export type HlAction = L1Action | UserAction;
|
|
56
|
+
export interface LimitOrderInput {
|
|
57
|
+
asset: AssetInfo;
|
|
58
|
+
isBuy: boolean;
|
|
59
|
+
/** Decimal string, in the asset's units. */
|
|
60
|
+
sz: string;
|
|
61
|
+
/** Decimal string. */
|
|
62
|
+
px: string;
|
|
63
|
+
tif?: Tif;
|
|
64
|
+
reduceOnly?: boolean;
|
|
65
|
+
/** 16-byte client order id, 0x + 32 hex. */
|
|
66
|
+
cloid?: string;
|
|
67
|
+
}
|
|
68
|
+
export declare function orderWire(o: LimitOrderInput): OrderWire;
|
|
69
|
+
export declare function buildOrder(o: LimitOrderInput): OrderAction;
|
|
70
|
+
export interface MarketOrderInput {
|
|
71
|
+
asset: AssetInfo;
|
|
72
|
+
isBuy: boolean;
|
|
73
|
+
sz: string;
|
|
74
|
+
/** The mid the caller read (allMids). The core never fetches it. */
|
|
75
|
+
mid: string;
|
|
76
|
+
/** Default 0.05, the python SDK's DEFAULT_SLIPPAGE. */
|
|
77
|
+
slippage?: number;
|
|
78
|
+
reduceOnly?: boolean;
|
|
79
|
+
cloid?: string;
|
|
80
|
+
}
|
|
81
|
+
/** A market order is an aggressive IOC limit (python `market_open` / `market_close`). */
|
|
82
|
+
export declare function buildMarketOrder(o: MarketOrderInput): OrderAction;
|
|
83
|
+
/** A cancel needs only the asset INDEX; pass the AssetInfo from the table when you have it. */
|
|
84
|
+
export declare function buildCancel(o: {
|
|
85
|
+
asset: Pick<AssetInfo, 'asset'>;
|
|
86
|
+
oid: number;
|
|
87
|
+
}): CancelAction;
|
|
88
|
+
/** Move USDC between the spot and perps balances of the SAME account (toPerp: spot → perps). */
|
|
89
|
+
export declare function buildUsdClassTransfer(o: {
|
|
90
|
+
amount: string;
|
|
91
|
+
toPerp: boolean;
|
|
92
|
+
nonce: number;
|
|
93
|
+
}): UsdClassTransferAction;
|
|
94
|
+
/** Withdraw USDC from the PERPS balance to an address on Arbitrum. */
|
|
95
|
+
export declare function buildWithdraw3(o: {
|
|
96
|
+
destination: string;
|
|
97
|
+
amount: string;
|
|
98
|
+
time: number;
|
|
99
|
+
}): Withdraw3Action;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
// VENDORED from one.ie/web/src/lib/hyperliquid/actions.ts by packages/cli/scripts/hl-core-vendor.mjs — do not edit; tests/hl-core-parity.test.ts compares bytes.
|
|
2
|
+
/**
|
|
3
|
+
* hyperliquid/actions — builders for the four actions ONE prepares (text/hyperliquid-plan.md H2):
|
|
4
|
+
*
|
|
5
|
+
* L1 (msgpack-hashed, phantom-agent signed) order · cancel
|
|
6
|
+
* user-signed (own EIP-712 domain) usdClassTransfer · withdraw3
|
|
7
|
+
*
|
|
8
|
+
* KEY ORDER IS PART OF THE HASH for L1 actions: msgpack keeps insertion order, so each literal
|
|
9
|
+
* below is written in exactly the python SDK's order (`order_request_to_order_wire`,
|
|
10
|
+
* `order_wires_to_order_action`, `bulk_cancel`). Do not "tidy" them.
|
|
11
|
+
*
|
|
12
|
+
* Every builder validates against the asset's tick rules and throws `HlRefusal` before an action
|
|
13
|
+
* exists. Nothing here reads the network or the clock: nonce and mid come in as arguments.
|
|
14
|
+
*/
|
|
15
|
+
import { HlRefusal } from './errors.js';
|
|
16
|
+
import { BUILDER_DEX_OFFSET } from './meta.js';
|
|
17
|
+
import { checkPrice, checkSize, checkUsd, marketPrice } from './wire.js';
|
|
18
|
+
const TIFS = ['Gtc', 'Ioc', 'Alo'];
|
|
19
|
+
const CLOID = /^0x[0-9a-fA-F]{32}$/;
|
|
20
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
21
|
+
export function orderWire(o) {
|
|
22
|
+
const tif = o.tif ?? 'Gtc';
|
|
23
|
+
if (!TIFS.includes(tif))
|
|
24
|
+
throw new HlRefusal('bad_tif', String(tif));
|
|
25
|
+
if (o.asset.delisted)
|
|
26
|
+
throw new HlRefusal('asset_delisted', o.asset.coin);
|
|
27
|
+
const s = checkSize(o.sz, o.asset.szDecimals);
|
|
28
|
+
const p = checkPrice(o.px, o.asset.szDecimals, o.asset.kind);
|
|
29
|
+
if (o.cloid !== undefined && !CLOID.test(o.cloid))
|
|
30
|
+
throw new HlRefusal('bad_cloid', o.cloid);
|
|
31
|
+
const w = { a: o.asset.asset, b: o.isBuy, p, s, r: o.reduceOnly ?? false, t: { limit: { tif } } };
|
|
32
|
+
if (o.cloid !== undefined)
|
|
33
|
+
w.c = o.cloid.toLowerCase();
|
|
34
|
+
return w;
|
|
35
|
+
}
|
|
36
|
+
export function buildOrder(o) {
|
|
37
|
+
return { type: 'order', orders: [orderWire(o)], grouping: 'na' };
|
|
38
|
+
}
|
|
39
|
+
/** A market order is an aggressive IOC limit (python `market_open` / `market_close`). */
|
|
40
|
+
export function buildMarketOrder(o) {
|
|
41
|
+
const px = marketPrice(o.mid, o.isBuy, o.slippage ?? 0.05, o.asset.szDecimals, o.asset.kind);
|
|
42
|
+
return buildOrder({ asset: o.asset, isBuy: o.isBuy, sz: o.sz, px, tif: 'Ioc', reduceOnly: o.reduceOnly, cloid: o.cloid });
|
|
43
|
+
}
|
|
44
|
+
/** A cancel needs only the asset INDEX; pass the AssetInfo from the table when you have it. */
|
|
45
|
+
export function buildCancel(o) {
|
|
46
|
+
const a = o.asset.asset;
|
|
47
|
+
if (!Number.isSafeInteger(a) || a < 0)
|
|
48
|
+
throw new HlRefusal('unknown_asset', String(a));
|
|
49
|
+
if (a >= BUILDER_DEX_OFFSET)
|
|
50
|
+
throw new HlRefusal('builder_dex_unsupported', String(a));
|
|
51
|
+
if (!Number.isSafeInteger(o.oid) || o.oid < 0)
|
|
52
|
+
throw new HlRefusal('bad_oid', String(o.oid));
|
|
53
|
+
return { type: 'cancel', cancels: [{ a, o: o.oid }] };
|
|
54
|
+
}
|
|
55
|
+
function checkNonce(n) {
|
|
56
|
+
if (!Number.isSafeInteger(n) || n <= 0)
|
|
57
|
+
throw new HlRefusal('nonce_required', String(n));
|
|
58
|
+
return n;
|
|
59
|
+
}
|
|
60
|
+
/** Move USDC between the spot and perps balances of the SAME account (toPerp: spot → perps). */
|
|
61
|
+
export function buildUsdClassTransfer(o) {
|
|
62
|
+
return { type: 'usdClassTransfer', amount: checkUsd(o.amount), toPerp: o.toPerp, nonce: checkNonce(o.nonce) };
|
|
63
|
+
}
|
|
64
|
+
/** Withdraw USDC from the PERPS balance to an address on Arbitrum. */
|
|
65
|
+
export function buildWithdraw3(o) {
|
|
66
|
+
if (!ADDRESS.test(o.destination))
|
|
67
|
+
throw new HlRefusal('bad_address', o.destination);
|
|
68
|
+
return { type: 'withdraw3', destination: o.destination.toLowerCase(), amount: checkUsd(o.amount), time: checkNonce(o.time) };
|
|
69
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hyperliquid/eip712 — the EIP-712 digest, in pure keccak, for the flat struct types Hyperliquid
|
|
3
|
+
* signs (text/hyperliquid-plan.md § The signer seam). Only the field types Hyperliquid uses are
|
|
4
|
+
* encoded: string · bytes32 · address · bool · uint64 · uint256. Any other type is refused,
|
|
5
|
+
* never guessed — a wrong encoding is a signature over a different message.
|
|
6
|
+
*
|
|
7
|
+
* Only the DECLARED fields are encoded. A user-signed action also carries `type` and
|
|
8
|
+
* `signatureChainId`; those are on the wire, not in the struct, exactly as eth_account ignores them.
|
|
9
|
+
*/
|
|
10
|
+
export interface TypedField {
|
|
11
|
+
name: string;
|
|
12
|
+
type: 'string' | 'bytes32' | 'address' | 'bool' | 'uint64' | 'uint256';
|
|
13
|
+
}
|
|
14
|
+
export interface Eip712Domain {
|
|
15
|
+
name: string;
|
|
16
|
+
version: string;
|
|
17
|
+
chainId: number;
|
|
18
|
+
verifyingContract: `0x${string}`;
|
|
19
|
+
}
|
|
20
|
+
/** The full eth_signTypedData_v4 shape: `types` INCLUDES EIP712Domain, `primaryType` is named. */
|
|
21
|
+
export interface TypedData {
|
|
22
|
+
domain: Eip712Domain;
|
|
23
|
+
types: Record<string, TypedField[]>;
|
|
24
|
+
primaryType: string;
|
|
25
|
+
message: Record<string, unknown>;
|
|
26
|
+
}
|
|
27
|
+
export declare const EIP712_DOMAIN_FIELDS: TypedField[];
|
|
28
|
+
export declare const toHex: (b: Uint8Array) => string;
|
|
29
|
+
export declare const hex0x: (b: Uint8Array) => `0x${string}`;
|
|
30
|
+
export declare function hexToBytes(h: string): Uint8Array;
|
|
31
|
+
export declare const encodeType: (name: string, fields: TypedField[]) => string;
|
|
32
|
+
export declare function hashStruct(name: string, fields: TypedField[], message: Record<string, unknown>): Uint8Array;
|
|
33
|
+
export declare function typedDataDigest(td: TypedData): Uint8Array;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
// VENDORED from one.ie/web/src/lib/hyperliquid/eip712.ts by packages/cli/scripts/hl-core-vendor.mjs — do not edit; tests/hl-core-parity.test.ts compares bytes.
|
|
2
|
+
/**
|
|
3
|
+
* hyperliquid/eip712 — the EIP-712 digest, in pure keccak, for the flat struct types Hyperliquid
|
|
4
|
+
* signs (text/hyperliquid-plan.md § The signer seam). Only the field types Hyperliquid uses are
|
|
5
|
+
* encoded: string · bytes32 · address · bool · uint64 · uint256. Any other type is refused,
|
|
6
|
+
* never guessed — a wrong encoding is a signature over a different message.
|
|
7
|
+
*
|
|
8
|
+
* Only the DECLARED fields are encoded. A user-signed action also carries `type` and
|
|
9
|
+
* `signatureChainId`; those are on the wire, not in the struct, exactly as eth_account ignores them.
|
|
10
|
+
*/
|
|
11
|
+
import { keccak_256 } from '@noble/hashes/sha3.js';
|
|
12
|
+
import { HlRefusal } from './errors.js';
|
|
13
|
+
export const EIP712_DOMAIN_FIELDS = [
|
|
14
|
+
{ name: 'name', type: 'string' },
|
|
15
|
+
{ name: 'version', type: 'string' },
|
|
16
|
+
{ name: 'chainId', type: 'uint256' },
|
|
17
|
+
{ name: 'verifyingContract', type: 'address' },
|
|
18
|
+
];
|
|
19
|
+
export const toHex = (b) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
|
|
20
|
+
export const hex0x = (b) => `0x${toHex(b)}`;
|
|
21
|
+
export function hexToBytes(h) {
|
|
22
|
+
const s = h.startsWith('0x') ? h.slice(2) : h;
|
|
23
|
+
if (s.length % 2 !== 0 || !/^[0-9a-fA-F]*$/.test(s))
|
|
24
|
+
throw new HlRefusal('bad_hex', h);
|
|
25
|
+
const out = new Uint8Array(s.length / 2);
|
|
26
|
+
for (let i = 0; i < out.length; i++)
|
|
27
|
+
out[i] = parseInt(s.slice(2 * i, 2 * i + 2), 16);
|
|
28
|
+
return out;
|
|
29
|
+
}
|
|
30
|
+
function word(n) {
|
|
31
|
+
if (n < 0n || n >= 1n << 256n)
|
|
32
|
+
throw new HlRefusal('eip712_range', String(n));
|
|
33
|
+
const out = new Uint8Array(32);
|
|
34
|
+
for (let i = 31; i >= 0; i--) {
|
|
35
|
+
out[i] = Number(n & 0xffn);
|
|
36
|
+
n >>= 8n;
|
|
37
|
+
}
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
function toUint(v, bits, at) {
|
|
41
|
+
let n;
|
|
42
|
+
if (typeof v === 'bigint')
|
|
43
|
+
n = v;
|
|
44
|
+
else if (typeof v === 'number' && Number.isSafeInteger(v))
|
|
45
|
+
n = BigInt(v);
|
|
46
|
+
else if (typeof v === 'string' && /^(0x[0-9a-fA-F]+|\d+)$/.test(v))
|
|
47
|
+
n = BigInt(v);
|
|
48
|
+
else
|
|
49
|
+
throw new HlRefusal('eip712_value', `${at} not a uint`);
|
|
50
|
+
if (n < 0n || n >= 1n << BigInt(bits))
|
|
51
|
+
throw new HlRefusal('eip712_range', at);
|
|
52
|
+
return n;
|
|
53
|
+
}
|
|
54
|
+
function encodeValue(f, v) {
|
|
55
|
+
switch (f.type) {
|
|
56
|
+
case 'string':
|
|
57
|
+
if (typeof v !== 'string')
|
|
58
|
+
throw new HlRefusal('eip712_value', `${f.name} not a string`);
|
|
59
|
+
return keccak_256(new TextEncoder().encode(v));
|
|
60
|
+
case 'bytes32': {
|
|
61
|
+
const b = v instanceof Uint8Array ? v : typeof v === 'string' ? hexToBytes(v) : null;
|
|
62
|
+
if (!b || b.length !== 32)
|
|
63
|
+
throw new HlRefusal('eip712_value', `${f.name} not bytes32`);
|
|
64
|
+
return b;
|
|
65
|
+
}
|
|
66
|
+
case 'address': {
|
|
67
|
+
if (typeof v !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(v))
|
|
68
|
+
throw new HlRefusal('eip712_value', `${f.name} not an address`);
|
|
69
|
+
return word(BigInt(v));
|
|
70
|
+
}
|
|
71
|
+
case 'bool':
|
|
72
|
+
if (typeof v !== 'boolean')
|
|
73
|
+
throw new HlRefusal('eip712_value', `${f.name} not a bool`);
|
|
74
|
+
return word(v ? 1n : 0n);
|
|
75
|
+
case 'uint64':
|
|
76
|
+
return word(toUint(v, 64, f.name));
|
|
77
|
+
case 'uint256':
|
|
78
|
+
return word(toUint(v, 256, f.name));
|
|
79
|
+
default:
|
|
80
|
+
throw new HlRefusal('eip712_type', String(f.type));
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export const encodeType = (name, fields) => `${name}(${fields.map((f) => `${f.type} ${f.name}`).join(',')})`;
|
|
84
|
+
export function hashStruct(name, fields, message) {
|
|
85
|
+
const parts = [keccak_256(new TextEncoder().encode(encodeType(name, fields)))];
|
|
86
|
+
for (const f of fields) {
|
|
87
|
+
if (!(f.name in message))
|
|
88
|
+
throw new HlRefusal('eip712_missing', f.name);
|
|
89
|
+
parts.push(encodeValue(f, message[f.name]));
|
|
90
|
+
}
|
|
91
|
+
const buf = new Uint8Array(parts.length * 32);
|
|
92
|
+
parts.forEach((p, i) => buf.set(p, i * 32));
|
|
93
|
+
return keccak_256(buf);
|
|
94
|
+
}
|
|
95
|
+
export function typedDataDigest(td) {
|
|
96
|
+
const fields = td.types[td.primaryType];
|
|
97
|
+
if (!fields)
|
|
98
|
+
throw new HlRefusal('eip712_type', td.primaryType);
|
|
99
|
+
const domainSep = hashStruct('EIP712Domain', EIP712_DOMAIN_FIELDS, td.domain);
|
|
100
|
+
const body = hashStruct(td.primaryType, fields, td.message);
|
|
101
|
+
const buf = new Uint8Array(66);
|
|
102
|
+
buf[0] = 0x19;
|
|
103
|
+
buf[1] = 0x01;
|
|
104
|
+
buf.set(domainSep, 2);
|
|
105
|
+
buf.set(body, 34);
|
|
106
|
+
return keccak_256(buf);
|
|
107
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hyperliquid/errors — every refusal in the core is a named code, thrown BEFORE any typed data
|
|
3
|
+
* exists or any signer is asked. Callers (CLI, page, receiver) catch `HlRefusal` and show the code.
|
|
4
|
+
*/
|
|
5
|
+
export type HlRefusalCode = 'bad_hex' | 'bad_address' | 'bad_decimal' | 'size_zero' | 'size_too_precise' | 'price_zero' | 'price_sig_figs' | 'price_too_precise' | 'amount_zero' | 'amount_too_precise' | 'bad_slippage' | 'bad_cloid' | 'bad_oid' | 'bad_tif' | 'unknown_asset' | 'asset_delisted' | 'asset_mismatch' | 'builder_dex_unsupported' | 'meta_required' | 'nonce_required' | 'nonce_mismatch' | 'vault_unsupported' | 'expires_unsupported' | 'unsupported_action' | 'signer_mismatch' | 'bad_signature' | 'eip712_type' | 'eip712_value' | 'eip712_range' | 'eip712_missing';
|
|
6
|
+
export declare class HlRefusal extends Error {
|
|
7
|
+
code: HlRefusalCode;
|
|
8
|
+
detail?: string | undefined;
|
|
9
|
+
constructor(code: HlRefusalCode, detail?: string | undefined);
|
|
10
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// VENDORED from one.ie/web/src/lib/hyperliquid/errors.ts by packages/cli/scripts/hl-core-vendor.mjs — do not edit; tests/hl-core-parity.test.ts compares bytes.
|
|
2
|
+
/**
|
|
3
|
+
* hyperliquid/errors — every refusal in the core is a named code, thrown BEFORE any typed data
|
|
4
|
+
* exists or any signer is asked. Callers (CLI, page, receiver) catch `HlRefusal` and show the code.
|
|
5
|
+
*/
|
|
6
|
+
export class HlRefusal extends Error {
|
|
7
|
+
code;
|
|
8
|
+
detail;
|
|
9
|
+
constructor(code, detail) {
|
|
10
|
+
super(detail ? `${code}: ${detail}` : code);
|
|
11
|
+
this.code = code;
|
|
12
|
+
this.detail = detail;
|
|
13
|
+
this.name = 'HlRefusal';
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hyperliquid/exchange — the ONE function that POSTs to /exchange (text/hyperliquid-plan.md H7).
|
|
3
|
+
* It takes an already-signed request; it cannot sign and it never builds an action. The server
|
|
4
|
+
* never calls it (R19 / H8): it runs in the browser or the CLI, beside the key that signed.
|
|
5
|
+
*
|
|
6
|
+
* Hyperliquid answers 200 for refusals too: `{status:'err', response:'<reason>'}`, and an order's
|
|
7
|
+
* per-order `statuses[i].error`. Both come back `ok:false` with the exchange's own words.
|
|
8
|
+
*/
|
|
9
|
+
import type { HlNet } from './net.js';
|
|
10
|
+
import { type ExchangeRequest } from './signing.js';
|
|
11
|
+
export type ExchangeResult = {
|
|
12
|
+
ok: true;
|
|
13
|
+
response: unknown;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
error: 'exchange_refused' | 'exchange_unavailable';
|
|
17
|
+
detail: string;
|
|
18
|
+
response?: unknown;
|
|
19
|
+
};
|
|
20
|
+
export declare function readExchangeAnswer(body: unknown): ExchangeResult;
|
|
21
|
+
export declare function postExchange(request: ExchangeRequest, net: HlNet, o?: {
|
|
22
|
+
fetchImpl?: typeof fetch;
|
|
23
|
+
timeoutMs?: number;
|
|
24
|
+
}): Promise<ExchangeResult>;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// VENDORED from one.ie/web/src/lib/hyperliquid/exchange.ts by packages/cli/scripts/hl-core-vendor.mjs — do not edit; tests/hl-core-parity.test.ts compares bytes.
|
|
2
|
+
/**
|
|
3
|
+
* hyperliquid/exchange — the ONE function that POSTs to /exchange (text/hyperliquid-plan.md H7).
|
|
4
|
+
* It takes an already-signed request; it cannot sign and it never builds an action. The server
|
|
5
|
+
* never calls it (R19 / H8): it runs in the browser or the CLI, beside the key that signed.
|
|
6
|
+
*
|
|
7
|
+
* Hyperliquid answers 200 for refusals too: `{status:'err', response:'<reason>'}`, and an order's
|
|
8
|
+
* per-order `statuses[i].error`. Both come back `ok:false` with the exchange's own words.
|
|
9
|
+
*/
|
|
10
|
+
import { HL_EXCHANGE } from './signing.js';
|
|
11
|
+
const isObj = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
|
|
12
|
+
export function readExchangeAnswer(body) {
|
|
13
|
+
if (!isObj(body))
|
|
14
|
+
return { ok: false, error: 'exchange_unavailable', detail: 'not json' };
|
|
15
|
+
if (body['status'] !== 'ok') {
|
|
16
|
+
return { ok: false, error: 'exchange_refused', detail: typeof body['response'] === 'string' ? body['response'] : 'err', response: body['response'] };
|
|
17
|
+
}
|
|
18
|
+
const resp = body['response'];
|
|
19
|
+
const statuses = isObj(resp) && isObj(resp['data']) && Array.isArray(resp['data']['statuses']) ? resp['data']['statuses'] : [];
|
|
20
|
+
const firstErr = statuses.find((s) => isObj(s) && typeof s['error'] === 'string');
|
|
21
|
+
if (firstErr)
|
|
22
|
+
return { ok: false, error: 'exchange_refused', detail: String(firstErr['error']), response: resp };
|
|
23
|
+
return { ok: true, response: resp };
|
|
24
|
+
}
|
|
25
|
+
export async function postExchange(request, net, o = {}) {
|
|
26
|
+
const f = o.fetchImpl ?? fetch;
|
|
27
|
+
try {
|
|
28
|
+
const res = await f(HL_EXCHANGE[net], {
|
|
29
|
+
method: 'POST',
|
|
30
|
+
headers: { 'content-type': 'application/json' },
|
|
31
|
+
body: JSON.stringify(request),
|
|
32
|
+
signal: AbortSignal.timeout(o.timeoutMs ?? 10_000),
|
|
33
|
+
});
|
|
34
|
+
const text = await res.text();
|
|
35
|
+
let body;
|
|
36
|
+
try {
|
|
37
|
+
body = JSON.parse(text);
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return { ok: false, error: 'exchange_unavailable', detail: `status_${res.status}: ${text.slice(0, 200)}` };
|
|
41
|
+
}
|
|
42
|
+
return readExchangeAnswer(body);
|
|
43
|
+
}
|
|
44
|
+
catch (e) {
|
|
45
|
+
return { ok: false, error: 'exchange_unavailable', detail: e.message };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* hyperliquid — the core the CLI and the browser both sign with (text/hyperliquid-plan.md).
|
|
3
|
+
* Pure except `meta.ts` reads and `exchange.ts` posts, both through a `fetchImpl` seam.
|
|
4
|
+
* No key material anywhere: a key is a `Signer` the caller brings.
|
|
5
|
+
*/
|
|
6
|
+
export * from './errors.js';
|
|
7
|
+
export * from './wire.js';
|
|
8
|
+
export * from './meta.js';
|
|
9
|
+
export * from './actions.js';
|
|
10
|
+
export * from './signing.js';
|
|
11
|
+
export * from './exchange.js';
|
|
12
|
+
export { packb } from './msgpack.js';
|
|
13
|
+
export { typedDataDigest, type TypedData, type TypedField, type Eip712Domain } from './eip712.js';
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// VENDORED from one.ie/web/src/lib/hyperliquid/index.ts by packages/cli/scripts/hl-core-vendor.mjs — do not edit; tests/hl-core-parity.test.ts compares bytes.
|
|
2
|
+
/**
|
|
3
|
+
* hyperliquid — the core the CLI and the browser both sign with (text/hyperliquid-plan.md).
|
|
4
|
+
* Pure except `meta.ts` reads and `exchange.ts` posts, both through a `fetchImpl` seam.
|
|
5
|
+
* No key material anywhere: a key is a `Signer` the caller brings.
|
|
6
|
+
*/
|
|
7
|
+
export * from './errors.js';
|
|
8
|
+
export * from './wire.js';
|
|
9
|
+
export * from './meta.js';
|
|
10
|
+
export * from './actions.js';
|
|
11
|
+
export * from './signing.js';
|
|
12
|
+
export * from './exchange.js';
|
|
13
|
+
export { packb } from './msgpack.js';
|
|
14
|
+
export { typedDataDigest } from './eip712.js';
|