@vordium/sdk 0.0.0-stage → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +109 -2
- package/dist/cjs/account.js +126 -0
- package/dist/cjs/agents.js +237 -0
- package/dist/cjs/client.js +526 -0
- package/dist/cjs/domains.js +37 -0
- package/dist/cjs/errors.js +39 -0
- package/dist/cjs/feeds.js +278 -0
- package/dist/cjs/http.js +97 -0
- package/dist/cjs/index.js +37 -0
- package/dist/cjs/network.js +114 -0
- package/dist/cjs/nonce.js +36 -0
- package/dist/cjs/orders.js +260 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/reads.js +121 -0
- package/dist/cjs/rounding.js +252 -0
- package/dist/cjs/sign.js +49 -0
- package/dist/cjs/types.js +57 -0
- package/dist/cjs/units.js +78 -0
- package/dist/esm/account.d.ts +61 -0
- package/dist/esm/account.js +114 -0
- package/dist/esm/agents.d.ts +71 -0
- package/dist/esm/agents.js +225 -0
- package/dist/esm/client.d.ts +239 -0
- package/dist/esm/client.js +520 -0
- package/dist/esm/domains.d.ts +21 -0
- package/dist/esm/domains.js +30 -0
- package/dist/esm/errors.d.ts +18 -0
- package/dist/esm/errors.js +32 -0
- package/dist/esm/feeds.d.ts +97 -0
- package/dist/esm/feeds.js +267 -0
- package/dist/esm/http.d.ts +24 -0
- package/dist/esm/http.js +93 -0
- package/dist/esm/index.d.ts +15 -0
- package/dist/esm/index.js +15 -0
- package/dist/esm/network.d.ts +44 -0
- package/dist/esm/network.js +107 -0
- package/dist/esm/nonce.d.ts +15 -0
- package/dist/esm/nonce.js +31 -0
- package/dist/esm/orders.d.ts +141 -0
- package/dist/esm/orders.js +238 -0
- package/dist/esm/reads.d.ts +59 -0
- package/dist/esm/reads.js +113 -0
- package/dist/esm/rounding.d.ts +70 -0
- package/dist/esm/rounding.js +229 -0
- package/dist/esm/sign.d.ts +27 -0
- package/dist/esm/sign.js +43 -0
- package/dist/esm/types.d.ts +41 -0
- package/dist/esm/types.js +51 -0
- package/dist/esm/units.d.ts +16 -0
- package/dist/esm/units.js +70 -0
- package/package.json +53 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Vordium
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,110 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Vordium JavaScript / TypeScript SDK
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Sign and send orders, manage session keys and agents, place TWAP orders, set the margin mode and follow live feeds on
|
|
4
|
+
Vordium Chain and the Vordex perpetuals exchange — from Node.js (20+) or the browser.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm install @vordium/sdk
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
The SDK's one dependency is [ethers](https://docs.ethers.org/v6/). A signer is anything with `getAddress()` and
|
|
11
|
+
`signTypedData()`: an ethers `Wallet`, a browser wallet through ethers, or your own key-management adapter.
|
|
12
|
+
|
|
13
|
+
## Connect
|
|
14
|
+
|
|
15
|
+
```ts
|
|
16
|
+
import { Vordium } from '@vordium/sdk'
|
|
17
|
+
|
|
18
|
+
const v = await Vordium.connect({ network: 'testnet' }) // or 'mainnet'
|
|
19
|
+
```
|
|
20
|
+
|
|
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. Every signature is bound to that genesis (the EIP-712 domain's `salt`), so a
|
|
23
|
+
signature made for one network can never be used on another.
|
|
24
|
+
|
|
25
|
+
## Trade
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
import { Wallet } from 'ethers'
|
|
29
|
+
|
|
30
|
+
const owner = new Wallet(process.env.PRIVATE_KEY!)
|
|
31
|
+
const session = Wallet.createRandom()
|
|
32
|
+
const me = await v.account(owner, { sessionSigner: session })
|
|
33
|
+
|
|
34
|
+
await me.createSession(session.address, Date.now() + 7 * 86400_000) // applied once the chain confirms it
|
|
35
|
+
|
|
36
|
+
const order = await me.placeOrder({ pairId: 1, side: 'buy', size: '0.01', orderType: 'Limit', price: '2400.5' })
|
|
37
|
+
const state = await me.waitForOrder(order.clientNonce) // 'resting' | 'filled' | 'cancelled' | …
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
- Order types are `Market` and `Limit`. A limit price keeps 6 decimals; a market order carries no price. Stop orders are
|
|
41
|
+
not available and are refused before anything is signed.
|
|
42
|
+
- Market makers: `batch()` (place / cancel / cancel by client nonce, with good-till-cancelled, post-only, IOC and FOK),
|
|
43
|
+
`cancelAll()`, `modify()`, and the dead-man switch `scheduleCancel()`.
|
|
44
|
+
- Take-profit and stop-loss on a position: `setTpSl()`.
|
|
45
|
+
- Every nonce comes from one millisecond clock per account, so batches, single orders and the dead-man switch never
|
|
46
|
+
collide.
|
|
47
|
+
|
|
48
|
+
## What "applied" means
|
|
49
|
+
|
|
50
|
+
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 and margin mode — return `{ applied, status, answer, detail }`, and
|
|
52
|
+
`applied` is true only once the chain's own read shows the change. Orders return the submission; read them back with
|
|
53
|
+
`waitForOrder()`, `openOrders()` and `positions()`.
|
|
54
|
+
|
|
55
|
+
## Agents
|
|
56
|
+
|
|
57
|
+
```ts
|
|
58
|
+
await me.registerAgent({ agent: agentAddress, name: 'Night Desk', mandate: 'market making on ETH', expiresMs })
|
|
59
|
+
await me.setAgentPolicy(agentAddress, policy) // refused before signing if the chain would refuse it
|
|
60
|
+
await me.setAgentMarketLimit(agentAddress, { pair: 1, allowed: true, maxOrder18, maxPosition18, maxLeverageBps: 20000 })
|
|
61
|
+
await me.createSession(agentAddress, endMs) // the agent trades with its own key for this account
|
|
62
|
+
|
|
63
|
+
const agent = await v.agentKey(owner.address, agentWallet)
|
|
64
|
+
await agent.placeOrder({ pairId: 1, side: 'buy', size: '0.01', orderType: 'Limit', price: '2390' })
|
|
65
|
+
console.log(await v.agentRefusals(agentAddress)) // what the chain refused, with its reason in plain words
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Agent names follow the chain's rule (`requireName`, `nameRefusalStep`). The agent may sign only a tightening of its own
|
|
69
|
+
policy; every other agent operation is signed by the owner.
|
|
70
|
+
|
|
71
|
+
## TWAP and margin mode
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
const twap = await me.placeTwap({ pairId: 1, side: 'buy', totalSize18, durationMs: 30 * 60_000 }) // owner key only
|
|
75
|
+
await me.cancelTwap(twapId)
|
|
76
|
+
await me.setMarginMode(1, 'isolated') // only while the market has no open position and no resting order
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
TWAP limits are read from the network spec; an order outside them is refused before signing.
|
|
80
|
+
|
|
81
|
+
## Live feeds
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { Feeds } from '@vordium/sdk'
|
|
85
|
+
|
|
86
|
+
const f = new Feeds(v.network.feeds!)
|
|
87
|
+
f.onEvent = (e) => { if (e.kind === 'update') console.log(f.books.get(1)?.bestBid()) }
|
|
88
|
+
await f.open()
|
|
89
|
+
f.subscribe('book', 1) // also: 'trades', and 'orders' / 'fills' for an account
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Each subscription starts with a snapshot. A missed message is detected from the sequence numbers, and the SDK
|
|
93
|
+
subscribes again from a fresh snapshot by itself; a lost connection is reopened with a random back-off.
|
|
94
|
+
|
|
95
|
+
## Units
|
|
96
|
+
|
|
97
|
+
Signed prices are 8-decimal integers and sizes 18-decimal integers (`bigint`). `toUnits`, `fromUnits`, `limitPrice8`
|
|
98
|
+
and `size18` convert exactly and refuse a value they would have to round.
|
|
99
|
+
|
|
100
|
+
Each market has a price step (tick) and a size step (lot), published in `GET /markets/specs`; the chain does not apply
|
|
101
|
+
an order that is off them. Every order the SDK signs (`placeOrder`, `batch`, `modify`, `setTpSl`, `placeTwap`) is put on
|
|
102
|
+
them first: a number is read exactly from its decimal form (a floating-point number is never multiplied), a buy's limit
|
|
103
|
+
price rounds down and a sell's up (never a worse price than asked), a take-profit or stop-loss trigger goes to the
|
|
104
|
+
nearest tick, and a size rounds down onto the lot (never more than asked). A size that rounds to 0, a size below the
|
|
105
|
+
market's smallest size, or a limit order below the network's smallest order value raises `OrderValueError` before
|
|
106
|
+
anything is signed. `price8OnTick`, `size18OnLot` and `pairSpecs` apply the same rules on their own.
|
|
107
|
+
|
|
108
|
+
## Licence
|
|
109
|
+
|
|
110
|
+
MIT
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TWAP_BODY = exports.MODE_CODE = exports.SESSION_MAX_SECONDS = void 0;
|
|
4
|
+
exports.nextNonce = nextNonce;
|
|
5
|
+
exports.sessionEnd = sessionEnd;
|
|
6
|
+
exports.sessionCreateBody = sessionCreateBody;
|
|
7
|
+
exports.sessionRevokeBody = sessionRevokeBody;
|
|
8
|
+
exports.twapBody = twapBody;
|
|
9
|
+
exports.cancelTwapBody = cancelTwapBody;
|
|
10
|
+
exports.marginModeBody = marginModeBody;
|
|
11
|
+
exports.readTwapRules = readTwapRules;
|
|
12
|
+
exports.planTwap = planTwap;
|
|
13
|
+
const errors_js_1 = require("./errors.js");
|
|
14
|
+
const types_js_1 = require("./types.js");
|
|
15
|
+
/**
|
|
16
|
+
* Session keys, TWAP orders and margin mode — signed by the account's own key.
|
|
17
|
+
*
|
|
18
|
+
* Session key: SessionCreate / SessionRevoke in the VordexSession domain. The chain keeps one session per account, so a
|
|
19
|
+
* session it holds for another key is revoked first. Each nonce is larger than the last.
|
|
20
|
+
* TWAP: PlaceTwap / CancelTwap in the VordCore domain, owner key only (a session key is refused). The route and limits
|
|
21
|
+
* come from the network spec's `twap` section.
|
|
22
|
+
* Margin mode: SetMarginMode in the VordCore domain — cross or isolated per market, only while the market has no open
|
|
23
|
+
* position and no resting order of the account.
|
|
24
|
+
*/
|
|
25
|
+
exports.SESSION_MAX_SECONDS = 90 * 86400 - 3600;
|
|
26
|
+
exports.MODE_CODE = { cross: 1, isolated: 2 };
|
|
27
|
+
/** Larger than the last nonce: the time in ms, or the previous nonce + 1. */
|
|
28
|
+
function nextNonce(after = 0, nowMs = Date.now()) {
|
|
29
|
+
return Math.max(Math.floor(nowMs), after + 1);
|
|
30
|
+
}
|
|
31
|
+
/** The session's end in seconds: the asked end, at most 90 days less an hour from now. */
|
|
32
|
+
function sessionEnd(endMs, nowMs = Date.now()) {
|
|
33
|
+
return Math.min(Math.floor(endMs / 1000), Math.floor(nowMs / 1000) + exports.SESSION_MAX_SECONDS);
|
|
34
|
+
}
|
|
35
|
+
function sessionCreateBody(owner, sessionKey, expiresAt, nonce, signature) {
|
|
36
|
+
return JSON.stringify({ owner, session_key: sessionKey, expires_at: expiresAt, nonce, signature });
|
|
37
|
+
}
|
|
38
|
+
function sessionRevokeBody(owner, sessionKey, nonce, signature) {
|
|
39
|
+
return JSON.stringify({ owner, session_key: sessionKey, nonce, signature });
|
|
40
|
+
}
|
|
41
|
+
const digits = (v) => BigInt(v).toString();
|
|
42
|
+
/** snake_case, the chain's field order, every integer as its exact digits. */
|
|
43
|
+
function twapBody(v, signature) {
|
|
44
|
+
const parts = [
|
|
45
|
+
['owner', JSON.stringify(v.owner)], ['pair_id', digits(v.pairId)], ['side', digits(v.side)], ['total_size_18dec', digits(v.totalSize18dec)],
|
|
46
|
+
['num_slices', digits(v.numSlices)], ['duration_ms', digits(v.durationMs)], ['leverage_bps', digits(v.leverageBps)], ['slippage_bps', digits(v.slippageBps)],
|
|
47
|
+
['randomize', v.randomize === true ? 'true' : 'false'], ['trigger_price_8dec', digits(v.triggerPrice8dec)], ['trigger_dir', digits(v.triggerDir)],
|
|
48
|
+
['min_price_8dec', digits(v.minPrice8dec)], ['max_price_8dec', digits(v.maxPrice8dec)], ['client_nonce', digits(v.clientNonce)], ['signature', JSON.stringify(signature)],
|
|
49
|
+
];
|
|
50
|
+
return '{' + parts.map(([k, x]) => `${JSON.stringify(k)}:${x}`).join(',') + '}';
|
|
51
|
+
}
|
|
52
|
+
function cancelTwapBody(owner, twapId, clientNonce, signature) {
|
|
53
|
+
return `{"owner":${JSON.stringify(owner)},"twap_id":${digits(twapId)},"client_nonce":${digits(clientNonce)},"signature":${JSON.stringify(signature)}}`;
|
|
54
|
+
}
|
|
55
|
+
function marginModeBody(owner, pairId, mode, nonce, signature) {
|
|
56
|
+
return `{"owner":"${owner.toLowerCase()}","pair_id":${digits(pairId)},"mode":${digits(mode)},"nonce":${digits(nonce)},"signature":"${signature}"}`;
|
|
57
|
+
}
|
|
58
|
+
exports.TWAP_BODY = ['owner', 'pair_id', 'side', 'total_size_18dec', 'num_slices', 'duration_ms', 'leverage_bps', 'slippage_bps',
|
|
59
|
+
'randomize', 'trigger_price_8dec', 'trigger_dir', 'min_price_8dec', 'max_price_8dec', 'client_nonce', 'signature'];
|
|
60
|
+
const val = (x) => (x && typeof x === 'object' && 'value' in x ? x.value : x);
|
|
61
|
+
const num = (src, k) => {
|
|
62
|
+
const v = src && typeof src === 'object' ? val(src[k]) : undefined;
|
|
63
|
+
if (typeof v === 'number' && Number.isSafeInteger(v))
|
|
64
|
+
return v;
|
|
65
|
+
if (typeof v === 'string' && /^\d+$/.test(v))
|
|
66
|
+
return Number(v);
|
|
67
|
+
return null;
|
|
68
|
+
};
|
|
69
|
+
/**
|
|
70
|
+
* The spec's `twap` section. Refuses (NotAvailable, nothing signed) when it is not published, names another route, signs
|
|
71
|
+
* another type or sends another body than this SDK, or does not publish its limits.
|
|
72
|
+
*/
|
|
73
|
+
function readTwapRules(spec) {
|
|
74
|
+
const t = spec && typeof spec === 'object' ? spec.twap : undefined;
|
|
75
|
+
if (!t || typeof t !== 'object' || t.liveToday === false || t.available === false) {
|
|
76
|
+
const why = t && typeof t.reason === 'string' ? ` (${t.reason})` : '';
|
|
77
|
+
throw new errors_js_1.NotAvailable('The network does not publish TWAP placement' + why + '.');
|
|
78
|
+
}
|
|
79
|
+
const place = t.place;
|
|
80
|
+
const cancel = (t.cancel && typeof t.cancel === 'object' ? t.cancel : {});
|
|
81
|
+
if (!place || typeof place !== 'object')
|
|
82
|
+
throw new errors_js_1.NotAvailable("The network's TWAP section names no placement route.");
|
|
83
|
+
const path = place.path;
|
|
84
|
+
if (place.method !== 'POST' || typeof path !== 'string' || !path.startsWith('/'))
|
|
85
|
+
throw new errors_js_1.NotAvailable('The network publishes a TWAP route this SDK cannot use.');
|
|
86
|
+
if (val(place.typeString) !== types_js_1.TYPE_STRINGS.PlaceTwap)
|
|
87
|
+
throw new errors_js_1.NotAvailable('The network signs PlaceTwap in another format than this SDK; nothing is signed.');
|
|
88
|
+
const body = (Array.isArray(place.body) ? place.body : []).map((b) => (b && typeof b === 'object' ? b.name : b)).filter((b) => b !== 'reduce_only');
|
|
89
|
+
if (JSON.stringify(body) !== JSON.stringify(exports.TWAP_BODY))
|
|
90
|
+
throw new errors_js_1.NotAvailable('The network publishes a TWAP body this SDK does not send; nothing is signed.');
|
|
91
|
+
const ct = val(cancel.typeString);
|
|
92
|
+
if (ct !== undefined && ct !== null && ct !== types_js_1.TYPE_STRINGS.CancelTwap)
|
|
93
|
+
throw new errors_js_1.NotAvailable('The network signs CancelTwap in another format than this SDK; nothing is signed.');
|
|
94
|
+
const lim = place.limits ?? t.limits;
|
|
95
|
+
const d = t.durationMs, so = t.subOrders;
|
|
96
|
+
let v;
|
|
97
|
+
if (lim && typeof lim === 'object') {
|
|
98
|
+
v = [num(lim, 'minDurationMs'), num(lim, 'maxDurationMs'), num(lim, 'minIntervalMs'), num(lim, 'maxNumSlices'), num(lim, 'maxSlippageBps'),
|
|
99
|
+
num(lim, 'minSubOrderNotional6dec') ?? 0, num(lim, 'minTotalNotional6dec')];
|
|
100
|
+
}
|
|
101
|
+
else if (d && typeof d === 'object' && so && typeof so === 'object') {
|
|
102
|
+
v = [num(d, 'min'), num(d, 'max'), num(so, 'minIntervalMs'), num(so, 'maxNumSlices'), num(so, 'maxSlippageBpsPerSubOrder'),
|
|
103
|
+
num(so, 'minSubOrderNotional6dec') ?? 0, num(so, 'minTotalNotional6dec')];
|
|
104
|
+
}
|
|
105
|
+
else
|
|
106
|
+
v = [null];
|
|
107
|
+
if (v.some((x) => x === null) || v[0] > v[1])
|
|
108
|
+
throw new errors_js_1.NotAvailable('The network does not publish its TWAP limits, so an order cannot be checked before signing.');
|
|
109
|
+
const [a, b, c, e, f, g, h] = v;
|
|
110
|
+
return { path, cancelPath: typeof cancel.path === 'string' ? cancel.path : '/twap/cancel', minDurationMs: a, maxDurationMs: b, minIntervalMs: c,
|
|
111
|
+
maxSlices: e, maxSlippageBps: f, minSliceNotional6dec: g, minTotalNotional6dec: h };
|
|
112
|
+
}
|
|
113
|
+
/** [slices, interval ms]: as many slices as the limits allow, the interval being the duration shared out. */
|
|
114
|
+
function planTwap(durationMs, r, totalNotional6dec) {
|
|
115
|
+
if (durationMs < r.minDurationMs || durationMs > r.maxDurationMs)
|
|
116
|
+
throw new errors_js_1.InvalidRequest("The running time is outside the network's TWAP range.");
|
|
117
|
+
let n = Math.min(r.maxSlices, Math.floor(durationMs / Math.max(1, r.minIntervalMs)));
|
|
118
|
+
if (totalNotional6dec !== undefined) {
|
|
119
|
+
if (totalNotional6dec < r.minTotalNotional6dec)
|
|
120
|
+
throw new errors_js_1.InvalidRequest("The order is smaller than the network's smallest TWAP.");
|
|
121
|
+
n = Math.min(n, Math.floor(totalNotional6dec / Math.max(1, r.minSliceNotional6dec)));
|
|
122
|
+
}
|
|
123
|
+
if (n < 1)
|
|
124
|
+
throw new errors_js_1.InvalidRequest("No plan fits the network's TWAP limits.");
|
|
125
|
+
return [n, Math.floor(durationMs / n)];
|
|
126
|
+
}
|
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.LOWERCASE_ADDRESS_OPS = exports.SUBMIT_FIELDS = exports.DAY_MS = exports.MAX_LEVERAGE_BPS = exports.ORACLE_BAND_MAX_BPS = exports.ORACLE_BAND_MIN_BPS = exports.CAPS_ALL = exports.CAPABILITY_BITS = exports.RESERVED_WORDS_DEFAULT = exports.NAME_MAX_BYTES = exports.NAME_MIN_BYTES = void 0;
|
|
4
|
+
exports.normalizeName = normalizeName;
|
|
5
|
+
exports.nameSkeleton = nameSkeleton;
|
|
6
|
+
exports.nameRefusalStep = nameRefusalStep;
|
|
7
|
+
exports.requireName = requireName;
|
|
8
|
+
exports.policyProblems = policyProblems;
|
|
9
|
+
exports.loosens = loosens;
|
|
10
|
+
exports.submitBody = submitBody;
|
|
11
|
+
exports.policyValue = policyValue;
|
|
12
|
+
exports.policyFromRead = policyFromRead;
|
|
13
|
+
const errors_js_1 = require("./errors.js");
|
|
14
|
+
/**
|
|
15
|
+
* Agents: a key that trades for an account within the limits its owner signs. The operations in force:
|
|
16
|
+
* RegisterAgentV2 (a name is required), SetAgentName, SetAgentPolicyV1, SetAgentMarketLimit, ClearAgentLock and
|
|
17
|
+
* RevokeAgent. Each is signed by the OWNER in the VordCore domain and sent to `POST /submit`; only SetAgentPolicyV1 may
|
|
18
|
+
* also be signed by the agent itself, and then only to tighten the stored policy.
|
|
19
|
+
*/
|
|
20
|
+
// ── Names ───────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
21
|
+
exports.NAME_MIN_BYTES = 3;
|
|
22
|
+
exports.NAME_MAX_BYTES = 32;
|
|
23
|
+
exports.RESERVED_WORDS_DEFAULT = ['admin', 'helpdesk', 'moderator', 'official', 'support', 'validator', 'vordex', 'vordium', 'vordscan'];
|
|
24
|
+
/** What is signed: NFKC, every run of ASCII whitespace becomes one space, no space at either end. */
|
|
25
|
+
function normalizeName(raw) {
|
|
26
|
+
let s = raw.normalize('NFKC').replace(/[ \t\n\r\f\v]+/g, ' ');
|
|
27
|
+
if (s.startsWith(' '))
|
|
28
|
+
s = s.slice(1);
|
|
29
|
+
if (s.endsWith(' '))
|
|
30
|
+
s = s.slice(0, -1);
|
|
31
|
+
return s;
|
|
32
|
+
}
|
|
33
|
+
/** ASCII letters lower-cased, with `space - _ .` removed: what reserved words are matched in (as the node builds it). */
|
|
34
|
+
function nameSkeleton(name) {
|
|
35
|
+
return name.replace(/[A-Z]/g, (c) => c.toLowerCase()).replace(/[ \-_.]/g, '');
|
|
36
|
+
}
|
|
37
|
+
function judge(name, reserved) {
|
|
38
|
+
if (!name)
|
|
39
|
+
return ['TooShort', 'Enter a name.'];
|
|
40
|
+
if ([...name].some((c) => c.codePointAt(0) > 0x7f))
|
|
41
|
+
return ['NonAscii', 'Use plain letters and digits: no accents, emoji or other symbols.'];
|
|
42
|
+
if (/[\x00-\x1f\x7f]/.test(name))
|
|
43
|
+
return ['ControlChar', 'No tabs, line breaks or other control characters.'];
|
|
44
|
+
if (!/^[A-Za-z0-9 \-_.]+$/.test(name))
|
|
45
|
+
return ['BadChar', 'Use only letters, digits, spaces, hyphens (-), underscores (_) and dots (.).'];
|
|
46
|
+
if (name.length < exports.NAME_MIN_BYTES)
|
|
47
|
+
return ['TooShort', `Use at least ${exports.NAME_MIN_BYTES} characters.`];
|
|
48
|
+
if (name.length > exports.NAME_MAX_BYTES)
|
|
49
|
+
return ['TooLong', `Use at most ${exports.NAME_MAX_BYTES} characters.`];
|
|
50
|
+
if (name.startsWith(' ') || name.endsWith(' ') || name.includes(' '))
|
|
51
|
+
return ['NotCanonical', 'No space at the start or end, and no double spaces.'];
|
|
52
|
+
if (!/[A-Za-z0-9]/.test(name))
|
|
53
|
+
return ['NoAlphanumeric', 'Include at least one letter or digit.'];
|
|
54
|
+
const sk = nameSkeleton(name);
|
|
55
|
+
for (const w of reserved)
|
|
56
|
+
if (sk.includes(w))
|
|
57
|
+
return ['Reserved', `A name can't contain the reserved word "${w}".`];
|
|
58
|
+
return null;
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The chain's form rule for an ALREADY-normalised name, in the chain's own step order: `null` when accepted, else the
|
|
62
|
+
* refusing step. Uniqueness among the owner's agents, the rename wait and the live-agent limit are the chain's to judge.
|
|
63
|
+
*/
|
|
64
|
+
function nameRefusalStep(name, reserved = exports.RESERVED_WORDS_DEFAULT) {
|
|
65
|
+
return judge(name, reserved)?.[0] ?? null;
|
|
66
|
+
}
|
|
67
|
+
/** Normalise then check: the name to sign, or InvalidRequest with the reason. */
|
|
68
|
+
function requireName(raw, reserved = exports.RESERVED_WORDS_DEFAULT) {
|
|
69
|
+
const n = normalizeName(raw);
|
|
70
|
+
const j = judge(n, reserved);
|
|
71
|
+
if (j)
|
|
72
|
+
throw new errors_js_1.InvalidRequest(j[1]);
|
|
73
|
+
return n;
|
|
74
|
+
}
|
|
75
|
+
// ── Policy ──────────────────────────────────────────────────────────────────────────────────────────────────────────
|
|
76
|
+
exports.CAPABILITY_BITS = { place: 0, cancel: 1, modify: 2, tpsl: 3, close: 4, vault: 5 };
|
|
77
|
+
exports.CAPS_ALL = 0b111111;
|
|
78
|
+
exports.ORACLE_BAND_MIN_BPS = 1;
|
|
79
|
+
exports.ORACLE_BAND_MAX_BPS = 1000;
|
|
80
|
+
exports.MAX_LEVERAGE_BPS = 500_000;
|
|
81
|
+
exports.DAY_MS = 86_400_000;
|
|
82
|
+
const isU = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
|
|
83
|
+
const fmt = (n) => (Number.isInteger(n) ? String(n) : String(n));
|
|
84
|
+
/** Why the chain would refuse this policy at apply (it refuses silently); [] = none of the stateless reasons. */
|
|
85
|
+
function policyProblems(p, nowMs) {
|
|
86
|
+
const out = [];
|
|
87
|
+
if (!isU(p.capsBitmask) || (p.capsBitmask & ~exports.CAPS_ALL) !== 0)
|
|
88
|
+
out.push('Choose capabilities from the list only.');
|
|
89
|
+
if (p.sideMode !== 0 && p.sideMode !== 1)
|
|
90
|
+
out.push('Choose whether the agent may open positions or only reduce them.');
|
|
91
|
+
if (typeof p.maxTotalExposure6dec !== 'bigint' || p.maxTotalExposure6dec <= 0n)
|
|
92
|
+
out.push('Set a total exposure above zero.');
|
|
93
|
+
if (typeof p.dailyLossLimit6dec !== 'bigint' || p.dailyLossLimit6dec <= 0n)
|
|
94
|
+
out.push('Set a daily loss limit above zero.');
|
|
95
|
+
if (typeof p.dailyFeeCap6dec !== 'bigint' || p.dailyFeeCap6dec < 0n)
|
|
96
|
+
out.push('The daily fee cap cannot be negative.');
|
|
97
|
+
if (!isU(p.maxLeverageBps) || p.maxLeverageBps > exports.MAX_LEVERAGE_BPS)
|
|
98
|
+
out.push(`Leverage can be at most ${fmt(exports.MAX_LEVERAGE_BPS / 10000)}x (or 0 for no limit).`);
|
|
99
|
+
if (!isU(p.oracleBandBps) || p.oracleBandBps < exports.ORACLE_BAND_MIN_BPS || p.oracleBandBps > exports.ORACLE_BAND_MAX_BPS) {
|
|
100
|
+
out.push(`The oracle band must be between ${fmt(exports.ORACLE_BAND_MIN_BPS / 100)}% and ${fmt(exports.ORACLE_BAND_MAX_BPS / 100)}%.`);
|
|
101
|
+
}
|
|
102
|
+
const bothZero = p.opsPerWindow === 0 && p.opsWindowMs === 0;
|
|
103
|
+
if (!isU(p.opsPerWindow) || !isU(p.opsWindowMs) || !(bothZero || (p.opsPerWindow > 0 && p.opsWindowMs > 0 && p.opsWindowMs <= exports.DAY_MS))) {
|
|
104
|
+
out.push('Set both the operations per window and a window of at most a day, or leave both at zero for no limit.');
|
|
105
|
+
}
|
|
106
|
+
if (!isU(p.activeFromMsOfDay) || !isU(p.activeToMsOfDay) || p.activeFromMsOfDay >= exports.DAY_MS || p.activeToMsOfDay >= exports.DAY_MS
|
|
107
|
+
|| (p.activeFromMsOfDay === p.activeToMsOfDay && p.activeFromMsOfDay !== 0)) {
|
|
108
|
+
out.push('Set active hours that start and end at different times within the day, or leave both at midnight for always.');
|
|
109
|
+
}
|
|
110
|
+
if (!isU(p.expiresMs) || p.expiresMs <= nowMs)
|
|
111
|
+
out.push('Set an expiry in the future.');
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
/** What in `next` would LOOSEN `prev`; [] = a tightening or no change (and always [] with nothing stored). */
|
|
115
|
+
function loosens(prev, next) {
|
|
116
|
+
if (!prev)
|
|
117
|
+
return [];
|
|
118
|
+
const out = [];
|
|
119
|
+
const higherOrUnlimited = (a, b) => (b === 0n ? a !== 0n : a !== 0n && b > a);
|
|
120
|
+
if ((next.capsBitmask & ~prev.capsBitmask) !== 0)
|
|
121
|
+
out.push('adds a capability');
|
|
122
|
+
if (next.sideMode < prev.sideMode)
|
|
123
|
+
out.push('lets the agent open positions');
|
|
124
|
+
if (next.maxTotalExposure6dec > prev.maxTotalExposure6dec)
|
|
125
|
+
out.push('raises the total exposure');
|
|
126
|
+
if (higherOrUnlimited(BigInt(prev.maxLeverageBps), BigInt(next.maxLeverageBps)))
|
|
127
|
+
out.push('raises the leverage');
|
|
128
|
+
if (next.dailyLossLimit6dec > prev.dailyLossLimit6dec)
|
|
129
|
+
out.push('raises the daily loss limit');
|
|
130
|
+
if (higherOrUnlimited(prev.dailyFeeCap6dec, next.dailyFeeCap6dec))
|
|
131
|
+
out.push('raises the daily fee cap');
|
|
132
|
+
if (next.expiresMs > prev.expiresMs)
|
|
133
|
+
out.push('extends the expiry');
|
|
134
|
+
if (next.oracleBandBps > prev.oracleBandBps)
|
|
135
|
+
out.push('widens the oracle band');
|
|
136
|
+
if (next.lockAutoClear && !prev.lockAutoClear)
|
|
137
|
+
out.push('turns on automatic lock clearing');
|
|
138
|
+
if (next.enabled && !prev.enabled)
|
|
139
|
+
out.push('turns the policy on');
|
|
140
|
+
if (next.opsPerWindow !== prev.opsPerWindow || next.opsWindowMs !== prev.opsWindowMs)
|
|
141
|
+
out.push('changes the operations limit');
|
|
142
|
+
if (next.activeFromMsOfDay !== prev.activeFromMsOfDay || next.activeToMsOfDay !== prev.activeToMsOfDay)
|
|
143
|
+
out.push('changes the active hours');
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
/** Per operation: [struct name, wire name, kind], in the order the node reads them. */
|
|
147
|
+
exports.SUBMIT_FIELDS = {
|
|
148
|
+
RegisterAgentV2: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['name', 'name', 'string'], ['mandate', 'mandate', 'string'], ['expiresMs', 'expires_ms', 'u64'], ['nonce', 'nonce', 'u64']],
|
|
149
|
+
SetAgentName: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['name', 'name', 'string'], ['nonce', 'nonce', 'u64']],
|
|
150
|
+
SetAgentPolicyV1: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['capsBitmask', 'caps_bitmask', 'u32'], ['sideMode', 'side_mode', 'u8'],
|
|
151
|
+
['maxTotalExposure6dec', 'max_total_exposure_6dec', 'u128'], ['maxLeverageBps', 'max_leverage_bps', 'u32'], ['dailyLossLimit6dec', 'daily_loss_limit_6dec', 'u128'],
|
|
152
|
+
['dailyFeeCap6dec', 'daily_fee_cap_6dec', 'u128'], ['opsPerWindow', 'ops_per_window', 'u32'], ['opsWindowMs', 'ops_window_ms', 'u32'],
|
|
153
|
+
['activeFromMsOfDay', 'active_from_ms_of_day', 'u32'], ['activeToMsOfDay', 'active_to_ms_of_day', 'u32'], ['oracleBandBps', 'oracle_band_bps', 'u32'],
|
|
154
|
+
['lockAutoClear', 'lock_auto_clear', 'bool'], ['expiresMs', 'expires_ms', 'u64'], ['enabled', 'enabled', 'bool'], ['nonce', 'nonce', 'u64']],
|
|
155
|
+
SetAgentMarketLimit: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['pair', 'pair', 'u32'], ['allowed', 'allowed', 'bool'],
|
|
156
|
+
['maxOrder18dec', 'max_order_18dec', 'u128'], ['maxPosition18dec', 'max_position_18dec', 'u128'], ['maxLeverageBps', 'max_leverage_bps', 'u32'], ['nonce', 'nonce', 'u64']],
|
|
157
|
+
ClearAgentLock: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['lockSinceMs', 'lock_since_ms', 'u64'], ['nonce', 'nonce', 'u64']],
|
|
158
|
+
RevokeAgent: [['owner', 'owner', 'address'], ['agent', 'agent', 'address'], ['nonce', 'nonce', 'u64']],
|
|
159
|
+
};
|
|
160
|
+
/** These operations carry their addresses in lower case on the wire; the others as given. */
|
|
161
|
+
exports.LOWERCASE_ADDRESS_OPS = new Set(['RegisterAgentV2', 'SetAgentName', 'SetAgentPolicyV1', 'ClearAgentLock']);
|
|
162
|
+
function encode(op, kind, wire, v) {
|
|
163
|
+
if (kind === 'address') {
|
|
164
|
+
if (typeof v !== 'string' || !/^0x[0-9a-fA-F]{40}$/.test(v))
|
|
165
|
+
throw new errors_js_1.InvalidRequest(`${wire} is not an address.`);
|
|
166
|
+
return exports.LOWERCASE_ADDRESS_OPS.has(op) ? v.toLowerCase() : v;
|
|
167
|
+
}
|
|
168
|
+
if (kind === 'string') {
|
|
169
|
+
if (typeof v !== 'string')
|
|
170
|
+
throw new errors_js_1.InvalidRequest(`${wire} is not text.`);
|
|
171
|
+
return v;
|
|
172
|
+
}
|
|
173
|
+
if (kind === 'bool') {
|
|
174
|
+
if (typeof v !== 'boolean')
|
|
175
|
+
throw new errors_js_1.InvalidRequest(`${wire} is not true or false.`);
|
|
176
|
+
return v;
|
|
177
|
+
}
|
|
178
|
+
let b;
|
|
179
|
+
if (typeof v === 'bigint')
|
|
180
|
+
b = v;
|
|
181
|
+
else if (typeof v === 'number' && Number.isSafeInteger(v))
|
|
182
|
+
b = BigInt(v);
|
|
183
|
+
else if (typeof v === 'string' && /^\d+$/.test(v))
|
|
184
|
+
b = BigInt(v);
|
|
185
|
+
else
|
|
186
|
+
throw new errors_js_1.InvalidRequest(`${wire} is not a whole number.`);
|
|
187
|
+
if (b < 0n)
|
|
188
|
+
throw new errors_js_1.InvalidRequest(`${wire} is not a whole number.`);
|
|
189
|
+
if (kind === 'u128')
|
|
190
|
+
return b.toString();
|
|
191
|
+
if (b > BigInt(Number.MAX_SAFE_INTEGER))
|
|
192
|
+
throw new errors_js_1.InvalidRequest(`${wire} is past the exact-integer range.`);
|
|
193
|
+
return Number(b);
|
|
194
|
+
}
|
|
195
|
+
/** The exact `POST /submit` body for one signed agent operation (every field, in wire order). */
|
|
196
|
+
function submitBody(op, value, signature) {
|
|
197
|
+
const fields = exports.SUBMIT_FIELDS[op];
|
|
198
|
+
if (!fields)
|
|
199
|
+
throw new errors_js_1.InvalidRequest(`${String(op)} is not an agent operation in force.`);
|
|
200
|
+
const s = signature.toLowerCase();
|
|
201
|
+
if (!/^0x[0-9a-f]{130}$/.test(s))
|
|
202
|
+
throw new errors_js_1.InvalidRequest('The signature is not 65 bytes of hex.');
|
|
203
|
+
const body = { op };
|
|
204
|
+
for (const [struct, wire, kind] of fields) {
|
|
205
|
+
if (!(struct in value))
|
|
206
|
+
throw new errors_js_1.InvalidRequest(`${struct} is missing from the signed operation.`);
|
|
207
|
+
body[wire] = encode(op, kind, wire, value[struct]);
|
|
208
|
+
}
|
|
209
|
+
body.signature = s;
|
|
210
|
+
return body;
|
|
211
|
+
}
|
|
212
|
+
function policyValue(owner, agent, p, nonce) {
|
|
213
|
+
return {
|
|
214
|
+
owner, agent, capsBitmask: p.capsBitmask, sideMode: p.sideMode, maxTotalExposure6dec: p.maxTotalExposure6dec, maxLeverageBps: p.maxLeverageBps,
|
|
215
|
+
dailyLossLimit6dec: p.dailyLossLimit6dec, dailyFeeCap6dec: p.dailyFeeCap6dec, opsPerWindow: p.opsPerWindow, opsWindowMs: p.opsWindowMs,
|
|
216
|
+
activeFromMsOfDay: p.activeFromMsOfDay, activeToMsOfDay: p.activeToMsOfDay, oracleBandBps: p.oracleBandBps, lockAutoClear: p.lockAutoClear,
|
|
217
|
+
expiresMs: p.expiresMs, enabled: p.enabled, nonce,
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
/** The stored policy from `GET /agents/{owner}/{agent}` (`policy_v1`, the node's snake_case names), or null. */
|
|
221
|
+
function policyFromRead(x) {
|
|
222
|
+
if (!x || typeof x !== 'object')
|
|
223
|
+
return null;
|
|
224
|
+
const o = x;
|
|
225
|
+
const n = (k) => (typeof o[k] === 'number' && Number.isSafeInteger(o[k]) && o[k] >= 0 ? o[k]
|
|
226
|
+
: typeof o[k] === 'string' && /^\d+$/.test(o[k]) && Number.isSafeInteger(Number(o[k])) ? Number(o[k]) : null);
|
|
227
|
+
const b = (k) => (typeof o[k] === 'number' && Number.isSafeInteger(o[k]) && o[k] >= 0 ? BigInt(o[k])
|
|
228
|
+
: typeof o[k] === 'string' && /^\d+$/.test(o[k]) ? BigInt(o[k]) : null);
|
|
229
|
+
const t = (k) => (typeof o[k] === 'boolean' ? o[k] : null);
|
|
230
|
+
const p = {
|
|
231
|
+
capsBitmask: n('caps_bitmask'), sideMode: n('side_mode'), maxTotalExposure6dec: b('max_total_exposure_6dec'), maxLeverageBps: n('max_leverage_bps'),
|
|
232
|
+
dailyLossLimit6dec: b('daily_loss_limit_6dec'), dailyFeeCap6dec: b('daily_fee_cap_6dec'), opsPerWindow: n('ops_per_window'), opsWindowMs: n('ops_window_ms'),
|
|
233
|
+
activeFromMsOfDay: n('active_from_ms_of_day'), activeToMsOfDay: n('active_to_ms_of_day'), oracleBandBps: n('oracle_band_bps'),
|
|
234
|
+
lockAutoClear: t('lock_auto_clear'), expiresMs: n('expires_ms'), enabled: t('enabled'),
|
|
235
|
+
};
|
|
236
|
+
return Object.values(p).some((v) => v === null) ? null : p;
|
|
237
|
+
}
|