@vordium/sdk 0.1.3 → 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 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) {
@@ -177,6 +178,32 @@ class Vordium {
177
178
  crossMargin(owner) { return this.get(`/account/cross/${owner}`); }
178
179
  /** The dead-man switch's committed state and limits. */
179
180
  scheduleCancelState(owner) { return this.get(`/schedule-cancel/${owner}`); }
181
+ // ── builder codes and referral levels ───────────────────────────────────────────────────────────────────────────
182
+ /** `GET /builder/approvals/<user>`: the builders `user` approved, the count, the most allowed, its nonce, `active`. */
183
+ async builderApprovals(user) {
184
+ const j = await this.get(`/builder/approvals/${builderAddress(user)}`);
185
+ if (!j || typeof j !== 'object')
186
+ throw new builder_js_1.BuilderNotActive('The network does not answer the builder approvals read, so nothing was signed.');
187
+ return j;
188
+ }
189
+ /** `GET /builder/stats/<builder>`: volume, fees (= unclaimed + claimed), users in 30 days, caps, claim nonce, `active`. */
190
+ async builderStats(builder) {
191
+ const j = await this.get(`/builder/stats/${builderAddress(builder)}`);
192
+ if (!j || typeof j !== 'object')
193
+ throw new builder_js_1.BuilderNotActive('The network does not answer the builder stats read, so nothing was signed.');
194
+ return j;
195
+ }
196
+ /** `GET /referral/stats/<address>` as the network answers it. */
197
+ referralStats(address) { return this.get(`/referral/stats/${(0, ethers_1.getAddress)(address)}`); }
198
+ /** The account's referral level (`L1`, `L2`, `PARTNER`) and its period progress; null where levels are not shown. */
199
+ async referralLevel(address) { return (0, builder_js_1.referralLevel)(await this.referralStats(address)); }
200
+ /** `GET /referral/tiers`: the levels table, the L2 rule, the partner bounds and the referee caps. */
201
+ referralTiers() { return this.get('/referral/tiers'); }
202
+ /** The network's block time in whole seconds, else this computer's clock. */
203
+ async nowS() {
204
+ const ms = await this.chainTimeMs().catch(() => null);
205
+ return Math.floor((typeof ms === 'number' && ms > 0 ? ms : Date.now()) / 1000);
206
+ }
180
207
  /** The TWAP route and limits from the network spec (refused when not published). */
181
208
  twapRules() { return (0, account_js_1.readTwapRules)(this.network.specRead); }
182
209
  /** A trading account: `owner` signs account operations; `sessionSigner` (a session or agent key) signs orders. */
@@ -295,12 +322,26 @@ class Account {
295
322
  */
296
323
  async placeOrder(o) {
297
324
  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
325
+ const { builder: wanted, worstPrice, ...plain } = o;
326
+ if (worstPrice != null && (wanted == null || o.orderType !== 'Market'))
327
+ throw new errors_js_1.InvalidRequest('worstPrice applies to a market order that names a builder.');
328
+ (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
329
+ const ob = wanted == null ? null : await this.checkedBuilder(wanted); // null or undefined: no builder
299
330
  const spec = await this.pairSpec(o.pairId);
300
331
  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));
332
+ const v = (0, orders_js_1.placeOrderValue)({ ...plain, owner: this.owner, clientNonce }, spec);
333
+ let body;
334
+ if (ob) {
335
+ // a buy's cap rounds down onto the price step and a sell's floor up: never worse than the caller gave
336
+ const worst8 = worstPrice == null ? 0n : (0, rounding_js_1.price8OnTick)(worstPrice, spec, o.side, true);
337
+ const v3 = (0, builder_js_1.placeOrderV3Value)(v, (0, builder_js_1.deadline)(null, await this.client.nowS()), ob, undefined, worst8);
338
+ body = (0, builder_js_1.placeOrderV3Body)(v3, await this.sign(signer, 'PlaceOrderV3', v3));
339
+ }
340
+ else {
341
+ const sig = await this.sign(signer, 'PlaceOrder', v);
342
+ body = (0, orders_js_1.placeOrderBody)(v, (0, ethers_1.getAddress)(await signer.getAddress()), (0, sign_js_1.rs64)(sig));
343
+ }
344
+ const withBuilder = ob ? { builder: ob } : {};
304
345
  const signed = { pairId: v.pairId, side: v.side, size: v.size, price: v.orderType === 1 ? v.price : null };
305
346
  // after the mark was set back to the clock, a nonce may repeat one handed out before: a read-back must be newer
306
347
  const rewound = this.nonce instanceof nonce_js_1.NonceAllocator ? await this.nonce.rewoundBefore(clientNonce) : null;
@@ -320,18 +361,18 @@ class Account {
320
361
  const found = ours(await this.orderByClientNonce(clientNonce, signed));
321
362
  if (!found)
322
363
  throw e;
323
- return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found };
364
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
324
365
  }
325
366
  if (r.needsReadBack) {
326
367
  // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
327
368
  // signer": it is ours only when the order the network lists carries what was signed
328
369
  const found = ours(await this.orderByClientNonce(clientNonce, signed));
329
370
  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 };
371
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
372
+ 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
373
  }
333
374
  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 };
