@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/dist/cjs/sign.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.keySigner = keySigner;
|
|
4
|
+
exports.digest = digest;
|
|
5
|
+
exports.signOp = signOp;
|
|
6
|
+
exports.rs64 = rs64;
|
|
7
|
+
const ethers_1 = require("ethers");
|
|
8
|
+
const errors_js_1 = require("./errors.js");
|
|
9
|
+
const types_js_1 = require("./types.js");
|
|
10
|
+
/**
|
|
11
|
+
* A signer from a private key (an ethers `Wallet`). A key that is not 32 bytes of hex is refused with a message that
|
|
12
|
+
* never carries the value (the library's own error would print it).
|
|
13
|
+
*/
|
|
14
|
+
function keySigner(privateKey) {
|
|
15
|
+
const k = typeof privateKey === 'string' ? privateKey.trim() : '';
|
|
16
|
+
if (!/^(0x)?[0-9a-fA-F]{64}$/.test(k)) {
|
|
17
|
+
throw new errors_js_1.InvalidRequest('A private key must be 32 bytes written as 64 hex characters (the value is not shown).');
|
|
18
|
+
}
|
|
19
|
+
try {
|
|
20
|
+
return new ethers_1.Wallet(k.startsWith('0x') ? k : '0x' + k);
|
|
21
|
+
}
|
|
22
|
+
catch {
|
|
23
|
+
throw new errors_js_1.InvalidRequest('The private key is not a valid key (the value is not shown).');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** The 32-byte digest the chain verifies: keccak256(0x1901 ‖ domainSeparator ‖ hashStruct(value)). */
|
|
27
|
+
function digest(dom, primary, value) {
|
|
28
|
+
return ethers_1.TypedDataEncoder.hash(dom, (0, types_js_1.typesFor)(primary), value);
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Sign one operation. Returns the 65-byte `r‖s‖v` signature as lower-case 0x-hex (v = 27 or 28), and checks that it
|
|
32
|
+
* recovers the signer's address before it is used.
|
|
33
|
+
*/
|
|
34
|
+
async function signOp(signer, dom, primary, value) {
|
|
35
|
+
const types = (0, types_js_1.typesFor)(primary);
|
|
36
|
+
const raw = await signer.signTypedData(dom, types, value);
|
|
37
|
+
const sig = ethers_1.Signature.from(raw);
|
|
38
|
+
const by = ethers_1.TypedDataEncoder.hash(dom, types, value);
|
|
39
|
+
if ((0, ethers_1.getAddress)((0, ethers_1.recoverAddress)(by, sig)) !== (0, ethers_1.getAddress)(await signer.getAddress())) {
|
|
40
|
+
throw new errors_js_1.InvalidRequest('The signature does not recover to the signer: the wallet signed something else.');
|
|
41
|
+
}
|
|
42
|
+
return sig.serialized.toLowerCase();
|
|
43
|
+
}
|
|
44
|
+
/** The first 64 bytes (`r‖s`) of a 65-byte signature: the form the single-order intake reads. */
|
|
45
|
+
function rs64(sig65) {
|
|
46
|
+
if (!/^0x[0-9a-f]{130}$/.test(sig65))
|
|
47
|
+
throw new errors_js_1.InvalidRequest('A signature is 65 bytes of lower-case hex.');
|
|
48
|
+
return sig65.slice(0, 130);
|
|
49
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TYPE_STRINGS = void 0;
|
|
4
|
+
exports.parseTypeString = parseTypeString;
|
|
5
|
+
exports.typesFor = typesFor;
|
|
6
|
+
exports.domainOf = domainOf;
|
|
7
|
+
exports.TYPE_STRINGS = {
|
|
8
|
+
// VordCore — orders
|
|
9
|
+
PlaceOrder: 'PlaceOrder(address owner,uint32 pairId,uint8 side,uint128 size,uint64 price,uint32 leverageBps,uint8 orderType,bool reduceOnly,bool postOnly,uint64 triggerPrice8dec,uint8 triggerDir,uint64 clientNonce)',
|
|
10
|
+
CancelOrder: 'CancelOrder(address owner,uint64 orderId)',
|
|
11
|
+
SetTpSl: 'SetTpSl(address owner,uint32 pairId,uint64 positionId,uint64 takeProfit8dec,uint64 stopLoss8dec)',
|
|
12
|
+
BatchAction: 'BatchAction(uint8 kind,uint32 pairId,uint8 side,uint128 size,uint64 price,uint32 leverageBps,uint8 orderType,bool reduceOnly,bool postOnly,uint64 clientNonce,uint64 orderId)',
|
|
13
|
+
BatchOrders: 'BatchOrders(address owner,uint64 nonce,BatchAction[] actions)',
|
|
14
|
+
CancelAllOrders: 'CancelAllOrders(address owner,uint32 pairId,uint64 nonce)',
|
|
15
|
+
ModifyOrderV2: 'ModifyOrderV2(address owner,uint64 orderId,uint64 newPrice,uint128 newSize,uint64 clientNonce)',
|
|
16
|
+
SetMmp: 'SetMmp(address owner,uint64 windowMs,uint32 maxFills,uint128 maxFilledNotional6dec,uint128 maxNetSize18dec,uint64 freezeMs,uint64 nonce)',
|
|
17
|
+
ScheduleCancel: 'ScheduleCancel(address owner,uint64 cancelAtMs,uint64 nonce)',
|
|
18
|
+
// VordCore — account
|
|
19
|
+
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
|
+
CancelTwap: 'CancelTwap(address owner,uint64 twapId,uint64 clientNonce)',
|
|
21
|
+
SetMarginMode: 'SetMarginMode(address owner,uint32 pairId,uint8 mode,uint64 nonce)',
|
|
22
|
+
// VordCore — agents (the operations in force)
|
|
23
|
+
RegisterAgentV2: 'RegisterAgentV2(address owner,address agent,string name,string mandate,uint64 expiresMs,uint64 nonce)',
|
|
24
|
+
SetAgentName: 'SetAgentName(address owner,address agent,string name,uint64 nonce)',
|
|
25
|
+
SetAgentPolicyV1: 'SetAgentPolicyV1(address owner,address agent,uint32 capsBitmask,uint8 sideMode,uint128 maxTotalExposure6dec,uint32 maxLeverageBps,uint128 dailyLossLimit6dec,uint128 dailyFeeCap6dec,uint32 opsPerWindow,uint32 opsWindowMs,uint32 activeFromMsOfDay,uint32 activeToMsOfDay,uint32 oracleBandBps,bool lockAutoClear,uint64 expiresMs,bool enabled,uint64 nonce)',
|
|
26
|
+
SetAgentMarketLimit: 'SetAgentMarketLimit(address owner,address agent,uint32 pair,bool allowed,uint128 maxOrder18dec,uint128 maxPosition18dec,uint32 maxLeverageBps,uint64 nonce)',
|
|
27
|
+
ClearAgentLock: 'ClearAgentLock(address owner,address agent,uint64 lockSinceMs,uint64 nonce)',
|
|
28
|
+
RevokeAgent: 'RevokeAgent(address owner,address agent,uint64 nonce)',
|
|
29
|
+
// VordexSession
|
|
30
|
+
SessionCreate: 'SessionCreate(address sessionKey,uint256 expiresAt,uint256 nonce)',
|
|
31
|
+
SessionRevoke: 'SessionRevoke(address owner,uint256 nonce)',
|
|
32
|
+
};
|
|
33
|
+
function parseTypeString(s) {
|
|
34
|
+
const m = /^([A-Za-z0-9]+)\(([^()]*)\)$/.exec(s);
|
|
35
|
+
if (!m)
|
|
36
|
+
throw new Error(`not a type string: ${s}`);
|
|
37
|
+
const fields = m[2] === '' ? [] : m[2].split(',').map((f) => {
|
|
38
|
+
const [type, name] = f.split(' ');
|
|
39
|
+
return { name, type };
|
|
40
|
+
});
|
|
41
|
+
return { name: m[1], fields };
|
|
42
|
+
}
|
|
43
|
+
/** The `types` object for one primary type (with the structs it references). */
|
|
44
|
+
function typesFor(primary) {
|
|
45
|
+
const own = parseTypeString(exports.TYPE_STRINGS[primary]);
|
|
46
|
+
const out = { [own.name]: own.fields };
|
|
47
|
+
for (const f of own.fields) {
|
|
48
|
+
const base = f.type.replace(/\[\]$/, '');
|
|
49
|
+
if (base in exports.TYPE_STRINGS)
|
|
50
|
+
out[base] = parseTypeString(exports.TYPE_STRINGS[base]).fields;
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
/** Which domain each operation is signed in. */
|
|
55
|
+
function domainOf(primary) {
|
|
56
|
+
return primary === 'SessionCreate' || primary === 'SessionRevoke' ? 'VordexSession' : 'VordCore';
|
|
57
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.U128 = exports.U64 = exports.U32 = void 0;
|
|
4
|
+
exports.toUnits = toUnits;
|
|
5
|
+
exports.numberToDecimal = numberToDecimal;
|
|
6
|
+
exports.fromUnits = fromUnits;
|
|
7
|
+
exports.uint = uint;
|
|
8
|
+
exports.safeNumber = safeNumber;
|
|
9
|
+
const errors_js_1 = require("./errors.js");
|
|
10
|
+
exports.U32 = 2n ** 32n - 1n;
|
|
11
|
+
exports.U64 = 2n ** 64n - 1n;
|
|
12
|
+
exports.U128 = 2n ** 128n - 1n;
|
|
13
|
+
/**
|
|
14
|
+
* A decimal amount as an exact integer of base units. Accepts a decimal string ("2420.5") or a number; refuses more
|
|
15
|
+
* decimals than the unit has (nothing is rounded silently: a rounded value would be a different signed value).
|
|
16
|
+
*/
|
|
17
|
+
function toUnits(x, decimals, what = 'amount') {
|
|
18
|
+
if (typeof x === 'bigint') {
|
|
19
|
+
if (x < 0n)
|
|
20
|
+
throw new errors_js_1.InvalidRequest(`${what} cannot be negative.`);
|
|
21
|
+
return x * 10n ** BigInt(decimals);
|
|
22
|
+
}
|
|
23
|
+
const s = typeof x === 'number' ? numberToDecimal(x) : x.trim();
|
|
24
|
+
const m = /^(\d+)(?:\.(\d*))?$/.exec(s);
|
|
25
|
+
if (!m)
|
|
26
|
+
throw new errors_js_1.InvalidRequest(`${what} is not a positive decimal number (${String(x)}).`);
|
|
27
|
+
const frac = (m[2] ?? '').replace(/0+$/, '');
|
|
28
|
+
if (frac.length > decimals)
|
|
29
|
+
throw new errors_js_1.InvalidRequest(`${what} has more than ${decimals} decimals (${String(x)}).`);
|
|
30
|
+
return BigInt(m[1]) * 10n ** BigInt(decimals) + BigInt((frac + '0'.repeat(decimals)).slice(0, decimals) || '0');
|
|
31
|
+
}
|
|
32
|
+
/** A number written out in full decimal form (no exponent), shortest round-trip digits. */
|
|
33
|
+
function numberToDecimal(n) {
|
|
34
|
+
if (!Number.isFinite(n) || n < 0)
|
|
35
|
+
throw new errors_js_1.InvalidRequest(`${n} is not a positive number.`);
|
|
36
|
+
const s = String(n);
|
|
37
|
+
if (!/e/i.test(s))
|
|
38
|
+
return s;
|
|
39
|
+
const [mant, expS] = s.toLowerCase().split('e');
|
|
40
|
+
const exp = Number(expS);
|
|
41
|
+
const [ip, fp = ''] = mant.split('.');
|
|
42
|
+
const digits = ip + fp;
|
|
43
|
+
const point = ip.length + exp;
|
|
44
|
+
if (point <= 0)
|
|
45
|
+
return '0.' + '0'.repeat(-point) + digits;
|
|
46
|
+
if (point >= digits.length)
|
|
47
|
+
return digits + '0'.repeat(point - digits.length);
|
|
48
|
+
return digits.slice(0, point) + '.' + digits.slice(point);
|
|
49
|
+
}
|
|
50
|
+
/** Base units back to a decimal string, without trailing zeros. */
|
|
51
|
+
function fromUnits(v, decimals) {
|
|
52
|
+
const neg = v < 0n;
|
|
53
|
+
const a = neg ? -v : v;
|
|
54
|
+
const d = 10n ** BigInt(decimals);
|
|
55
|
+
const frac = (a % d).toString().padStart(decimals, '0').replace(/0+$/, '');
|
|
56
|
+
return (neg ? '-' : '') + (a / d).toString() + (frac ? '.' + frac : '');
|
|
57
|
+
}
|
|
58
|
+
/** A whole number within range, as a bigint (accepts number, bigint or a digit string). */
|
|
59
|
+
function uint(v, max, what) {
|
|
60
|
+
let b;
|
|
61
|
+
if (typeof v === 'bigint')
|
|
62
|
+
b = v;
|
|
63
|
+
else if (typeof v === 'number' && Number.isSafeInteger(v))
|
|
64
|
+
b = BigInt(v);
|
|
65
|
+
else if (typeof v === 'string' && /^\d+$/.test(v))
|
|
66
|
+
b = BigInt(v);
|
|
67
|
+
else
|
|
68
|
+
throw new errors_js_1.InvalidRequest(`${what} is not a whole number.`);
|
|
69
|
+
if (b < 0n || b > max)
|
|
70
|
+
throw new errors_js_1.InvalidRequest(`${what} is out of range.`);
|
|
71
|
+
return b;
|
|
72
|
+
}
|
|
73
|
+
/** A whole number that the body carries as a JSON number: it must be exact in JavaScript. */
|
|
74
|
+
function safeNumber(v, what) {
|
|
75
|
+
if (v > BigInt(Number.MAX_SAFE_INTEGER))
|
|
76
|
+
throw new errors_js_1.InvalidRequest(`${what} is past the exact-integer range.`);
|
|
77
|
+
return Number(v);
|
|
78
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session keys, TWAP orders and margin mode — signed by the account's own key.
|
|
3
|
+
*
|
|
4
|
+
* Session key: SessionCreate / SessionRevoke in the VordexSession domain. The chain keeps one session per account, so a
|
|
5
|
+
* session it holds for another key is revoked first. Each nonce is larger than the last.
|
|
6
|
+
* TWAP: PlaceTwap / CancelTwap in the VordCore domain, owner key only (a session key is refused). The route and limits
|
|
7
|
+
* come from the network spec's `twap` section.
|
|
8
|
+
* Margin mode: SetMarginMode in the VordCore domain — cross or isolated per market, only while the market has no open
|
|
9
|
+
* position and no resting order of the account.
|
|
10
|
+
*/
|
|
11
|
+
export declare const SESSION_MAX_SECONDS: number;
|
|
12
|
+
export declare const MODE_CODE: {
|
|
13
|
+
readonly cross: 1;
|
|
14
|
+
readonly isolated: 2;
|
|
15
|
+
};
|
|
16
|
+
export type MarginMode = keyof typeof MODE_CODE;
|
|
17
|
+
/** Larger than the last nonce: the time in ms, or the previous nonce + 1. */
|
|
18
|
+
export declare function nextNonce(after?: number, nowMs?: number): number;
|
|
19
|
+
/** The session's end in seconds: the asked end, at most 90 days less an hour from now. */
|
|
20
|
+
export declare function sessionEnd(endMs: number, nowMs?: number): number;
|
|
21
|
+
export declare function sessionCreateBody(owner: string, sessionKey: string, expiresAt: number, nonce: number, signature: string): string;
|
|
22
|
+
export declare function sessionRevokeBody(owner: string, sessionKey: string, nonce: number, signature: string): string;
|
|
23
|
+
export interface TwapValue {
|
|
24
|
+
owner: string;
|
|
25
|
+
pairId: number;
|
|
26
|
+
side: number;
|
|
27
|
+
totalSize18dec: bigint;
|
|
28
|
+
numSlices: number;
|
|
29
|
+
durationMs: number;
|
|
30
|
+
leverageBps: number;
|
|
31
|
+
slippageBps: number;
|
|
32
|
+
randomize: boolean;
|
|
33
|
+
triggerPrice8dec: bigint;
|
|
34
|
+
triggerDir: number;
|
|
35
|
+
minPrice8dec: bigint;
|
|
36
|
+
maxPrice8dec: bigint;
|
|
37
|
+
clientNonce: number;
|
|
38
|
+
}
|
|
39
|
+
/** snake_case, the chain's field order, every integer as its exact digits. */
|
|
40
|
+
export declare function twapBody(v: TwapValue, signature: string): string;
|
|
41
|
+
export declare function cancelTwapBody(owner: string, twapId: bigint | number, clientNonce: number, signature: string): string;
|
|
42
|
+
export declare function marginModeBody(owner: string, pairId: number, mode: number, nonce: number, signature: string): string;
|
|
43
|
+
export interface TwapRules {
|
|
44
|
+
path: string;
|
|
45
|
+
cancelPath: string;
|
|
46
|
+
minDurationMs: number;
|
|
47
|
+
maxDurationMs: number;
|
|
48
|
+
minIntervalMs: number;
|
|
49
|
+
maxSlices: number;
|
|
50
|
+
maxSlippageBps: number;
|
|
51
|
+
minSliceNotional6dec: number;
|
|
52
|
+
minTotalNotional6dec: number;
|
|
53
|
+
}
|
|
54
|
+
export declare const TWAP_BODY: string[];
|
|
55
|
+
/**
|
|
56
|
+
* The spec's `twap` section. Refuses (NotAvailable, nothing signed) when it is not published, names another route, signs
|
|
57
|
+
* another type or sends another body than this SDK, or does not publish its limits.
|
|
58
|
+
*/
|
|
59
|
+
export declare function readTwapRules(spec: unknown): TwapRules;
|
|
60
|
+
/** [slices, interval ms]: as many slices as the limits allow, the interval being the duration shared out. */
|
|
61
|
+
export declare function planTwap(durationMs: number, r: TwapRules, totalNotional6dec?: number): [number, number];
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
import { InvalidRequest, NotAvailable } from './errors.js';
|
|
2
|
+
import { TYPE_STRINGS } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Session keys, TWAP orders and margin mode — signed by the account's own key.
|
|
5
|
+
*
|
|
6
|
+
* Session key: SessionCreate / SessionRevoke in the VordexSession domain. The chain keeps one session per account, so a
|
|
7
|
+
* session it holds for another key is revoked first. Each nonce is larger than the last.
|
|
8
|
+
* TWAP: PlaceTwap / CancelTwap in the VordCore domain, owner key only (a session key is refused). The route and limits
|
|
9
|
+
* come from the network spec's `twap` section.
|
|
10
|
+
* Margin mode: SetMarginMode in the VordCore domain — cross or isolated per market, only while the market has no open
|
|
11
|
+
* position and no resting order of the account.
|
|
12
|
+
*/
|
|
13
|
+
export const SESSION_MAX_SECONDS = 90 * 86400 - 3600;
|
|
14
|
+
export const MODE_CODE = { cross: 1, isolated: 2 };
|
|
15
|
+
/** Larger than the last nonce: the time in ms, or the previous nonce + 1. */
|
|
16
|
+
export function nextNonce(after = 0, nowMs = Date.now()) {
|
|
17
|
+
return Math.max(Math.floor(nowMs), after + 1);
|
|
18
|
+
}
|
|
19
|
+
/** The session's end in seconds: the asked end, at most 90 days less an hour from now. */
|
|
20
|
+
export function sessionEnd(endMs, nowMs = Date.now()) {
|
|
21
|
+
return Math.min(Math.floor(endMs / 1000), Math.floor(nowMs / 1000) + SESSION_MAX_SECONDS);
|
|
22
|
+
}
|
|
23
|
+
export function sessionCreateBody(owner, sessionKey, expiresAt, nonce, signature) {
|
|
24
|
+
return JSON.stringify({ owner, session_key: sessionKey, expires_at: expiresAt, nonce, signature });
|
|
25
|
+
}
|
|
26
|
+
export function sessionRevokeBody(owner, sessionKey, nonce, signature) {
|
|
27
|
+
return JSON.stringify({ owner, session_key: sessionKey, nonce, signature });
|
|
28
|
+
}
|
|
29
|
+
const digits = (v) => BigInt(v).toString();
|
|
30
|
+
/** snake_case, the chain's field order, every integer as its exact digits. */
|
|
31
|
+
export function twapBody(v, signature) {
|
|
32
|
+
const parts = [
|
|
33
|
+
['owner', JSON.stringify(v.owner)], ['pair_id', digits(v.pairId)], ['side', digits(v.side)], ['total_size_18dec', digits(v.totalSize18dec)],
|
|
34
|
+
['num_slices', digits(v.numSlices)], ['duration_ms', digits(v.durationMs)], ['leverage_bps', digits(v.leverageBps)], ['slippage_bps', digits(v.slippageBps)],
|
|
35
|
+
['randomize', v.randomize === true ? 'true' : 'false'], ['trigger_price_8dec', digits(v.triggerPrice8dec)], ['trigger_dir', digits(v.triggerDir)],
|
|
36
|
+
['min_price_8dec', digits(v.minPrice8dec)], ['max_price_8dec', digits(v.maxPrice8dec)], ['client_nonce', digits(v.clientNonce)], ['signature', JSON.stringify(signature)],
|
|
37
|
+
];
|
|
38
|
+
return '{' + parts.map(([k, x]) => `${JSON.stringify(k)}:${x}`).join(',') + '}';
|
|
39
|
+
}
|
|
40
|
+
export function cancelTwapBody(owner, twapId, clientNonce, signature) {
|
|
41
|
+
return `{"owner":${JSON.stringify(owner)},"twap_id":${digits(twapId)},"client_nonce":${digits(clientNonce)},"signature":${JSON.stringify(signature)}}`;
|
|
42
|
+
}
|
|
43
|
+
export function marginModeBody(owner, pairId, mode, nonce, signature) {
|
|
44
|
+
return `{"owner":"${owner.toLowerCase()}","pair_id":${digits(pairId)},"mode":${digits(mode)},"nonce":${digits(nonce)},"signature":"${signature}"}`;
|
|
45
|
+
}
|
|
46
|
+
export const TWAP_BODY = ['owner', 'pair_id', 'side', 'total_size_18dec', 'num_slices', 'duration_ms', 'leverage_bps', 'slippage_bps',
|
|
47
|
+
'randomize', 'trigger_price_8dec', 'trigger_dir', 'min_price_8dec', 'max_price_8dec', 'client_nonce', 'signature'];
|
|
48
|
+
const val = (x) => (x && typeof x === 'object' && 'value' in x ? x.value : x);
|
|
49
|
+
const num = (src, k) => {
|
|
50
|
+
const v = src && typeof src === 'object' ? val(src[k]) : undefined;
|
|
51
|
+
if (typeof v === 'number' && Number.isSafeInteger(v))
|
|
52
|
+
return v;
|
|
53
|
+
if (typeof v === 'string' && /^\d+$/.test(v))
|
|
54
|
+
return Number(v);
|
|
55
|
+
return null;
|
|
56
|
+
};
|
|
57
|
+
/**
|
|
58
|
+
* The spec's `twap` section. Refuses (NotAvailable, nothing signed) when it is not published, names another route, signs
|
|
59
|
+
* another type or sends another body than this SDK, or does not publish its limits.
|
|
60
|
+
*/
|
|
61
|
+
export function readTwapRules(spec) {
|
|
62
|
+
const t = spec && typeof spec === 'object' ? spec.twap : undefined;
|
|
63
|
+
if (!t || typeof t !== 'object' || t.liveToday === false || t.available === false) {
|
|
64
|
+
const why = t && typeof t.reason === 'string' ? ` (${t.reason})` : '';
|
|
65
|
+
throw new NotAvailable('The network does not publish TWAP placement' + why + '.');
|
|
66
|
+
}
|
|
67
|
+
const place = t.place;
|
|
68
|
+
const cancel = (t.cancel && typeof t.cancel === 'object' ? t.cancel : {});
|
|
69
|
+
if (!place || typeof place !== 'object')
|
|
70
|
+
throw new NotAvailable("The network's TWAP section names no placement route.");
|
|
71
|
+
const path = place.path;
|
|
72
|
+
if (place.method !== 'POST' || typeof path !== 'string' || !path.startsWith('/'))
|
|
73
|
+
throw new NotAvailable('The network publishes a TWAP route this SDK cannot use.');
|
|
74
|
+
if (val(place.typeString) !== TYPE_STRINGS.PlaceTwap)
|
|
75
|
+
throw new NotAvailable('The network signs PlaceTwap in another format than this SDK; nothing is signed.');
|
|
76
|
+
const body = (Array.isArray(place.body) ? place.body : []).map((b) => (b && typeof b === 'object' ? b.name : b)).filter((b) => b !== 'reduce_only');
|
|
77
|
+
if (JSON.stringify(body) !== JSON.stringify(TWAP_BODY))
|
|
78
|
+
throw new NotAvailable('The network publishes a TWAP body this SDK does not send; nothing is signed.');
|
|
79
|
+
const ct = val(cancel.typeString);
|
|
80
|
+
if (ct !== undefined && ct !== null && ct !== TYPE_STRINGS.CancelTwap)
|
|
81
|
+
throw new NotAvailable('The network signs CancelTwap in another format than this SDK; nothing is signed.');
|
|
82
|
+
const lim = place.limits ?? t.limits;
|
|
83
|
+
const d = t.durationMs, so = t.subOrders;
|
|
84
|
+
let v;
|
|
85
|
+
if (lim && typeof lim === 'object') {
|
|
86
|
+
v = [num(lim, 'minDurationMs'), num(lim, 'maxDurationMs'), num(lim, 'minIntervalMs'), num(lim, 'maxNumSlices'), num(lim, 'maxSlippageBps'),
|
|
87
|
+
num(lim, 'minSubOrderNotional6dec') ?? 0, num(lim, 'minTotalNotional6dec')];
|
|
88
|
+
}
|
|
89
|
+
else if (d && typeof d === 'object' && so && typeof so === 'object') {
|
|
90
|
+
v = [num(d, 'min'), num(d, 'max'), num(so, 'minIntervalMs'), num(so, 'maxNumSlices'), num(so, 'maxSlippageBpsPerSubOrder'),
|
|
91
|
+
num(so, 'minSubOrderNotional6dec') ?? 0, num(so, 'minTotalNotional6dec')];
|
|
92
|
+
}
|
|
93
|
+
else
|
|
94
|
+
v = [null];
|
|
95
|
+
if (v.some((x) => x === null) || v[0] > v[1])
|
|
96
|
+
throw new NotAvailable('The network does not publish its TWAP limits, so an order cannot be checked before signing.');
|
|
97
|
+
const [a, b, c, e, f, g, h] = v;
|
|
98
|
+
return { path, cancelPath: typeof cancel.path === 'string' ? cancel.path : '/twap/cancel', minDurationMs: a, maxDurationMs: b, minIntervalMs: c,
|
|
99
|
+
maxSlices: e, maxSlippageBps: f, minSliceNotional6dec: g, minTotalNotional6dec: h };
|
|
100
|
+
}
|
|
101
|
+
/** [slices, interval ms]: as many slices as the limits allow, the interval being the duration shared out. */
|
|
102
|
+
export function planTwap(durationMs, r, totalNotional6dec) {
|
|
103
|
+
if (durationMs < r.minDurationMs || durationMs > r.maxDurationMs)
|
|
104
|
+
throw new InvalidRequest("The running time is outside the network's TWAP range.");
|
|
105
|
+
let n = Math.min(r.maxSlices, Math.floor(durationMs / Math.max(1, r.minIntervalMs)));
|
|
106
|
+
if (totalNotional6dec !== undefined) {
|
|
107
|
+
if (totalNotional6dec < r.minTotalNotional6dec)
|
|
108
|
+
throw new InvalidRequest("The order is smaller than the network's smallest TWAP.");
|
|
109
|
+
n = Math.min(n, Math.floor(totalNotional6dec / Math.max(1, r.minSliceNotional6dec)));
|
|
110
|
+
}
|
|
111
|
+
if (n < 1)
|
|
112
|
+
throw new InvalidRequest("No plan fits the network's TWAP limits.");
|
|
113
|
+
return [n, Math.floor(durationMs / n)];
|
|
114
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agents: a key that trades for an account within the limits its owner signs. The operations in force:
|
|
3
|
+
* RegisterAgentV2 (a name is required), SetAgentName, SetAgentPolicyV1, SetAgentMarketLimit, ClearAgentLock and
|
|
4
|
+
* RevokeAgent. Each is signed by the OWNER in the VordCore domain and sent to `POST /submit`; only SetAgentPolicyV1 may
|
|
5
|
+
* also be signed by the agent itself, and then only to tighten the stored policy.
|
|
6
|
+
*/
|
|
7
|
+
export declare const NAME_MIN_BYTES = 3;
|
|
8
|
+
export declare const NAME_MAX_BYTES = 32;
|
|
9
|
+
export declare const RESERVED_WORDS_DEFAULT: readonly ["admin", "helpdesk", "moderator", "official", "support", "validator", "vordex", "vordium", "vordscan"];
|
|
10
|
+
export type NameStep = 'NonAscii' | 'ControlChar' | 'BadChar' | 'TooShort' | 'TooLong' | 'NotCanonical' | 'NoAlphanumeric' | 'Reserved';
|
|
11
|
+
/** What is signed: NFKC, every run of ASCII whitespace becomes one space, no space at either end. */
|
|
12
|
+
export declare function normalizeName(raw: string): string;
|
|
13
|
+
/** ASCII letters lower-cased, with `space - _ .` removed: what reserved words are matched in (as the node builds it). */
|
|
14
|
+
export declare function nameSkeleton(name: string): string;
|
|
15
|
+
/**
|
|
16
|
+
* The chain's form rule for an ALREADY-normalised name, in the chain's own step order: `null` when accepted, else the
|
|
17
|
+
* refusing step. Uniqueness among the owner's agents, the rename wait and the live-agent limit are the chain's to judge.
|
|
18
|
+
*/
|
|
19
|
+
export declare function nameRefusalStep(name: string, reserved?: readonly string[]): NameStep | null;
|
|
20
|
+
/** Normalise then check: the name to sign, or InvalidRequest with the reason. */
|
|
21
|
+
export declare function requireName(raw: string, reserved?: readonly string[]): string;
|
|
22
|
+
export declare const CAPABILITY_BITS: {
|
|
23
|
+
readonly place: 0;
|
|
24
|
+
readonly cancel: 1;
|
|
25
|
+
readonly modify: 2;
|
|
26
|
+
readonly tpsl: 3;
|
|
27
|
+
readonly close: 4;
|
|
28
|
+
readonly vault: 5;
|
|
29
|
+
};
|
|
30
|
+
export declare const CAPS_ALL = 63;
|
|
31
|
+
export declare const ORACLE_BAND_MIN_BPS = 1;
|
|
32
|
+
export declare const ORACLE_BAND_MAX_BPS = 1000;
|
|
33
|
+
export declare const MAX_LEVERAGE_BPS = 500000;
|
|
34
|
+
export declare const DAY_MS = 86400000;
|
|
35
|
+
export interface PolicyV1 {
|
|
36
|
+
capsBitmask: number;
|
|
37
|
+
/** 0 open and reduce, 1 reduce only. */
|
|
38
|
+
sideMode: number;
|
|
39
|
+
maxTotalExposure6dec: bigint;
|
|
40
|
+
/** 0 = unlimited. */
|
|
41
|
+
maxLeverageBps: number;
|
|
42
|
+
dailyLossLimit6dec: bigint;
|
|
43
|
+
/** 0 = unlimited. */
|
|
44
|
+
dailyFeeCap6dec: bigint;
|
|
45
|
+
/** Both 0 = unlimited. */
|
|
46
|
+
opsPerWindow: number;
|
|
47
|
+
opsWindowMs: number;
|
|
48
|
+
/** Both 0 = always. */
|
|
49
|
+
activeFromMsOfDay: number;
|
|
50
|
+
activeToMsOfDay: number;
|
|
51
|
+
oracleBandBps: number;
|
|
52
|
+
lockAutoClear: boolean;
|
|
53
|
+
expiresMs: number;
|
|
54
|
+
enabled: boolean;
|
|
55
|
+
}
|
|
56
|
+
/** Why the chain would refuse this policy at apply (it refuses silently); [] = none of the stateless reasons. */
|
|
57
|
+
export declare function policyProblems(p: PolicyV1, nowMs: number): string[];
|
|
58
|
+
/** What in `next` would LOOSEN `prev`; [] = a tightening or no change (and always [] with nothing stored). */
|
|
59
|
+
export declare function loosens(prev: PolicyV1 | null, next: PolicyV1): string[];
|
|
60
|
+
export type AgentOp = 'RegisterAgentV2' | 'SetAgentName' | 'SetAgentPolicyV1' | 'SetAgentMarketLimit' | 'ClearAgentLock' | 'RevokeAgent';
|
|
61
|
+
type Kind = 'address' | 'string' | 'bool' | 'u8' | 'u32' | 'u64' | 'u128';
|
|
62
|
+
/** Per operation: [struct name, wire name, kind], in the order the node reads them. */
|
|
63
|
+
export declare const SUBMIT_FIELDS: Record<AgentOp, Array<[string, string, Kind]>>;
|
|
64
|
+
/** These operations carry their addresses in lower case on the wire; the others as given. */
|
|
65
|
+
export declare const LOWERCASE_ADDRESS_OPS: ReadonlySet<AgentOp>;
|
|
66
|
+
/** The exact `POST /submit` body for one signed agent operation (every field, in wire order). */
|
|
67
|
+
export declare function submitBody(op: AgentOp, value: Record<string, unknown>, signature: string): Record<string, unknown>;
|
|
68
|
+
export declare function policyValue(owner: string, agent: string, p: PolicyV1, nonce: number): Record<string, unknown>;
|
|
69
|
+
/** The stored policy from `GET /agents/{owner}/{agent}` (`policy_v1`, the node's snake_case names), or null. */
|
|
70
|
+
export declare function policyFromRead(x: unknown): PolicyV1 | null;
|
|
71
|
+
export {};
|