@vordium/sdk 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +55 -3
- package/dist/cjs/builder.js +256 -0
- package/dist/cjs/client.js +452 -62
- package/dist/cjs/index.js +7 -1
- package/dist/cjs/network.js +53 -1
- package/dist/cjs/nonce.js +419 -1
- package/dist/cjs/orders.js +3 -0
- package/dist/cjs/pins.js +60 -0
- package/dist/cjs/resend.js +188 -0
- package/dist/cjs/types.js +4 -0
- package/dist/esm/builder.d.ts +158 -0
- package/dist/esm/builder.js +235 -0
- package/dist/esm/client.d.ts +119 -9
- package/dist/esm/client.js +453 -66
- package/dist/esm/index.d.ts +4 -1
- package/dist/esm/index.js +4 -1
- package/dist/esm/network.d.ts +23 -4
- package/dist/esm/network.js +51 -1
- package/dist/esm/nonce.d.ts +109 -0
- package/dist/esm/nonce.js +410 -0
- package/dist/esm/orders.js +3 -0
- package/dist/esm/pins.d.ts +29 -0
- package/dist/esm/pins.js +51 -0
- package/dist/esm/resend.d.ts +74 -0
- package/dist/esm/resend.js +180 -0
- package/dist/esm/types.d.ts +3 -0
- package/dist/esm/types.js +4 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -19,8 +19,21 @@ const v = await Vordium.connect({ network: 'testnet' }) // or 'mainnet'
|
|
|
19
19
|
```
|
|
20
20
|
|
|
21
21
|
`connect` reads the network spec, the node's `/status` and the JSON-RPC `eth_chainId`, and refuses unless all three name
|
|
22
|
-
the same chain and the same genesis.
|
|
23
|
-
signature made
|
|
22
|
+
the same chain and the same genesis. Each named network is pinned in the SDK (`PINS`: mainnet chain 101101, testnet chain
|
|
23
|
+
101102, each with its genesis sha256), and every signature is made under the pin: the EIP-712 domain's chain id and
|
|
24
|
+
`salt` come from it. When what the network reports differs from its pin, reads still work, `network.pinProblem` says
|
|
25
|
+
why (and `onPinProblem`, when given, is called), and every signature is refused with `PinMismatch`, naming the network,
|
|
26
|
+
the expected and the reported values. A new genesis for a named network needs a new SDK release.
|
|
27
|
+
|
|
28
|
+
An address of your own must say which network it serves, or carry a pin; without one it can be read, but nothing is
|
|
29
|
+
signed for it (`UnpinnedNetwork`):
|
|
30
|
+
|
|
31
|
+
```ts
|
|
32
|
+
const mine = await Vordium.connect({ network: { ...NETWORKS.mainnet, spec: 'https://node.example/network-spec.json',
|
|
33
|
+
rpc: 'https://node.example', api: 'https://node.example' } }) // held to the mainnet pin
|
|
34
|
+
const dev = await Vordium.connect({ network: { name: 'devnet', spec: '…', rpc: '…', api: '…',
|
|
35
|
+
pin: { chainId: 777001, genesis: '<64 hex>' } } }) // a network of your own
|
|
36
|
+
```
|
|
24
37
|
|
|
25
38
|
## Trade
|
|
26
39
|
|
|
@@ -45,10 +58,49 @@ const state = await me.waitForOrder(order.clientNonce) // 'rest
|
|
|
45
58
|
- Every nonce comes from one millisecond clock per account, so batches, single orders and the dead-man switch never
|
|
46
59
|
collide.
|
|
47
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
|
+
|
|
48
100
|
## What "applied" means
|
|
49
101
|
|
|
50
102
|
A write is answered when the network accepts it for a coming block (HTTP 202). That is a submission, not a result. The
|
|
51
|
-
account operations — session keys, agents, TWAP
|
|
103
|
+
account operations — session keys, agents, TWAP, margin mode and builder approvals and claims — return `{ applied, status, answer, detail }`, and
|
|
52
104
|
`applied` is true only once the chain's own read shows the change. Orders return the submission; read them back with
|
|
53
105
|
`waitForOrder()`, `openOrders()` and `positions()`.
|
|
54
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
|
+
}
|