@vordium/sdk 0.1.3 → 0.2.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/README.md CHANGED
@@ -58,10 +58,49 @@ const state = await me.waitForOrder(order.clientNonce) // 'rest
58
58
  - Every nonce comes from one millisecond clock per account, so batches, single orders and the dead-man switch never
59
59
  collide.
60
60
 
61
+ ## Builder codes
62
+
63
+ An app or bot that sends orders for traders (a builder) can add its own fee to those orders, up to what each trader
64
+ approved. Fees are in cbps, hundredths of a basis point: 1,000 cbps = 0.1 %, 500 cbps = 5 bps = 0.05 %. The network
65
+ publishes its limits in its reads: the fee cap per market kind (`caps_cbps` in `builderStats()`), the most builders an
66
+ account may approve (`max` in `builderApprovals()`), and the account value a builder needs for orders that name it to
67
+ be accepted (`min_account_value_6dec`, with `account_value_ok`).
68
+
69
+ ```ts
70
+ await me.approveBuilderFee(builderAddress, 500) // owner key: let the builder charge up to 5 bps
71
+ await v.builderApprovals(me.owner) // { approvals: [{ builder, max_fee_cbps }], count, max, active, … }
72
+ await me.placeOrder({ pairId: 1, side: 'buy', size: '0.01', orderType: 'Limit', price: '1700',
73
+ builder: { address: builderAddress, feeCbps: 500 } }) // signed as PlaceOrderV3
74
+ await me.placeOrder({ pairId: 1, side: 'buy', size: '0.01', orderType: 'Market',
75
+ builder: { address: builderAddress, feeCbps: 500 }, worstPrice: '1950' }) // a market order with a worst price
76
+ await me.revokeBuilderFee(builderAddress) // an approval of 0
77
+
78
+ const builder = await v.account(builderWallet)
79
+ await v.builderStats(builder.owner) // volume, fees = unclaimed + claimed, users in 30 days, caps
80
+ await builder.claimBuilderFees() // unclaimed fees to the builder's balance
81
+ ```
82
+
83
+ Before anything is signed the SDK reads the network: builder fees active (`active` in the builder reads), the fee
84
+ above 0 and within the cap (`caps_cbps`), the builder approved at or above the fee, its account value enough, and the builder not the
85
+ trader. Otherwise it throws `BuilderError` with the network's code (`builder_fee_above_cap`, `builder_not_approved`,
86
+ `builder_too_small`, …) and a sentence saying what to do, or `BuilderNotActive`. An order without `builder` is signed
87
+ exactly as before. A market order with a builder takes `worstPrice`: it is put on the market's price step so it is
88
+ never worse than given (a buy's rounds down, a sell's up) and signed as both the slippage cap and the worst price; the
89
+ network refuses the order (`slippage`, `worst_price`) when the market is already past it. Without `worstPrice` a
90
+ builder market order has no price limit.
91
+
92
+ The fee a fill charged is in that fill's record, under its `builder` key (`taker_builder`, `taker_fee_6dec`,
93
+ `maker_builder`, `maker_fee_6dec`; the key is absent when no builder fee was charged), and the builder's totals in its
94
+ stats read.
95
+
96
+ `v.referralLevel(address)` reads an account's referral level (`L1`, `L2` or `PARTNER`), its fee share and its referees'
97
+ discount, its progress in the current 30-day period toward L2, and whether its own volume meets the referrer minimum;
98
+ `v.referralTiers()` reads the table and its rules.
99
+
61
100
  ## What "applied" means
62
101
 
63
102
  A write is answered when the network accepts it for a coming block (HTTP 202). That is a submission, not a result. The
64
- account operations — session keys, agents, TWAP and margin mode — return `{ applied, status, answer, detail }`, and
103
+ account operations — session keys, agents, TWAP, margin mode and builder approvals and claims — return `{ applied, status, answer, detail }`, and
65
104
  `applied` is true only once the chain's own read shows the change. Orders return the submission; read them back with
66
105
  `waitForOrder()`, `openOrders()` and `positions()`.
67
106
 
