skewtape 0.0.1 → 0.1.4
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 +182 -0
- package/dist/cjs/backtest.d.ts +146 -0
- package/dist/cjs/backtest.js +410 -0
- package/dist/cjs/client.d.ts +255 -0
- package/dist/cjs/client.js +447 -0
- package/dist/cjs/download.d.ts +33 -0
- package/dist/cjs/download.js +160 -0
- package/dist/cjs/errors.d.ts +76 -0
- package/dist/cjs/errors.js +159 -0
- package/dist/cjs/exact.d.ts +36 -0
- package/dist/cjs/exact.js +168 -0
- package/dist/cjs/fees.d.ts +68 -0
- package/dist/cjs/fees.js +196 -0
- package/dist/cjs/geoblock.d.ts +48 -0
- package/dist/cjs/geoblock.js +78 -0
- package/dist/cjs/index.d.ts +31 -0
- package/dist/cjs/index.js +98 -0
- package/dist/cjs/kalshi.d.ts +261 -0
- package/dist/cjs/kalshi.js +416 -0
- package/dist/cjs/keccak.d.ts +10 -0
- package/dist/cjs/keccak.js +84 -0
- package/dist/cjs/msgpack.d.ts +15 -0
- package/dist/cjs/msgpack.js +112 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/paginated.d.ts +26 -0
- package/dist/cjs/paginated.js +51 -0
- package/dist/cjs/quote-math.d.ts +146 -0
- package/dist/cjs/quote-math.js +446 -0
- package/dist/cjs/quote.d.ts +108 -0
- package/dist/cjs/quote.js +307 -0
- package/dist/cjs/route-hyperliquid.d.ts +228 -0
- package/dist/cjs/route-hyperliquid.js +387 -0
- package/dist/cjs/route.d.ts +297 -0
- package/dist/cjs/route.js +516 -0
- package/dist/cjs/stream.d.ts +99 -0
- package/dist/cjs/stream.js +529 -0
- package/dist/cjs/version.d.ts +6 -0
- package/dist/cjs/version.js +9 -0
- package/dist/esm/backtest.d.ts +146 -0
- package/dist/esm/backtest.js +403 -0
- package/dist/esm/client.d.ts +255 -0
- package/dist/esm/client.js +441 -0
- package/dist/esm/download.d.ts +33 -0
- package/dist/esm/download.js +155 -0
- package/dist/esm/errors.d.ts +76 -0
- package/dist/esm/errors.js +142 -0
- package/dist/esm/exact.d.ts +36 -0
- package/dist/esm/exact.js +158 -0
- package/dist/esm/fees.d.ts +68 -0
- package/dist/esm/fees.js +185 -0
- package/dist/esm/geoblock.d.ts +48 -0
- package/dist/esm/geoblock.js +74 -0
- package/dist/esm/index.d.ts +31 -0
- package/dist/esm/index.js +30 -0
- package/dist/esm/kalshi.d.ts +261 -0
- package/dist/esm/kalshi.js +404 -0
- package/dist/esm/keccak.d.ts +10 -0
- package/dist/esm/keccak.js +80 -0
- package/dist/esm/msgpack.d.ts +15 -0
- package/dist/esm/msgpack.js +109 -0
- package/dist/esm/paginated.d.ts +26 -0
- package/dist/esm/paginated.js +47 -0
- package/dist/esm/quote-math.d.ts +146 -0
- package/dist/esm/quote-math.js +437 -0
- package/dist/esm/quote.d.ts +108 -0
- package/dist/esm/quote.js +297 -0
- package/dist/esm/route-hyperliquid.d.ts +228 -0
- package/dist/esm/route-hyperliquid.js +376 -0
- package/dist/esm/route.d.ts +297 -0
- package/dist/esm/route.js +507 -0
- package/dist/esm/stream.d.ts +99 -0
- package/dist/esm/stream.js +524 -0
- package/dist/esm/version.d.ts +6 -0
- package/dist/esm/version.js +6 -0
- package/package.json +48 -1
- package/src/backtest.ts +490 -0
- package/src/client.ts +595 -0
- package/src/download.ts +161 -0
- package/src/errors.ts +143 -0
- package/src/exact.ts +159 -0
- package/src/fees.ts +189 -0
- package/src/generated/schema.d.ts +2500 -0
- package/src/geoblock.ts +90 -0
- package/src/index.ts +146 -0
- package/src/kalshi.ts +563 -0
- package/src/keccak.ts +82 -0
- package/src/msgpack.ts +83 -0
- package/src/paginated.ts +51 -0
- package/src/quote-math.ts +555 -0
- package/src/quote.ts +324 -0
- package/src/route-hyperliquid.ts +457 -0
- package/src/route.ts +631 -0
- package/src/stream.ts +539 -0
- package/src/version.ts +6 -0
|
@@ -0,0 +1,516 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* sk.route: an unsigned order for the developer to sign and submit (F2,
|
|
4
|
+
* ADR-0016, ARCHITECTURE 13.3).
|
|
5
|
+
*
|
|
6
|
+
* route() builds and checks an order, and stops there: it never signs, never
|
|
7
|
+
* sends, never takes a private key, and needs no Skewtape key. Every code and
|
|
8
|
+
* fee it carries is the developer's own: the Polymarket builder code, the
|
|
9
|
+
* DFlow fee account and fee. Omitting them sends none, and no Skewtape value
|
|
10
|
+
* exists in this package (a test scans it). The developer is responsible for
|
|
11
|
+
* their users: who may trade where, and under which terms (sk.geoblock helps
|
|
12
|
+
* with Polymarket's).
|
|
13
|
+
*
|
|
14
|
+
* const order = route({
|
|
15
|
+
* venue: "polymarket", exchange: "ctf", tokenId: "7132...", side: "BUY",
|
|
16
|
+
* price: "0.52", size: "10", tickSize: "0.01", maker: "0xYourAddress",
|
|
17
|
+
* builder: "0xYourBuilderCode", // optional, yours
|
|
18
|
+
* });
|
|
19
|
+
* const signature = await walletClient.signTypedData(order.typedData);
|
|
20
|
+
* const body = order.postBody(signature, yourClobApiKeyId);
|
|
21
|
+
*/
|
|
22
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
23
|
+
exports.DFlowOrderRequest = exports.DFLOW_FEE_BPS_MAX = exports.DFLOW_FEE_SCALE_MAX = exports.DFLOW_API_KEY_HEADER = exports.DFLOW_TRADING_API = exports.ROUTE_FIELDS = exports.PolymarketOrder = exports.ZERO_BYTES32 = exports.MAX_SAFE_SALT = exports.POLYMARKET_GTD_MIN_SECONDS = exports.POLYMARKET_MAX_SIZE = exports.POLYMARKET_DECIMALS = exports.POLYMARKET_TICKS = exports.POLYMARKET_SIGNATURE_TYPES = exports.POLYMARKET_SIDES = exports.POLYMARKET_EXCHANGES = exports.POLYGON_CHAIN_ID = exports.POLYMARKET_DOMAIN_NAME = exports.EIP712_DOMAIN_TYPE = exports.POLYMARKET_ORDER_TYPE = exports.RouteError = void 0;
|
|
24
|
+
exports.polymarketAmounts = polymarketAmounts;
|
|
25
|
+
exports.polymarketOrder = polymarketOrder;
|
|
26
|
+
exports.dflowOrder = dflowOrder;
|
|
27
|
+
exports.route = route;
|
|
28
|
+
const errors_js_1 = require("./errors.js");
|
|
29
|
+
Object.defineProperty(exports, "RouteError", { enumerable: true, get: function () { return errors_js_1.RouteError; } });
|
|
30
|
+
const route_hyperliquid_js_1 = require("./route-hyperliquid.js");
|
|
31
|
+
/** A table's own entry for key, never one inherited from Object.prototype ("toString", "constructor"). */
|
|
32
|
+
function own(table, key) {
|
|
33
|
+
return typeof key === "string" && Object.hasOwn(table, key) ? table[key] : undefined;
|
|
34
|
+
}
|
|
35
|
+
const pow10 = (k) => 10n ** BigInt(k);
|
|
36
|
+
function parseDec(name, value) {
|
|
37
|
+
if (typeof value !== "string") {
|
|
38
|
+
throw new errors_js_1.RouteError(`${name}: pass a decimal string such as "0.52" (a number is a float, not exact)`);
|
|
39
|
+
}
|
|
40
|
+
const m = /^(\d+)(?:\.(\d+))?$/.exec(value.trim());
|
|
41
|
+
if (!m)
|
|
42
|
+
throw new errors_js_1.RouteError(`${name}: ${JSON.stringify(value)} is not a non-negative decimal`);
|
|
43
|
+
const frac = m[2] ?? "";
|
|
44
|
+
return { n: BigInt((m[1] ?? "") + frac), s: frac.length };
|
|
45
|
+
}
|
|
46
|
+
function normalize(d) {
|
|
47
|
+
let { n, s } = d;
|
|
48
|
+
while (s > 0 && n % 10n === 0n) {
|
|
49
|
+
n /= 10n;
|
|
50
|
+
s -= 1;
|
|
51
|
+
}
|
|
52
|
+
return { n, s };
|
|
53
|
+
}
|
|
54
|
+
const places = (d) => normalize(d).s;
|
|
55
|
+
const cmp = (a, b) => {
|
|
56
|
+
const x = a.n * pow10(b.s);
|
|
57
|
+
const y = b.n * pow10(a.s);
|
|
58
|
+
return x < y ? -1 : x > y ? 1 : 0;
|
|
59
|
+
};
|
|
60
|
+
const mul = (a, b) => ({ n: a.n * b.n, s: a.s + b.s });
|
|
61
|
+
const sub = (a, b) => {
|
|
62
|
+
const s = Math.max(a.s, b.s);
|
|
63
|
+
return { n: a.n * pow10(s - a.s) - b.n * pow10(s - b.s), s };
|
|
64
|
+
};
|
|
65
|
+
function roundDown(d, p) {
|
|
66
|
+
return d.s <= p ? { n: d.n * pow10(p - d.s), s: p } : { n: d.n / pow10(d.s - p), s: p };
|
|
67
|
+
}
|
|
68
|
+
function roundUp(d, p) {
|
|
69
|
+
if (d.s <= p)
|
|
70
|
+
return { n: d.n * pow10(p - d.s), s: p };
|
|
71
|
+
const q = pow10(d.s - p);
|
|
72
|
+
return { n: (d.n + q - 1n) / q, s: p };
|
|
73
|
+
}
|
|
74
|
+
/** a / b rounded up to p places, exactly. */
|
|
75
|
+
function divUp(a, b, p) {
|
|
76
|
+
const num = a.n * pow10(b.s + p);
|
|
77
|
+
const den = b.n * pow10(a.s);
|
|
78
|
+
return { n: (num + den - 1n) / den, s: p };
|
|
79
|
+
}
|
|
80
|
+
const toString = (d) => {
|
|
81
|
+
const x = normalize(d);
|
|
82
|
+
const str = x.n.toString().padStart(x.s + 1, "0");
|
|
83
|
+
return x.s ? `${str.slice(0, -x.s)}.${str.slice(-x.s)}` : str;
|
|
84
|
+
};
|
|
85
|
+
// --- Polymarket ---------------------------------------------------------------
|
|
86
|
+
/**
|
|
87
|
+
* The V2 order the exchange hashes (Polymarket/ctf-exchange-v2 @ 5c65f2d,
|
|
88
|
+
* src/exchange/libraries/Structs.sol,
|
|
89
|
+
* ORDER_TYPEHASH 0xbb86318a...818589), the same type
|
|
90
|
+
* docs.polymarket.com/trading/place-orders.md gives. `signature` is not
|
|
91
|
+
* hashed, and `expiration` is not part of the order: it rides in the POST body.
|
|
92
|
+
*/
|
|
93
|
+
exports.POLYMARKET_ORDER_TYPE = [
|
|
94
|
+
{ name: "salt", type: "uint256" },
|
|
95
|
+
{ name: "maker", type: "address" },
|
|
96
|
+
{ name: "signer", type: "address" },
|
|
97
|
+
{ name: "tokenId", type: "uint256" },
|
|
98
|
+
{ name: "makerAmount", type: "uint256" },
|
|
99
|
+
{ name: "takerAmount", type: "uint256" },
|
|
100
|
+
{ name: "side", type: "uint8" },
|
|
101
|
+
{ name: "signatureType", type: "uint8" },
|
|
102
|
+
{ name: "timestamp", type: "uint256" },
|
|
103
|
+
{ name: "metadata", type: "bytes32" },
|
|
104
|
+
{ name: "builder", type: "bytes32" },
|
|
105
|
+
];
|
|
106
|
+
exports.EIP712_DOMAIN_TYPE = [
|
|
107
|
+
{ name: "name", type: "string" },
|
|
108
|
+
{ name: "version", type: "string" },
|
|
109
|
+
{ name: "chainId", type: "uint256" },
|
|
110
|
+
{ name: "verifyingContract", type: "address" },
|
|
111
|
+
];
|
|
112
|
+
exports.POLYMARKET_DOMAIN_NAME = "Polymarket CTF Exchange";
|
|
113
|
+
exports.POLYGON_CHAIN_ID = 137;
|
|
114
|
+
/**
|
|
115
|
+
* The exchange that verifies the order, and its domain version, by book
|
|
116
|
+
* (place-orders.md, "Create the Order Typed Data"; addresses also on
|
|
117
|
+
* docs.polymarket.com/resources/contracts.md, Polygon 137): the CTF exchange
|
|
118
|
+
* and the neg risk CTF exchange sign with version "2", a Protocol V2 book
|
|
119
|
+
* ("version": "v2" in the market's data, ExchangeV3) with "3". The developer
|
|
120
|
+
* names it: route() never guesses which book a token trades on.
|
|
121
|
+
*/
|
|
122
|
+
exports.POLYMARKET_EXCHANGES = {
|
|
123
|
+
ctf: { version: "2", verifyingContract: "0xE111180000d2663C0091e4f400237545B87B996B" },
|
|
124
|
+
neg_risk: { version: "2", verifyingContract: "0xe2222d279d744050d28e00520010520000310F59" },
|
|
125
|
+
protocol_v2: { version: "3", verifyingContract: "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa" },
|
|
126
|
+
};
|
|
127
|
+
/** Side and SignatureType (Structs.sol): BUY 0, SELL 1; EOA 0, POLY_PROXY 1, POLY_GNOSIS_SAFE 2, POLY_1271 3. */
|
|
128
|
+
exports.POLYMARKET_SIDES = { BUY: 0, SELL: 1 };
|
|
129
|
+
exports.POLYMARKET_SIGNATURE_TYPES = { EOA: 0, POLY_PROXY: 1, POLY_GNOSIS_SAFE: 2, POLY_1271: 3 };
|
|
130
|
+
const ORDER_TYPES = ["GTC", "GTD", "FOK", "FAK"];
|
|
131
|
+
/** Price, size and amount decimals by tick size (place-orders.md, "Rounding"). */
|
|
132
|
+
exports.POLYMARKET_TICKS = {
|
|
133
|
+
"0.1": [1, 2, 3],
|
|
134
|
+
"0.01": [2, 2, 4],
|
|
135
|
+
"0.005": [3, 2, 5],
|
|
136
|
+
"0.0025": [4, 2, 6],
|
|
137
|
+
"0.001": [3, 2, 5],
|
|
138
|
+
"0.0001": [4, 2, 6],
|
|
139
|
+
};
|
|
140
|
+
/** Six-decimal base units: "1_000_000 is one pUSD or one share" (migrate/polymarket-v2/contract-integrations.md). */
|
|
141
|
+
exports.POLYMARKET_DECIMALS = 6;
|
|
142
|
+
/** A size or amount (shares or USD) at or above 10^15 is refused, as in the Python SDK, which needs the bound for its decimal context. */
|
|
143
|
+
exports.POLYMARKET_MAX_SIZE = 10n ** 15n;
|
|
144
|
+
function sized(name, value) {
|
|
145
|
+
const d = parseDec(name, value);
|
|
146
|
+
if (cmp(d, { n: exports.POLYMARKET_MAX_SIZE, s: 0 }) >= 0)
|
|
147
|
+
throw new errors_js_1.RouteError(`${name}: below 10^15, not ${value}`);
|
|
148
|
+
return d;
|
|
149
|
+
}
|
|
150
|
+
/** A GTD order's expiration is Unix seconds at least three minutes ahead (place-orders.md). */
|
|
151
|
+
exports.POLYMARKET_GTD_MIN_SECONDS = 180;
|
|
152
|
+
exports.MAX_SAFE_SALT = 2 ** 53 - 1;
|
|
153
|
+
exports.ZERO_BYTES32 = `0x${"00".repeat(32)}`;
|
|
154
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
155
|
+
const BYTES32 = /^0x[0-9a-fA-F]{64}$/;
|
|
156
|
+
const SIGNATURE = /^0x[0-9a-fA-F]{130}$/;
|
|
157
|
+
function address(name, value) {
|
|
158
|
+
if (typeof value !== "string" || !ADDRESS.test(value)) {
|
|
159
|
+
throw new errors_js_1.RouteError(`${name}: ${JSON.stringify(value)} is not a 0x-prefixed 20-byte address`);
|
|
160
|
+
}
|
|
161
|
+
return value;
|
|
162
|
+
}
|
|
163
|
+
function bytes32(name, value) {
|
|
164
|
+
if (typeof value !== "string" || !BYTES32.test(value)) {
|
|
165
|
+
throw new errors_js_1.RouteError(`${name}: ${JSON.stringify(value)} is not a 0x-prefixed 32-byte hex value`);
|
|
166
|
+
}
|
|
167
|
+
return value;
|
|
168
|
+
}
|
|
169
|
+
function wholeNumber(name, value, max) {
|
|
170
|
+
if (typeof value === "bigint") {
|
|
171
|
+
if (value < 0n || value > max)
|
|
172
|
+
throw new errors_js_1.RouteError(`${name}: out of range`);
|
|
173
|
+
return value;
|
|
174
|
+
}
|
|
175
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0 && BigInt(value) <= max)
|
|
176
|
+
return BigInt(value);
|
|
177
|
+
throw new errors_js_1.RouteError(`${name}: an integer from 0 to ${max}`);
|
|
178
|
+
}
|
|
179
|
+
/** The docs' third rounding step: a USD amount with more than the amount decimals is rounded up to amount + 4, then down to amount. */
|
|
180
|
+
function usd(d, amountDecimals) {
|
|
181
|
+
if (places(d) > amountDecimals) {
|
|
182
|
+
d = roundUp(d, amountDecimals + 4);
|
|
183
|
+
if (places(d) > amountDecimals)
|
|
184
|
+
d = roundDown(d, amountDecimals);
|
|
185
|
+
}
|
|
186
|
+
return d;
|
|
187
|
+
}
|
|
188
|
+
const units = (d) => roundDown(d, exports.POLYMARKET_DECIMALS).n;
|
|
189
|
+
/**
|
|
190
|
+
* makerAmount and takerAmount in six-decimal units, by the docs' rounding: a
|
|
191
|
+
* BUY gives USD and takes shares, a SELL the reverse. A limit order (GTC, GTD)
|
|
192
|
+
* and a market SELL (FOK, FAK) are sized in shares; a market BUY in USD to
|
|
193
|
+
* spend, at most `price` a share.
|
|
194
|
+
*/
|
|
195
|
+
function polymarketAmounts(side, price, tickSize, orderType, sizing) {
|
|
196
|
+
const tick = own(exports.POLYMARKET_TICKS, tickSize);
|
|
197
|
+
if (!tick)
|
|
198
|
+
throw new errors_js_1.RouteError(`tickSize: one of ${Object.keys(exports.POLYMARKET_TICKS).join(", ")}, the book's tick size`);
|
|
199
|
+
const [, sizeDec, amountDec] = tick;
|
|
200
|
+
const p = parseDec("price", price);
|
|
201
|
+
if (orderType === "FOK" || orderType === "FAK" ? side === "BUY" : false) {
|
|
202
|
+
if (sizing.amount === undefined || sizing.size !== undefined) {
|
|
203
|
+
throw new errors_js_1.RouteError("a market BUY (FOK, FAK) is sized by amount, the USD to spend, not size");
|
|
204
|
+
}
|
|
205
|
+
const maker = roundDown(sized("amount", sizing.amount), sizeDec);
|
|
206
|
+
if (maker.n === 0n)
|
|
207
|
+
throw new errors_js_1.RouteError(`amount ${sizing.amount} rounds to nothing at ${sizeDec} decimals`);
|
|
208
|
+
// maker / price, rounded up past the +4 decimals the docs round at, then by usd().
|
|
209
|
+
const taker = usd(divUp(maker, p, amountDec + 8), amountDec);
|
|
210
|
+
return { makerAmount: units(maker), takerAmount: units(taker) };
|
|
211
|
+
}
|
|
212
|
+
if (sizing.size === undefined || sizing.amount !== undefined) {
|
|
213
|
+
throw new errors_js_1.RouteError("this order is sized by size, the shares; amount is for a market BUY only");
|
|
214
|
+
}
|
|
215
|
+
const shares = roundDown(sized("size", sizing.size), sizeDec);
|
|
216
|
+
if (shares.n === 0n)
|
|
217
|
+
throw new errors_js_1.RouteError(`size ${sizing.size} rounds to nothing at ${sizeDec} decimals`);
|
|
218
|
+
const value = usd(mul(shares, p), amountDec);
|
|
219
|
+
return side === "BUY"
|
|
220
|
+
? { makerAmount: units(value), takerAmount: units(shares) }
|
|
221
|
+
: { makerAmount: units(shares), takerAmount: units(value) };
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* An unsigned Polymarket V2 order. Sign `typedData` (EIP-712, the `Order`
|
|
225
|
+
* primary type) with the signer's wallet, then post `postBody(signature,
|
|
226
|
+
* owner)` to the CLOB's POST /order with your own CLOB credentials. Nothing
|
|
227
|
+
* here was signed or sent.
|
|
228
|
+
*/
|
|
229
|
+
class PolymarketOrder {
|
|
230
|
+
typedData;
|
|
231
|
+
orderType;
|
|
232
|
+
expiration;
|
|
233
|
+
side;
|
|
234
|
+
venue = "polymarket";
|
|
235
|
+
constructor(typedData, orderType,
|
|
236
|
+
/** Unix seconds for a GTD order, 0 otherwise; not signed. */
|
|
237
|
+
expiration, side) {
|
|
238
|
+
this.typedData = typedData;
|
|
239
|
+
this.orderType = orderType;
|
|
240
|
+
this.expiration = expiration;
|
|
241
|
+
this.side = side;
|
|
242
|
+
}
|
|
243
|
+
/** The typed data as eth_signTypedData_v4 takes it: JSON, the EIP712Domain type included, integers as decimal strings. */
|
|
244
|
+
typedDataJson() {
|
|
245
|
+
const { domain, message } = this.typedData;
|
|
246
|
+
return JSON.stringify({
|
|
247
|
+
types: { EIP712Domain: exports.EIP712_DOMAIN_TYPE, Order: exports.POLYMARKET_ORDER_TYPE },
|
|
248
|
+
primaryType: "Order",
|
|
249
|
+
domain,
|
|
250
|
+
message: Object.fromEntries(Object.entries(message).map(([k, v]) => [k, typeof v === "bigint" ? v.toString() : v])),
|
|
251
|
+
});
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* The JSON body of POST /order (place-orders.md): the order with its
|
|
255
|
+
* signature, amounts and timestamp as strings, the salt a number, the side a
|
|
256
|
+
* word; `owner` is your CLOB API key's id. orderType and expiration are not
|
|
257
|
+
* part of what was signed.
|
|
258
|
+
*/
|
|
259
|
+
postBody(signature, owner, options = {}) {
|
|
260
|
+
if (typeof signature !== "string" || !SIGNATURE.test(signature)) {
|
|
261
|
+
throw new errors_js_1.RouteError("signature: a 0x-prefixed 65-byte signature over typedData");
|
|
262
|
+
}
|
|
263
|
+
if (typeof owner !== "string" || !owner)
|
|
264
|
+
throw new errors_js_1.RouteError("owner: your CLOB API key's id");
|
|
265
|
+
const m = this.typedData.message;
|
|
266
|
+
const body = {
|
|
267
|
+
deferExec: options.deferExec ?? false,
|
|
268
|
+
order: {
|
|
269
|
+
builder: m.builder,
|
|
270
|
+
expiration: String(this.expiration),
|
|
271
|
+
maker: m.maker,
|
|
272
|
+
makerAmount: m.makerAmount.toString(),
|
|
273
|
+
metadata: m.metadata,
|
|
274
|
+
salt: Number(m.salt),
|
|
275
|
+
side: this.side,
|
|
276
|
+
signature,
|
|
277
|
+
signatureType: m.signatureType,
|
|
278
|
+
signer: m.signer,
|
|
279
|
+
takerAmount: m.takerAmount.toString(),
|
|
280
|
+
timestamp: m.timestamp.toString(),
|
|
281
|
+
tokenId: m.tokenId.toString(),
|
|
282
|
+
},
|
|
283
|
+
orderType: this.orderType,
|
|
284
|
+
owner,
|
|
285
|
+
};
|
|
286
|
+
if (options.postOnly !== undefined)
|
|
287
|
+
body.postOnly = options.postOnly;
|
|
288
|
+
return body;
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
exports.PolymarketOrder = PolymarketOrder;
|
|
292
|
+
/** The fields each venue's order takes: anything else, a private key above all, is refused. */
|
|
293
|
+
exports.ROUTE_FIELDS = {
|
|
294
|
+
polymarket: [
|
|
295
|
+
"venue", "exchange", "tokenId", "side", "price", "tickSize", "maker", "size", "amount", "orderType",
|
|
296
|
+
"signatureType", "signer", "builder", "metadata", "expiration", "salt", "timestampMs",
|
|
297
|
+
],
|
|
298
|
+
kalshi_dflow: [
|
|
299
|
+
"venue", "inputMint", "outputMint", "amount", "userPublicKey", "slippageBps", "predictionMarketSlippageBps",
|
|
300
|
+
"platformFeeScale", "platformFeeBps", "platformFeeMode", "feeAccount", "baseUrl",
|
|
301
|
+
],
|
|
302
|
+
hyperliquid: route_hyperliquid_js_1.HYPERLIQUID_FIELDS,
|
|
303
|
+
};
|
|
304
|
+
function onlyFields(venue, input) {
|
|
305
|
+
const known = exports.ROUTE_FIELDS[venue];
|
|
306
|
+
const unknown = Object.keys(input).filter((k) => !known.includes(k));
|
|
307
|
+
if (unknown.length)
|
|
308
|
+
throw new errors_js_1.RouteError(`${venue}: unknown field ${unknown.join(", ")}; route() takes no key and nothing else`);
|
|
309
|
+
}
|
|
310
|
+
function randomSalt() {
|
|
311
|
+
const words = new Uint32Array(2);
|
|
312
|
+
globalThis.crypto.getRandomValues(words);
|
|
313
|
+
return ((BigInt(words[0] ?? 0) & 0x1fffffn) << 32n) | BigInt(words[1] ?? 0);
|
|
314
|
+
}
|
|
315
|
+
function polymarketOrder(input) {
|
|
316
|
+
onlyFields("polymarket", input);
|
|
317
|
+
const ex = own(exports.POLYMARKET_EXCHANGES, input.exchange);
|
|
318
|
+
if (!ex)
|
|
319
|
+
throw new errors_js_1.RouteError(`exchange: one of ${Object.keys(exports.POLYMARKET_EXCHANGES).join(", ")}, the book's exchange (no default)`);
|
|
320
|
+
const side = typeof input.side === "string" ? input.side.toUpperCase() : input.side;
|
|
321
|
+
if (side !== "BUY" && side !== "SELL")
|
|
322
|
+
throw new errors_js_1.RouteError("side: BUY or SELL");
|
|
323
|
+
const orderType = input.orderType ?? "GTC";
|
|
324
|
+
if (!ORDER_TYPES.includes(orderType))
|
|
325
|
+
throw new errors_js_1.RouteError(`orderType: one of ${ORDER_TYPES.join(", ")}`);
|
|
326
|
+
const tick = own(exports.POLYMARKET_TICKS, input.tickSize);
|
|
327
|
+
if (!tick)
|
|
328
|
+
throw new errors_js_1.RouteError(`tickSize: one of ${Object.keys(exports.POLYMARKET_TICKS).join(", ")}, the book's tick size`);
|
|
329
|
+
const tickDec = parseDec("tickSize", input.tickSize);
|
|
330
|
+
const price = parseDec("price", input.price);
|
|
331
|
+
const one = { n: 1n, s: 0 };
|
|
332
|
+
// On the tick: price / tick is a whole number.
|
|
333
|
+
const onTick = (price.n * pow10(tickDec.s)) % (tickDec.n * pow10(price.s)) === 0n;
|
|
334
|
+
if (!onTick || cmp(price, tickDec) < 0 || cmp(price, sub(one, tickDec)) > 0) {
|
|
335
|
+
throw new errors_js_1.RouteError(`price ${input.price} is not on the ${input.tickSize} tick between ${input.tickSize} and ${toString(sub(one, tickDec))}`);
|
|
336
|
+
}
|
|
337
|
+
const { makerAmount, takerAmount } = polymarketAmounts(side, input.price, input.tickSize, orderType, { size: input.size, amount: input.amount });
|
|
338
|
+
const sigInput = input.signatureType ?? "EOA";
|
|
339
|
+
const sigType = typeof sigInput === "string" ? exports.POLYMARKET_SIGNATURE_TYPES[sigInput] : sigInput;
|
|
340
|
+
if (sigType !== 0 && sigType !== 1 && sigType !== 2 && sigType !== 3) {
|
|
341
|
+
throw new errors_js_1.RouteError(`signatureType: one of ${Object.keys(exports.POLYMARKET_SIGNATURE_TYPES).join(", ")} or 0 to 3`);
|
|
342
|
+
}
|
|
343
|
+
if (sigType === 3) {
|
|
344
|
+
throw new errors_js_1.RouteError("signatureType POLY_1271 (a Deposit Wallet): its order is signed as an ERC-7739 TypedDataSign wrapper, which route() does not build; sign it with Polymarket's own client");
|
|
345
|
+
}
|
|
346
|
+
const maker = address("maker", input.maker);
|
|
347
|
+
let signer;
|
|
348
|
+
if (input.signer === undefined) {
|
|
349
|
+
if (sigType !== 0)
|
|
350
|
+
throw new errors_js_1.RouteError("signer: the address that owns the proxy or Safe and signs (required unless EOA)");
|
|
351
|
+
signer = maker;
|
|
352
|
+
}
|
|
353
|
+
else {
|
|
354
|
+
signer = address("signer", input.signer);
|
|
355
|
+
}
|
|
356
|
+
if (sigType === 0 && signer.toLowerCase() !== maker.toLowerCase()) {
|
|
357
|
+
throw new errors_js_1.RouteError("an EOA order is signed by its maker: signer must equal maker");
|
|
358
|
+
}
|
|
359
|
+
const token = typeof input.tokenId === "bigint" ? input.tokenId.toString() : input.tokenId;
|
|
360
|
+
if (typeof token !== "string" || !/^\d+$/.test(token) || BigInt(token) >= 2n ** 256n) {
|
|
361
|
+
throw new errors_js_1.RouteError("tokenId: the outcome's asset id, a decimal uint256");
|
|
362
|
+
}
|
|
363
|
+
const builder = input.builder === undefined ? exports.ZERO_BYTES32 : bytes32("builder", input.builder);
|
|
364
|
+
const metadata = input.metadata === undefined ? exports.ZERO_BYTES32 : bytes32("metadata", input.metadata);
|
|
365
|
+
const ts = input.timestampMs ?? Date.now();
|
|
366
|
+
if (!Number.isSafeInteger(ts) || ts <= 0)
|
|
367
|
+
throw new errors_js_1.RouteError("timestampMs: Unix milliseconds");
|
|
368
|
+
let expiration = 0;
|
|
369
|
+
if (orderType === "GTD") {
|
|
370
|
+
if (!Number.isSafeInteger(input.expiration) || (input.expiration ?? 0) < Math.floor(ts / 1000) + exports.POLYMARKET_GTD_MIN_SECONDS) {
|
|
371
|
+
throw new errors_js_1.RouteError("expiration: a GTD order's Unix seconds, at least three minutes after the order's timestamp");
|
|
372
|
+
}
|
|
373
|
+
expiration = input.expiration;
|
|
374
|
+
}
|
|
375
|
+
else if (input.expiration !== undefined && input.expiration !== 0) {
|
|
376
|
+
throw new errors_js_1.RouteError(`expiration: only a GTD order has one; a ${orderType} order sends 0`);
|
|
377
|
+
}
|
|
378
|
+
const salt = input.salt === undefined ? randomSalt() : wholeNumber("salt", input.salt, BigInt(exports.MAX_SAFE_SALT));
|
|
379
|
+
return new PolymarketOrder({
|
|
380
|
+
domain: { name: exports.POLYMARKET_DOMAIN_NAME, version: ex.version, chainId: exports.POLYGON_CHAIN_ID, verifyingContract: ex.verifyingContract },
|
|
381
|
+
types: { Order: exports.POLYMARKET_ORDER_TYPE },
|
|
382
|
+
primaryType: "Order",
|
|
383
|
+
message: {
|
|
384
|
+
salt,
|
|
385
|
+
maker,
|
|
386
|
+
signer,
|
|
387
|
+
tokenId: BigInt(token),
|
|
388
|
+
makerAmount,
|
|
389
|
+
takerAmount,
|
|
390
|
+
side: exports.POLYMARKET_SIDES[side],
|
|
391
|
+
signatureType: sigType,
|
|
392
|
+
timestamp: BigInt(ts),
|
|
393
|
+
metadata,
|
|
394
|
+
builder,
|
|
395
|
+
},
|
|
396
|
+
}, orderType, expiration, side);
|
|
397
|
+
}
|
|
398
|
+
// --- DFlow --------------------------------------------------------------------
|
|
399
|
+
/**
|
|
400
|
+
* The Trading API that returns the unsigned transaction: GET /order on
|
|
401
|
+
* https://quote-api.dflow.net (pond.dflow.net/get-started/endpoints.md), with
|
|
402
|
+
* the developer's own key in the x-api-key header ("All calls to the
|
|
403
|
+
* production endpoints must use an API key", pond.dflow.net/get-started/api-key.md).
|
|
404
|
+
*/
|
|
405
|
+
exports.DFLOW_TRADING_API = "https://quote-api.dflow.net";
|
|
406
|
+
exports.DFLOW_API_KEY_HEADER = "x-api-key";
|
|
407
|
+
/**
|
|
408
|
+
* platformFeeScale: "Optional platform fee scale for World prediction market
|
|
409
|
+
* swaps and async prediction market swaps, with 3 decimals ... Must be >= 0 and
|
|
410
|
+
* < 1000. For example, a value of 50 means 0.050." platformFeeBps: a fixed fee
|
|
411
|
+
* in basis points, for spot trades (pond.dflow.net/spot/trading/platform-fees.md).
|
|
412
|
+
*/
|
|
413
|
+
exports.DFLOW_FEE_SCALE_MAX = 999;
|
|
414
|
+
exports.DFLOW_FEE_BPS_MAX = 10_000;
|
|
415
|
+
const DFLOW_FEE_MODES = ["outputMint", "inputMint"];
|
|
416
|
+
const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
|
|
417
|
+
function solanaAddress(name, value) {
|
|
418
|
+
if (typeof value !== "string" || value.length < 32 || value.length > 44 || [...value].some((c) => !BASE58.includes(c))) {
|
|
419
|
+
throw new errors_js_1.RouteError(`${name}: ${JSON.stringify(value)} is not a base58 Solana address`);
|
|
420
|
+
}
|
|
421
|
+
let n = 0n;
|
|
422
|
+
for (const c of value)
|
|
423
|
+
n = n * 58n + BigInt(BASE58.indexOf(c));
|
|
424
|
+
let bytes = n === 0n ? 0 : Math.ceil(n.toString(16).length / 2);
|
|
425
|
+
bytes += value.length - value.replace(/^1+/, "").length;
|
|
426
|
+
if (bytes !== 32)
|
|
427
|
+
throw new errors_js_1.RouteError(`${name}: ${JSON.stringify(value)} does not decode to 32 bytes`);
|
|
428
|
+
return value;
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* The request that returns an unsigned DFlow transaction: GET `url` with
|
|
432
|
+
* `params` and your own DFlow key in the x-api-key header. The response's
|
|
433
|
+
* `transaction` (base64) is for your user to sign and submit. Nothing was
|
|
434
|
+
* sent: route() never calls DFlow.
|
|
435
|
+
*/
|
|
436
|
+
class DFlowOrderRequest {
|
|
437
|
+
url;
|
|
438
|
+
params;
|
|
439
|
+
venue = "kalshi_dflow";
|
|
440
|
+
apiKeyHeader = exports.DFLOW_API_KEY_HEADER;
|
|
441
|
+
constructor(url, params) {
|
|
442
|
+
this.url = url;
|
|
443
|
+
this.params = params;
|
|
444
|
+
}
|
|
445
|
+
get fullUrl() {
|
|
446
|
+
return `${this.url}?${new URLSearchParams(this.params).toString()}`;
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
exports.DFlowOrderRequest = DFlowOrderRequest;
|
|
450
|
+
function intIn(name, value, max) {
|
|
451
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > max) {
|
|
452
|
+
throw new errors_js_1.RouteError(`${name}: an integer from 0 to ${max}`);
|
|
453
|
+
}
|
|
454
|
+
return value;
|
|
455
|
+
}
|
|
456
|
+
function dflowOrder(input) {
|
|
457
|
+
onlyFields("kalshi_dflow", input);
|
|
458
|
+
const params = {
|
|
459
|
+
inputMint: solanaAddress("inputMint", input.inputMint),
|
|
460
|
+
outputMint: solanaAddress("outputMint", input.outputMint),
|
|
461
|
+
};
|
|
462
|
+
const amount = input.amount;
|
|
463
|
+
if (!(typeof amount === "bigint" ? amount > 0n : Number.isSafeInteger(amount) && amount > 0)) {
|
|
464
|
+
throw new errors_js_1.RouteError("amount: a positive integer, in the input mint's base units");
|
|
465
|
+
}
|
|
466
|
+
params.amount = amount.toString();
|
|
467
|
+
params.userPublicKey = solanaAddress("userPublicKey", input.userPublicKey);
|
|
468
|
+
if (input.slippageBps !== undefined) {
|
|
469
|
+
if (input.slippageBps !== "auto")
|
|
470
|
+
intIn('slippageBps (or "auto")', input.slippageBps, 65535);
|
|
471
|
+
params.slippageBps = String(input.slippageBps);
|
|
472
|
+
}
|
|
473
|
+
if (input.predictionMarketSlippageBps !== undefined) {
|
|
474
|
+
params.predictionMarketSlippageBps = String(intIn("predictionMarketSlippageBps", input.predictionMarketSlippageBps, 65535));
|
|
475
|
+
}
|
|
476
|
+
if (input.platformFeeScale !== undefined && input.platformFeeBps !== undefined) {
|
|
477
|
+
throw new errors_js_1.RouteError("platformFeeScale (a prediction market swap) or platformFeeBps (spot), not both");
|
|
478
|
+
}
|
|
479
|
+
let fee = 0;
|
|
480
|
+
if (input.platformFeeScale !== undefined) {
|
|
481
|
+
fee = intIn("platformFeeScale (in thousandths, 50 is 0.050)", input.platformFeeScale, exports.DFLOW_FEE_SCALE_MAX);
|
|
482
|
+
if (fee)
|
|
483
|
+
params.platformFeeScale = String(fee);
|
|
484
|
+
}
|
|
485
|
+
if (input.platformFeeBps !== undefined) {
|
|
486
|
+
fee = intIn("platformFeeBps", input.platformFeeBps, exports.DFLOW_FEE_BPS_MAX);
|
|
487
|
+
if (fee)
|
|
488
|
+
params.platformFeeBps = String(fee);
|
|
489
|
+
}
|
|
490
|
+
if (fee && input.feeAccount === undefined) {
|
|
491
|
+
throw new errors_js_1.RouteError("feeAccount: your token account for the fee mint; DFlow requires it with a fee");
|
|
492
|
+
}
|
|
493
|
+
if (!fee && input.feeAccount !== undefined) {
|
|
494
|
+
throw new errors_js_1.RouteError("feeAccount without a fee: DFlow collects nothing, so send neither");
|
|
495
|
+
}
|
|
496
|
+
if (input.feeAccount !== undefined)
|
|
497
|
+
params.feeAccount = solanaAddress("feeAccount", input.feeAccount);
|
|
498
|
+
if (input.platformFeeMode !== undefined) {
|
|
499
|
+
if (!DFLOW_FEE_MODES.includes(input.platformFeeMode))
|
|
500
|
+
throw new errors_js_1.RouteError(`platformFeeMode: one of ${DFLOW_FEE_MODES.join(", ")}`);
|
|
501
|
+
params.platformFeeMode = input.platformFeeMode;
|
|
502
|
+
}
|
|
503
|
+
const base = input.baseUrl ?? exports.DFLOW_TRADING_API;
|
|
504
|
+
if (typeof base !== "string" || !base.startsWith("https://"))
|
|
505
|
+
throw new errors_js_1.RouteError("baseUrl: an https URL of DFlow's Trading API");
|
|
506
|
+
return new DFlowOrderRequest(`${base.replace(/\/+$/, "")}/order`, params);
|
|
507
|
+
}
|
|
508
|
+
function route(order) {
|
|
509
|
+
if (order.venue === "polymarket")
|
|
510
|
+
return polymarketOrder(order);
|
|
511
|
+
if (order.venue === "kalshi_dflow")
|
|
512
|
+
return dflowOrder(order);
|
|
513
|
+
if (order.venue === "hyperliquid")
|
|
514
|
+
return (0, route_hyperliquid_js_1.hyperliquidOrder)(order);
|
|
515
|
+
throw new errors_js_1.RouteError(`venue: one of ${Object.keys(exports.ROUTE_FIELDS).join(", ")}`);
|
|
516
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
export declare const FEED_PATH = "/v1/feed";
|
|
2
|
+
/** A server message, as docs/public/feed.md gives it. */
|
|
3
|
+
export type FeedMessage = {
|
|
4
|
+
op: string;
|
|
5
|
+
[field: string]: unknown;
|
|
6
|
+
};
|
|
7
|
+
/**
|
|
8
|
+
* What the stream needs of a WebSocket: the WHATWG interface. The handlers'
|
|
9
|
+
* events are typed loosely so the platform's WebSocket and the ws package's
|
|
10
|
+
* both fit as they are; the stream reads data, code and reason alone.
|
|
11
|
+
*/
|
|
12
|
+
export interface FeedSocket {
|
|
13
|
+
send(data: string): void;
|
|
14
|
+
close(code?: number, reason?: string): void;
|
|
15
|
+
onopen: ((ev: any) => void) | null;
|
|
16
|
+
onmessage: ((ev: any) => void) | null;
|
|
17
|
+
onclose: ((ev: any) => void) | null;
|
|
18
|
+
onerror: ((ev: any) => void) | null;
|
|
19
|
+
}
|
|
20
|
+
export type FeedSocketConstructor = new (url: string) => FeedSocket;
|
|
21
|
+
export interface StreamOptions {
|
|
22
|
+
topics: string[];
|
|
23
|
+
venues?: string[];
|
|
24
|
+
markets?: {
|
|
25
|
+
venue: string;
|
|
26
|
+
market_id: string;
|
|
27
|
+
}[];
|
|
28
|
+
events?: string[];
|
|
29
|
+
/** A seq kept earlier: the feed replays the events after it. */
|
|
30
|
+
resumeFrom?: number;
|
|
31
|
+
/** Failed connections in a row before the stream gives up; none by default. */
|
|
32
|
+
maxReconnects?: number;
|
|
33
|
+
/** A WebSocket constructor, where the platform has none (Node 20). */
|
|
34
|
+
WebSocket?: FeedSocketConstructor;
|
|
35
|
+
}
|
|
36
|
+
/** Messages received and not yet taken by the loop, at most. */
|
|
37
|
+
export declare const MAX_BUFFERED = 10000;
|
|
38
|
+
/** How many trade identities are remembered. */
|
|
39
|
+
export declare const DEDUPE_TRADES = 100000;
|
|
40
|
+
/** The feed's WebSocket URL for an API base URL: https to wss, http to ws. */
|
|
41
|
+
export declare function feedUrl(baseUrl: string): string;
|
|
42
|
+
/** One subscription to the live feed, across as many connections as it takes. */
|
|
43
|
+
export declare class Stream implements AsyncIterable<FeedMessage> {
|
|
44
|
+
#private;
|
|
45
|
+
readonly url: string;
|
|
46
|
+
/** A sleep for tests; none is a timer close() clears. */
|
|
47
|
+
private readonly sleep?;
|
|
48
|
+
private readonly jitter;
|
|
49
|
+
private readonly now;
|
|
50
|
+
/** The seq of the last event yielded, or the resumeFrom given. */
|
|
51
|
+
lastSeq: number | undefined;
|
|
52
|
+
hello: FeedMessage | undefined;
|
|
53
|
+
subscribed: FeedMessage | undefined;
|
|
54
|
+
private readonly subscription;
|
|
55
|
+
private readonly seen;
|
|
56
|
+
private socket;
|
|
57
|
+
private closed;
|
|
58
|
+
private wake;
|
|
59
|
+
/** Where to resume when no event was yielded since: the first hello's seq, raised by a close reason's or a resync's. */
|
|
60
|
+
private floor;
|
|
61
|
+
private failures;
|
|
62
|
+
/** A connection of this stream was subscribed once: a connection limit after it may be its own moved connection. */
|
|
63
|
+
private worked;
|
|
64
|
+
private limitedSince;
|
|
65
|
+
private readonly closedSignal;
|
|
66
|
+
/** Ends the timer of a wait in progress (pause), at once. */
|
|
67
|
+
private endPause;
|
|
68
|
+
private signalClosed;
|
|
69
|
+
constructor(url: string, apiKey: string, options: StreamOptions,
|
|
70
|
+
/** A sleep for tests; none is a timer close() clears. */
|
|
71
|
+
sleep?: ((seconds: number) => Promise<void>) | undefined, jitter?: () => number, now?: () => number);
|
|
72
|
+
private readonly WS;
|
|
73
|
+
private readonly maxReconnects;
|
|
74
|
+
/** Ends the stream: the connection closes, a wait ends, and iteration stops. */
|
|
75
|
+
close(): void;
|
|
76
|
+
[Symbol.asyncIterator](): AsyncIterator<FeedMessage>;
|
|
77
|
+
/**
|
|
78
|
+
* Waits seconds, or less when close() runs. With no sleep given, the wait
|
|
79
|
+
* is a timer close() clears, so a closed stream keeps no timer pending
|
|
80
|
+
* and the process can exit.
|
|
81
|
+
*/
|
|
82
|
+
private pause;
|
|
83
|
+
private push;
|
|
84
|
+
private next;
|
|
85
|
+
private wait;
|
|
86
|
+
/**
|
|
87
|
+
* Where the stream would resume: the last seq yielded, or its position
|
|
88
|
+
* before its first event or past a resync, the later of the two. Keep
|
|
89
|
+
* this one, not lastSeq, to go on later with sk.stream({ ..., resumeFrom }).
|
|
90
|
+
*/
|
|
91
|
+
get resumeFrom(): number | undefined;
|
|
92
|
+
private raiseFloor;
|
|
93
|
+
/** Whether a connection limit is tried again: on a reconnect, for LIMIT_RETRY after the first refusal. */
|
|
94
|
+
private limitRetry;
|
|
95
|
+
private sendSubscribe;
|
|
96
|
+
private session;
|
|
97
|
+
private event;
|
|
98
|
+
private remember;
|
|
99
|
+
}
|