375
+ return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false, ...withBuilder };
335
376
  }
336
377
  /**
337
378
  * The account's order with `clientNonce` as the network lists it: resting (open orders), else its record; null when
@@ -588,6 +629,83 @@ class Account {
588
629
  const map = { 1: 'cross', 2: 'isolated', cross: 'cross', isolated: 'isolated' };
589
630
  return map[String(m)] ?? null;
590
631
  }
632
+ // ── builder codes ─────────────────────────────────────────────────────────────────────────────────────────────
633
+ /** An order's builder after the network's reads allow it (rule active, fee within the perps cap, approved, funded). */
634
+ async checkedBuilder(b) {
635
+ const ob = (0, builder_js_1.parseBuilder)(b);
636
+ let approvals, stats;
637
+ try {
638
+ approvals = await this.client.builderApprovals(this.owner);
639
+ stats = await this.client.builderStats(ob.address);
640
+ }
641
+ catch (e) {
642
+ if (e instanceof builder_js_1.BuilderError)
643
+ throw e;
644
+ 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.');
645
+ }
646
+ (0, builder_js_1.requireActive)(approvals);
647
+ (0, builder_js_1.requireActive)(stats);
648
+ (0, builder_js_1.checkFee)(ob.feeCbps, 'perps', (0, builder_js_1.capsFrom)(stats));
649
+ (0, builder_js_1.checkOrderBuilder)(this.owner, ob.address, ob.feeCbps, approvals, stats);
650
+ return ob;
651
+ }
652
+ /** The builders this account approved (`approvals`, `count`, `max`, `nonce`, `active`). */
653
+ builderApprovals() { return this.client.builderApprovals(this.owner); }
654
+ /** This account's stats as a builder. */
655
+ builderStats() { return this.client.builderStats(this.owner); }
656
+ /**
657
+ * Let `builder` charge this account up to `maxFeeCbps` per order (500 cbps = 5 bps = 0.05 %); approving a builder
658
+ * again replaces its fee. Signed with the account's own key. Refused before signing when builder fees are not active,
659
+ * the fee is 0 or above the highest cap (`caps_cbps`), the builder is this account, or the account already approved
660
+ * the most builders it may (`max`).
661
+ */
662
+ async approveBuilderFee(builder, maxFeeCbps, waitMs = 30000) {
663
+ const signer = this.needOwner('A builder approval');
664
+ const b = builderAddress(builder);
665
+ const read = await this.client.builderApprovals(this.owner);
666
+ (0, builder_js_1.requireActive)(read);
667
+ const fee = (0, builder_js_1.checkMaxFee)(maxFeeCbps, (0, builder_js_1.capsFrom)(await this.client.builderStats(b)));
668
+ if (b.toLowerCase() === this.owner.toLowerCase())
669
+ throw new builder_js_1.BuilderError('builder_self', 'An account cannot be its own builder: name another builder.');
670
+ const max = read.max, count = read.count;
671
+ if (typeof max !== 'number' || typeof count !== 'number')
672
+ throw new builder_js_1.BuilderError('unreadable', "The network's approvals read gives no count or maximum, so nothing was signed.");
673
+ if ((0, builder_js_1.approvalOf)(read, b) === null && count >= max)
674
+ throw new builder_js_1.BuilderError('builder_approvals_full', `The account has approved the most builders it may (${max}): revoke one first.`);
675
+ return this.approve(signer, b, fee, read, (r) => (0, builder_js_1.approvalOf)(r, b) === fee, 'the chain does not show the approval', waitMs);
676
+ }
677
+ /** Withdraw the approval of `builder` (an approval of 0). Orders that name it are refused from then on. */
678
+ async revokeBuilderFee(builder, waitMs = 30000) {
679
+ const signer = this.needOwner('A builder approval');
680
+ const b = builderAddress(builder);
681
+ const read = await this.client.builderApprovals(this.owner);
682
+ (0, builder_js_1.requireActive)(read);
683
+ if ((0, builder_js_1.approvalOf)(read, b) === null)
684
+ return { applied: true, status: 0, answer: null, detail: 'no approval to revoke' };
685
+ return this.approve(signer, b, 0, read, (r) => (0, builder_js_1.approvalOf)(r, b) === null, 'the chain still shows the approval', waitMs);
686
+ }
687
+ async approve(signer, b, fee, read, shows, notShown, waitMs) {
688
+ const nonce = (typeof read.nonce === 'number' ? read.nonce : 0) + 1;
689
+ const v = (0, builder_js_1.approveBuilderFeeValue)(this.owner, b, fee, nonce, (0, builder_js_1.deadline)(null, await this.client.nowS()));
690
+ const sig = await this.sign(signer, 'ApproveBuilderFee', v);
691
+ const r = await this.postForResult(builder_js_1.BUILDER_ROUTES.approve, JSON.stringify((0, builder_js_1.approveBuilderFeeBody)(v, sig)));
692
+ // applied once the account's approval nonce has reached ours and the approval reads as asked
693
+ return outcome(r, async () => { const a = await this.client.builderApprovals(this.owner); return a.nonce >= nonce && shows(a); }, waitMs, notShown);
694
+ }
695
+ /** As a builder: move the unclaimed fees to this account's balance. Refused before signing when there is nothing. */
696
+ async claimBuilderFees(waitMs = 30000) {
697
+ const signer = this.needOwner('A claim of builder fees');
698
+ const st = await this.client.builderStats(this.owner);
699
+ (0, builder_js_1.requireActive)(st);
700
+ if (!(typeof st.unclaimed_6dec === 'string' && /^\d+$/.test(st.unclaimed_6dec) && BigInt(st.unclaimed_6dec) > 0n)) {
701
+ throw new builder_js_1.BuilderError('builder_nothing_to_claim', 'There are no builder fees to claim; nothing was signed.');
702
+ }
703
+ const before = typeof st.claim_nonce === 'number' ? st.claim_nonce : 0;
704
+ const v = (0, builder_js_1.claimBuilderFeesValue)(this.owner, before + 1, (0, builder_js_1.deadline)(null, await this.client.nowS()));
705
+ const sig = await this.sign(signer, 'ClaimBuilderFees', v);
706
+ const r = await this.postForResult(builder_js_1.BUILDER_ROUTES.claim, JSON.stringify((0, builder_js_1.claimBuilderFeesBody)(v, sig)));
707
+ return outcome(r, async () => (await this.client.builderStats(this.owner)).claim_nonce > before, waitMs, 'the chain does not show the claim');
708
+ }
591
709
  /** Cross or isolated for one market — only while it holds no open position and no resting order of the account. */
