@vordium/sdk 0.0.0-stage → 0.1.1

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.
Files changed (52) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +109 -2
  3. package/dist/cjs/account.js +126 -0
  4. package/dist/cjs/agents.js +237 -0
  5. package/dist/cjs/client.js +526 -0
  6. package/dist/cjs/domains.js +37 -0
  7. package/dist/cjs/errors.js +39 -0
  8. package/dist/cjs/feeds.js +278 -0
  9. package/dist/cjs/http.js +97 -0
  10. package/dist/cjs/index.js +37 -0
  11. package/dist/cjs/network.js +114 -0
  12. package/dist/cjs/nonce.js +36 -0
  13. package/dist/cjs/orders.js +260 -0
  14. package/dist/cjs/package.json +1 -0
  15. package/dist/cjs/reads.js +121 -0
  16. package/dist/cjs/rounding.js +252 -0
  17. package/dist/cjs/sign.js +49 -0
  18. package/dist/cjs/types.js +57 -0
  19. package/dist/cjs/units.js +78 -0
  20. package/dist/esm/account.d.ts +61 -0
  21. package/dist/esm/account.js +114 -0
  22. package/dist/esm/agents.d.ts +71 -0
  23. package/dist/esm/agents.js +225 -0
  24. package/dist/esm/client.d.ts +239 -0
  25. package/dist/esm/client.js +520 -0
  26. package/dist/esm/domains.d.ts +21 -0
  27. package/dist/esm/domains.js +30 -0
  28. package/dist/esm/errors.d.ts +18 -0
  29. package/dist/esm/errors.js +32 -0
  30. package/dist/esm/feeds.d.ts +97 -0
  31. package/dist/esm/feeds.js +267 -0
  32. package/dist/esm/http.d.ts +24 -0
  33. package/dist/esm/http.js +93 -0
  34. package/dist/esm/index.d.ts +15 -0
  35. package/dist/esm/index.js +15 -0
  36. package/dist/esm/network.d.ts +44 -0
  37. package/dist/esm/network.js +107 -0
  38. package/dist/esm/nonce.d.ts +15 -0
  39. package/dist/esm/nonce.js +31 -0
  40. package/dist/esm/orders.d.ts +141 -0
  41. package/dist/esm/orders.js +238 -0
  42. package/dist/esm/reads.d.ts +59 -0
  43. package/dist/esm/reads.js +113 -0
  44. package/dist/esm/rounding.d.ts +70 -0
  45. package/dist/esm/rounding.js +229 -0
  46. package/dist/esm/sign.d.ts +27 -0
  47. package/dist/esm/sign.js +43 -0
  48. package/dist/esm/types.d.ts +41 -0
  49. package/dist/esm/types.js +51 -0
  50. package/dist/esm/units.d.ts +16 -0
  51. package/dist/esm/units.js +70 -0
  52. package/package.json +53 -4
