@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.
- package/LICENSE +21 -0
- package/README.md +109 -2
- package/dist/cjs/account.js +126 -0
- package/dist/cjs/agents.js +237 -0
- package/dist/cjs/client.js +526 -0
- package/dist/cjs/domains.js +37 -0
- package/dist/cjs/errors.js +39 -0
- package/dist/cjs/feeds.js +278 -0
- package/dist/cjs/http.js +97 -0
- package/dist/cjs/index.js +37 -0
- package/dist/cjs/network.js +114 -0
- package/dist/cjs/nonce.js +36 -0
- package/dist/cjs/orders.js +260 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/reads.js +121 -0
- package/dist/cjs/rounding.js +252 -0
- package/dist/cjs/sign.js +49 -0
- package/dist/cjs/types.js +57 -0
- package/dist/cjs/units.js +78 -0
- package/dist/esm/account.d.ts +61 -0
- package/dist/esm/account.js +114 -0
- package/dist/esm/agents.d.ts +71 -0
- package/dist/esm/agents.js +225 -0
- package/dist/esm/client.d.ts +239 -0
- package/dist/esm/client.js +520 -0
- package/dist/esm/domains.d.ts +21 -0
- package/dist/esm/domains.js +30 -0
- package/dist/esm/errors.d.ts +18 -0
- package/dist/esm/errors.js +32 -0
- package/dist/esm/feeds.d.ts +97 -0
- package/dist/esm/feeds.js +267 -0
- package/dist/esm/http.d.ts +24 -0
- package/dist/esm/http.js +93 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +15 -0
- package/dist/esm/network.d.ts +44 -0
- package/dist/esm/network.js +107 -0
- package/dist/esm/nonce.d.ts +15 -0
- package/dist/esm/nonce.js +31 -0
- package/dist/esm/orders.d.ts +141 -0
- package/dist/esm/orders.js +238 -0
- package/dist/esm/reads.d.ts +59 -0
- package/dist/esm/reads.js +113 -0
- package/dist/esm/rounding.d.ts +70 -0
- package/dist/esm/rounding.js +229 -0
- package/dist/esm/sign.d.ts +27 -0
- package/dist/esm/sign.js +43 -0
- package/dist/esm/types.d.ts +41 -0
- package/dist/esm/types.js +51 -0
- package/dist/esm/units.d.ts +16 -0
- package/dist/esm/units.js +70 -0
- package/package.json +53 -4
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { InvalidRequest } from './errors.js';
|
|
2
|
+
import { U64, U128, numberToDecimal } from './units.js';
|
|
3
|
+
/**
|
|
4
|
+
* Exact order units on each market's tick and lot.
|
|
5
|
+
*
|
|
6
|
+
* The chain keeps a price step (`tick_8dec`) and a size step (`lot_18dec`) per market, published in `GET /markets/specs`,
|
|
7
|
+
* and does not apply an order that is off them. Every order this SDK signs is put on them first:
|
|
8
|
+
*
|
|
9
|
+
* - a number is read exactly from its decimal form: a decimal string ("2420.5", ".5", "1e-4"), a bigint, or a number from
|
|
10
|
+
* its shortest decimal form (0.1 is 0.1). Nothing is multiplied as a floating-point number;
|
|
11
|
+
* - a limit price rounds toward the passive side: a buy's DOWN, a sell's UP onto the tick (never a worse price than
|
|
12
|
+
* asked). On `/order/place` it is also kept at 6 decimals (a multiple of 100 in 8-decimal units);
|
|
13
|
+
* - a take-profit / stop-loss trigger goes to the NEAREST tick (a half tick rounds up);
|
|
14
|
+
* - a size rounds DOWN onto the lot (never more than asked);
|
|
15
|
+
* - a tick or lot of 0 means the network sets none: only the signed unit applies.
|
|
16
|
+
*
|
|
17
|
+
* Refused before anything is signed ({@link OrderValueError}): a size that rounds to 0 or is below the market's smallest
|
|
18
|
+
* size, a limit price that rounds to 0, a priced order below the network's smallest order value, a market the network does
|
|
19
|
+
* not list.
|
|
20
|
+
*/
|
|
21
|
+
export class OrderValueError extends InvalidRequest {
|
|
22
|
+
constructor(message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = 'OrderValueError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
/** The market rules (`GET /markets/specs`) could not be read, so no order value can be put on its step. */
|
|
28
|
+
export class SpecsUnavailable extends OrderValueError {
|
|
29
|
+
constructor(message) {
|
|
30
|
+
super(message);
|
|
31
|
+
this.name = 'SpecsUnavailable';
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const PRICE_DECIMALS = 8;
|
|
35
|
+
const SIZE_DECIMALS = 18;
|
|
36
|
+
export const PLACE_PRICE_STEP_8DEC = 100n;
|
|
37
|
+
const PLAIN = /^(?:\d+\.?\d*|\.\d+)(?:[eE][+-]?\d+)?$/;
|
|
38
|
+
/** `x` × 10^`decimals` as an exact fraction [numerator, denominator]. */
|
|
39
|
+
export function scaled(x, decimals, what = 'a value') {
|
|
40
|
+
let s;
|
|
41
|
+
if (typeof x === 'bigint') {
|
|
42
|
+
if (x < 0n)
|
|
43
|
+
throw new OrderValueError(`${what} cannot be negative (${x}).`);
|
|
44
|
+
return [x * 10n ** BigInt(decimals), 1n];
|
|
45
|
+
}
|
|
46
|
+
else if (typeof x === 'number') {
|
|
47
|
+
if (!Number.isFinite(x))
|
|
48
|
+
throw new OrderValueError(`${what} is not a finite number (${x}).`);
|
|
49
|
+
if (x < 0)
|
|
50
|
+
throw new OrderValueError(`${what} cannot be negative (${x}).`);
|
|
51
|
+
s = numberToDecimal(x);
|
|
52
|
+
}
|
|
53
|
+
else if (typeof x === 'string') {
|
|
54
|
+
if (!PLAIN.test(x))
|
|
55
|
+
throw new OrderValueError(`${what} is not a plain decimal number (${JSON.stringify(x)}).`);
|
|
56
|
+
s = x;
|
|
57
|
+
}
|
|
58
|
+
else {
|
|
59
|
+
throw new OrderValueError(`${what} is not a number (${String(x)}).`);
|
|
60
|
+
}
|
|
61
|
+
const [mant, expS] = s.toLowerCase().split('e');
|
|
62
|
+
const [ip, fp = ''] = mant.split('.');
|
|
63
|
+
let n = BigInt((ip || '0') + fp || '0');
|
|
64
|
+
let exp = BigInt(decimals) - BigInt(fp.length) + (expS === undefined ? 0n : BigInt(expS));
|
|
65
|
+
let d = 1n;
|
|
66
|
+
if (exp >= 0n)
|
|
67
|
+
n *= 10n ** exp;
|
|
68
|
+
else
|
|
69
|
+
d = 10n ** -exp;
|
|
70
|
+
return [n, d];
|
|
71
|
+
}
|
|
72
|
+
/** A count of base units: a whole number (bigint, safe-integer number, digit string, or an integral decimal). */
|
|
73
|
+
export function whole(x, what = 'a value') {
|
|
74
|
+
const [n, d] = scaled(x, 0, what);
|
|
75
|
+
if (n % d !== 0n)
|
|
76
|
+
throw new OrderValueError(`${what} is a count of base units and must be a whole number (${String(x)}).`);
|
|
77
|
+
return n / d;
|
|
78
|
+
}
|
|
79
|
+
function gcd(a, b) {
|
|
80
|
+
while (b)
|
|
81
|
+
[a, b] = [b, a % b];
|
|
82
|
+
return a;
|
|
83
|
+
}
|
|
84
|
+
/** num/den onto a multiple of `step`: down, up, or nearest (a half step rounds up). */
|
|
85
|
+
export function onStep(num, den, step, mode) {
|
|
86
|
+
if (step <= 0n)
|
|
87
|
+
throw new RangeError('a step is at least 1');
|
|
88
|
+
const q = num / (den * step), r = num % (den * step);
|
|
89
|
+
if (r === 0n || mode === 'down')
|
|
90
|
+
return q * step;
|
|
91
|
+
if (mode === 'up')
|
|
92
|
+
return (q + 1n) * step;
|
|
93
|
+
return 2n * r >= den * step ? (q + 1n) * step : q * step;
|
|
94
|
+
}
|
|
95
|
+
function sideOf(side) {
|
|
96
|
+
if (side === 'buy' || side === 0)
|
|
97
|
+
return 'buy';
|
|
98
|
+
if (side === 'sell' || side === 1)
|
|
99
|
+
return 'sell';
|
|
100
|
+
throw new OrderValueError(`side is buy or sell, not ${String(side)}.`);
|
|
101
|
+
}
|
|
102
|
+
export function priceStep(spec, placeRoute = true) {
|
|
103
|
+
const tick = spec?.tick8 ?? 0n;
|
|
104
|
+
const base = placeRoute ? PLACE_PRICE_STEP_8DEC : 1n;
|
|
105
|
+
return tick > 0n ? (tick * base) / gcd(tick, base) : base;
|
|
106
|
+
}
|
|
107
|
+
export function sizeStep(spec) {
|
|
108
|
+
const lot = spec?.lot18 ?? 0n;
|
|
109
|
+
return lot > 0n ? lot : 1n;
|
|
110
|
+
}
|
|
111
|
+
function inPrice(out, what) {
|
|
112
|
+
if (out <= 0n)
|
|
113
|
+
throw new OrderValueError(`${what} rounds to 0 on this market's tick.`);
|
|
114
|
+
if (out > U64)
|
|
115
|
+
throw new OrderValueError(`${what} is out of range.`);
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
/** A limit price as the signed 8-decimal integer on the tick: a buy's rounds down, a sell's up. */
|
|
119
|
+
export function price8OnTick(price, spec, side, placeRoute = true) {
|
|
120
|
+
const [n, d] = scaled(price, PRICE_DECIMALS, 'a limit price');
|
|
121
|
+
return inPrice(onStep(n, d, priceStep(spec, placeRoute), sideOf(side) === 'buy' ? 'down' : 'up'), `the limit price ${String(price)}`);
|
|
122
|
+
}
|
|
123
|
+
/** A size as the signed 18-decimal integer, down onto the lot. */
|
|
124
|
+
export function size18OnLot(size, spec) {
|
|
125
|
+
const [n, d] = scaled(size, SIZE_DECIMALS, 'a size');
|
|
126
|
+
return checkSize(onStep(n, d, sizeStep(spec), 'down'), spec, size);
|
|
127
|
+
}
|
|
128
|
+
/** A take-profit / stop-loss trigger as the 8-decimal integer, to the nearest tick (0 = no trigger). */
|
|
129
|
+
export function trigger8OnTick(price, spec) {
|
|
130
|
+
const [n, d] = scaled(price, PRICE_DECIMALS, 'a trigger price');
|
|
131
|
+
if (n === 0n)
|
|
132
|
+
return 0n;
|
|
133
|
+
return inPrice(onStep(n, d, priceStep(spec, false), 'nearest'), `the trigger price ${String(price)}`);
|
|
134
|
+
}
|
|
135
|
+
/** A signed 8-decimal price already in base units, onto the tick by the passive rule (0 stays 0: no price). */
|
|
136
|
+
export function snapPrice8(price8, spec, side, placeRoute = false) {
|
|
137
|
+
const p = whole(price8, 'price8');
|
|
138
|
+
if (p === 0n)
|
|
139
|
+
return 0n;
|
|
140
|
+
return inPrice(onStep(p, 1n, priceStep(spec, placeRoute), sideOf(side) === 'buy' ? 'down' : 'up'), `the price ${p}`);
|
|
141
|
+
}
|
|
142
|
+
export function snapSize18(size18, spec) {
|
|
143
|
+
const s = whole(size18, 'size18');
|
|
144
|
+
return checkSize(s - (s % sizeStep(spec)), spec, size18);
|
|
145
|
+
}
|
|
146
|
+
export function snapTrigger8(price8, spec) {
|
|
147
|
+
const p = whole(price8, 'trigger price');
|
|
148
|
+
if (p === 0n)
|
|
149
|
+
return 0n;
|
|
150
|
+
return inPrice(onStep(p, 1n, priceStep(spec, false), 'nearest'), `the trigger price ${p}`);
|
|
151
|
+
}
|
|
152
|
+
export function checkSize(size18, spec, asked) {
|
|
153
|
+
if (size18 <= 0n) {
|
|
154
|
+
const lot = sizeStep(spec);
|
|
155
|
+
throw new OrderValueError(lot > 1n ? `the size ${String(asked)} rounds to 0 on this market's lot (${lot} base units).` : `the size ${String(asked)} is below one base unit.`);
|
|
156
|
+
}
|
|
157
|
+
if (size18 > U128)
|
|
158
|
+
throw new OrderValueError('the size is out of range.');
|
|
159
|
+
const min = spec?.minSize18 ?? 0n;
|
|
160
|
+
if (min > 0n && size18 < min)
|
|
161
|
+
throw new OrderValueError(`the size is below this market's smallest order (${min} base units).`);
|
|
162
|
+
return size18;
|
|
163
|
+
}
|
|
164
|
+
/** size × price in USDC base units (6 decimals), rounded down. */
|
|
165
|
+
export function notional6(size18, price8) {
|
|
166
|
+
return (size18 * price8) / 10n ** 20n;
|
|
167
|
+
}
|
|
168
|
+
export function checkNotional(size18, price8, spec) {
|
|
169
|
+
const min = spec?.minNotional6 ?? 0n;
|
|
170
|
+
if (min > 0n && price8 > 0n && notional6(size18, price8) < min) {
|
|
171
|
+
throw new OrderValueError(`the order's value is below the smallest order the network takes (${Number(min) / 1e6} USDC).`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
/** Leverage (2 or "2.5") as basis points, exactly (half to even). */
|
|
175
|
+
export function leverageBpsExact(leverage) {
|
|
176
|
+
const [n, d] = scaled(leverage, 4, 'leverage');
|
|
177
|
+
const q = n / d, r = n % d;
|
|
178
|
+
return q + (2n * r > d || (2n * r === d && q % 2n === 1n) ? 1n : 0n);
|
|
179
|
+
}
|
|
180
|
+
// ── the market rules ────────────────────────────────────────────────────────────────────────────────────────────
|
|
181
|
+
/** Every market without a tick, lot or minimum: for dry runs and offline tests. Never what a network publishes. */
|
|
182
|
+
export const NO_RULES = Object.freeze({ noRules: true });
|
|
183
|
+
function count(v) {
|
|
184
|
+
if (typeof v === 'bigint' && v >= 0n)
|
|
185
|
+
return v;
|
|
186
|
+
if (typeof v === 'number' && Number.isSafeInteger(v) && v >= 0)
|
|
187
|
+
return BigInt(v);
|
|
188
|
+
if (typeof v === 'string' && /^\d+$/.test(v))
|
|
189
|
+
return BigInt(v);
|
|
190
|
+
if (v === undefined || v === null || v === '')
|
|
191
|
+
return 0n;
|
|
192
|
+
throw new OrderValueError(`a market rule is not a whole number (${String(v)}).`);
|
|
193
|
+
}
|
|
194
|
+
/** Each market's tick, lot and smallest size from a `/markets/specs` read, with the network's smallest order value. */
|
|
195
|
+
export function pairSpecs(read) {
|
|
196
|
+
const s = read && typeof read === 'object' ? read.specs : null;
|
|
197
|
+
if (!s || typeof s !== 'object')
|
|
198
|
+
throw new OrderValueError('the market rules read has no specs; nothing was signed.');
|
|
199
|
+
const sp = s;
|
|
200
|
+
const minNotional6 = count(sp.min_order_notional_6dec);
|
|
201
|
+
const out = new Map();
|
|
202
|
+
for (const p of Array.isArray(sp.pairs) ? sp.pairs : []) {
|
|
203
|
+
const pr = (p && typeof p === 'object' ? p.pair : null);
|
|
204
|
+
const pid = pr?.pair_id;
|
|
205
|
+
if (typeof pid !== 'number' || !Number.isSafeInteger(pid))
|
|
206
|
+
continue;
|
|
207
|
+
const q = p;
|
|
208
|
+
out.set(pid, { pairId: pid, symbol: String(pr?.symbol ?? pr?.name ?? pid), tick8: count(q.tick_8dec), lot18: count(q.lot_18dec),
|
|
209
|
+
minSize18: count(pr?.min_size_18dec), minNotional6 });
|
|
210
|
+
}
|
|
211
|
+
return out;
|
|
212
|
+
}
|
|
213
|
+
/** One market's rules; a market the read does not list is refused. */
|
|
214
|
+
export function selectSpec(rules, pairId) {
|
|
215
|
+
if ('noRules' in rules)
|
|
216
|
+
return { pairId, symbol: String(pairId), tick8: 0n, lot18: 0n, minSize18: 0n, minNotional6: 0n };
|
|
217
|
+
const s = rules.get(pairId);
|
|
218
|
+
if (!s)
|
|
219
|
+
throw new OrderValueError(`the network lists no market ${pairId} (GET /markets/specs).`);
|
|
220
|
+
return s;
|
|
221
|
+
}
|
|
222
|
+
/** A /markets/specs read, a parsed map, or NO_RULES, as market rules. */
|
|
223
|
+
export function marketRules(x) {
|
|
224
|
+
if (x === NO_RULES)
|
|
225
|
+
return NO_RULES;
|
|
226
|
+
if (x instanceof Map)
|
|
227
|
+
return x;
|
|
228
|
+
return pairSpecs(x);
|
|
229
|
+
}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { TypedDomain } from './domains.js';
|
|
2
|
+
import { type PrimaryType } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Anything that can sign EIP-712 typed data: an ethers `Wallet` or `Signer`, a browser wallet wrapped by ethers, or your
|
|
5
|
+
* own key-management adapter.
|
|
6
|
+
*/
|
|
7
|
+
export interface TypedSigner {
|
|
8
|
+
getAddress(): Promise<string>;
|
|
9
|
+
signTypedData(domain: TypedDomain, types: Record<string, Array<{
|
|
10
|
+
name: string;
|
|
11
|
+
type: string;
|
|
12
|
+
}>>, value: Record<string, unknown>): Promise<string>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* A signer from a private key (an ethers `Wallet`). A key that is not 32 bytes of hex is refused with a message that
|
|
16
|
+
* never carries the value (the library's own error would print it).
|
|
17
|
+
*/
|
|
18
|
+
export declare function keySigner(privateKey: string): TypedSigner;
|
|
19
|
+
/** The 32-byte digest the chain verifies: keccak256(0x1901 ‖ domainSeparator ‖ hashStruct(value)). */
|
|
20
|
+
export declare function digest(dom: TypedDomain, primary: PrimaryType, value: Record<string, unknown>): string;
|
|
21
|
+
/**
|
|
22
|
+
* Sign one operation. Returns the 65-byte `r‖s‖v` signature as lower-case 0x-hex (v = 27 or 28), and checks that it
|
|
23
|
+
* recovers the signer's address before it is used.
|
|
24
|
+
*/
|
|
25
|
+
export declare function signOp(signer: TypedSigner, dom: TypedDomain, primary: PrimaryType, value: Record<string, unknown>): Promise<string>;
|
|
26
|
+
/** The first 64 bytes (`r‖s`) of a 65-byte signature: the form the single-order intake reads. */
|
|
27
|
+
export declare function rs64(sig65: string): string;
|
package/dist/esm/sign.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { Signature, TypedDataEncoder, Wallet, getAddress, recoverAddress } from 'ethers';
|
|
2
|
+
import { InvalidRequest } from './errors.js';
|
|
3
|
+
import { typesFor } from './types.js';
|
|
4
|
+
/**
|
|
5
|
+
* A signer from a private key (an ethers `Wallet`). A key that is not 32 bytes of hex is refused with a message that
|
|
6
|
+
* never carries the value (the library's own error would print it).
|
|
7
|
+
*/
|
|
8
|
+
export function keySigner(privateKey) {
|
|
9
|
+
const k = typeof privateKey === 'string' ? privateKey.trim() : '';
|
|
10
|
+
if (!/^(0x)?[0-9a-fA-F]{64}$/.test(k)) {
|
|
11
|
+
throw new InvalidRequest('A private key must be 32 bytes written as 64 hex characters (the value is not shown).');
|
|
12
|
+
}
|
|
13
|
+
try {
|
|
14
|
+
return new Wallet(k.startsWith('0x') ? k : '0x' + k);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
throw new InvalidRequest('The private key is not a valid key (the value is not shown).');
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
/** The 32-byte digest the chain verifies: keccak256(0x1901 ‖ domainSeparator ‖ hashStruct(value)). */
|
|
21
|
+
export function digest(dom, primary, value) {
|
|
22
|
+
return TypedDataEncoder.hash(dom, typesFor(primary), value);
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* Sign one operation. Returns the 65-byte `r‖s‖v` signature as lower-case 0x-hex (v = 27 or 28), and checks that it
|
|
26
|
+
* recovers the signer's address before it is used.
|
|
27
|
+
*/
|
|
28
|
+
export async function signOp(signer, dom, primary, value) {
|
|
29
|
+
const types = typesFor(primary);
|
|
30
|
+
const raw = await signer.signTypedData(dom, types, value);
|
|
31
|
+
const sig = Signature.from(raw);
|
|
32
|
+
const by = TypedDataEncoder.hash(dom, types, value);
|
|
33
|
+
if (getAddress(recoverAddress(by, sig)) !== getAddress(await signer.getAddress())) {
|
|
34
|
+
throw new InvalidRequest('The signature does not recover to the signer: the wallet signed something else.');
|
|
35
|
+
}
|
|
36
|
+
return sig.serialized.toLowerCase();
|
|
37
|
+
}
|
|
38
|
+
/** The first 64 bytes (`r‖s`) of a 65-byte signature: the form the single-order intake reads. */
|
|
39
|
+
export function rs64(sig65) {
|
|
40
|
+
if (!/^0x[0-9a-f]{130}$/.test(sig65))
|
|
41
|
+
throw new InvalidRequest('A signature is 65 bytes of lower-case hex.');
|
|
42
|
+
return sig65.slice(0, 130);
|
|
43
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The EIP-712 types the chain signs, as its own type strings. Field order, names and solidity types are byte-exact with
|
|
3
|
+
* the chain's signing code: never reorder or rename a field. Each string is parsed into the `types` object a signer
|
|
4
|
+
* takes, so the strings below are the single source.
|
|
5
|
+
*/
|
|
6
|
+
export type TypeField = {
|
|
7
|
+
name: string;
|
|
8
|
+
type: string;
|
|
9
|
+
};
|
|
10
|
+
export type Types = Record<string, TypeField[]>;
|
|
11
|
+
export declare const TYPE_STRINGS: {
|
|
12
|
+
readonly PlaceOrder: "PlaceOrder(address owner,uint32 pairId,uint8 side,uint128 size,uint64 price,uint32 leverageBps,uint8 orderType,bool reduceOnly,bool postOnly,uint64 triggerPrice8dec,uint8 triggerDir,uint64 clientNonce)";
|
|
13
|
+
readonly CancelOrder: "CancelOrder(address owner,uint64 orderId)";
|
|
14
|
+
readonly SetTpSl: "SetTpSl(address owner,uint32 pairId,uint64 positionId,uint64 takeProfit8dec,uint64 stopLoss8dec)";
|
|
15
|
+
readonly BatchAction: "BatchAction(uint8 kind,uint32 pairId,uint8 side,uint128 size,uint64 price,uint32 leverageBps,uint8 orderType,bool reduceOnly,bool postOnly,uint64 clientNonce,uint64 orderId)";
|
|
16
|
+
readonly BatchOrders: "BatchOrders(address owner,uint64 nonce,BatchAction[] actions)";
|
|
17
|
+
readonly CancelAllOrders: "CancelAllOrders(address owner,uint32 pairId,uint64 nonce)";
|
|
18
|
+
readonly ModifyOrderV2: "ModifyOrderV2(address owner,uint64 orderId,uint64 newPrice,uint128 newSize,uint64 clientNonce)";
|
|
19
|
+
readonly SetMmp: "SetMmp(address owner,uint64 windowMs,uint32 maxFills,uint128 maxFilledNotional6dec,uint128 maxNetSize18dec,uint64 freezeMs,uint64 nonce)";
|
|
20
|
+
readonly ScheduleCancel: "ScheduleCancel(address owner,uint64 cancelAtMs,uint64 nonce)";
|
|
21
|
+
readonly PlaceTwap: "PlaceTwap(address owner,uint32 pairId,uint8 side,uint128 totalSize18dec,uint32 numSlices,uint64 durationMs,uint32 leverageBps,uint32 slippageBps,bool randomize,uint64 triggerPrice8dec,uint8 triggerDir,uint64 minPrice8dec,uint64 maxPrice8dec,uint64 clientNonce)";
|
|
22
|
+
readonly CancelTwap: "CancelTwap(address owner,uint64 twapId,uint64 clientNonce)";
|
|
23
|
+
readonly SetMarginMode: "SetMarginMode(address owner,uint32 pairId,uint8 mode,uint64 nonce)";
|
|
24
|
+
readonly RegisterAgentV2: "RegisterAgentV2(address owner,address agent,string name,string mandate,uint64 expiresMs,uint64 nonce)";
|
|
25
|
+
readonly SetAgentName: "SetAgentName(address owner,address agent,string name,uint64 nonce)";
|
|
26
|
+
readonly SetAgentPolicyV1: "SetAgentPolicyV1(address owner,address agent,uint32 capsBitmask,uint8 sideMode,uint128 maxTotalExposure6dec,uint32 maxLeverageBps,uint128 dailyLossLimit6dec,uint128 dailyFeeCap6dec,uint32 opsPerWindow,uint32 opsWindowMs,uint32 activeFromMsOfDay,uint32 activeToMsOfDay,uint32 oracleBandBps,bool lockAutoClear,uint64 expiresMs,bool enabled,uint64 nonce)";
|
|
27
|
+
readonly SetAgentMarketLimit: "SetAgentMarketLimit(address owner,address agent,uint32 pair,bool allowed,uint128 maxOrder18dec,uint128 maxPosition18dec,uint32 maxLeverageBps,uint64 nonce)";
|
|
28
|
+
readonly ClearAgentLock: "ClearAgentLock(address owner,address agent,uint64 lockSinceMs,uint64 nonce)";
|
|
29
|
+
readonly RevokeAgent: "RevokeAgent(address owner,address agent,uint64 nonce)";
|
|
30
|
+
readonly SessionCreate: "SessionCreate(address sessionKey,uint256 expiresAt,uint256 nonce)";
|
|
31
|
+
readonly SessionRevoke: "SessionRevoke(address owner,uint256 nonce)";
|
|
32
|
+
};
|
|
33
|
+
export type PrimaryType = Exclude<keyof typeof TYPE_STRINGS, 'BatchAction'>;
|
|
34
|
+
export declare function parseTypeString(s: string): {
|
|
35
|
+
name: string;
|
|
36
|
+
fields: TypeField[];
|
|
37
|
+
};
|
|
38
|
+
/** The `types` object for one primary type (with the structs it references). */
|
|
39
|
+
export declare function typesFor(primary: PrimaryType): Types;
|
|
40
|
+
/** Which domain each operation is signed in. */
|
|
41
|
+
export declare function domainOf(primary: PrimaryType): 'VordCore' | 'VordexSession';
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
export const TYPE_STRINGS = {
|
|
2
|
+
// VordCore — orders
|
|
3
|
+
PlaceOrder: 'PlaceOrder(address owner,uint32 pairId,uint8 side,uint128 size,uint64 price,uint32 leverageBps,uint8 orderType,bool reduceOnly,bool postOnly,uint64 triggerPrice8dec,uint8 triggerDir,uint64 clientNonce)',
|
|
4
|
+
CancelOrder: 'CancelOrder(address owner,uint64 orderId)',
|
|
5
|
+
SetTpSl: 'SetTpSl(address owner,uint32 pairId,uint64 positionId,uint64 takeProfit8dec,uint64 stopLoss8dec)',
|
|
6
|
+
BatchAction: 'BatchAction(uint8 kind,uint32 pairId,uint8 side,uint128 size,uint64 price,uint32 leverageBps,uint8 orderType,bool reduceOnly,bool postOnly,uint64 clientNonce,uint64 orderId)',
|
|
7
|
+
BatchOrders: 'BatchOrders(address owner,uint64 nonce,BatchAction[] actions)',
|
|
8
|
+
CancelAllOrders: 'CancelAllOrders(address owner,uint32 pairId,uint64 nonce)',
|
|
9
|
+
ModifyOrderV2: 'ModifyOrderV2(address owner,uint64 orderId,uint64 newPrice,uint128 newSize,uint64 clientNonce)',
|
|
10
|
+
SetMmp: 'SetMmp(address owner,uint64 windowMs,uint32 maxFills,uint128 maxFilledNotional6dec,uint128 maxNetSize18dec,uint64 freezeMs,uint64 nonce)',
|
|
11
|
+
ScheduleCancel: 'ScheduleCancel(address owner,uint64 cancelAtMs,uint64 nonce)',
|
|
12
|
+
// VordCore — account
|
|
13
|
+
PlaceTwap: 'PlaceTwap(address owner,uint32 pairId,uint8 side,uint128 totalSize18dec,uint32 numSlices,uint64 durationMs,uint32 leverageBps,uint32 slippageBps,bool randomize,uint64 triggerPrice8dec,uint8 triggerDir,uint64 minPrice8dec,uint64 maxPrice8dec,uint64 clientNonce)',
|
|
14
|
+
CancelTwap: 'CancelTwap(address owner,uint64 twapId,uint64 clientNonce)',
|
|
15
|
+
SetMarginMode: 'SetMarginMode(address owner,uint32 pairId,uint8 mode,uint64 nonce)',
|
|
16
|
+
// VordCore — agents (the operations in force)
|
|
17
|
+
RegisterAgentV2: 'RegisterAgentV2(address owner,address agent,string name,string mandate,uint64 expiresMs,uint64 nonce)',
|
|
18
|
+
SetAgentName: 'SetAgentName(address owner,address agent,string name,uint64 nonce)',
|
|
19
|
+
SetAgentPolicyV1: 'SetAgentPolicyV1(address owner,address agent,uint32 capsBitmask,uint8 sideMode,uint128 maxTotalExposure6dec,uint32 maxLeverageBps,uint128 dailyLossLimit6dec,uint128 dailyFeeCap6dec,uint32 opsPerWindow,uint32 opsWindowMs,uint32 activeFromMsOfDay,uint32 activeToMsOfDay,uint32 oracleBandBps,bool lockAutoClear,uint64 expiresMs,bool enabled,uint64 nonce)',
|
|
20
|
+
SetAgentMarketLimit: 'SetAgentMarketLimit(address owner,address agent,uint32 pair,bool allowed,uint128 maxOrder18dec,uint128 maxPosition18dec,uint32 maxLeverageBps,uint64 nonce)',
|
|
21
|
+
ClearAgentLock: 'ClearAgentLock(address owner,address agent,uint64 lockSinceMs,uint64 nonce)',
|
|
22
|
+
RevokeAgent: 'RevokeAgent(address owner,address agent,uint64 nonce)',
|
|
23
|
+
// VordexSession
|
|
24
|
+
SessionCreate: 'SessionCreate(address sessionKey,uint256 expiresAt,uint256 nonce)',
|
|
25
|
+
SessionRevoke: 'SessionRevoke(address owner,uint256 nonce)',
|
|
26
|
+
};
|
|
27
|
+
export function parseTypeString(s) {
|
|
28
|
+
const m = /^([A-Za-z0-9]+)\(([^()]*)\)$/.exec(s);
|
|
29
|
+
if (!m)
|
|
30
|
+
throw new Error(`not a type string: ${s}`);
|
|
31
|
+
const fields = m[2] === '' ? [] : m[2].split(',').map((f) => {
|
|
32
|
+
const [type, name] = f.split(' ');
|
|
33
|
+
return { name, type };
|
|
34
|
+
});
|
|
35
|
+
return { name: m[1], fields };
|
|
36
|
+
}
|
|
37
|
+
/** The `types` object for one primary type (with the structs it references). */
|
|
38
|
+
export function typesFor(primary) {
|
|
39
|
+
const own = parseTypeString(TYPE_STRINGS[primary]);
|
|
40
|
+
const out = { [own.name]: own.fields };
|
|
41
|
+
for (const f of own.fields) {
|
|
42
|
+
const base = f.type.replace(/\[\]$/, '');
|
|
43
|
+
if (base in TYPE_STRINGS)
|
|
44
|
+
out[base] = parseTypeString(TYPE_STRINGS[base]).fields;
|
|
45
|
+
}
|
|
46
|
+
return out;
|
|
47
|
+
}
|
|
48
|
+
/** Which domain each operation is signed in. */
|
|
49
|
+
export function domainOf(primary) {
|
|
50
|
+
return primary === 'SessionCreate' || primary === 'SessionRevoke' ? 'VordexSession' : 'VordCore';
|
|
51
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export declare const U32: bigint;
|
|
2
|
+
export declare const U64: bigint;
|
|
3
|
+
export declare const U128: bigint;
|
|
4
|
+
/**
|
|
5
|
+
* A decimal amount as an exact integer of base units. Accepts a decimal string ("2420.5") or a number; refuses more
|
|
6
|
+
* decimals than the unit has (nothing is rounded silently: a rounded value would be a different signed value).
|
|
7
|
+
*/
|
|
8
|
+
export declare function toUnits(x: string | number | bigint, decimals: number, what?: string): bigint;
|
|
9
|
+
/** A number written out in full decimal form (no exponent), shortest round-trip digits. */
|
|
10
|
+
export declare function numberToDecimal(n: number): string;
|
|
11
|
+
/** Base units back to a decimal string, without trailing zeros. */
|
|
12
|
+
export declare function fromUnits(v: bigint, decimals: number): string;
|
|
13
|
+
/** A whole number within range, as a bigint (accepts number, bigint or a digit string). */
|
|
14
|
+
export declare function uint(v: unknown, max: bigint, what: string): bigint;
|
|
15
|
+
/** A whole number that the body carries as a JSON number: it must be exact in JavaScript. */
|
|
16
|
+
export declare function safeNumber(v: bigint, what: string): number;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { InvalidRequest } from './errors.js';
|
|
2
|
+
export const U32 = 2n ** 32n - 1n;
|
|
3
|
+
export const U64 = 2n ** 64n - 1n;
|
|
4
|
+
export const U128 = 2n ** 128n - 1n;
|
|
5
|
+
/**
|
|
6
|
+
* A decimal amount as an exact integer of base units. Accepts a decimal string ("2420.5") or a number; refuses more
|
|
7
|
+
* decimals than the unit has (nothing is rounded silently: a rounded value would be a different signed value).
|
|
8
|
+
*/
|
|
9
|
+
export function toUnits(x, decimals, what = 'amount') {
|
|
10
|
+
if (typeof x === 'bigint') {
|
|
11
|
+
if (x < 0n)
|
|
12
|
+
throw new InvalidRequest(`${what} cannot be negative.`);
|
|
13
|
+
return x * 10n ** BigInt(decimals);
|
|
14
|
+
}
|
|
15
|
+
const s = typeof x === 'number' ? numberToDecimal(x) : x.trim();
|
|
16
|
+
const m = /^(\d+)(?:\.(\d*))?$/.exec(s);
|
|
17
|
+
if (!m)
|
|
18
|
+
throw new InvalidRequest(`${what} is not a positive decimal number (${String(x)}).`);
|
|
19
|
+
const frac = (m[2] ?? '').replace(/0+$/, '');
|
|
20
|
+
if (frac.length > decimals)
|
|
21
|
+
throw new InvalidRequest(`${what} has more than ${decimals} decimals (${String(x)}).`);
|
|
22
|
+
return BigInt(m[1]) * 10n ** BigInt(decimals) + BigInt((frac + '0'.repeat(decimals)).slice(0, decimals) || '0');
|
|
23
|
+
}
|
|
24
|
+
/** A number written out in full decimal form (no exponent), shortest round-trip digits. */
|
|
25
|
+
export function numberToDecimal(n) {
|
|
26
|
+
if (!Number.isFinite(n) || n < 0)
|
|
27
|
+
throw new InvalidRequest(`${n} is not a positive number.`);
|
|
28
|
+
const s = String(n);
|
|
29
|
+
if (!/e/i.test(s))
|
|
30
|
+
return s;
|
|
31
|
+
const [mant, expS] = s.toLowerCase().split('e');
|
|
32
|
+
const exp = Number(expS);
|
|
33
|
+
const [ip, fp = ''] = mant.split('.');
|
|
34
|
+
const digits = ip + fp;
|
|
35
|
+
const point = ip.length + exp;
|
|
36
|
+
if (point <= 0)
|
|
37
|
+
return '0.' + '0'.repeat(-point) + digits;
|
|
38
|
+
if (point >= digits.length)
|
|
39
|
+
return digits + '0'.repeat(point - digits.length);
|
|
40
|
+
return digits.slice(0, point) + '.' + digits.slice(point);
|
|
41
|
+
}
|
|
42
|
+
/** Base units back to a decimal string, without trailing zeros. */
|
|
43
|
+
export function fromUnits(v, decimals) {
|
|
44
|
+
const neg = v < 0n;
|
|
45
|
+
const a = neg ? -v : v;
|
|
46
|
+
const d = 10n ** BigInt(decimals);
|
|
47
|
+
const frac = (a % d).toString().padStart(decimals, '0').replace(/0+$/, '');
|
|
48
|
+
return (neg ? '-' : '') + (a / d).toString() + (frac ? '.' + frac : '');
|
|
49
|
+
}
|
|
50
|
+
/** A whole number within range, as a bigint (accepts number, bigint or a digit string). */
|
|
51
|
+
export function uint(v, max, what) {
|
|
52
|
+
let b;
|
|
53
|
+
if (typeof v === 'bigint')
|
|
54
|
+
b = v;
|
|
55
|
+
else if (typeof v === 'number' && Number.isSafeInteger(v))
|
|
56
|
+
b = BigInt(v);
|
|
57
|
+
else if (typeof v === 'string' && /^\d+$/.test(v))
|
|
58
|
+
b = BigInt(v);
|
|
59
|
+
else
|
|
60
|
+
throw new InvalidRequest(`${what} is not a whole number.`);
|
|
61
|
+
if (b < 0n || b > max)
|
|
62
|
+
throw new InvalidRequest(`${what} is out of range.`);
|
|
63
|
+
return b;
|
|
64
|
+
}
|
|
65
|
+
/** A whole number that the body carries as a JSON number: it must be exact in JavaScript. */
|
|
66
|
+
export function safeNumber(v, what) {
|
|
67
|
+
if (v > BigInt(Number.MAX_SAFE_INTEGER))
|
|
68
|
+
throw new InvalidRequest(`${what} is past the exact-integer range.`);
|
|
69
|
+
return Number(v);
|
|
70
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,55 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vordium/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "TypeScript and JavaScript SDK for Vordium Chain and the Vordex perpetuals exchange: signing, orders, session keys, agents, TWAP, margin mode and live feeds.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Vordium <dev@vordium.com>",
|
|
7
|
+
"homepage": "https://docs.vordium.com",
|
|
8
|
+
"repository": {
|
|
9
|
+
"type": "git",
|
|
10
|
+
"url": "git+https://github.com/Vordium/vordium-sdk-js.git"
|
|
11
|
+
},
|
|
12
|
+
"keywords": [
|
|
13
|
+
"vordium",
|
|
14
|
+
"vordex",
|
|
15
|
+
"perpetuals",
|
|
16
|
+
"eip-712",
|
|
17
|
+
"sdk"
|
|
18
|
+
],
|
|
19
|
+
"type": "module",
|
|
20
|
+
"main": "./dist/cjs/index.js",
|
|
21
|
+
"module": "./dist/esm/index.js",
|
|
22
|
+
"types": "./dist/esm/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/esm/index.d.ts",
|
|
26
|
+
"import": "./dist/esm/index.js",
|
|
27
|
+
"require": "./dist/cjs/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"files": [
|
|
31
|
+
"dist",
|
|
32
|
+
"README.md",
|
|
33
|
+
"LICENSE"
|
|
34
|
+
],
|
|
35
|
+
"sideEffects": false,
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=20"
|
|
38
|
+
},
|
|
39
|
+
"scripts": {
|
|
40
|
+
"build": "node scripts/build.mjs",
|
|
41
|
+
"test": "node --test test/*.test.mjs"
|
|
42
|
+
},
|
|
43
|
+
"dependencies": {
|
|
44
|
+
"ethers": "^6.13.0",
|
|
45
|
+
"ws": "^8.18.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"@types/ws": "^8.18.1",
|
|
49
|
+
"typescript": "^5.6.0"
|
|
50
|
+
},
|
|
51
|
+
"publishConfig": {
|
|
52
|
+
"access": "public",
|
|
53
|
+
"provenance": true
|
|
54
|
+
}
|
|
55
|
+
}
|