592
710
  async setMarginMode(pairId, mode, waitMs = 30000) {
593
711
  const signer = this.needOwner('The margin mode');
@@ -769,6 +887,15 @@ function twapMatches(row, v) {
769
887
  }
770
888
  return true;
771
889
  }
890
+ /** A builder address, or BuilderError('invalid_body') with a plain sentence (never the library's own error). */
891
+ function builderAddress(a) {
892
+ try {
893
+ return (0, ethers_1.getAddress)(String(a));
894
+ }
895
+ catch {
896
+ throw new builder_js_1.BuilderError('invalid_body', 'The builder must be an address (0x and 40 hex characters).');
897
+ }
898
+ }
772
899
  function unknownResult(attempts, message, answer) {
773
900
  return { submitted: false, status: 0, refusal: { code: 'delivery_unknown', message, detail: '', retryAfter: null }, actions: [], answer, attempts, unknown: true };
774
901
  }
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; } });
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
+ }
@@ -9,6 +9,7 @@ import { type BatchAction, type OrderInput, type Submitted } from './orders.js';
9
9
  import { type AgentRefusal, type Equity, type OpenOrder, type Position } from './reads.js';
10
10
  import { type TypedSigner } from './sign.js';
11
11
  import { type MarketRules, type PairSpec } from './rounding.js';