@@ -0,0 +1,256 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BuilderNotActive = exports.BuilderError = exports.ORDER_SOURCE = exports.DEFAULT_AHEAD_S = exports.MAX_AHEAD_S = exports.MARKET_KINDS = exports.BUILDER_TYPEHASHES = exports.BUILDER_ROUTES = void 0;
4
+ exports.requireActive = requireActive;
5
+ exports.capsFrom = capsFrom;
6
+ exports.describeCbps = describeCbps;
7
+ exports.checkFee = checkFee;
8
+ exports.checkMaxFee = checkMaxFee;
9
+ exports.deadline = deadline;
10
+ exports.approvalOf = approvalOf;
11
+ exports.checkOrderBuilder = checkOrderBuilder;
12
+ exports.parseBuilder = parseBuilder;
13
+ exports.approveBuilderFeeValue = approveBuilderFeeValue;
14
+ exports.approveBuilderFeeBody = approveBuilderFeeBody;
15
+ exports.claimBuilderFeesValue = claimBuilderFeesValue;
16
+ exports.claimBuilderFeesBody = claimBuilderFeesBody;
17
+ exports.placeOrderV3Value = placeOrderV3Value;
18
+ exports.placeOrderV3Body = placeOrderV3Body;
19
+ exports.referralLevel = referralLevel;
20
+ const ethers_1 = require("ethers");
21
+ const errors_js_1 = require("./errors.js");
22
+ const units_js_1 = require("./units.js");
23
+ /**
24
+ * Builder codes: a fee an app or bot (the builder) adds to the orders it sends, up to what the trader approved.
25
+ *
26
+ * Three signed operations in the VordCore domain, each signed as 65 bytes `r‖s‖v`:
27
+ * - `ApproveBuilderFee` (POST /builder/approve), the trader's own key: let `builder` charge up to `maxFeeCbps`.
28
+ * A revoke is an approval of 0.
29
+ * - `PlaceOrderV3` (POST /order/place): an order that names a builder and its fee.
30
+ * - `ClaimBuilderFees` (POST /builder/claim), the builder's own key: move its accrued fees to its balance.
31
+ *
32
+ * Fees are in cbps, hundredths of a basis point: 1,000 cbps = 0.1 %, 500 cbps = 5 bps = 0.05 %. The network publishes
33
+ * its limits in its reads: the cap per market kind (`caps_cbps` {perps, spot} of the stats read), the most builders an
34
+ * account may approve (`max` of the approvals read), and the account value a builder needs for orders that name it to
35
+ * be accepted (`min_account_value_6dec`, with `account_value_ok`). The SDK checks against these reads, never against
36
+ * fixed figures; a read without them is refused before signing. The reads carry `active`: whether builder fees are
37
+ * active at the next block; nothing is signed while it is not true.
38
+ */
39
+ exports.BUILDER_ROUTES = { approve: '/builder/approve', claim: '/builder/claim', order: '/order/place' };
40
+ /** keccak256 of each type string (checked against the strings in the tests). */
41
+ exports.BUILDER_TYPEHASHES = {
42
+ ApproveBuilderFee: '0xe63fa83d341ba3dfe6b57bc221d00f03edce9f043613f5243078e294ff0c849a',
43
+ ClaimBuilderFees: '0xd5774785d91fe35740b030286fca8338c06609f3ba19595ee63a21d6e020500f',
44
+ PlaceOrderV3: '0xe328eb68341f2a35a289620b7147dc72672f356f6dff3b10098ae02f19a6c5d5',
45
+ };
46
+ /** The market kinds a builder fee cap is published for (`caps_cbps` of the stats read). */
47
+ exports.MARKET_KINDS = ['perps', 'spot'];
48
+ /** An approval deadline is at most this many seconds ahead of the network's block time. */
49
+ exports.MAX_AHEAD_S = 300;
50
+ exports.DEFAULT_AHEAD_S = 120;
51
+ /** The `source` an order placed through this SDK signs. */
52
+ exports.ORDER_SOURCE = 'sdk';
53
+ /** A builder operation the network would refuse, caught before anything was signed. `code` is the network's code. */
54
+ class BuilderError extends errors_js_1.VordiumError {
55
+ constructor(code, message) {
56
+ super(code, message);
57
+ this.name = 'BuilderError';
58
+ }
59
+ }
60
+ exports.BuilderError = BuilderError;
61
+ /** Builder fees are not active on this network. Nothing was signed. */
62
+ class BuilderNotActive extends BuilderError {
63
+ constructor(message = 'Builder fees are not active on this network, so nothing was signed.') {
64
+ super('builder_not_active', message);
65
+ this.name = 'BuilderNotActive';
66
+ }
67
+ }
68
+ exports.BuilderNotActive = BuilderNotActive;
69
+ function addr(v, what) {
70
+ try {
71
+ return (0, ethers_1.getAddress)(String(v));
72
+ }
73
+ catch {
74
+ throw new BuilderError('invalid_body', `${what} must be an address (0x and 40 hex characters).`);
75
+ }
76
+ }
77
+ function whole(v, max, what) {
78
+ try {
79
+ return (0, units_js_1.uint)(v, max, what);
80
+ }
81
+ catch {
82
+ throw new BuilderError('invalid_body', `${what} must be a whole number from 0 to ${max}.`);
83
+ }
84
+ }
85
+ /** Raise {@link BuilderNotActive} unless a builder read says `active: true`. */
86
+ function requireActive(read) {
87
+ if (!read || typeof read !== 'object' || read.active !== true)
88
+ throw new BuilderNotActive();
89
+ }
90
+ /** The caps in cbps from a stats read (`caps_cbps` {perps, spot}); a read without both is refused (`unreadable`). */
91
+ function capsFrom(read) {
92
+ const got = read && typeof read === 'object' ? read.caps_cbps : null;
93
+ const caps = {};
94
+ for (const k of exports.MARKET_KINDS) {
95
+ const v = got && typeof got === 'object' ? got[k] : undefined;
96
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < 0)
97
+ 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.");
98
+ caps[k] = v;
99
+ }
100
+ return caps;
101
+ }
102
+ function isKind(kind) { return kind === 'perps' || kind === 'spot'; }
103
+ /** A fee in plain words: 500 → "5 bps (0.05%)". */
104
+ function describeCbps(cbps) {
105
+ const pct = (cbps / 10000).toFixed(4).replace(/0+$/, '').replace(/\.$/, '');
106
+ return `${cbps / 100} bps (${pct}%)`;
107
+ }
108
+ /** A builder fee on an order: above 0 and at most the cap of `kind`. */
109
+ function checkFee(feeCbps, kind, caps) {
110
+ if (!isKind(kind))
111
+ throw new BuilderError('invalid_body', 'kind is perps or spot.');
112
+ if (!caps || typeof caps[kind] !== 'number')
113
+ throw new BuilderError('unreadable', 'No fee cap for this market kind; nothing was signed.');
114
+ const fee = Number(whole(feeCbps, units_js_1.U32, 'The builder fee'));
115
+ if (fee === 0)
116
+ throw new BuilderError('builder_fee_zero', 'A builder was named with a fee of 0: name no builder, or a fee above 0.');
117
+ if (fee > caps[kind])
118
+ 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.`);
119
+ return fee;
120
+ }
121
+ /** The most a builder may charge under an approval: above 0 and at most the highest cap. 0 is a revoke. */
122
+ function checkMaxFee(maxFeeCbps, caps) {
123
+ const fee = Number(whole(maxFeeCbps, units_js_1.U32, 'The approved fee'));
124
+ if (fee === 0)
125
+ throw new BuilderError('builder_fee_zero', 'An approval of 0 is a revoke: use revokeBuilderFee.');
126
+ const top = Math.max(caps.perps, caps.spot);
127
+ if (fee > top)
128
+ 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.`);
129
+ return fee;
130
+ }
131
+ /** The `validUntil` to sign (unix seconds): at most 300 s ahead of `nowS`, and after it. */
132
+ function deadline(validUntil, nowS, aheadS = exports.DEFAULT_AHEAD_S) {
133
+ const vu = validUntil ?? nowS + aheadS;
134
+ if (!Number.isSafeInteger(vu))
135
+ throw new BuilderError('invalid_body', 'validUntil must be whole unix seconds.');
136
+ if (vu - nowS > exports.MAX_AHEAD_S)
137
+ throw new BuilderError('approval_too_far', `Not signed: the deadline is ${vu - nowS} s ahead; the network takes at most ${exports.MAX_AHEAD_S} s.`);
138
+ if (vu <= nowS)
139
+ throw new BuilderError('approval_expired', 'Not signed: the deadline has already passed.');
140
+ return vu;
141
+ }
142
+ /** The fee (cbps) an approvals read shows for `builder`, or null. */
143
+ function approvalOf(read, builder) {
144
+ const rows = read && typeof read === 'object' ? read.approvals : null;
145
+ const b = builder.toLowerCase();
146
+ for (const r of Array.isArray(rows) ? rows : []) {
147
+ if (r && typeof r === 'object' && String(r.builder ?? '').toLowerCase() === b) {
148
+ const v = r.max_fee_cbps;
149
+ return typeof v === 'number' && Number.isSafeInteger(v) ? v : null;
150
+ }
151
+ }
152
+ return null;
153
+ }
154
+ /** What the network checks for an order that names a builder, from the two reads. */
155
+ function checkOrderBuilder(owner, builder, feeCbps, approvals, stats) {
156
+ requireActive(approvals);
157
+ requireActive(stats);
158
+ if (owner.toLowerCase() === builder.toLowerCase())
159
+ throw new BuilderError('builder_self', 'An account cannot be its own builder: name another builder.');
160
+ const approved = approvalOf(approvals, builder);
161
+ if (approved === null || approved === 0)
162
+ throw new BuilderError('builder_not_approved', `The account has not approved builder ${builder}: approve it first (approveBuilderFee).`);
163
+ if (feeCbps > approved)
164
+ 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.`);
165
+ if (stats.account_value_ok === false) {
166
+ const need = stats.min_account_value_6dec;
167
+ const floor = typeof need === 'string' && /^\d+$/.test(need) ? `the ${usdc(BigInt(need))} USDC minimum` : "the network's minimum account value";
168
+ 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.`);
169
+ }
170
+ }
171
+ /** 6-decimal USDC as a plain decimal: 100000000n → "100", 1500000n → "1.5". */
172
+ function usdc(v) {
173
+ const whole = v / 1000000n, frac = v % 1000000n;
174
+ return whole.toLocaleString('en-US') + (frac ? '.' + frac.toString().padStart(6, '0').replace(/0+$/, '') : '');
175
+ }
176
+ /** `{address, feeCbps}` checked: a checksummed address and a whole fee. */
177
+ function parseBuilder(b) {
178
+ if (!b || typeof b !== 'object')
179
+ throw new BuilderError('invalid_body', 'builder is { address: "0x…", feeCbps: 500 }.');
180
+ const o = b;
181
+ if (o.feeCbps === undefined || o.feeCbps === null)
182
+ throw new BuilderError('invalid_body', 'The builder fee is missing (feeCbps).');
183
+ return { address: addr(o.address, 'The builder'), feeCbps: Number(whole(o.feeCbps, units_js_1.U32, 'The builder fee')) };
184
+ }
185
+ function approveBuilderFeeValue(user, builder, maxFeeCbps, nonce, validUntil) {
186
+ const u = addr(user, 'The account'), b = addr(builder, 'The builder');
187
+ if (u.toLowerCase() === b.toLowerCase())
188
+ throw new BuilderError('builder_self', 'An account cannot be its own builder: name another builder.');
189
+ return { user: u, builder: b, maxFeeCbps: Number(whole(maxFeeCbps, units_js_1.U32, 'The approved fee')), nonce: whole(nonce, units_js_1.U64, 'nonce'), validUntil: whole(validUntil, units_js_1.U64, 'validUntil') };
190
+ }
191
+ function approveBuilderFeeBody(v, signature) {
192
+ return { user: v.user, builder: v.builder, maxFeeCbps: v.maxFeeCbps, nonce: Number(v.nonce), validUntil: Number(v.validUntil), signature };
193
+ }
194
+ function claimBuilderFeesValue(builder, nonce, validUntil) {
195
+ return { builder: addr(builder, 'The builder'), nonce: whole(nonce, units_js_1.U64, 'nonce'), validUntil: whole(validUntil, units_js_1.U64, 'validUntil') };
196
+ }
197
+ function claimBuilderFeesBody(v, signature) {
198
+ return { builder: v.builder, nonce: Number(v.nonce), validUntil: Number(v.validUntil), signature };
199
+ }
200
+ /**
201
+ * The signed PlaceOrderV3 value from a checked PlaceOrder value, its deadline and its builder. Market and limit only.
202
+ * A market order's `worstPrice8` (already on the market's price step) is signed as both `price` (the slippage cap: the
203
+ * network refuses `slippage` when the market is past it) and `worstPrice8dec` (refused `worst_price`); 0 = no limit.
204
+ * A limit order signs its price and a worst price of 0.
205
+ */
206
+ function placeOrderV3Value(v, validUntil, b, source = exports.ORDER_SOURCE, worstPrice8 = 0n) {
207
+ if (v.orderType !== 0 && v.orderType !== 1)
208
+ throw new BuilderError('builder_on_stop', 'Only market and limit orders can carry a builder fee: place a stop without a builder.');
209
+ if (v.triggerPrice8dec !== 0n || v.triggerDir !== 0)
210
+ throw new BuilderError('builder_on_stop', 'A stop order cannot carry a builder fee.');
211
+ const worst = whole(worstPrice8, units_js_1.U64, 'The worst price');
212
+ if (v.orderType === 0 && v.price !== 0n && v.price !== worst)
213
+ throw new BuilderError('invalid_body', "A market order's price is its worst price: give it as worstPrice.");
214
+ if (v.orderType === 1 && worst !== 0n)
215
+ throw new BuilderError('invalid_body', "A worst price applies to a market order; a limit order's price is its limit.");
216
+ const price = v.orderType === 0 ? worst : whole(v.price, units_js_1.U64, 'price');
217
+ return {
218
+ owner: addr(v.owner, 'The account'), pairId: v.pairId, side: v.side, size: whole(v.size, units_js_1.U128, 'size'), price,
219
+ leverageBps: v.leverageBps, orderType: v.orderType, reduceOnly: v.reduceOnly, postOnly: v.postOnly, triggerPrice8dec: 0n, triggerDir: 0,
220
+ timeInForce: 0, expiresAt: 0n, clientNonce: whole(v.clientNonce, units_js_1.U64, 'clientNonce'), validUntil: whole(validUntil, units_js_1.U64, 'validUntil'),
221
+ worstPrice8dec: v.orderType === 0 ? worst : 0n, source, builder: addr(b.address, 'The builder'), builderFeeCbps: Number(whole(b.feeCbps, units_js_1.U32, 'builderFeeCbps')),
222
+ };
223
+ }
224
+ const SIDE_NAME = ['buy', 'sell'];
225
+ const TYPE_NAME = ['Market', 'Limit'];
226
+ /** The `/order/place` body of a signed PlaceOrderV3 (`signature` = the 65-byte form). A market order carries no price. */
227
+ function placeOrderV3Body(v, signature) {
228
+ const body = {
229
+ owner: v.owner, pairId: v.pairId, side: SIDE_NAME[v.side], size_18dec: v.size.toString(), orderType: TYPE_NAME[v.orderType],
230
+ leverageBps: v.leverageBps, clientNonce: v.clientNonce.toString(), validUntil: v.validUntil.toString(), worstPrice8dec: v.worstPrice8dec.toString(),
231
+ source: v.source, builder: v.builder, builderFeeCbps: v.builderFeeCbps, signature,
232
+ };
233
+ if (v.price !== 0n)
234
+ body.price_8dec = v.price.toString();
235
+ if (v.reduceOnly)
236
+ body.reduceOnly = true;
237
+ if (v.postOnly)
238
+ body.postOnly = true;
239
+ return body;
240
+ }
241
+ /** The level fields of a `/referral/stats` read, or null when it carries no `level` (levels not in force). */
242
+ function referralLevel(read) {
243
+ if (!read || typeof read !== 'object')
244
+ return null;
245
+ const r = read;
246
+ if (typeof r.level !== 'string')
247
+ return null;
248
+ const n = (k) => (typeof r[k] === 'number' && Number.isSafeInteger(r[k]) ? r[k] : null);
249
+ const s = (k) => (typeof r[k] === 'string' ? r[k] : null);
250
+ const o = (k) => (r[k] && typeof r[k] === 'object' ? { ...r[k] } : {});
251
+ return {
252
+ level: r.level, shareBps: n('share_bps'), discountBps: n('discount_bps'), l2Progress: o('l2_progress'), nextCheckMs: n('next_check_ms'),
253
+ ownVolume6dec: s('own_volume_6dec'), minOwnVolume6dec: s('min_own_volume_6dec'), meetsMin: typeof r.meets_min === 'boolean' ? r.meets_min : null,
254
+ limits: o('limits'), refereeVolume6dec: s('referee_volume_6dec'),
255
+ };
256
+ }
@@ -21,6 +21,7 @@ const sign_js_1 = require("./sign.js");
21
21
  const units_js_1 = require("./units.js");
