@vordium/sdk 0.1.2 → 0.2.0
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 +55 -3
- package/dist/cjs/builder.js +256 -0
- package/dist/cjs/client.js +452 -62
- package/dist/cjs/index.js +7 -1
- package/dist/cjs/network.js +53 -1
- package/dist/cjs/nonce.js +419 -1
- package/dist/cjs/orders.js +3 -0
- package/dist/cjs/pins.js +60 -0
- package/dist/cjs/resend.js +188 -0
- package/dist/cjs/types.js +4 -0
- package/dist/esm/builder.d.ts +158 -0
- package/dist/esm/builder.js +235 -0
- package/dist/esm/client.d.ts +119 -9
- package/dist/esm/client.js +453 -66
- package/dist/esm/index.d.ts +4 -1
- package/dist/esm/index.js +4 -1
- package/dist/esm/network.d.ts +23 -4
- package/dist/esm/network.js +51 -1
- package/dist/esm/nonce.d.ts +109 -0
- package/dist/esm/nonce.js +410 -0
- package/dist/esm/orders.js +3 -0
- package/dist/esm/pins.d.ts +29 -0
- package/dist/esm/pins.js +51 -0
- package/dist/esm/resend.d.ts +74 -0
- package/dist/esm/resend.js +180 -0
- package/dist/esm/types.d.ts +3 -0
- package/dist/esm/types.js +4 -0
- package/package.json +1 -1
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ChainClock = exports.DeliveryUnknown = exports.RESEND_STATUS = void 0;
|
|
4
|
+
exports.nonceUsedAnswer = nonceUsedAnswer;
|
|
5
|
+
exports.neverSent = neverSent;
|
|
6
|
+
exports.sendSame = sendSame;
|
|
7
|
+
const errors_js_1 = require("./errors.js");
|
|
8
|
+
/** Answers that mean "try again": the write was not taken, or a gateway cannot tell. */
|
|
9
|
+
exports.RESEND_STATUS = new Set([429, 502, 503, 504]);
|
|
10
|
+
const USED = /already used|already applied|duplicate|nonce not above|not above the account's last|must be greater than/i;
|
|
11
|
+
const USED_CODES = new Set(['nonce', 'nonce_used', 'duplicate', 'duplicate_nonce', 'vault_nonce']);
|
|
12
|
+
/** Whether an answer says the nonce (of a body we sent) is already used. */
|
|
13
|
+
function nonceUsedAnswer(status, body) {
|
|
14
|
+
if (status === 409)
|
|
15
|
+
return true;
|
|
16
|
+
if (typeof body === 'string')
|
|
17
|
+
return USED.test(body);
|
|
18
|
+
if (!body || typeof body !== 'object')
|
|
19
|
+
return false;
|
|
20
|
+
const j = body;
|
|
21
|
+
if (typeof j.code === 'string' && USED_CODES.has(j.code.toLowerCase()))
|
|
22
|
+
return true;
|
|
23
|
+
return USED.test(['error', 'reason', 'message'].map((k) => String(j[k] ?? '')).join(' '));
|
|
24
|
+
}
|
|
25
|
+
/** The network did not answer any copy of a signed write. It may have arrived: read the account before sending a new
|
|
26
|
+
* one (a new one takes a new nonce). */
|
|
27
|
+
class DeliveryUnknown extends errors_js_1.VordiumError {
|
|
28
|
+
nonce;
|
|
29
|
+
attempts;
|
|
30
|
+
/** True when no copy left this machine (the connection could not be made on any try): it certainly did not arrive. */
|
|
31
|
+
neverSent = false;
|
|
32
|
+
constructor(message, nonce, attempts) {
|
|
33
|
+
super('delivery_unknown', message);
|
|
34
|
+
this.nonce = nonce;
|
|
35
|
+
this.attempts = attempts;
|
|
36
|
+
this.name = 'DeliveryUnknown';
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
exports.DeliveryUnknown = DeliveryUnknown;
|
|
40
|
+
const DNS = new Set(['ENOTFOUND', 'EAI_AGAIN']);
|
|
41
|
+
const AT_CONNECT = new Set(['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'ETIMEDOUT']);
|
|
42
|
+
/** True when the error happened while the connection was being made: the name lookup, a connect timeout, or a refused
|
|
43
|
+
* / unreachable error whose `syscall` is `connect`. The same refused or unreachable code on a connection that was
|
|
44
|
+
* already open (after a retransmit timeout), a timeout, or a gateway answer is not that: the copy may have arrived. */
|
|
45
|
+
function neverSent(e) {
|
|
46
|
+
const name = e?.name;
|
|
47
|
+
if (name === 'TimeoutError' || name === 'AbortError')
|
|
48
|
+
return false; // our own time limit: the request had left
|
|
49
|
+
for (let x = e, i = 0; x && i < 4; x = x.cause, i++) {
|
|
50
|
+
const { code, syscall } = x;
|
|
51
|
+
if (typeof code !== 'string')
|
|
52
|
+
continue;
|
|
53
|
+
if (DNS.has(code) || code === 'UND_ERR_CONNECT_TIMEOUT')
|
|
54
|
+
return true;
|
|
55
|
+
if (AT_CONNECT.has(code) && syscall === 'connect')
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
61
|
+
const wait = (attempt, retryAfter) => {
|
|
62
|
+
const ra = Number(retryAfter);
|
|
63
|
+
return Math.max(Math.random() * Math.min(500 * 2 ** attempt, 8000), Number.isFinite(ra) && ra > 0 ? Math.min(ra, 30) * 1000 : 0);
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* Send one signed body until the network answers it, at most `attempts` times, each time the same bytes.
|
|
67
|
+
*
|
|
68
|
+
* `dedup` says whether the network applies this write once per nonce. Then a thrown error (a lost connection, a
|
|
69
|
+
* timeout) or HTTP 429/502/503/504 sends it again after a short random wait (at least the server's Retry-After); when an
|
|
70
|
+
* earlier copy may have arrived and the final answer is not a 2xx, `needsReadBack` is set. For a write the network does
|
|
71
|
+
* not deduplicate (`dedup: false`) a copy is sent again only when the first never left this machine or was answered
|
|
72
|
+
* 429; a timeout, a dropped connection or any 5xx throws {@link DeliveryUnknown} at once, so the caller reads state
|
|
73
|
+
* instead of risking a second effect.
|
|
74
|
+
*/
|
|
75
|
+
async function sendSame(send, opts = {}) {
|
|
76
|
+
const n = Math.max(1, Math.floor(opts.attempts ?? 3));
|
|
77
|
+
const pause = opts.sleep ?? sleep;
|
|
78
|
+
const dedup = opts.dedup ?? true;
|
|
79
|
+
let maybeArrived = false; // a copy sent in THIS call may have reached the network
|
|
80
|
+
let lastErr = null;
|
|
81
|
+
let last = null;
|
|
82
|
+
const unknown = (i, why) => new DeliveryUnknown(`It is not known whether the network received this write${opts.nonce != null ? ` (nonce ${opts.nonce})` : ''}: ${why} after ${i} ${i === 1 ? 'try' : 'tries'}. Read the account before sending a new one.`, opts.nonce ?? null, i);
|
|
83
|
+
const done = (r, i) => {
|
|
84
|
+
const ok = r.status >= 200 && r.status < 300;
|
|
85
|
+
if (!ok && r.status >= 500) {
|
|
86
|
+
if (!dedup)
|
|
87
|
+
throw unknown(i, `the network answered ${r.status}`);
|
|
88
|
+
return { ...r, attempts: i, needsReadBack: true }; // a gateway or node error: it may have applied
|
|
89
|
+
}
|
|
90
|
+
return { ...r, attempts: i, needsReadBack: maybeArrived && !ok };
|
|
91
|
+
};
|
|
92
|
+
for (let i = 0; i < n; i++) {
|
|
93
|
+
let r;
|
|
94
|
+
try {
|
|
95
|
+
r = await send();
|
|
96
|
+
}
|
|
97
|
+
catch (e) {
|
|
98
|
+
if (e instanceof errors_js_1.VordiumError && !(e instanceof DeliveryUnknown) && e.code !== 'unreachable')
|
|
99
|
+
throw e;
|
|
100
|
+
lastErr = e;
|
|
101
|
+
if (!neverSent(e)) {
|
|
102
|
+
maybeArrived = true;
|
|
103
|
+
if (!dedup)
|
|
104
|
+
throw unknown(i + 1, 'the answer was lost');
|
|
105
|
+
}
|
|
106
|
+
if (i < n - 1)
|
|
107
|
+
await pause(wait(i, null));
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (exports.RESEND_STATUS.has(r.status) && i < n - 1) {
|
|
111
|
+
if (r.status !== 429) {
|
|
112
|
+
maybeArrived = true;
|
|
113
|
+
if (!dedup)
|
|
114
|
+
throw unknown(i + 1, `a gateway answered ${r.status}`);
|
|
115
|
+
}
|
|
116
|
+
last = r;
|
|
117
|
+
lastErr = null;
|
|
118
|
+
await pause(wait(i, r.retryAfter));
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
return done(r, i + 1);
|
|
122
|
+
}
|
|
123
|
+
if (last && lastErr === null)
|
|
124
|
+
return done(last, n);
|
|
125
|
+
if (!maybeArrived)
|
|
126
|
+
throw Object.assign(new DeliveryUnknown(`The network could not be reached${opts.nonce != null ? ` (nonce ${opts.nonce})` : ''} after ${n} tries; nothing was sent.`, opts.nonce ?? null, n), { neverSent: true });
|
|
127
|
+
throw unknown(n, 'no copy was answered');
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* The network's block time, estimated as this computer's clock plus the offset measured at the last read: the latest
|
|
131
|
+
* block (JSON-RPC), cross-checked against the node's `/status` head (a JSON-RPC that serves another head is not this
|
|
132
|
+
* chain's clock). Null when unavailable. A reading is kept `ttlMs`; a failed one is retried after a fifth of that.
|
|
133
|
+
*/
|
|
134
|
+
class ChainClock {
|
|
135
|
+
readBlock;
|
|
136
|
+
readHead;
|
|
137
|
+
ttlMs;
|
|
138
|
+
now;
|
|
139
|
+
maxHeadGap;
|
|
140
|
+
offset = null;
|
|
141
|
+
nextRead = 0;
|
|
142
|
+
constructor(readBlock, readHead, ttlMs = 300_000, now = Date.now, maxHeadGap = 10_000) {
|
|
143
|
+
this.readBlock = readBlock;
|
|
144
|
+
this.readHead = readHead;
|
|
145
|
+
this.ttlMs = ttlMs;
|
|
146
|
+
this.now = now;
|
|
147
|
+
this.maxHeadGap = maxHeadGap;
|
|
148
|
+
}
|
|
149
|
+
static int(v) {
|
|
150
|
+
if (typeof v === 'number' && Number.isSafeInteger(v))
|
|
151
|
+
return v;
|
|
152
|
+
if (typeof v === 'string' && /^(0x[0-9a-f]+|\d+)$/i.test(v))
|
|
153
|
+
return Number(BigInt(v));
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
/** Read the network now: block time minus this computer's clock (ms), or null. */
|
|
157
|
+
async measure() {
|
|
158
|
+
try {
|
|
159
|
+
const b = await this.readBlock();
|
|
160
|
+
const ts = ChainClock.int(b?.timestamp), num = ChainClock.int(b?.number);
|
|
161
|
+
if (ts === null || ts <= 0)
|
|
162
|
+
return null;
|
|
163
|
+
const head = await this.readHead().catch(() => null);
|
|
164
|
+
if (head !== null && (num === null || Math.abs(head - num) > this.maxHeadGap))
|
|
165
|
+
return null;
|
|
166
|
+
return ts * 1000 + 500 - Math.floor(this.now());
|
|
167
|
+
}
|
|
168
|
+
catch {
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
inFlight = null;
|
|
173
|
+
/** Block time now, or null. When a reading is due, the caller that finds it due runs ONE read and waits for it;
|
|
174
|
+
* every other caller meanwhile is served the last reading at once (null before the first). */
|
|
175
|
+
async time() {
|
|
176
|
+
let o = this.offset;
|
|
177
|
+
if (this.now() >= this.nextRead && !this.inFlight) {
|
|
178
|
+
this.inFlight = this.measure().then((x) => {
|
|
179
|
+
this.offset = x;
|
|
180
|
+
this.nextRead = this.now() + (x !== null ? this.ttlMs : this.ttlMs / 5);
|
|
181
|
+
return x;
|
|
182
|
+
}).finally(() => { this.inFlight = null; });
|
|
183
|
+
o = await this.inFlight;
|
|
184
|
+
}
|
|
185
|
+
return o === null ? null : Math.floor(this.now()) + o;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
exports.ChainClock = ChainClock;
|
package/dist/cjs/types.js
CHANGED
|
@@ -15,6 +15,10 @@ exports.TYPE_STRINGS = {
|
|
|
15
15
|
ModifyOrderV2: 'ModifyOrderV2(address owner,uint64 orderId,uint64 newPrice,uint128 newSize,uint64 clientNonce)',
|
|
16
16
|
SetMmp: 'SetMmp(address owner,uint64 windowMs,uint32 maxFills,uint128 maxFilledNotional6dec,uint128 maxNetSize18dec,uint64 freezeMs,uint64 nonce)',
|
|
17
17
|
ScheduleCancel: 'ScheduleCancel(address owner,uint64 cancelAtMs,uint64 nonce)',
|
|
18
|
+
// VordCore — builder codes
|
|
19
|
+
PlaceOrderV3: 'PlaceOrderV3(address owner,uint32 pairId,uint8 side,uint128 size,uint64 price,uint32 leverageBps,uint8 orderType,bool reduceOnly,bool postOnly,uint64 triggerPrice8dec,uint8 triggerDir,uint8 timeInForce,uint64 expiresAt,uint64 clientNonce,uint64 validUntil,uint64 worstPrice8dec,string source,address builder,uint32 builderFeeCbps)',
|
|
20
|
+
ApproveBuilderFee: 'ApproveBuilderFee(address user,address builder,uint32 maxFeeCbps,uint64 nonce,uint64 validUntil)',
|
|
21
|
+
ClaimBuilderFees: 'ClaimBuilderFees(address builder,uint64 nonce,uint64 validUntil)',
|
|
18
22
|
// VordCore — account
|
|
19
23
|
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)',
|
|
20
24
|
CancelTwap: 'CancelTwap(address owner,uint64 twapId,uint64 clientNonce)',
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { VordiumError } from './errors.js';
|
|
2
|
+
import type { PlaceOrderValue } from './orders.js';
|
|
3
|
+
/**
|
|
4
|
+
* Builder codes: a fee an app or bot (the builder) adds to the orders it sends, up to what the trader approved.
|
|
5
|
+
*
|
|
6
|
+
* Three signed operations in the VordCore domain, each signed as 65 bytes `r‖s‖v`:
|
|
7
|
+
* - `ApproveBuilderFee` (POST /builder/approve), the trader's own key: let `builder` charge up to `maxFeeCbps`.
|
|
8
|
+
* A revoke is an approval of 0.
|
|
9
|
+
* - `PlaceOrderV3` (POST /order/place): an order that names a builder and its fee.
|
|
10
|
+
* - `ClaimBuilderFees` (POST /builder/claim), the builder's own key: move its accrued fees to its balance.
|
|
11
|
+
*
|
|
12
|
+
* Fees are in cbps, hundredths of a basis point: 1,000 cbps = 0.1 %, 500 cbps = 5 bps = 0.05 %. The network publishes
|
|
13
|
+
* its limits in its reads: the cap per market kind (`caps_cbps` {perps, spot} of the stats read), the most builders an
|
|
14
|
+
* account may approve (`max` of the approvals read), and the account value a builder needs for orders that name it to
|
|
15
|
+
* be accepted (`min_account_value_6dec`, with `account_value_ok`). The SDK checks against these reads, never against
|
|
16
|
+
* fixed figures; a read without them is refused before signing. The reads carry `active`: whether builder fees are
|
|
17
|
+
* active at the next block; nothing is signed while it is not true.
|
|
18
|
+
*/
|
|
19
|
+
export declare const BUILDER_ROUTES: {
|
|
20
|
+
readonly approve: "/builder/approve";
|
|
21
|
+
readonly claim: "/builder/claim";
|
|
22
|
+
readonly order: "/order/place";
|
|
23
|
+
};
|
|
24
|
+
/** keccak256 of each type string (checked against the strings in the tests). */
|
|
25
|
+
export declare const BUILDER_TYPEHASHES: {
|
|
26
|
+
readonly ApproveBuilderFee: "0xe63fa83d341ba3dfe6b57bc221d00f03edce9f043613f5243078e294ff0c849a";
|
|
27
|
+
readonly ClaimBuilderFees: "0xd5774785d91fe35740b030286fca8338c06609f3ba19595ee63a21d6e020500f";
|
|
28
|
+
readonly PlaceOrderV3: "0xe328eb68341f2a35a289620b7147dc72672f356f6dff3b10098ae02f19a6c5d5";
|
|
29
|
+
};
|
|
30
|
+
/** The market kinds a builder fee cap is published for (`caps_cbps` of the stats read). */
|
|
31
|
+
export declare const MARKET_KINDS: readonly ["perps", "spot"];
|
|
32
|
+
export type MarketKind = (typeof MARKET_KINDS)[number];
|
|
33
|
+
export type Caps = Record<MarketKind, number>;
|
|
34
|
+
/** An approval deadline is at most this many seconds ahead of the network's block time. */
|
|
35
|
+
export declare const MAX_AHEAD_S = 300;
|
|
36
|
+
export declare const DEFAULT_AHEAD_S = 120;
|
|
37
|
+
/** The `source` an order placed through this SDK signs. */
|
|
38
|
+
export declare const ORDER_SOURCE = "sdk";
|
|
39
|
+
/** A builder operation the network would refuse, caught before anything was signed. `code` is the network's code. */
|
|
40
|
+
export declare class BuilderError extends VordiumError {
|
|
41
|
+
constructor(code: string, message: string);
|
|
42
|
+
}
|
|
43
|
+
/** Builder fees are not active on this network. Nothing was signed. */
|
|
44
|
+
export declare class BuilderNotActive extends BuilderError {
|
|
45
|
+
constructor(message?: string);
|
|
46
|
+
}
|
|
47
|
+
export interface BuilderApprovals {
|
|
48
|
+
user: string;
|
|
49
|
+
approvals: Array<{
|
|
50
|
+
builder: string;
|
|
51
|
+
max_fee_cbps: number;
|
|
52
|
+
}>;
|
|
53
|
+
count: number;
|
|
54
|
+
max: number;
|
|
55
|
+
nonce: number;
|
|
56
|
+
active: boolean;
|
|
57
|
+
source?: string;
|
|
58
|
+
head_height?: number;
|
|
59
|
+
}
|
|
60
|
+
export interface BuilderStats {
|
|
61
|
+
builder: string;
|
|
62
|
+
volume_6dec: string;
|
|
63
|
+
fees_6dec: string;
|
|
64
|
+
unclaimed_6dec: string;
|
|
65
|
+
claimed_6dec: string;
|
|
66
|
+
users_30d: number;
|
|
67
|
+
account_value_ok: boolean;
|
|
68
|
+
min_account_value_6dec: string;
|
|
69
|
+
claim_nonce: number;
|
|
70
|
+
caps_cbps: Caps;
|
|
71
|
+
active: boolean;
|
|
72
|
+
source?: string;
|
|
73
|
+
head_height?: number;
|
|
74
|
+
}
|
|
75
|
+
/** An order's builder: its address and the fee in cbps. */
|
|
76
|
+
export interface OrderBuilder {
|
|
77
|
+
address: string;
|
|
78
|
+
feeCbps: number;
|
|
79
|
+
}
|
|
80
|
+
/** Raise {@link BuilderNotActive} unless a builder read says `active: true`. */
|
|
81
|
+
export declare function requireActive(read: unknown): void;
|
|
82
|
+
/** The caps in cbps from a stats read (`caps_cbps` {perps, spot}); a read without both is refused (`unreadable`). */
|
|
83
|
+
export declare function capsFrom(read: unknown): Caps;
|
|
84
|
+
/** A fee in plain words: 500 → "5 bps (0.05%)". */
|
|
85
|
+
export declare function describeCbps(cbps: number): string;
|
|
86
|
+
/** A builder fee on an order: above 0 and at most the cap of `kind`. */
|
|
87
|
+
export declare function checkFee(feeCbps: unknown, kind: MarketKind, caps: Caps): number;
|
|
88
|
+
/** The most a builder may charge under an approval: above 0 and at most the highest cap. 0 is a revoke. */
|
|
89
|
+
export declare function checkMaxFee(maxFeeCbps: unknown, caps: Caps): number;
|
|
90
|
+
/** The `validUntil` to sign (unix seconds): at most 300 s ahead of `nowS`, and after it. */
|
|
91
|
+
export declare function deadline(validUntil: number | null, nowS: number, aheadS?: number): number;
|
|
92
|
+
/** The fee (cbps) an approvals read shows for `builder`, or null. */
|
|
93
|
+
export declare function approvalOf(read: unknown, builder: string): number | null;
|
|
94
|
+
/** What the network checks for an order that names a builder, from the two reads. */
|
|
95
|
+
export declare function checkOrderBuilder(owner: string, builder: string, feeCbps: number, approvals: unknown, stats: unknown): void;
|
|
96
|
+
/** `{address, feeCbps}` checked: a checksummed address and a whole fee. */
|
|
97
|
+
export declare function parseBuilder(b: unknown): OrderBuilder;
|
|
98
|
+
export interface ApproveBuilderFeeValue {
|
|
99
|
+
user: string;
|
|
100
|
+
builder: string;
|
|
101
|
+
maxFeeCbps: number;
|
|
102
|
+
nonce: bigint;
|
|
103
|
+
validUntil: bigint;
|
|
104
|
+
}
|
|
105
|
+
export interface ClaimBuilderFeesValue {
|
|
106
|
+
builder: string;
|
|
107
|
+
nonce: bigint;
|
|
108
|
+
validUntil: bigint;
|
|
109
|
+
}
|
|
110
|
+
export interface PlaceOrderV3Value {
|
|
111
|
+
owner: string;
|
|
112
|
+
pairId: number;
|
|
113
|
+
side: number;
|
|
114
|
+
size: bigint;
|
|
115
|
+
price: bigint;
|
|
116
|
+
leverageBps: number;
|
|
117
|
+
orderType: number;
|
|
118
|
+
reduceOnly: boolean;
|
|
119
|
+
postOnly: boolean;
|
|
120
|
+
triggerPrice8dec: bigint;
|
|
121
|
+
triggerDir: number;
|
|
122
|
+
timeInForce: number;
|
|
123
|
+
expiresAt: bigint;
|
|
124
|
+
clientNonce: bigint;
|
|
125
|
+
validUntil: bigint;
|
|
126
|
+
worstPrice8dec: bigint;
|
|
127
|
+
source: string;
|
|
128
|
+
builder: string;
|
|
129
|
+
builderFeeCbps: number;
|
|
130
|
+
}
|
|
131
|
+
export declare function approveBuilderFeeValue(user: string, builder: string, maxFeeCbps: number, nonce: number | bigint, validUntil: number | bigint): ApproveBuilderFeeValue;
|
|
132
|
+
export declare function approveBuilderFeeBody(v: ApproveBuilderFeeValue, signature: string): Record<string, unknown>;
|
|
133
|
+
export declare function claimBuilderFeesValue(builder: string, nonce: number | bigint, validUntil: number | bigint): ClaimBuilderFeesValue;
|
|
134
|
+
export declare function claimBuilderFeesBody(v: ClaimBuilderFeesValue, signature: string): Record<string, unknown>;
|
|
135
|
+
/**
|
|
136
|
+
* The signed PlaceOrderV3 value from a checked PlaceOrder value, its deadline and its builder. Market and limit only.
|
|
137
|
+
* A market order's `worstPrice8` (already on the market's price step) is signed as both `price` (the slippage cap: the
|
|
138
|
+
* network refuses `slippage` when the market is past it) and `worstPrice8dec` (refused `worst_price`); 0 = no limit.
|
|
139
|
+
* A limit order signs its price and a worst price of 0.
|
|
140
|
+
*/
|
|
141
|
+
export declare function placeOrderV3Value(v: PlaceOrderValue, validUntil: number | bigint, b: OrderBuilder, source?: string, worstPrice8?: bigint): PlaceOrderV3Value;
|
|
142
|
+
/** The `/order/place` body of a signed PlaceOrderV3 (`signature` = the 65-byte form). A market order carries no price. */
|
|
143
|
+
export declare function placeOrderV3Body(v: PlaceOrderV3Value, signature: string): Record<string, unknown>;
|
|
144
|
+
/** An account's referral level as the network reads it (amounts are 6-decimal USDC strings). */
|
|
145
|
+
export interface ReferralLevel {
|
|
146
|
+
level: 'L1' | 'L2' | 'PARTNER' | string;
|
|
147
|
+
shareBps: number | null;
|
|
148
|
+
discountBps: number | null;
|
|
149
|
+
l2Progress: Record<string, unknown>;
|
|
150
|
+
nextCheckMs: number | null;
|
|
151
|
+
ownVolume6dec: string | null;
|
|
152
|
+
minOwnVolume6dec: string | null;
|
|
153
|
+
meetsMin: boolean | null;
|
|
154
|
+
limits: Record<string, unknown>;
|
|
155
|
+
refereeVolume6dec: string | null;
|
|
156
|
+
}
|
|
157
|
+
/** The level fields of a `/referral/stats` read, or null when it carries no `level` (levels not in force). */
|
|
158
|
+
export declare function referralLevel(read: unknown): ReferralLevel | null;
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { getAddress } from 'ethers';
|
|
2
|
+
import { VordiumError } from './errors.js';
|
|
3
|
+
import { U32, U64, U128, uint } from './units.js';
|
|
4
|
+
/**
|
|
5
|
+
* Builder codes: a fee an app or bot (the builder) adds to the orders it sends, up to what the trader approved.
|
|
6
|
+
*
|
|
7
|
+
* Three signed operations in the VordCore domain, each signed as 65 bytes `r‖s‖v`:
|
|
8
|
+
* - `ApproveBuilderFee` (POST /builder/approve), the trader's own key: let `builder` charge up to `maxFeeCbps`.
|
|
9
|
+
* A revoke is an approval of 0.
|
|
10
|
+
* - `PlaceOrderV3` (POST /order/place): an order that names a builder and its fee.
|
|
11
|
+
* - `ClaimBuilderFees` (POST /builder/claim), the builder's own key: move its accrued fees to its balance.
|
|
12
|
+
*
|
|
13
|
+
* Fees are in cbps, hundredths of a basis point: 1,000 cbps = 0.1 %, 500 cbps = 5 bps = 0.05 %. The network publishes
|
|
14
|
+
* its limits in its reads: the cap per market kind (`caps_cbps` {perps, spot} of the stats read), the most builders an
|
|
15
|
+
* account may approve (`max` of the approvals read), and the account value a builder needs for orders that name it to
|
|
16
|
+
* be accepted (`min_account_value_6dec`, with `account_value_ok`). The SDK checks against these reads, never against
|
|
17
|
+
* fixed figures; a read without them is refused before signing. The reads carry `active`: whether builder fees are
|
|
18
|
+
* active at the next block; nothing is signed while it is not true.
|
|
19
|
+
*/
|
|
20
|
+
export const BUILDER_ROUTES = { approve: '/builder/approve', claim: '/builder/claim', order: '/order/place' };
|
|
21
|
+
/** keccak256 of each type string (checked against the strings in the tests). */
|
|
22
|
+
export const BUILDER_TYPEHASHES = {
|
|
23
|
+
ApproveBuilderFee: '0xe63fa83d341ba3dfe6b57bc221d00f03edce9f043613f5243078e294ff0c849a',
|
|
24
|
+
ClaimBuilderFees: '0xd5774785d91fe35740b030286fca8338c06609f3ba19595ee63a21d6e020500f',
|
|
25
|
+
PlaceOrderV3: '0xe328eb68341f2a35a289620b7147dc72672f356f6dff3b10098ae02f19a6c5d5',
|
|
26
|
+
};
|
|
27
|
+
/** The market kinds a builder fee cap is published for (`caps_cbps` of the stats read). */
|
|
28
|
+
export const MARKET_KINDS = ['perps', 'spot'];
|
|
29
|
+
/** An approval deadline is at most this many seconds ahead of the network's block time. */
|
|
30
|
+
export const MAX_AHEAD_S = 300;
|
|
31
|
+
export const DEFAULT_AHEAD_S = 120;
|
|
32
|
+
/** The `source` an order placed through this SDK signs. */
|
|
33
|
+
export const ORDER_SOURCE = 'sdk';
|
|
34
|
+
/** A builder operation the network would refuse, caught before anything was signed. `code` is the network's code. */
|
|
35
|
+
export class BuilderError extends VordiumError {
|
|
36
|
+
constructor(code, message) {
|
|
37
|
+
super(code, message);
|
|
38
|
+
this.name = 'BuilderError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/** Builder fees are not active on this network. Nothing was signed. */
|
|
42
|
+
export class BuilderNotActive extends BuilderError {
|
|
43
|
+
constructor(message = 'Builder fees are not active on this network, so nothing was signed.') {
|
|
44
|
+
super('builder_not_active', message);
|
|
45
|
+
this.name = 'BuilderNotActive';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function addr(v, what) {
|
|
49
|
+
try {
|
|
50
|
+
return getAddress(String(v));
|
|
51
|
+
}
|
|
52
|
+
catch {
|
|
53
|
+
throw new BuilderError('invalid_body', `${what} must be an address (0x and 40 hex characters).`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
function whole(v, max, what) {
|
|
57
|
+
try {
|
|
58
|
+
return uint(v, max, what);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
throw new BuilderError('invalid_body', `${what} must be a whole number from 0 to ${max}.`);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/** Raise {@link BuilderNotActive} unless a builder read says `active: true`. */
|
|
65
|
+
export function requireActive(read) {
|
|
66
|
+
if (!read || typeof read !== 'object' || read.active !== true)
|
|
67
|
+
throw new BuilderNotActive();
|
|
68
|
+
}
|
|
69
|
+
/** The caps in cbps from a stats read (`caps_cbps` {perps, spot}); a read without both is refused (`unreadable`). */
|
|
70
|
+
export function capsFrom(read) {
|
|
71
|
+
const got = read && typeof read === 'object' ? read.caps_cbps : null;
|
|
72
|
+
const caps = {};
|
|
73
|
+
for (const k of MARKET_KINDS) {
|
|
74
|
+
const v = got && typeof got === 'object' ? got[k] : undefined;
|
|
75
|
+
if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0)
|
|
76
|
+
throw new BuilderError('unreadable', "The network's builder read gives no fee caps (caps_cbps), so the fee cannot be checked and nothing was signed.");
|
|
77
|
+
caps[k] = v;
|
|
78
|
+
}
|
|
79
|
+
return caps;
|
|
80
|
+
}
|
|
81
|
+
function isKind(kind) { return kind === 'perps' || kind === 'spot'; }
|
|
82
|
+
/** A fee in plain words: 500 → "5 bps (0.05%)". */
|
|
83
|
+
export function describeCbps(cbps) {
|
|
84
|
+
const pct = (cbps / 10000).toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
|
|
85
|
+
return `${cbps / 100} bps (${pct}%)`;
|
|
86
|
+
}
|
|
87
|
+
/** A builder fee on an order: above 0 and at most the cap of `kind`. */
|
|
88
|
+
export function checkFee(feeCbps, kind, caps) {
|
|
89
|
+
if (!isKind(kind))
|
|
90
|
+
throw new BuilderError('invalid_body', 'kind is perps or spot.');
|
|
91
|
+
if (!caps || typeof caps[kind] !== 'number')
|
|
92
|
+
throw new BuilderError('unreadable', 'No fee cap for this market kind; nothing was signed.');
|
|
93
|
+
const fee = Number(whole(feeCbps, U32, 'The builder fee'));
|
|
94
|
+
if (fee === 0)
|
|
95
|
+
throw new BuilderError('builder_fee_zero', 'A builder was named with a fee of 0: name no builder, or a fee above 0.');
|
|
96
|
+
if (fee > caps[kind])
|
|
97
|
+
throw new BuilderError('builder_fee_above_cap', `A builder fee of ${fee} cbps is above the ${kind} cap of ${caps[kind]} cbps (${describeCbps(caps[kind])}). Use a fee at or below the cap.`);
|
|
98
|
+
return fee;
|
|
99
|
+
}
|
|
100
|
+
/** The most a builder may charge under an approval: above 0 and at most the highest cap. 0 is a revoke. */
|
|
101
|
+
export function checkMaxFee(maxFeeCbps, caps) {
|
|
102
|
+
const fee = Number(whole(maxFeeCbps, U32, 'The approved fee'));
|
|
103
|
+
if (fee === 0)
|
|
104
|
+
throw new BuilderError('builder_fee_zero', 'An approval of 0 is a revoke: use revokeBuilderFee.');
|
|
105
|
+
const top = Math.max(caps.perps, caps.spot);
|
|
106
|
+
if (fee > top)
|
|
107
|
+
throw new BuilderError('builder_fee_above_cap', `An approved fee of ${fee} cbps is above the highest cap of ${top} cbps (${describeCbps(top)}). Approve a fee at or below it.`);
|
|
108
|
+
return fee;
|
|
109
|
+
}
|
|
110
|
+
/** The `validUntil` to sign (unix seconds): at most 300 s ahead of `nowS`, and after it. */
|
|
111
|
+
export function deadline(validUntil, nowS, aheadS = DEFAULT_AHEAD_S) {
|
|
112
|
+
const vu = validUntil ?? nowS + aheadS;
|
|
113
|
+
if (!Number.isSafeInteger(vu))
|
|
114
|
+
throw new BuilderError('invalid_body', 'validUntil must be whole unix seconds.');
|
|
115
|
+
if (vu - nowS > MAX_AHEAD_S)
|
|
116
|
+
throw new BuilderError('approval_too_far', `Not signed: the deadline is ${vu - nowS} s ahead; the network takes at most ${MAX_AHEAD_S} s.`);
|
|
117
|
+
if (vu <= nowS)
|
|
118
|
+
throw new BuilderError('approval_expired', 'Not signed: the deadline has already passed.');
|
|
119
|
+
return vu;
|
|
120
|
+
}
|
|
121
|
+
/** The fee (cbps) an approvals read shows for `builder`, or null. */
|
|
122
|
+
export function approvalOf(read, builder) {
|
|
123
|
+
const rows = read && typeof read === 'object' ? read.approvals : null;
|
|
124
|
+
const b = builder.toLowerCase();
|
|
125
|
+
for (const r of Array.isArray(rows) ? rows : []) {
|
|
126
|
+
if (r && typeof r === 'object' && String(r.builder ?? '').toLowerCase() === b) {
|
|
127
|
+
const v = r.max_fee_cbps;
|
|
128
|
+
return typeof v === 'number' && Number.isSafeInteger(v) ? v : null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
/** What the network checks for an order that names a builder, from the two reads. */
|
|
134
|
+
export function checkOrderBuilder(owner, builder, feeCbps, approvals, stats) {
|
|
135
|
+
requireActive(approvals);
|
|
136
|
+
requireActive(stats);
|
|
137
|
+
if (owner.toLowerCase() === builder.toLowerCase())
|
|
138
|
+
throw new BuilderError('builder_self', 'An account cannot be its own builder: name another builder.');
|
|
139
|
+
const approved = approvalOf(approvals, builder);
|
|
140
|
+
if (approved === null || approved === 0)
|
|
141
|
+
throw new BuilderError('builder_not_approved', `The account has not approved builder ${builder}: approve it first (approveBuilderFee).`);
|
|
142
|
+
if (feeCbps > approved)
|
|
143
|
+
throw new BuilderError('builder_fee_above_approved', `A builder fee of ${feeCbps} cbps is above the ${approved} cbps the account approved: use a lower fee, or approve a higher one.`);
|
|
144
|
+
if (stats.account_value_ok === false) {
|
|
145
|
+
const need = stats.min_account_value_6dec;
|
|
146
|
+
const floor = typeof need === 'string' && /^\d+$/.test(need) ? `the ${usdc(BigInt(need))} USDC minimum` : "the network's minimum account value";
|
|
147
|
+
throw new BuilderError('builder_too_small', `The builder's account value is below ${floor}, so the network refuses orders that name it. The builder must fund its account first.`);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
/** 6-decimal USDC as a plain decimal: 100000000n → "100", 1500000n → "1.5". */
|
|
151
|
+
function usdc(v) {
|
|
152
|
+
const whole = v / 1000000n, frac = v % 1000000n;
|
|
153
|
+
return whole.toLocaleString('en-US') + (frac ? '.' + frac.toString().padStart(6, '0').replace(/0+$/, '') : '');
|
|
154
|
+
}
|
|
155
|
+
/** `{address, feeCbps}` checked: a checksummed address and a whole fee. */
|
|
156
|
+
export function parseBuilder(b) {
|
|
157
|
+
if (!b || typeof b !== 'object')
|
|
158
|
+
throw new BuilderError('invalid_body', 'builder is { address: "0x…", feeCbps: 500 }.');
|
|
159
|
+
const o = b;
|
|
160
|
+
if (o.feeCbps === undefined || o.feeCbps === null)
|
|
161
|
+
throw new BuilderError('invalid_body', 'The builder fee is missing (feeCbps).');
|
|
162
|
+
return { address: addr(o.address, 'The builder'), feeCbps: Number(whole(o.feeCbps, U32, 'The builder fee')) };
|
|
163
|
+
}
|
|
164
|
+
export function approveBuilderFeeValue(user, builder, maxFeeCbps, nonce, validUntil) {
|
|
165
|
+
const u = addr(user, 'The account'), b = addr(builder, 'The builder');
|
|
166
|
+
if (u.toLowerCase() === b.toLowerCase())
|
|
167
|
+
throw new BuilderError('builder_self', 'An account cannot be its own builder: name another builder.');
|
|
168
|
+
return { user: u, builder: b, maxFeeCbps: Number(whole(maxFeeCbps, U32, 'The approved fee')), nonce: whole(nonce, U64, 'nonce'), validUntil: whole(validUntil, U64, 'validUntil') };
|
|
169
|
+
}
|
|
170
|
+
export function approveBuilderFeeBody(v, signature) {
|
|
171
|
+
return { user: v.user, builder: v.builder, maxFeeCbps: v.maxFeeCbps, nonce: Number(v.nonce), validUntil: Number(v.validUntil), signature };
|
|
172
|
+
}
|
|
173
|
+
export function claimBuilderFeesValue(builder, nonce, validUntil) {
|
|
174
|
+
return { builder: addr(builder, 'The builder'), nonce: whole(nonce, U64, 'nonce'), validUntil: whole(validUntil, U64, 'validUntil') };
|
|
175
|
+
}
|
|
176
|
+
export function claimBuilderFeesBody(v, signature) {
|
|
177
|
+
return { builder: v.builder, nonce: Number(v.nonce), validUntil: Number(v.validUntil), signature };
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* The signed PlaceOrderV3 value from a checked PlaceOrder value, its deadline and its builder. Market and limit only.
|
|
181
|
+
* A market order's `worstPrice8` (already on the market's price step) is signed as both `price` (the slippage cap: the
|
|
182
|
+
* network refuses `slippage` when the market is past it) and `worstPrice8dec` (refused `worst_price`); 0 = no limit.
|
|
183
|
+
* A limit order signs its price and a worst price of 0.
|
|
184
|
+
*/
|
|
185
|
+
export function placeOrderV3Value(v, validUntil, b, source = ORDER_SOURCE, worstPrice8 = 0n) {
|
|
186
|
+
if (v.orderType !== 0 && v.orderType !== 1)
|
|
187
|
+
throw new BuilderError('builder_on_stop', 'Only market and limit orders can carry a builder fee: place a stop without a builder.');
|
|
188
|
+
if (v.triggerPrice8dec !== 0n || v.triggerDir !== 0)
|
|
189
|
+
throw new BuilderError('builder_on_stop', 'A stop order cannot carry a builder fee.');
|
|
190
|
+
const worst = whole(worstPrice8, U64, 'The worst price');
|
|
191
|
+
if (v.orderType === 0 && v.price !== 0n && v.price !== worst)
|
|
192
|
+
throw new BuilderError('invalid_body', "A market order's price is its worst price: give it as worstPrice.");
|
|
193
|
+
if (v.orderType === 1 && worst !== 0n)
|
|
194
|
+
throw new BuilderError('invalid_body', "A worst price applies to a market order; a limit order's price is its limit.");
|
|
195
|
+
const price = v.orderType === 0 ? worst : whole(v.price, U64, 'price');
|
|
196
|
+
return {
|
|
197
|
+
owner: addr(v.owner, 'The account'), pairId: v.pairId, side: v.side, size: whole(v.size, U128, 'size'), price,
|
|
198
|
+
leverageBps: v.leverageBps, orderType: v.orderType, reduceOnly: v.reduceOnly, postOnly: v.postOnly, triggerPrice8dec: 0n, triggerDir: 0,
|
|
199
|
+
timeInForce: 0, expiresAt: 0n, clientNonce: whole(v.clientNonce, U64, 'clientNonce'), validUntil: whole(validUntil, U64, 'validUntil'),
|
|
200
|
+
worstPrice8dec: v.orderType === 0 ? worst : 0n, source, builder: addr(b.address, 'The builder'), builderFeeCbps: Number(whole(b.feeCbps, U32, 'builderFeeCbps')),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
const SIDE_NAME = ['buy', 'sell'];
|
|
204
|
+
const TYPE_NAME = ['Market', 'Limit'];
|
|
205
|
+
/** The `/order/place` body of a signed PlaceOrderV3 (`signature` = the 65-byte form). A market order carries no price. */
|
|
206
|
+
export function placeOrderV3Body(v, signature) {
|
|
207
|
+
const body = {
|
|
208
|
+
owner: v.owner, pairId: v.pairId, side: SIDE_NAME[v.side], size_18dec: v.size.toString(), orderType: TYPE_NAME[v.orderType],
|
|
209
|
+
leverageBps: v.leverageBps, clientNonce: v.clientNonce.toString(), validUntil: v.validUntil.toString(), worstPrice8dec: v.worstPrice8dec.toString(),
|
|
210
|
+
source: v.source, builder: v.builder, builderFeeCbps: v.builderFeeCbps, signature,
|
|
211
|
+
};
|
|
212
|
+
if (v.price !== 0n)
|
|
213
|
+
body.price_8dec = v.price.toString();
|
|
214
|
+
if (v.reduceOnly)
|
|
215
|
+
body.reduceOnly = true;
|
|
216
|
+
if (v.postOnly)
|
|
217
|
+
body.postOnly = true;
|
|
218
|
+
return body;
|
|
219
|
+
}
|
|
220
|
+
/** The level fields of a `/referral/stats` read, or null when it carries no `level` (levels not in force). */
|
|
221
|
+
export function referralLevel(read) {
|
|
222
|
+
if (!read || typeof read !== 'object')
|
|
223
|
+
return null;
|
|
224
|
+
const r = read;
|
|
225
|
+
if (typeof r.level !== 'string')
|
|
226
|
+
return null;
|
|
227
|
+
const n = (k) => (typeof r[k] === 'number' && Number.isSafeInteger(r[k]) ? r[k] : null);
|
|
228
|
+
const s = (k) => (typeof r[k] === 'string' ? r[k] : null);
|
|
229
|
+
const o = (k) => (r[k] && typeof r[k] === 'object' ? { ...r[k] } : {});
|
|
230
|
+
return {
|
|
231
|
+
level: r.level, shareBps: n('share_bps'), discountBps: n('discount_bps'), l2Progress: o('l2_progress'), nextCheckMs: n('next_check_ms'),
|
|
232
|
+
ownVolume6dec: s('own_volume_6dec'), minOwnVolume6dec: s('min_own_volume_6dec'), meetsMin: typeof r.meets_min === 'boolean' ? r.meets_min : null,
|
|
233
|
+
limits: o('limits'), refereeVolume6dec: s('referee_volume_6dec'),
|
|
234
|
+
};
|
|
235
|
+
}
|