@@ -0,0 +1,225 @@
1
+ import { InvalidRequest } from './errors.js';
2
+ /**
3
+ * Agents: a key that trades for an account within the limits its owner signs. The operations in force:
4
+ * RegisterAgentV2 (a name is required), SetAgentName, SetAgentPolicyV1, SetAgentMarketLimit, ClearAgentLock and
5
+ * RevokeAgent. Each is signed by the OWNER in the VordCore domain and sent to `POST /submit`; only SetAgentPolicyV1 may
6
+ * also be signed by the agent itself, and then only to tighten the stored policy.
7
+ */
8
+ // ── Names ───────────────────────────────────────────────────────────────────────────────────────────────────────────
9
+ export const NAME_MIN_BYTES = 3;
10
+ export const NAME_MAX_BYTES = 32;
11
+ export const RESERVED_WORDS_DEFAULT = ['admin', 'helpdesk', 'moderator', 'official', 'support', 'validator', 'vordex', 'vordium', 'vordscan'];
12
+ /** What is signed: NFKC, every run of ASCII whitespace becomes one space, no space at either end. */
13
+ export function normalizeName(raw) {
14
+ let s = raw.normalize('NFKC').replace(/[ \t\n\r\f\v]+/g, ' ');
15
+ if (s.startsWith(' '))
16
+ s = s.slice(1);
17
+ if (s.endsWith(' '))
18
+ s = s.slice(0, -1);
19
+ return s;
20
+ }
21
+ /** ASCII letters lower-cased, with `space - _ .` removed: what reserved words are matched in (as the node builds it). */
22
+ export function nameSkeleton(name) {
23
+ return name.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/[ \-_.]/g, '');
24
+ }
25
+ function judge(name, reserved) {
26
+ if (!name)
27
+ return ['TooShort', 'Enter a name.'];
28
+ if ([...name].some((c) => c.codePointAt(0) > 0x7f))
29
+ return ['NonAscii', 'Use plain letters and digits: no accents, emoji or other symbols.'];
30
+ if (/[\x00-\x1f\x7f]/.test(name))
31
+ return ['ControlChar', 'No tabs, line breaks or other control characters.'];
32
+ if (!/^[A-Za-z0-9 \-_.]+$/.test(name))
33
+ return ['BadChar', 'Use only letters, digits, spaces, hyphens (-), underscores (_) and dots (.).'];
34
+ if (name.length < NAME_MIN_BYTES)
35
+ return ['TooShort', `Use at least ${NAME_MIN_BYTES} characters.`];
36
+ if (name.length > NAME_MAX_BYTES)
37
+ return ['TooLong', `Use at most ${NAME_MAX_BYTES} characters.`];
38
+ if (name.startsWith(' ') || name.endsWith(' ') || name.includes(' '))
39
+ return ['NotCanonical', 'No space at the start or end, and no double spaces.'];
40
+ if (!/[A-Za-z0-9]/.test(name))
41
+ return ['NoAlphanumeric', 'Include at least one letter or digit.'];
42
+ const sk = nameSkeleton(name);
43
+ for (const w of reserved)
44
+ if (sk.includes(w))
45
+ return ['Reserved', `A name can't contain the reserved word "${w}".`];
46
+ return null;
47
+ }
48
+ /**
49
+ * The chain's form rule for an ALREADY-normalised name, in the chain's own step order: `null` when accepted, else the
50
+ * refusing step. Uniqueness among the owner's agents, the rename wait and the live-agent limit are the chain's to judge.
51
+ */
52
+ export function nameRefusalStep(name, reserved = RESERVED_WORDS_DEFAULT) {
53
+ return judge(name, reserved)?.[0] ?? null;
54
+ }
55
+ /** Normalise then check: the name to sign, or InvalidRequest with the reason. */
56
+ export function requireName(raw, reserved = RESERVED_WORDS_DEFAULT) {
57
+ const n = normalizeName(raw);
58
+ const j = judge(n, reserved);
59
+ if (j)
60
+ throw new InvalidRequest(j[1]);
61
+ return n;
62
+ }
63
+ // ── Policy ──────────────────────────────────────────────────────────────────────────────────────────────────────────
64
+ export const CAPABILITY_BITS = { place: 0, cancel: 1, modify: 2, tpsl: 3, close: 4, vault: 5 };
65
+ export const CAPS_ALL = 0b111111;
66
+ export const ORACLE_BAND_MIN_BPS = 1;
67
+ export const ORACLE_BAND_MAX_BPS = 1000;
68
+ export const MAX_LEVERAGE_BPS = 500_000;
69
+ export const DAY_MS = 86_400_000;
70
+ const isU = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
71
+ const fmt = (n) => (Number.isInteger(n) ? String(n) : String(n));
72
+ /** Why the chain would refuse this policy at apply (it refuses silently); [] = none of the stateless reasons. */
73
+ export function policyProblems(p, nowMs) {
74
+ const out = [];
75
+ if (!isU(p.capsBitmask) || (p.capsBitmask & ~CAPS_ALL) !== 0)
76
+ out.push('Choose capabilities from the list only.');
77
+ if (p.sideMode !== 0 && p.sideMode !== 1)
78
+ out.push('Choose whether the agent may open positions or only reduce them.');
79
+ if (typeof p.maxTotalExposure6dec !== 'bigint' || p.maxTotalExposure6dec <= 0n)
80
+ out.push('Set a total exposure above zero.');
81
+ if (typeof p.dailyLossLimit6dec !== 'bigint' || p.dailyLossLimit6dec <= 0n)
82
+ out.push('Set a daily loss limit above zero.');
83
+ if (typeof p.dailyFeeCap6dec !== 'bigint' || p.dailyFeeCap6dec < 0n)
84
+ out.push('The daily fee cap cannot be negative.');
85
+ if (!isU(p.maxLeverageBps) || p.maxLeverageBps > MAX_LEVERAGE_BPS)
86
+ out.push(`Leverage can be at most ${fmt(MAX_LEVERAGE_BPS / 10000)}x (or 0 for no limit).`);
87
+ if (!isU(p.oracleBandBps) || p.oracleBandBps < ORACLE_BAND_MIN_BPS || p.oracleBandBps > ORACLE_BAND_MAX_BPS) {
88
+ out.push(`The oracle band must be between ${fmt(ORACLE_BAND_MIN_BPS / 100)}% and ${fmt(ORACLE_BAND_MAX_BPS / 100)}%.`);
89
+ }
90
+ const bothZero = p.opsPerWindow === 0 && p.opsWindowMs === 0;
91
+ if (!isU(p.opsPerWindow) || !isU(p.opsWindowMs) || !(bothZero || (p.opsPerWindow > 0 && p.opsWindowMs > 0 && p.opsWindowMs <= DAY_MS))) {
92
+ out.push('Set both the operations per window and a window of at most a day, or leave both at zero for no limit.');
93
+ }
94
+ if (!isU(p.activeFromMsOfDay) || !isU(p.activeToMsOfDay) || p.activeFromMsOfDay >= DAY_MS || p.activeToMsOfDay >= DAY_MS
95
+ || (p.activeFromMsOfDay === p.activeToMsOfDay && p.activeFromMsOfDay !== 0)) {
96
+ out.push('Set active hours that start and end at different times within the day, or leave both at midnight for always.');
97
+ }
98
+ if (!isU(p.expiresMs) || p.expiresMs <= nowMs)
99
+ out.push('Set an expiry in the future.');
100
+ return out;
101
+ }
102
+ /** What in `next` would LOOSEN `prev`; [] = a tightening or no change (and always [] with nothing stored). */
103
+ export function loosens(prev, next) {
104
+ if (!prev)
105
+ return [];
106
+ const out = [];
107
+ const higherOrUnlimited = (a, b) => (b === 0n ? a !== 0n : a !== 0n && b > a);
108
+ if ((next.capsBitmask & ~prev.capsBitmask) !== 0)
109
+ out.push('adds a capability');
110
+ if (next.sideMode < prev.sideMode)
111
+ out.push('lets the agent open positions');
112
+ if (next.maxTotalExposure6dec > prev.maxTotalExposure6dec)
113
+ out.push('raises the total exposure');
114
+ if (higherOrUnlimited(BigInt(prev.maxLeverageBps), BigInt(next.maxLeverageBps)))
115
+ out.push('raises the leverage');
116
+ if (next.dailyLossLimit6dec > prev.dailyLossLimit6dec)
117
+ out.push('raises the daily loss limit');
118
+ if (higherOrUnlimited(prev.dailyFeeCap6dec, next.dailyFeeCap6dec))
119
+ out.push('raises the daily fee cap');
120
+ if (next.expiresMs > prev.expiresMs)
121
+ out.push('extends the expiry');
122
+ if (next.oracleBandBps > prev.oracleBandBps)
123
+ out.push('widens the oracle band');
124
+ if (next.lockAutoClear && !prev.lockAutoClear)
125
+ out.push('turns on automatic lock clearing');
126
+ if (next.enabled && !prev.enabled)
127
+ out.push('turns the policy on');
128
+ if (next.opsPerWindow !== prev.opsPerWindow || next.opsWindowMs !== prev.opsWindowMs)
129
+ out.push('changes the operations limit');
130
+ if (next.activeFromMsOfDay !== prev.activeFromMsOfDay || next.activeToMsOfDay !== prev.activeToMsOfDay)
131
+ out.push('changes the active hours');
132
+ return out;
133
+ }
134
+ /** Per operation: [struct name, wire name, kind], in the order the node reads them. */
135
+ export const SUBMIT_FIELDS = {
136
+ RegisterAgentV2: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['name', 'name', 'string'], ['mandate', 'mandate', 'string'], ['expiresMs', 'expires_ms', 'u64'], ['nonce', 'nonce', 'u64']],
137
+ SetAgentName: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['name', 'name', 'string'], ['nonce', 'nonce', 'u64']],
138
+ SetAgentPolicyV1: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['capsBitmask', 'caps_bitmask', 'u32'], ['sideMode', 'side_mode', 'u8'],
139
+ ['maxTotalExposure6dec', 'max_total_exposure_6dec', 'u128'], ['maxLeverageBps', 'max_leverage_bps', 'u32'], ['dailyLossLimit6dec', 'daily_loss_limit_6dec', 'u128'],
140
+ ['dailyFeeCap6dec', 'daily_fee_cap_6dec', 'u128'], ['opsPerWindow', 'ops_per_window', 'u32'], ['opsWindowMs', 'ops_window_ms', 'u32'],
141
+ ['activeFromMsOfDay', 'active_from_ms_of_day', 'u32'], ['activeToMsOfDay', 'active_to_ms_of_day', 'u32'], ['oracleBandBps', 'oracle_band_bps', 'u32'],
142
+ ['lockAutoClear', 'lock_auto_clear', 'bool'], ['expiresMs', 'expires_ms', 'u64'], ['enabled', 'enabled', 'bool'], ['nonce', 'nonce', 'u64']],
143
+ SetAgentMarketLimit: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['pair', 'pair', 'u32'], ['allowed', 'allowed', 'bool'],
144
+ ['maxOrder18dec', 'max_order_18dec', 'u128'], ['maxPosition18dec', 'max_position_18dec', 'u128'], ['maxLeverageBps', 'max_leverage_bps', 'u32'], ['nonce', 'nonce', 'u64']],
145
+ ClearAgentLock: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['lockSinceMs', 'lock_since_ms', 'u64'], ['nonce', 'nonce', 'u64']],
146
+ RevokeAgent: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['nonce', 'nonce', 'u64']],
147
+ };
148
+ /** These operations carry their addresses in lower case on the wire; the others as given. */
149
+ export const LOWERCASE_ADDRESS_OPS = new Set(['RegisterAgentV2', 'SetAgentName', 'SetAgentPolicyV1', 'ClearAgentLock']);
150
+ function encode(op, kind, wire, v) {
151
+ if (kind === 'address') {
152
+ if (typeof v !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(v))
153
+ throw new InvalidRequest(`${wire} is not an address.`);
154
+ return LOWERCASE_ADDRESS_OPS.has(op) ? v.toLowerCase() : v;
155
+ }
156
+ if (kind === 'string') {
157
+ if (typeof v !== 'string')
158
+ throw new InvalidRequest(`${wire} is not text.`);
159
+ return v;
160
+ }
161
+ if (kind === 'bool') {
162
+ if (typeof v !== 'boolean')
163
+ throw new InvalidRequest(`${wire} is not true or false.`);
164
+ return v;
165
+ }
166
+ let b;
167
+ if (typeof v === 'bigint')
168
+ b = v;
169
+ else if (typeof v === 'number' && Number.isSafeInteger(v))
170
+ b = BigInt(v);
171
+ else if (typeof v === 'string' && /^\d+$/.test(v))
172
+ b = BigInt(v);
173
+ else
174
+ throw new InvalidRequest(`${wire} is not a whole number.`);
175
+ if (b < 0n)
176
+ throw new InvalidRequest(`${wire} is not a whole number.`);
177
+ if (kind === 'u128')
178
+ return b.toString();
179
+ if (b > BigInt(Number.MAX_SAFE_INTEGER))
180
+ throw new InvalidRequest(`${wire} is past the exact-integer range.`);
181
+ return Number(b);
182
+ }
183
+ /** The exact `POST /submit` body for one signed agent operation (every field, in wire order). */
184
+ export function submitBody(op, value, signature) {
185
+ const fields = SUBMIT_FIELDS[op];
186
+ if (!fields)
187
+ throw new InvalidRequest(`${String(op)} is not an agent operation in force.`);
188
+ const s = signature.toLowerCase();
189
+ if (!/^0x[0-9a-f]{130}$/.test(s))
190
+ throw new InvalidRequest('The signature is not 65 bytes of hex.');
191
+ const body = { op };
192
+ for (const [struct, wire, kind] of fields) {
193
+ if (!(struct in value))
194
+ throw new InvalidRequest(`${struct} is missing from the signed operation.`);
195
+ body[wire] = encode(op, kind, wire, value[struct]);
196
+ }
197
+ body.signature = s;
198
+ return body;
199
+ }
200
+ export function policyValue(owner, agent, p, nonce) {
201
+ return {
202
+ owner, agent, capsBitmask: p.capsBitmask, sideMode: p.sideMode, maxTotalExposure6dec: p.maxTotalExposure6dec, maxLeverageBps: p.maxLeverageBps,
203
+ dailyLossLimit6dec: p.dailyLossLimit6dec, dailyFeeCap6dec: p.dailyFeeCap6dec, opsPerWindow: p.opsPerWindow, opsWindowMs: p.opsWindowMs,
204
+ activeFromMsOfDay: p.activeFromMsOfDay, activeToMsOfDay: p.activeToMsOfDay, oracleBandBps: p.oracleBandBps, lockAutoClear: p.lockAutoClear,
205
+ expiresMs: p.expiresMs, enabled: p.enabled, nonce,
206
+ };
207
+ }
208
+ /** The stored policy from `GET /agents/{owner}/{agent}` (`policy_v1`, the node's snake_case names), or null. */
209
+ export function policyFromRead(x) {
210
+ if (!x || typeof x !== 'object')
211
+ return null;
212
+ const o = x;
213
+ const n = (k) => (typeof o[k] === 'number' && Number.isSafeInteger(o[k]) && o[k] >= 0 ? o[k]
214
+ : typeof o[k] === 'string' && /^\d+$/.test(o[k]) && Number.isSafeInteger(Number(o[k])) ? Number(o[k]) : null);
215
+ const b = (k) => (typeof o[k] === 'number' && Number.isSafeInteger(o[k]) && o[k] >= 0 ? BigInt(o[k])
216
+ : typeof o[k] === 'string' && /^\d+$/.test(o[k]) ? BigInt(o[k]) : null);
217
+ const t = (k) => (typeof o[k] === 'boolean' ? o[k] : null);
218
+ const p = {
219
+ capsBitmask: n('caps_bitmask'), sideMode: n('side_mode'), maxTotalExposure6dec: b('max_total_exposure_6dec'), maxLeverageBps: n('max_leverage_bps'),
220
+ dailyLossLimit6dec: b('daily_loss_limit_6dec'), dailyFeeCap6dec: b('daily_fee_cap_6dec'), opsPerWindow: n('ops_per_window'), opsWindowMs: n('ops_window_ms'),
221
+ activeFromMsOfDay: n('active_from_ms_of_day'), activeToMsOfDay: n('active_to_ms_of_day'), oracleBandBps: n('oracle_band_bps'),
222
+ lockAutoClear: t('lock_auto_clear'), expiresMs: n('expires_ms'), enabled: t('enabled'),
223
+ };
224
+ return Object.values(p).some((v) => v === null) ? null : p;
225
+ }
@@ -0,0 +1,239 @@
1
+ import { type MarginMode, type TwapRules } from './account.js';
2
+ import { type PolicyV1 } from './agents.js';
3
+ import { type DomainClass, type TypedDomain } from './domains.js';
4
+ import { type Transport } from './http.js';
5
+ import { type Network, type NetworkPreset } from './network.js';
6
+ import { type NonceClock } from './nonce.js';
7
+ import { type BatchAction, type OrderInput, type Submitted } from './orders.js';
8
+ import { type AgentRefusal, type Equity, type OpenOrder, type Position } from './reads.js';
9
+ import { type TypedSigner } from './sign.js';
10
+ import { type MarketRules, type PairSpec } from './rounding.js';
11
+ /**
12
+ * The result of a write. `applied` is true only once the chain's own read shows the change. A submission (HTTP 202) is
13
+ * not an application: `applied: false` with the chain's answer means the chain has not shown it (yet, or at all).
14
+ */
15
+ export interface Result {
16
+ applied: boolean;
17
+ status: number;
18
+ answer: unknown;
19
+ detail: string;
20
+ }
21
+ export interface ConnectOptions {
22
+ network?: 'mainnet' | 'testnet' | NetworkPreset;
23
+ transport?: Transport;
24
+ timeoutMs?: number;
25
+ /** How long a checked node identity is trusted before it is read again (ms). */
26
+ identityTtlMs?: number;
27
+ }
28
+ /** A connection to one Vordium network: reads, and the signing domains of its node. */
29
+ export declare class Vordium {
30
+ readonly network: Network;
31
+ private readonly transport;
32
+ private readonly timeoutMs;
33
+ private readonly ttlMs;
34
+ private checkedAt;
35
+ private constructor();
36
+ /** Read and check the network (spec, node and JSON-RPC must agree) and return a client for it. Testnet by default. */
37
+ static connect(opts?: ConnectOptions): Promise<Vordium>;
38
+ /**
39
+ * The signing domain of the node this client posts to. The node's identity is read again after the TTL; a node that
40
+ * now serves another chain is refused, never followed.
41
+ */
42
+ domain(cls: DomainClass): Promise<TypedDomain>;
43
+ /** GET a path of the REST API; null on 404, raises on another failure. */
44
+ get(path: string): Promise<unknown>;
45
+ post(path: string, body: string): Promise<{
46
+ status: number;
47
+ body: unknown;
48
+ retryAfter: string | null;
49
+ }>;
50
+ status(): Promise<unknown>;
51
+ /** Perpetual markets with their lifecycle and limits. */
52
+ markets(): Promise<unknown>;
53
+ /** Per-market rules from committed state: tick, lot, margins, fees, limits. */
54
+ marketSpecs(): Promise<unknown>;
55
+ /** The market rules read now (never cached): every market's tick, lot and minimums. */
56
+ marketRules(): Promise<MarketRules>;
57
+ orderbook(pairId: number): Promise<unknown>;
58
+ oracle(pairId: number): Promise<unknown>;
59
+ funding(pairId: number): Promise<unknown>;
60
+ /** The truth endpoint: facts the network vouches for. */
61
+ truth(): Promise<unknown>;
62
+ equity(address: string): Promise<Equity>;
63
+ positions(address: string): Promise<Position[]>;
64
+ openOrders(address: string): Promise<OpenOrder[]>;
65
+ /** The account's fills (newest first). */
66
+ orderHistory(address: string, limit?: number): Promise<unknown>;
67
+ /** The account's order records (order_placed, fill, order_closed with its status, …), newest first. */
68
+ orderRecords(address: string, limit?: number): Promise<Array<Record<string, unknown>>>;
69
+ /** The session the chain holds for `owner`: {session_key, expires_at, confirmed}, or null. */
70
+ session(owner: string): Promise<{
71
+ session_key: string;
72
+ expires_at: number;
73
+ confirmed?: boolean;
74
+ } | null>;
75
+ agents(owner: string): Promise<unknown>;
76
+ /** One agent's committed record (name, status, policy_v1, risk_v1, market limits), or null. */
77
+ agent(owner: string, agent: string): Promise<Record<string, unknown> | null>;
78
+ /** The actions the chain refused for an agent, with the reason it wrote (a refused agent order is answered 202). */
79
+ agentRefusals(agent: string, limit?: number): Promise<AgentRefusal[]>;
80
+ /** Agent refusal reasons and their meanings as the network publishes them (empty when it does not). */
81
+ refusalMeanings(): Map<string, string>;
82
+ /** The rename wait (ms) the network publishes for agent names, or null when it publishes none. */
83
+ renameWaitMs(): number | null;
84
+ twaps(owner: string): Promise<Array<Record<string, unknown>>>;
85
+ /** The cross-margin read: account value, maintenance, withdrawable, each market's mode. */
86
+ crossMargin(owner: string): Promise<unknown>;
87
+ /** The dead-man switch's committed state and limits. */
88
+ scheduleCancelState(owner: string): Promise<unknown>;
89
+ /** The TWAP route and limits from the network spec (refused when not published). */
90
+ twapRules(): TwapRules;
91
+ /** A trading account: `owner` signs account operations; `sessionSigner` (a session or agent key) signs orders. */
92
+ account(owner: TypedSigner, opts?: {
93
+ sessionSigner?: TypedSigner;
94
+ nonce?: NonceClock;
95
+ specs?: unknown;
96
+ }): Promise<Account>;
97
+ /** An agent's own handle: places orders with the agent key for its owner, and may tighten its own policy. */
98
+ agentKey(owner: string, agentSigner: TypedSigner, opts?: {
99
+ specs?: unknown;
100
+ }): Promise<Account>;
101
+ }
102
+ /** One account's writes. Every write is signed under the node's own genesis-bound domain. */
103
+ export declare class Account {
104
+ readonly client: Vordium;
105
+ readonly owner: string;
106
+ private readonly ownerSigner;
107
+ private readonly sessionSigner;
108
+ readonly nonce: NonceClock;
109
+ /** Market rules this handle holds; null = read them from the node for each order. */
110
+ readonly specs: MarketRules | null;
111
+ constructor(client: Vordium, owner: string, ownerSigner: TypedSigner | null, sessionSigner: TypedSigner | null, nonce: NonceClock,
112
+ /** Market rules this handle holds; null = read them from the node for each order. */
113
+ specs?: MarketRules | null);
114
+ /** The rules an order uses: the ones this handle holds, else read from the node now. */
115
+ rules(): Promise<MarketRules>;
116
+ /** One market's tick, lot and minimums. */
117
+ pairSpec(pairId: number): Promise<PairSpec>;
118
+ private needOwner;
119
+ /** Orders are signed by the session (or agent) key, else by the owner key. */
120
+ private orderSigner;
121
+ private sign;
122
+ private send;
123
+ /**
124
+ * Sign and submit one order (Market or Limit). The answer is a submission; the order is on the book when
125
+ * {@link Vordium.openOrders} lists its `clientNonce`, or filled when the account's fills show it. Use
126
+ * {@link waitForOrder} to read it back.
127
+ */
128
+ placeOrder(o: Omit<OrderInput, 'owner' | 'clientNonce'> & {
129
+ clientNonce?: number;
130
+ }): Promise<Submitted & {
131
+ clientNonce: number;
132
+ }>;
133
+ /**
134
+ * Where the order with `clientNonce` stands, from the chain: `resting` while the book holds it, else what the account's
135
+ * order records say (`filled`, `cancelled`, `expired`), or null when the chain has no record of it (a refused order
136
+ * has none). Reads until it is known or `ms` runs out. With `final: true` (a market order, or an order you expect to
137
+ * end) it waits for the order's closing record: the book can list an order for a moment before it fills.
138
+ */
139
+ waitForOrder(clientNonce: number, ms?: number, opts?: {
140
+ final?: boolean;
141
+ }): Promise<'resting' | 'filled' | 'cancelled' | 'expired' | null>;
142
+ cancelOrder(orderId: bigint | number): Promise<Submitted>;
143
+ /** Take-profit / stop-loss on an open position (8-decimal prices; 0 leaves a leg unset). */
144
+ setTpSl(pairId: number, positionId: bigint | number, takeProfit8: bigint, stopLoss8: bigint): Promise<Submitted>;
145
+ /** Up to the published maximum of place / cancel actions in one signed batch. Cancels apply first. */
146
+ batch(actions: BatchAction[], opts?: {
147
+ nonce?: number;
148
+ maxActions?: number;
149
+ }): Promise<Submitted & {
150
+ nonce: number;
151
+ }>;
152
+ /**
153
+ * The batch as it will be signed: every place action's price and size on its market's tick and lot (one rules read
154
+ * per batch). Refuses, before signing, a size that rounds to 0 or an order below the network's minimum.
155
+ */
156
+ onSteps(actions: BatchAction[]): Promise<BatchAction[]>;
157
+ /** Cancel every open order on `pairId` (0 = every market). */
158
+ cancelAll(pairId?: number): Promise<Submitted>;
159
+ /**
160
+ * Cancel-and-replace at a new price and size (a new order id, no time priority). The new price and size go onto the
161
+ * order's market tick and lot (a buy's price down, a sell's up, the size down); the market and side come from `opts`,
162
+ * else from the account's open orders.
163
+ */
164
+ modify(orderId: bigint | number, newPrice8: bigint, newSize18: bigint, opts?: {
165
+ pairId?: number;
166
+ side?: 'buy' | 'sell';
167
+ }): Promise<Submitted & {
168
+ clientNonce: number;
169
+ }>;
170
+ /**
171
+ * The dead-man switch: at the first block at or past `cancelAtMs` the chain cancels every open order and TWAP of the
172
+ * account. Call again with a later time to keep orders alive; 0 clears it.
173
+ */
174
+ scheduleCancel(cancelAtMs: number): Promise<Submitted & {
175
+ nonce: number;
176
+ }>;
177
+ revokeSession(waitMs?: number): Promise<Result>;
178
+ /**
179
+ * Give `sessionKey` (a session key, or a registered agent's key) this account's session until `endMs`. A session the
180
+ * chain holds for another key is revoked first (one more signature). Applied only once the chain shows it confirmed.
181
+ */
182
+ createSession(sessionKey: string, endMs: number, waitMs?: number): Promise<Result>;
183
+ placeTwap(t: {
184
+ pairId: number;
185
+ side: 'buy' | 'sell';
186
+ totalSize18: bigint;
187
+ durationMs: number;
188
+ leverageBps?: number;
189
+ slippageBps?: number;
190
+ randomize?: boolean;
191
+ numSlices?: number;
192
+ minPrice8?: bigint;
193
+ maxPrice8?: bigint;
194
+ }, waitMs?: number): Promise<Result & {
195
+ clientNonce: number;
196
+ }>;
197
+ cancelTwap(twapId: bigint | number, waitMs?: number): Promise<Result>;
198
+ /** The market's margin mode as the chain reads it ("cross" | "isolated"), or null. */
199
+ marginMode(pairId: number): Promise<MarginMode | null>;
200
+ /** Cross or isolated for one market — only while it holds no open position and no resting order of the account. */
201
+ setMarginMode(pairId: number, mode: MarginMode, waitMs?: number): Promise<Result>;
202
+ private submitAgentOp;
203
+ private addr;
204
+ /** Register an agent key with a name (the chain's name rule) and a mandate; applied once the chain lists it. */
205
+ registerAgent(a: {
206
+ agent: string;
207
+ name: string;
208
+ mandate: string;
209
+ expiresMs: number;
210
+ }, waitMs?: number): Promise<Result>;
211
+ /**
212
+ * Rename an agent. The chain applies one rename per wait (registering is the first naming) and ignores an earlier one
213
+ * silently: where the network publishes the wait it is refused here, before signing; otherwise the result says the
214
+ * chain did not show the new name.
215
+ */
216
+ renameAgent(agent: string, name: string, waitMs?: number): Promise<Result>;
217
+ revokeAgent(agent: string, waitMs?: number): Promise<Result>;
218
+ /**
219
+ * Set an agent's policy. Refused before signing when the chain would refuse it at apply (it does so silently). The
220
+ * agent itself may sign only a tightening of the stored policy, with its own nonce; the owner may loosen (the chain
221
+ * allows that once per cooldown).
222
+ */
223
+ setAgentPolicy(agent: string, policy: PolicyV1, waitMs?: number): Promise<Result>;
224
+ /** Per-market limits for an agent (sizes in 18-decimal units; 0 leverage = the policy's). */
225
+ setAgentMarketLimit(agent: string, m: {
226
+ pair: number;
227
+ allowed: boolean;
228
+ maxOrder18: bigint;
229
+ maxPosition18: bigint;
230
+ maxLeverageBps: number;
231
+ }, waitMs?: number): Promise<Result>;
232
+ /** Clear the agent's active lock (owner only); `lockSinceMs` names the lock, so a clear signed early never clears a later one. */
233
+ clearAgentLock(agent: string, lockSinceMs: number, waitMs?: number): Promise<Result>;
234
+ }
235
+ /**
236
+ * A TWAP's signed size and price bounds on the market's lot and tick: the total DOWN to a whole number of lots per slice
237
+ * (every slice on the lot, never more than asked), the lowest price UP and the highest DOWN (the band never widens).
238
+ */
239
+ export declare function twapOnSteps(spec: PairSpec, total18: bigint, numSlices: number, minPrice8: bigint, maxPrice8: bigint): [bigint, bigint, bigint];