22
22
  const rounding_js_1 = require("./rounding.js");
23
23
  const types_js_1 = require("./types.js");
24
+ const builder_js_1 = require("./builder.js");
24
25
  /** The result of an account write by the chain's own read: applied, refused, or not known yet. */
25
26
  async function outcome(r, shows, waitMs, notShown) {
26
27
  if (!r.proceed) {
@@ -104,6 +105,8 @@ class Vordium {
104
105
  const r = await this.transport.get(this.network.api + path, this.timeoutMs);
105
106
  if (r.status === 404)
106
107
  return null;
108
+ if (r.status >= 300 && r.status < 400)
109
+ throw new errors_js_1.VordiumError('redirect_refused', `The read ${path} was answered with a redirect, which is not followed: use the https address of the node.`);
107
110
  if (r.status !== 200)
108
111
  throw new errors_js_1.VordiumError('read_failed', `The read ${path} answered HTTP ${r.status}.`);
109
112
  return r.body;
@@ -177,6 +180,32 @@ class Vordium {
177
180
  crossMargin(owner) { return this.get(`/account/cross/${owner}`); }
178
181
  /** The dead-man switch's committed state and limits. */
179
182
  scheduleCancelState(owner) { return this.get(`/schedule-cancel/${owner}`); }
183
+ // ── builder codes and referral levels ───────────────────────────────────────────────────────────────────────────
184
+ /** `GET /builder/approvals/<user>`: the builders `user` approved, the count, the most allowed, its nonce, `active`. */
185
+ async builderApprovals(user) {
186
+ const j = await this.get(`/builder/approvals/${builderAddress(user)}`);
187
+ if (!j || typeof j !== 'object')
188
+ throw new builder_js_1.BuilderNotActive('The network does not answer the builder approvals read, so nothing was signed.');
189
+ return j;
190
+ }
191
+ /** `GET /builder/stats/<builder>`: volume, fees (= unclaimed + claimed), users in 30 days, caps, claim nonce, `active`. */
192
+ async builderStats(builder) {
193
+ const j = await this.get(`/builder/stats/${builderAddress(builder)}`);
194
+ if (!j || typeof j !== 'object')
195
+ throw new builder_js_1.BuilderNotActive('The network does not answer the builder stats read, so nothing was signed.');
196
+ return j;
197
+ }
198
+ /** `GET /referral/stats/<address>` as the network answers it. */
199
+ referralStats(address) { return this.get(`/referral/stats/${(0, ethers_1.getAddress)(address)}`); }
200
+ /** The account's referral level (`L1`, `L2`, `PARTNER`) and its period progress; null where levels are not shown. */
201
+ async referralLevel(address) { return (0, builder_js_1.referralLevel)(await this.referralStats(address)); }
202
+ /** `GET /referral/tiers`: the levels table, the L2 rule, the partner bounds and the referee caps. */
203
+ referralTiers() { return this.get('/referral/tiers'); }
204
+ /** The network's block time in whole seconds, else this computer's clock. */
205
+ async nowS() {
206
+ const ms = await this.chainTimeMs().catch(() => null);
207
+ return Math.floor((typeof ms === 'number' && ms > 0 ? ms : Date.now()) / 1000);
208
+ }
180
209
  /** The TWAP route and limits from the network spec (refused when not published). */
181
210
  twapRules() { return (0, account_js_1.readTwapRules)(this.network.specRead); }
182
211
  /** A trading account: `owner` signs account operations; `sessionSigner` (a session or agent key) signs orders. */
@@ -295,12 +324,26 @@ class Account {
295
324
  */
296
325
  async placeOrder(o) {
297
326
  const signer = this.orderSigner();
298
- (0, orders_js_1.placeOrderValue)({ ...o, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
327
+ const { builder: wanted, worstPrice, ...plain } = o;
328
+ if (worstPrice != null && (wanted == null || o.orderType !== 'Market'))
329
+ throw new errors_js_1.InvalidRequest('worstPrice applies to a market order that names a builder.');
330
+ (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
331
+ const ob = wanted == null ? null : await this.checkedBuilder(wanted); // null or undefined: no builder
299
332
  const spec = await this.pairSpec(o.pairId);
300
333
  const clientNonce = o.clientNonce ?? (await this.fresh('orders'));
301
- const v = (0, orders_js_1.placeOrderValue)({ ...o, owner: this.owner, clientNonce }, spec);
302
- const sig = await this.sign(signer, 'PlaceOrder', v);
303
- const body = (0, orders_js_1.placeOrderBody)(v, (0, ethers_1.getAddress)(await signer.getAddress()), (0, sign_js_1.rs64)(sig));
334
+ const v = (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce }, spec);
335
+ let body;
336
+ if (ob) {
337
+ // a buy's cap rounds down onto the price step and a sell's floor up: never worse than the caller gave
338
+ const worst8 = worstPrice == null ? 0n : (0, rounding_js_1.price8OnTick)(worstPrice, spec, o.side, true);
339
+ const v3 = (0, builder_js_1.placeOrderV3Value)(v, (0, builder_js_1.deadline)(null, await this.client.nowS()), ob, undefined, worst8);
340
+ body = (0, builder_js_1.placeOrderV3Body)(v3, await this.sign(signer, 'PlaceOrderV3', v3));
341
+ }
342
+ else {
343
+ const sig = await this.sign(signer, 'PlaceOrder', v);
344
+ body = (0, orders_js_1.placeOrderBody)(v, (0, ethers_1.getAddress)(await signer.getAddress()), (0, sign_js_1.rs64)(sig));
345
+ }
346
+ const withBuilder = ob ? { builder: ob } : {};
304
347
  const signed = { pairId: v.pairId, side: v.side, size: v.size, price: v.orderType === 1 ? v.price : null };
305
348
  // after the mark was set back to the clock, a nonce may repeat one handed out before: a read-back must be newer
306
349
  const rewound = this.nonce instanceof nonce_js_1.NonceAllocator ? await this.nonce.rewoundBefore(clientNonce) : null;
@@ -320,18 +363,18 @@ class Account {
320
363
  const found = ours(await this.orderByClientNonce(clientNonce, signed));
321
364
  if (!found)
322
365
  throw e;
323
- return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found };
366
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
324
367
  }
325
368
  if (r.needsReadBack) {
326
369
  // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
327
370
  // signer": it is ours only when the order the network lists carries what was signed
328
371
  const found = ours(await this.orderByClientNonce(clientNonce, signed));
329
372
  if (found)
330
- return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found };
331
- return { ...unknownResult(r.attempts, `An earlier copy may have arrived (its answer was lost), the network answered ${r.status}, and it does not list this order (yet). Read the account's orders before sending a new one.`, r.body), clientNonce, alreadyReceived: false, found: null };
373
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
374
+ return { ...unknownResult(r.attempts, `An earlier copy may have arrived (its answer was lost), the network answered ${r.status}, and it does not list this order (yet). Read the account's orders before sending a new one.`, r.body), clientNonce, alreadyReceived: false, found: null, ...withBuilder };
332
375
  }
333
376
  const s = (0, orders_js_1.readAnswer)(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
334
- return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false };
377
+ return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false, ...withBuilder };
335
378
  }
336
379
  /**
337
380
  * The account's order with `clientNonce` as the network lists it: resting (open orders), else its record; null when
@@ -588,6 +631,83 @@ class Account {
588
631
  const map = { 1: 'cross', 2: 'isolated', cross: 'cross', isolated: 'isolated' };
589
632
  return map[String(m)] ?? null;
590
633
  }
634
+ // ── builder codes ─────────────────────────────────────────────────────────────────────────────────────────────
635
+ /** An order's builder after the network's reads allow it (rule active, fee within the perps cap, approved, funded). */
636
+ async checkedBuilder(b) {
637
+ const ob = (0, builder_js_1.parseBuilder)(b);
638
+ let approvals, stats;
639
+ try {
640
+ approvals = await this.client.builderApprovals(this.owner);
641
+ stats = await this.client.builderStats(ob.address);
642
+ }
643
+ catch (e) {
644
+ if (e instanceof builder_js_1.BuilderError)
645
+ throw e;
646
+ throw new builder_js_1.BuilderNotActive('The network did not answer its builder reads, so the builder fee cannot be checked and nothing was signed. Try again, or send the order without a builder.');
647
+ }
648
+ (0, builder_js_1.requireActive)(approvals);
649
+ (0, builder_js_1.requireActive)(stats);
650
+ (0, builder_js_1.checkFee)(ob.feeCbps, 'perps', (0, builder_js_1.capsFrom)(stats));
651
+ (0, builder_js_1.checkOrderBuilder)(this.owner, ob.address, ob.feeCbps, approvals, stats);
652
+ return ob;
653
+ }
654
+ /** The builders this account approved (`approvals`, `count`, `max`, `nonce`, `active`). */
655
+ builderApprovals() { return this.client.builderApprovals(this.owner); }
656
+ /** This account's stats as a builder. */
657
+ builderStats() { return this.client.builderStats(this.owner); }
658
+ /**
659
+ * Let `builder` charge this account up to `maxFeeCbps` per order (500 cbps = 5 bps = 0.05 %); approving a builder
660
+ * again replaces its fee. Signed with the account's own key. Refused before signing when builder fees are not active,
661
+ * the fee is 0 or above the highest cap (`caps_cbps`), the builder is this account, or the account already approved
662
+ * the most builders it may (`max`).
663
+ */
664
+ async approveBuilderFee(builder, maxFeeCbps, waitMs = 30000) {
665
+ const signer = this.needOwner('A builder approval');
666
+ const b = builderAddress(builder);
667
+ const read = await this.client.builderApprovals(this.owner);
668
+ (0, builder_js_1.requireActive)(read);
669
+ const fee = (0, builder_js_1.checkMaxFee)(maxFeeCbps, (0, builder_js_1.capsFrom)(await this.client.builderStats(b)));
670
+ if (b.toLowerCase() === this.owner.toLowerCase())
671
+ throw new builder_js_1.BuilderError('builder_self', 'An account cannot be its own builder: name another builder.');
672
+ const max = read.max, count = read.count;
673
+ if (typeof max !== 'number' || typeof count !== 'number')
674
+ throw new builder_js_1.BuilderError('unreadable', "The network's approvals read gives no count or maximum, so nothing was signed.");
675
+ if ((0, builder_js_1.approvalOf)(read, b) === null && count >= max)
676
+ throw new builder_js_1.BuilderError('builder_approvals_full', `The account has approved the most builders it may (${max}): revoke one first.`);
677
+ return this.approve(signer, b, fee, read, (r) => (0, builder_js_1.approvalOf)(r, b) === fee, 'the chain does not show the approval', waitMs);
678
+ }
679
+ /** Withdraw the approval of `builder` (an approval of 0). Orders that name it are refused from then on. */
680
+ async revokeBuilderFee(builder, waitMs = 30000) {
681
+ const signer = this.needOwner('A builder approval');
682
+ const b = builderAddress(builder);
683
+ const read = await this.client.builderApprovals(this.owner);
684
+ (0, builder_js_1.requireActive)(read);
685
+ if ((0, builder_js_1.approvalOf)(read, b) === null)
686
+ return { applied: true, status: 0, answer: null, detail: 'no approval to revoke' };
687
+ return this.approve(signer, b, 0, read, (r) => (0, builder_js_1.approvalOf)(r, b) === null, 'the chain still shows the approval', waitMs);
688
+ }
689
+ async approve(signer, b, fee, read, shows, notShown, waitMs) {
690
+ const nonce = (typeof read.nonce === 'number' ? read.nonce : 0) + 1;
691
+ const v = (0, builder_js_1.approveBuilderFeeValue)(this.owner, b, fee, nonce, (0, builder_js_1.deadline)(null, await this.client.nowS()));
692
+ const sig = await this.sign(signer, 'ApproveBuilderFee', v);
693
+ const r = await this.postForResult(builder_js_1.BUILDER_ROUTES.approve, JSON.stringify((0, builder_js_1.approveBuilderFeeBody)(v, sig)));
694
+ // applied once the account's approval nonce has reached ours and the approval reads as asked
695
+ return outcome(r, async () => { const a = await this.client.builderApprovals(this.owner); return a.nonce >= nonce && shows(a); }, waitMs, notShown);
696
+ }
697
+ /** As a builder: move the unclaimed fees to this account's balance. Refused before signing when there is nothing. */
698
+ async claimBuilderFees(waitMs = 30000) {
699
+ const signer = this.needOwner('A claim of builder fees');
700
+ const st = await this.client.builderStats(this.owner);
701
+ (0, builder_js_1.requireActive)(st);
702
+ if (!(typeof st.unclaimed_6dec === 'string' && /^\d+$/.test(st.unclaimed_6dec) && BigInt(st.unclaimed_6dec) > 0n)) {
703
+ throw new builder_js_1.BuilderError('builder_nothing_to_claim', 'There are no builder fees to claim; nothing was signed.');
704
+ }
705
+ const before = typeof st.claim_nonce === 'number' ? st.claim_nonce : 0;
706
+ const v = (0, builder_js_1.claimBuilderFeesValue)(this.owner, before + 1, (0, builder_js_1.deadline)(null, await this.client.nowS()));
707
+ const sig = await this.sign(signer, 'ClaimBuilderFees', v);
708
+ const r = await this.postForResult(builder_js_1.BUILDER_ROUTES.claim, JSON.stringify((0, builder_js_1.claimBuilderFeesBody)(v, sig)));
709
+ return outcome(r, async () => (await this.client.builderStats(this.owner)).claim_nonce > before, waitMs, 'the chain does not show the claim');
710
+ }
591
711
  /** Cross or isolated for one market — only while it holds no open position and no resting order of the account. */
592
712
  async setMarginMode(pairId, mode, waitMs = 30000) {
593
713
  const signer = this.needOwner('The margin mode');
@@ -769,6 +889,15 @@ function twapMatches(row, v) {
769
889
  }
770
890
  return true;
771
891
  }
892
+ /** A builder address, or BuilderError('invalid_body') with a plain sentence (never the library's own error). */
893
+ function builderAddress(a) {
894
+ try {
895
+ return (0, ethers_1.getAddress)(String(a));
896
+ }
897
+ catch {
898
+ throw new builder_js_1.BuilderError('invalid_body', 'The builder must be an address (0x and 40 hex characters).');
899
+ }
900
+ }
772
901
  function unknownResult(attempts, message, answer) {
773
902
  return { submitted: false, status: 0, refusal: { code: 'delivery_unknown', message, detail: '', retryAfter: null }, actions: [], answer, attempts, unknown: true };
774
903
  }
package/dist/cjs/http.js CHANGED
@@ -1,14 +1,18 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.fetchTransport = void 0;
3
+ exports.fetchTransport = exports.REDIRECT_REFUSAL = void 0;
4
4
  exports.parseExactJson = parseExactJson;
5
5
  const errors_js_1 = require("./errors.js");
6
6
  const RETRY_STATUS = new Set([429, 502, 503, 504]);
7
+ /**
8
+ * One fetch with a time limit. Redirects are never followed (`redirect: 'manual'`), for reads or writes: a 3xx comes back
9
+ * as the answer it is, so a node (or anything in front of it) cannot send a signed body, or a read, to another address.
10
+ */
7
11
  async function fetchWithTimeout(url, init, timeoutMs) {
8
12
  const ctl = new AbortController();
9
13
  const t = setTimeout(() => ctl.abort(), timeoutMs);
10
14
  try {
11
- return await fetch(url, { ...init, signal: ctl.signal });
15
+ return await fetch(url, { ...init, redirect: 'manual', signal: ctl.signal });
12
16
  }
13
17
  finally {
14
18
  clearTimeout(t);
@@ -26,6 +30,9 @@ async function readBody(r) {
26
30
  }
27
31
  }
28
32
  const sleep = (ms) => new Promise((res) => setTimeout(res, ms));
33
+ const isRedirect = (status) => status >= 300 && status < 400;
34
+ /** What a redirect answer reads as: never the redirect's own body. */
35
+ exports.REDIRECT_REFUSAL = Object.freeze({ code: 'redirect_refused', error: 'The node answered with a redirect, which is not followed: use the https address of the node.' });
29
36
  /**
30
37
  * The default transport: `fetch`. A read (GET) is tried up to three times on a connection error, a timeout, 429 or
31
38
  * 502–504, with a random wait and the server's Retry-After. A write (POST) is never retried: a second attempt could
@@ -42,7 +49,7 @@ exports.fetchTransport = {
42
49
  await sleep(Number.isFinite(ra) && ra > 0 ? Math.min(ra, 5) * 1000 : 250 * 2 ** attempt * (0.5 + Math.random() / 2));
43
50
  continue;
44
51
  }
45
- return { status: r.status, body: await readBody(r) };
52
+ return { status: r.status, body: isRedirect(r.status) ? { ...exports.REDIRECT_REFUSAL } : await readBody(r) };
46
53
  }
47
54
  catch (e) {
48
55
  last = e;
@@ -54,7 +61,8 @@ exports.fetchTransport = {
54
61
  },
55
62
  async post(url, body, timeoutMs) {
56
63
  const r = await fetchWithTimeout(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body }, timeoutMs);
57
- return { status: r.status, body: await readBody(r), retryAfter: r.headers.get('retry-after') };
64
+ // a redirect is not an answer about the write: no body is read from it
65
+ return { status: r.status, body: isRedirect(r.status) ? { ...exports.REDIRECT_REFUSAL } : await readBody(r), retryAfter: r.headers.get('retry-after') };
58
66
  },
59
67
  };
60
68
  /**
package/dist/cjs/index.js CHANGED
@@ -33,6 +33,7 @@ __exportStar(require("./account.js"), exports);
33
33
  __exportStar(require("./agents.js"), exports);
34
34
  __exportStar(require("./reads.js"), exports);
35
35
  __exportStar(require("./feeds.js"), exports);
36
+ __exportStar(require("./builder.js"), exports);
36
37
  var client_js_1 = require("./client.js");
37
38
  Object.defineProperty(exports, "Vordium", { enumerable: true, get: function () { return client_js_1.Vordium; } });
38
39
  Object.defineProperty(exports, "Account", { enumerable: true, get: function () { return client_js_1.Account; } });
@@ -220,6 +220,10 @@ function pairSpecs(read) {
220
220
  if (!s || typeof s !== 'object')
221
221
  throw new OrderValueError('the market rules read has no specs; nothing was signed.');
222
222
  const sp = s;
223
+ if (Array.isArray(sp.pairs) && sp.pairs.length && (sp.min_order_notional_6dec === undefined || sp.min_order_notional_6dec === null || sp.min_order_notional_6dec === '')) {
224
+ // a read that lists markets but not the smallest order value is trimmed or out of date: never read it as "no minimum"
225
+ throw new SpecsUnavailable('the market rules do not name the smallest order value (min_order_notional_6dec); nothing was signed.');
226
+ }
223
227
  const minNotional6 = count(sp.min_order_notional_6dec);
224
228
  const out = new Map();
225
229
  for (const p of Array.isArray(sp.pairs) ? sp.pairs : []) {
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)',