12
+ import { type BuilderApprovals, type BuilderStats, type OrderBuilder, type ReferralLevel } from './builder.js';
12
13
  /**
13
14
  * The result of a write. `applied` is true only once the chain's own read shows the change. A submission (HTTP 202) is
14
15
  * not an application: `applied: false` with the chain's answer means the chain has not shown it (yet, or at all).
@@ -103,6 +104,18 @@ export declare class Vordium {
103
104
  crossMargin(owner: string): Promise<unknown>;
104
105
  /** The dead-man switch's committed state and limits. */
105
106
  scheduleCancelState(owner: string): Promise<unknown>;
107
+ /** `GET /builder/approvals/<user>`: the builders `user` approved, the count, the most allowed, its nonce, `active`. */
108
+ builderApprovals(user: string): Promise<BuilderApprovals>;
109
+ /** `GET /builder/stats/<builder>`: volume, fees (= unclaimed + claimed), users in 30 days, caps, claim nonce, `active`. */
110
+ builderStats(builder: string): Promise<BuilderStats>;
111
+ /** `GET /referral/stats/<address>` as the network answers it. */
112
+ referralStats(address: string): Promise<unknown>;
113
+ /** The account's referral level (`L1`, `L2`, `PARTNER`) and its period progress; null where levels are not shown. */
114
+ referralLevel(address: string): Promise<ReferralLevel | null>;
115
+ /** `GET /referral/tiers`: the levels table, the L2 rule, the partner bounds and the referee caps. */
116
+ referralTiers(): Promise<unknown>;
117
+ /** The network's block time in whole seconds, else this computer's clock. */
118
+ nowS(): Promise<number>;
106
119
  /** The TWAP route and limits from the network spec (refused when not published). */
107
120
  twapRules(): TwapRules;
108
121
  /** A trading account: `owner` signs account operations; `sessionSigner` (a session or agent key) signs orders. */
@@ -168,12 +181,15 @@ export declare class Account {
168
181
  */
169
182
  placeOrder(o: Omit<OrderInput, 'owner' | 'clientNonce'> & {
170
183
  clientNonce?: number;
184
+ builder?: OrderBuilder | null;
185
+ worstPrice?: string | number | null;
171
186
  }): Promise<Submitted & {
172
187
  clientNonce: number;
173
188
  attempts: number;
174
189
  alreadyReceived: boolean;
175
190
  unknown: boolean;
176
191
  found?: Record<string, unknown> | null;
192
+ builder?: OrderBuilder;
177
193
  }>;
178
194
  /**
179
195
  * The account's order with `clientNonce` as the network lists it: resting (open orders), else its record; null when
@@ -256,6 +272,24 @@ export declare class Account {
256
272
  cancelTwap(twapId: bigint | number, waitMs?: number): Promise<Result>;
257
273
  /** The market's margin mode as the chain reads it ("cross" | "isolated"), or null. */
258
274
  marginMode(pairId: number): Promise<MarginMode | null>;
275
+ /** An order's builder after the network's reads allow it (rule active, fee within the perps cap, approved, funded). */
276
+ private checkedBuilder;
277
+ /** The builders this account approved (`approvals`, `count`, `max`, `nonce`, `active`). */
278
+ builderApprovals(): Promise<BuilderApprovals>;
279
+ /** This account's stats as a builder. */
280
+ builderStats(): Promise<BuilderStats>;
281
+ /**
282
+ * Let `builder` charge this account up to `maxFeeCbps` per order (500 cbps = 5 bps = 0.05 %); approving a builder
283
+ * again replaces its fee. Signed with the account's own key. Refused before signing when builder fees are not active,
284
+ * the fee is 0 or above the highest cap (`caps_cbps`), the builder is this account, or the account already approved
285
+ * the most builders it may (`max`).
286
+ */
287
+ approveBuilderFee(builder: string, maxFeeCbps: number, waitMs?: number): Promise<Result>;
288
+ /** Withdraw the approval of `builder` (an approval of 0). Orders that name it are refused from then on. */
289
+ revokeBuilderFee(builder: string, waitMs?: number): Promise<Result>;
290
+ private approve;
291
+ /** As a builder: move the unclaimed fees to this account's balance. Refused before signing when there is nothing. */
292
+ claimBuilderFees(waitMs?: number): Promise<Result>;
259
293
  /** Cross or isolated for one market — only while it holds no open position and no resting order of the account. */
260
294
  setMarginMode(pairId: number, mode: MarginMode, waitMs?: number): Promise<Result>;
261
295
  private submitAgentOp;
@@ -12,8 +12,9 @@ import { BATCH_MAX, batchBody, cancelAllBody, cancelOrderBody, modifyBody, place
12
12
  import { readAgentRefusals, refusalMeanings, readEquity, readOpenOrders, readPositions } from './reads.js';
13
13
  import { rs64, signOp } from './sign.js';
14
14
  import { U32, U64, U128, safeNumber, uint } from './units.js';
15
- import { OrderValueError, SpecsUnavailable, checkNotional, checkSize, marketRules, selectSpec, sizeStep, snapPrice8, snapSize18, snapTrigger8, } from './rounding.js';
15
+ import { OrderValueError, SpecsUnavailable, checkNotional, price8OnTick, checkSize, marketRules, selectSpec, sizeStep, snapPrice8, snapSize18, snapTrigger8, } from './rounding.js';
16
16
  import { domainOf } from './types.js';
17
+ import { BUILDER_ROUTES, BuilderError, BuilderNotActive, approvalOf, approveBuilderFeeBody, approveBuilderFeeValue, capsFrom, checkFee, checkMaxFee, checkOrderBuilder, claimBuilderFeesBody, claimBuilderFeesValue, deadline, parseBuilder, placeOrderV3Body, placeOrderV3Value, referralLevel, requireActive, } from './builder.js';
17
18
  /** The result of an account write by the chain's own read: applied, refused, or not known yet. */
18
19
  async function outcome(r, shows, waitMs, notShown) {
19
20
  if (!r.proceed) {
@@ -170,6 +171,32 @@ export class Vordium {
170
171
  crossMargin(owner) { return this.get(`/account/cross/${owner}`); }
171
172
  /** The dead-man switch's committed state and limits. */
172
173
  scheduleCancelState(owner) { return this.get(`/schedule-cancel/${owner}`); }
174
+ // ── builder codes and referral levels ───────────────────────────────────────────────────────────────────────────
175
+ /** `GET /builder/approvals/<user>`: the builders `user` approved, the count, the most allowed, its nonce, `active`. */
176
+ async builderApprovals(user) {
177
+ const j = await this.get(`/builder/approvals/${builderAddress(user)}`);
178
+ if (!j || typeof j !== 'object')
179
+ throw new BuilderNotActive('The network does not answer the builder approvals read, so nothing was signed.');
180
+ return j;
181
+ }
182
+ /** `GET /builder/stats/<builder>`: volume, fees (= unclaimed + claimed), users in 30 days, caps, claim nonce, `active`. */
183
+ async builderStats(builder) {
184
+ const j = await this.get(`/builder/stats/${builderAddress(builder)}`);
185
+ if (!j || typeof j !== 'object')
186
+ throw new BuilderNotActive('The network does not answer the builder stats read, so nothing was signed.');
187
+ return j;
188
+ }
189
+ /** `GET /referral/stats/<address>` as the network answers it. */
190
+ referralStats(address) { return this.get(`/referral/stats/${getAddress(address)}`); }
191
+ /** The account's referral level (`L1`, `L2`, `PARTNER`) and its period progress; null where levels are not shown. */
192
+ async referralLevel(address) { return referralLevel(await this.referralStats(address)); }
193
+ /** `GET /referral/tiers`: the levels table, the L2 rule, the partner bounds and the referee caps. */
194
+ referralTiers() { return this.get('/referral/tiers'); }
195
+ /** The network's block time in whole seconds, else this computer's clock. */
196
+ async nowS() {
197
+ const ms = await this.chainTimeMs().catch(() => null);
198
+ return Math.floor((typeof ms === 'number' && ms > 0 ? ms : Date.now()) / 1000);
199
+ }
173
200
  /** The TWAP route and limits from the network spec (refused when not published). */
174
201
  twapRules() { return readTwapRules(this.network.specRead); }
175
202
  /** A trading account: `owner` signs account operations; `sessionSigner` (a session or agent key) signs orders. */
@@ -287,12 +314,26 @@ export class Account {
287
314
  */
288
315
  async placeOrder(o) {
289
316
  const signer = this.orderSigner();
290
- placeOrderValue({ ...o, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
317
+ const { builder: wanted, worstPrice, ...plain } = o;
318
+ if (worstPrice != null && (wanted == null || o.orderType !== 'Market'))
319
+ throw new InvalidRequest('worstPrice applies to a market order that names a builder.');
320
+ placeOrderValue({ ...plain, owner: this.owner, clientNonce: o.clientNonce ?? 1 }); // refusals that need no market rules come first
321
+ const ob = wanted == null ? null : await this.checkedBuilder(wanted); // null or undefined: no builder
291
322
  const spec = await this.pairSpec(o.pairId);
292
323
  const clientNonce = o.clientNonce ?? (await this.fresh('orders'));
293
- const v = placeOrderValue({ ...o, owner: this.owner, clientNonce }, spec);
294
- const sig = await this.sign(signer, 'PlaceOrder', v);
295
- const body = placeOrderBody(v, getAddress(await signer.getAddress()), rs64(sig));
324
+ const v = placeOrderValue({ ...plain, owner: this.owner, clientNonce }, spec);
325
+ let body;
326
+ if (ob) {
327
+ // a buy's cap rounds down onto the price step and a sell's floor up: never worse than the caller gave
328
+ const worst8 = worstPrice == null ? 0n : price8OnTick(worstPrice, spec, o.side, true);
329
+ const v3 = placeOrderV3Value(v, deadline(null, await this.client.nowS()), ob, undefined, worst8);
330
+ body = placeOrderV3Body(v3, await this.sign(signer, 'PlaceOrderV3', v3));
331
+ }
332
+ else {
333
+ const sig = await this.sign(signer, 'PlaceOrder', v);
334
+ body = placeOrderBody(v, getAddress(await signer.getAddress()), rs64(sig));
335
+ }
336
+ const withBuilder = ob ? { builder: ob } : {};
296
337
  const signed = { pairId: v.pairId, side: v.side, size: v.size, price: v.orderType === 1 ? v.price : null };
297
338
  // after the mark was set back to the clock, a nonce may repeat one handed out before: a read-back must be newer
298
339
  const rewound = this.nonce instanceof NonceAllocator ? await this.nonce.rewoundBefore(clientNonce) : null;
@@ -312,18 +353,18 @@ export class Account {
312
353
  const found = ours(await this.orderByClientNonce(clientNonce, signed));
313
354
  if (!found)
314
355
  throw e;
315
- return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found };
356
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: null, clientNonce, attempts: e.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
316
357
  }
317
358
  if (r.needsReadBack) {
318
359
  // the network's nonce code means "used" (perhaps by our earlier copy), "outside the window", or "used by another
319
360
  // signer": it is ours only when the order the network lists carries what was signed
320
361
  const found = ours(await this.orderByClientNonce(clientNonce, signed));
321
362
  if (found)
322
- return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found };
323
- 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 };
363
+ return { submitted: true, status: 0, refusal: null, actions: [], answer: r.body, clientNonce, attempts: r.attempts, alreadyReceived: true, unknown: false, found, ...withBuilder };
364
+ 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 };
324
365
  }
325
366
  const s = readAnswer(r.status === 200 && r.body?.status === 'submitted' ? 202 : r.status, r.body, r.retryAfter, this.client.refusalMeanings());
326
- return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false };
367
+ return { ...s, status: r.status, clientNonce, attempts: r.attempts, alreadyReceived: false, unknown: false, ...withBuilder };
327
368
  }
328
369
  /**
329
370
  * The account's order with `clientNonce` as the network lists it: resting (open orders), else its record; null when
@@ -580,6 +621,83 @@ export class Account {
580
621
  const map = { 1: 'cross', 2: 'isolated', cross: 'cross', isolated: 'isolated' };
581
622
  return map[String(m)] ?? null;
582
623
  }
624
+ // ── builder codes ─────────────────────────────────────────────────────────────────────────────────────────────
625
+ /** An order's builder after the network's reads allow it (rule active, fee within the perps cap, approved, funded). */
626
+ async checkedBuilder(b) {
627
+ const ob = parseBuilder(b);
628
+ let approvals, stats;
629
+ try {
630
+ approvals = await this.client.builderApprovals(this.owner);
631
+ stats = await this.client.builderStats(ob.address);
632
+ }
633
+ catch (e) {
634
+ if (e instanceof BuilderError)
635
+ throw e;
636
+ throw new 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.');
637
+ }
638
+ requireActive(approvals);
639
+ requireActive(stats);
640
+ checkFee(ob.feeCbps, 'perps', capsFrom(stats));
641
+ checkOrderBuilder(this.owner, ob.address, ob.feeCbps, approvals, stats);
642
+ return ob;
643
+ }
644
+ /** The builders this account approved (`approvals`, `count`, `max`, `nonce`, `active`). */
645
+ builderApprovals() { return this.client.builderApprovals(this.owner); }
646
+ /** This account's stats as a builder. */
647
+ builderStats() { return this.client.builderStats(this.owner); }
648
+ /**
649
+ * Let `builder` charge this account up to `maxFeeCbps` per order (500 cbps = 5 bps = 0.05 %); approving a builder
650
+ * again replaces its fee. Signed with the account's own key. Refused before signing when builder fees are not active,
651
+ * the fee is 0 or above the highest cap (`caps_cbps`), the builder is this account, or the account already approved
652
+ * the most builders it may (`max`).
653
+ */
654
+ async approveBuilderFee(builder, maxFeeCbps, waitMs = 30000) {
655
+ const signer = this.needOwner('A builder approval');
656
+ const b = builderAddress(builder);
657
+ const read = await this.client.builderApprovals(this.owner);
658
+ requireActive(read);
659
+ const fee = checkMaxFee(maxFeeCbps, capsFrom(await this.client.builderStats(b)));
660
+ if (b.toLowerCase() === this.owner.toLowerCase())
661
+ throw new BuilderError('builder_self', 'An account cannot be its own builder: name another builder.');
662
+ const max = read.max, count = read.count;
663
+ if (typeof max !== 'number' || typeof count !== 'number')
664
+ throw new BuilderError('unreadable', "The network's approvals read gives no count or maximum, so nothing was signed.");
665
+ if (approvalOf(read, b) === null && count >= max)
666
+ throw new BuilderError('builder_approvals_full', `The account has approved the most builders it may (${max}): revoke one first.`);
667
+ return this.approve(signer, b, fee, read, (r) => approvalOf(r, b) === fee, 'the chain does not show the approval', waitMs);
668
+ }
669
+ /** Withdraw the approval of `builder` (an approval of 0). Orders that name it are refused from then on. */
670
+ async revokeBuilderFee(builder, waitMs = 30000) {
671
+ const signer = this.needOwner('A builder approval');
672
+ const b = builderAddress(builder);
673
+ const read = await this.client.builderApprovals(this.owner);
674
+ requireActive(read);
675
+ if (approvalOf(read, b) === null)
676
+ return { applied: true, status: 0, answer: null, detail: 'no approval to revoke' };
677
+ return this.approve(signer, b, 0, read, (r) => approvalOf(r, b) === null, 'the chain still shows the approval', waitMs);
678
+ }
679
+ async approve(signer, b, fee, read, shows, notShown, waitMs) {
680
+ const nonce = (typeof read.nonce === 'number' ? read.nonce : 0) + 1;
681
+ const v = approveBuilderFeeValue(this.owner, b, fee, nonce, deadline(null, await this.client.nowS()));
682
+ const sig = await this.sign(signer, 'ApproveBuilderFee', v);
683
+ const r = await this.postForResult(BUILDER_ROUTES.approve, JSON.stringify(approveBuilderFeeBody(v, sig)));
684
+ // applied once the account's approval nonce has reached ours and the approval reads as asked
685
+ return outcome(r, async () => { const a = await this.client.builderApprovals(this.owner); return a.nonce >= nonce && shows(a); }, waitMs, notShown);
686
+ }
687
+ /** As a builder: move the unclaimed fees to this account's balance. Refused before signing when there is nothing. */
688
+ async claimBuilderFees(waitMs = 30000) {
689
+ const signer = this.needOwner('A claim of builder fees');
690
+ const st = await this.client.builderStats(this.owner);
691
+ requireActive(st);
692
+ if (!(typeof st.unclaimed_6dec === 'string' && /^\d+$/.test(st.unclaimed_6dec) && BigInt(st.unclaimed_6dec) > 0n)) {
693
+ throw new BuilderError('builder_nothing_to_claim', 'There are no builder fees to claim; nothing was signed.');
694
+ }
695
+ const before = typeof st.claim_nonce === 'number' ? st.claim_nonce : 0;
696
+ const v = claimBuilderFeesValue(this.owner, before + 1, deadline(null, await this.client.nowS()));
697
+ const sig = await this.sign(signer, 'ClaimBuilderFees', v);
698
+ const r = await this.postForResult(BUILDER_ROUTES.claim, JSON.stringify(claimBuilderFeesBody(v, sig)));
699
+ return outcome(r, async () => (await this.client.builderStats(this.owner)).claim_nonce > before, waitMs, 'the chain does not show the claim');
700
+ }
583
701
  /** Cross or isolated for one market — only while it holds no open position and no resting order of the account. */
584
702
  async setMarginMode(pairId, mode, waitMs = 30000) {
585
703
  const signer = this.needOwner('The margin mode');
@@ -760,6 +878,15 @@ export function twapMatches(row, v) {
760
878
  }
761
879
  return true;
762
880
  }
881
+ /** A builder address, or BuilderError('invalid_body') with a plain sentence (never the library's own error). */
882
+ function builderAddress(a) {
883
+ try {
884
+ return getAddress(String(a));
885
+ }
886
+ catch {
887
+ throw new BuilderError('invalid_body', 'The builder must be an address (0x and 40 hex characters).');
888
+ }
889
+ }
763
890
  function unknownResult(attempts, message, answer) {
764
891
  return { submitted: false, status: 0, refusal: { code: 'delivery_unknown', message, detail: '', retryAfter: null }, actions: [], answer, attempts, unknown: true };
765
892
  }
@@ -14,4 +14,5 @@ export * from './account.js';
14
14
  export * from './agents.js';
15
15
  export * from './reads.js';
16
16
  export * from './feeds.js';
17
+ export * from './builder.js';
17
18
  export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome, type Result, type ConnectOptions, type SignedOrder } from './client.js';
package/dist/esm/index.js CHANGED
@@ -14,4 +14,5 @@ export * from './account.js';
14
14
  export * from './agents.js';
15
15
  export * from './reads.js';
16
16
  export * from './feeds.js';
17
+ export * from './builder.js';
17
18
  export { Vordium, Account, twapOnSteps, matchesSigned, twapMatches, cancelOutcome } from './client.js';
@@ -18,6 +18,9 @@ export declare const TYPE_STRINGS: {
18
18
  readonly ModifyOrderV2: "ModifyOrderV2(address owner,uint64 orderId,uint64 newPrice,uint128 newSize,uint64 clientNonce)";
19
19
  readonly SetMmp: "SetMmp(address owner,uint64 windowMs,uint32 maxFills,uint128 maxFilledNotional6dec,uint128 maxNetSize18dec,uint64 freezeMs,uint64 nonce)";
20
20
  readonly ScheduleCancel: "ScheduleCancel(address owner,uint64 cancelAtMs,uint64 nonce)";
21
+ readonly 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)";
22
+ readonly ApproveBuilderFee: "ApproveBuilderFee(address user,address builder,uint32 maxFeeCbps,uint64 nonce,uint64 validUntil)";
23
+ readonly ClaimBuilderFees: "ClaimBuilderFees(address builder,uint64 nonce,uint64 validUntil)";
21
24
  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
25
  readonly CancelTwap: "CancelTwap(address owner,uint64 twapId,uint64 clientNonce)";
23
26
  readonly SetMarginMode: "SetMarginMode(address owner,uint32 pairId,uint8 mode,uint64 nonce)";
package/dist/esm/types.js CHANGED
@@ -9,6 +9,10 @@ export const TYPE_STRINGS = {
9
9
  ModifyOrderV2: 'ModifyOrderV2(address owner,uint64 orderId,uint64 newPrice,uint128 newSize,uint64 clientNonce)',
10
10
  SetMmp: 'SetMmp(address owner,uint64 windowMs,uint32 maxFills,uint128 maxFilledNotional6dec,uint128 maxNetSize18dec,uint64 freezeMs,uint64 nonce)',
11
11
  ScheduleCancel: 'ScheduleCancel(address owner,uint64 cancelAtMs,uint64 nonce)',
12
+ // VordCore — builder codes
13
+ 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)',
14
+ ApproveBuilderFee: 'ApproveBuilderFee(address user,address builder,uint32 maxFeeCbps,uint64 nonce,uint64 validUntil)',
15
+ ClaimBuilderFees: 'ClaimBuilderFees(address builder,uint64 nonce,uint64 validUntil)',
12
16
  // VordCore — account
13
17
  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
18
  CancelTwap: 'CancelTwap(address owner,uint64 twapId,uint64 clientNonce)',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vordium/sdk",
3
- "version": "0.1.3",
3
+ "version": "0.2.0",
4
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
5
  "license": "MIT",
6
6
  "author": "Vordium <dev@vordium.com>",