skewtape 0.1.5 → 0.1.7

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.
Files changed (46) hide show
  1. package/README.md +4 -13
  2. package/dist/cjs/client.d.ts +37 -6
  3. package/dist/cjs/client.js +42 -13
  4. package/dist/cjs/fees.d.ts +4 -2
  5. package/dist/cjs/fees.js +48 -8
  6. package/dist/cjs/index.d.ts +2 -2
  7. package/dist/cjs/index.js +2 -5
  8. package/dist/cjs/kalshi.d.ts +3 -3
  9. package/dist/cjs/kalshi.js +4 -4
  10. package/dist/cjs/paginated.d.ts +1 -1
  11. package/dist/cjs/paginated.js +1 -1
  12. package/dist/cjs/quote-math.js +4 -1
  13. package/dist/cjs/quote.d.ts +1 -12
  14. package/dist/cjs/quote.js +1 -16
  15. package/dist/cjs/route.d.ts +6 -65
  16. package/dist/cjs/route.js +3 -120
  17. package/dist/cjs/version.d.ts +1 -1
  18. package/dist/cjs/version.js +1 -1
  19. package/dist/esm/client.d.ts +37 -6
  20. package/dist/esm/client.js +42 -13
  21. package/dist/esm/fees.d.ts +4 -2
  22. package/dist/esm/fees.js +48 -8
  23. package/dist/esm/index.d.ts +2 -2
  24. package/dist/esm/index.js +2 -2
  25. package/dist/esm/kalshi.d.ts +3 -3
  26. package/dist/esm/kalshi.js +4 -4
  27. package/dist/esm/paginated.d.ts +1 -1
  28. package/dist/esm/paginated.js +1 -1
  29. package/dist/esm/quote-math.js +4 -1
  30. package/dist/esm/quote.d.ts +1 -12
  31. package/dist/esm/quote.js +0 -14
  32. package/dist/esm/route.d.ts +6 -65
  33. package/dist/esm/route.js +2 -117
  34. package/dist/esm/version.d.ts +1 -1
  35. package/dist/esm/version.js +1 -1
  36. package/package.json +1 -1
  37. package/src/client.ts +72 -21
  38. package/src/fees.ts +47 -7
  39. package/src/generated/schema.d.ts +388 -34
  40. package/src/index.ts +0 -4
  41. package/src/kalshi.ts +4 -4
  42. package/src/paginated.ts +1 -1
  43. package/src/quote-math.ts +3 -1
  44. package/src/quote.ts +1 -16
  45. package/src/route.ts +7 -147
  46. package/src/version.ts +1 -1
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * route() builds and checks an order, and stops there: it never signs, never
6
6
  * sends, never takes a private key, and needs no Skewtape key. Every code and
7
- * fee it carries is the developer's own: the Polymarket builder code, the
8
- * DFlow fee account and fee. Omitting them sends none, and no Skewtape value
7
+ * fee it carries is the developer's own: the Polymarket builder code and the
8
+ * Hyperliquid builder fee. Omitting them sends none, and no Skewtape value
9
9
  * exists in this package (a test scans it). The developer is responsible for
10
10
  * their users: who may trade where, and under which terms (sk.geoblock helps
11
11
  * with Polymarket's).
@@ -225,73 +225,14 @@ export interface PolymarketRoute {
225
225
  /** The fields each venue's order takes: anything else, a private key above all, is refused. */
226
226
  export declare const ROUTE_FIELDS: {
227
227
  readonly polymarket: readonly ["venue", "exchange", "tokenId", "side", "price", "tickSize", "maker", "size", "amount", "orderType", "signatureType", "signer", "builder", "metadata", "expiration", "salt", "timestampMs"];
228
- readonly kalshi_dflow: readonly ["venue", "inputMint", "outputMint", "amount", "userPublicKey", "slippageBps", "predictionMarketSlippageBps", "platformFeeScale", "platformFeeBps", "platformFeeMode", "feeAccount", "baseUrl"];
229
228
  readonly hyperliquid: readonly ["venue", "outcome", "side", "isBuy", "price", "size", "tif", "reduceOnly", "cloid", "builder", "builderFee", "szDecimals", "nonce", "vaultAddress", "expiresAfter", "mainnet"];
230
229
  };
231
230
  export declare function polymarketOrder(input: PolymarketRoute): PolymarketOrder;
231
+ export type RouteInput = PolymarketRoute | HyperliquidRoute;
232
232
  /**
233
- * The Trading API that returns the unsigned transaction: GET /order on
234
- * https://quote-api.dflow.net (pond.dflow.net/get-started/endpoints.md), with
235
- * the developer's own key in the x-api-key header ("All calls to the
236
- * production endpoints must use an API key", pond.dflow.net/get-started/api-key.md).
237
- */
238
- export declare const DFLOW_TRADING_API = "https://quote-api.dflow.net";
239
- export declare const DFLOW_API_KEY_HEADER = "x-api-key";
240
- /**
241
- * platformFeeScale: "Optional platform fee scale for World prediction market
242
- * swaps and async prediction market swaps, with 3 decimals ... Must be >= 0 and
243
- * < 1000. For example, a value of 50 means 0.050." platformFeeBps: a fixed fee
244
- * in basis points, for spot trades (pond.dflow.net/spot/trading/platform-fees.md).
245
- */
246
- export declare const DFLOW_FEE_SCALE_MAX = 999;
247
- export declare const DFLOW_FEE_BPS_MAX = 10000;
248
- /**
249
- * The request that returns an unsigned DFlow transaction: GET `url` with
250
- * `params` and your own DFlow key in the x-api-key header. The response's
251
- * `transaction` (base64) is for your user to sign and submit. Nothing was
252
- * sent: route() never calls DFlow.
253
- */
254
- export declare class DFlowOrderRequest {
255
- readonly url: string;
256
- readonly params: Readonly<Record<string, string>>;
257
- readonly venue: "kalshi_dflow";
258
- readonly apiKeyHeader = "x-api-key";
259
- constructor(url: string, params: Readonly<Record<string, string>>);
260
- get fullUrl(): string;
261
- }
262
- /**
263
- * A DFlow order to build, for tokenized Kalshi outcome tokens or any DFlow
264
- * trade, carrying the developer's own fee (ARCHITECTURE 13.3). amount: the
265
- * input amount in the input mint's base units. userPublicKey: your user's
266
- * wallet, so the response carries the transaction to sign. platformFeeScale:
267
- * your fee for a prediction market swap, 0 to 999 in thousandths (DFlow's
268
- * platformFeeScale; its docs give no formula). Or platformFeeBps: a fixed fee
269
- * in basis points, DFlow's spot fee. Either needs feeAccount, your token
270
- * account for the fee mint (the stablecoin for a prediction market swap),
271
- * which must exist before the trade. With no fee, none is sent.
272
- */
273
- export interface DFlowRoute {
274
- venue: "kalshi_dflow";
275
- inputMint: string;
276
- outputMint: string;
277
- amount: number | bigint;
278
- userPublicKey: string;
279
- slippageBps?: number | "auto";
280
- predictionMarketSlippageBps?: number;
281
- platformFeeScale?: number;
282
- platformFeeBps?: number;
283
- platformFeeMode?: "outputMint" | "inputMint";
284
- feeAccount?: string;
285
- baseUrl?: string;
286
- }
287
- export declare function dflowOrder(input: DFlowRoute): DFlowOrderRequest;
288
- export type RouteInput = PolymarketRoute | DFlowRoute | HyperliquidRoute;
289
- /**
290
- * An unsigned order for `venue` ("polymarket", "kalshi_dflow" or
291
- * "hyperliquid", a HIP-4 outcome), with the developer's own builder code or
292
- * fee. It never signs, never sends, and takes no private key.
233
+ * An unsigned order for `venue` ("polymarket" or "hyperliquid", a HIP-4
234
+ * outcome), with the developer's own builder code or fee. It never signs, never sends, and takes no private key.
293
235
  */
294
236
  export declare function route(order: PolymarketRoute): PolymarketOrder;
295
- export declare function route(order: DFlowRoute): DFlowOrderRequest;
296
237
  export declare function route(order: HyperliquidRoute): HyperliquidOrder;
297
- export declare function route(order: RouteInput): PolymarketOrder | DFlowOrderRequest | HyperliquidOrder;
238
+ export declare function route(order: RouteInput): PolymarketOrder | HyperliquidOrder;
package/dist/esm/route.js CHANGED
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * route() builds and checks an order, and stops there: it never signs, never
6
6
  * sends, never takes a private key, and needs no Skewtape key. Every code and
7
- * fee it carries is the developer's own: the Polymarket builder code, the
8
- * DFlow fee account and fee. Omitting them sends none, and no Skewtape value
7
+ * fee it carries is the developer's own: the Polymarket builder code and the
8
+ * Hyperliquid builder fee. Omitting them sends none, and no Skewtape value
9
9
  * exists in this package (a test scans it). The developer is responsible for
10
10
  * their users: who may trade where, and under which terms (sk.geoblock helps
11
11
  * with Polymarket's).
@@ -287,10 +287,6 @@ export const ROUTE_FIELDS = {
287
287
  "venue", "exchange", "tokenId", "side", "price", "tickSize", "maker", "size", "amount", "orderType",
288
288
  "signatureType", "signer", "builder", "metadata", "expiration", "salt", "timestampMs",
289
289
  ],
290
- kalshi_dflow: [
291
- "venue", "inputMint", "outputMint", "amount", "userPublicKey", "slippageBps", "predictionMarketSlippageBps",
292
- "platformFeeScale", "platformFeeBps", "platformFeeMode", "feeAccount", "baseUrl",
293
- ],
294
290
  hyperliquid: HYPERLIQUID_FIELDS,
295
291
  };
296
292
  function onlyFields(venue, input) {
@@ -387,120 +383,9 @@ export function polymarketOrder(input) {
387
383
  },
388
384
  }, orderType, expiration, side);
389
385
  }
390
- // --- DFlow --------------------------------------------------------------------
391
- /**
392
- * The Trading API that returns the unsigned transaction: GET /order on
393
- * https://quote-api.dflow.net (pond.dflow.net/get-started/endpoints.md), with
394
- * the developer's own key in the x-api-key header ("All calls to the
395
- * production endpoints must use an API key", pond.dflow.net/get-started/api-key.md).
396
- */
397
- export const DFLOW_TRADING_API = "https://quote-api.dflow.net";
398
- export const DFLOW_API_KEY_HEADER = "x-api-key";
399
- /**
400
- * platformFeeScale: "Optional platform fee scale for World prediction market
401
- * swaps and async prediction market swaps, with 3 decimals ... Must be >= 0 and
402
- * < 1000. For example, a value of 50 means 0.050." platformFeeBps: a fixed fee
403
- * in basis points, for spot trades (pond.dflow.net/spot/trading/platform-fees.md).
404
- */
405
- export const DFLOW_FEE_SCALE_MAX = 999;
406
- export const DFLOW_FEE_BPS_MAX = 10_000;
407
- const DFLOW_FEE_MODES = ["outputMint", "inputMint"];
408
- const BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
409
- function solanaAddress(name, value) {
410
- if (typeof value !== "string" || value.length < 32 || value.length > 44 || [...value].some((c) => !BASE58.includes(c))) {
411
- throw new RouteError(`${name}: ${JSON.stringify(value)} is not a base58 Solana address`);
412
- }
413
- let n = 0n;
414
- for (const c of value)
415
- n = n * 58n + BigInt(BASE58.indexOf(c));
416
- let bytes = n === 0n ? 0 : Math.ceil(n.toString(16).length / 2);
417
- bytes += value.length - value.replace(/^1+/, "").length;
418
- if (bytes !== 32)
419
- throw new RouteError(`${name}: ${JSON.stringify(value)} does not decode to 32 bytes`);
420
- return value;
421
- }
422
- /**
423
- * The request that returns an unsigned DFlow transaction: GET `url` with
424
- * `params` and your own DFlow key in the x-api-key header. The response's
425
- * `transaction` (base64) is for your user to sign and submit. Nothing was
426
- * sent: route() never calls DFlow.
427
- */
428
- export class DFlowOrderRequest {
429
- url;
430
- params;
431
- venue = "kalshi_dflow";
432
- apiKeyHeader = DFLOW_API_KEY_HEADER;
433
- constructor(url, params) {
434
- this.url = url;
435
- this.params = params;
436
- }
437
- get fullUrl() {
438
- return `${this.url}?${new URLSearchParams(this.params).toString()}`;
439
- }
440
- }
441
- function intIn(name, value, max) {
442
- if (typeof value !== "number" || !Number.isInteger(value) || value < 0 || value > max) {
443
- throw new RouteError(`${name}: an integer from 0 to ${max}`);
444
- }
445
- return value;
446
- }
447
- export function dflowOrder(input) {
448
- onlyFields("kalshi_dflow", input);
449
- const params = {
450
- inputMint: solanaAddress("inputMint", input.inputMint),
451
- outputMint: solanaAddress("outputMint", input.outputMint),
452
- };
453
- const amount = input.amount;
454
- if (!(typeof amount === "bigint" ? amount > 0n : Number.isSafeInteger(amount) && amount > 0)) {
455
- throw new RouteError("amount: a positive integer, in the input mint's base units");
456
- }
457
- params.amount = amount.toString();
458
- params.userPublicKey = solanaAddress("userPublicKey", input.userPublicKey);
459
- if (input.slippageBps !== undefined) {
460
- if (input.slippageBps !== "auto")
461
- intIn('slippageBps (or "auto")', input.slippageBps, 65535);
462
- params.slippageBps = String(input.slippageBps);
463
- }
464
- if (input.predictionMarketSlippageBps !== undefined) {
465
- params.predictionMarketSlippageBps = String(intIn("predictionMarketSlippageBps", input.predictionMarketSlippageBps, 65535));
466
- }
467
- if (input.platformFeeScale !== undefined && input.platformFeeBps !== undefined) {
468
- throw new RouteError("platformFeeScale (a prediction market swap) or platformFeeBps (spot), not both");
469
- }
470
- let fee = 0;
471
- if (input.platformFeeScale !== undefined) {
472
- fee = intIn("platformFeeScale (in thousandths, 50 is 0.050)", input.platformFeeScale, DFLOW_FEE_SCALE_MAX);
473
- if (fee)
474
- params.platformFeeScale = String(fee);
475
- }
476
- if (input.platformFeeBps !== undefined) {
477
- fee = intIn("platformFeeBps", input.platformFeeBps, DFLOW_FEE_BPS_MAX);
478
- if (fee)
479
- params.platformFeeBps = String(fee);
480
- }
481
- if (fee && input.feeAccount === undefined) {
482
- throw new RouteError("feeAccount: your token account for the fee mint; DFlow requires it with a fee");
483
- }
484
- if (!fee && input.feeAccount !== undefined) {
485
- throw new RouteError("feeAccount without a fee: DFlow collects nothing, so send neither");
486
- }
487
- if (input.feeAccount !== undefined)
488
- params.feeAccount = solanaAddress("feeAccount", input.feeAccount);
489
- if (input.platformFeeMode !== undefined) {
490
- if (!DFLOW_FEE_MODES.includes(input.platformFeeMode))
491
- throw new RouteError(`platformFeeMode: one of ${DFLOW_FEE_MODES.join(", ")}`);
492
- params.platformFeeMode = input.platformFeeMode;
493
- }
494
- const base = input.baseUrl ?? DFLOW_TRADING_API;
495
- if (typeof base !== "string" || !base.startsWith("https://"))
496
- throw new RouteError("baseUrl: an https URL of DFlow's Trading API");
497
- return new DFlowOrderRequest(`${base.replace(/\/+$/, "")}/order`, params);
498
- }
499
386
  export function route(order) {
500
387
  if (order.venue === "polymarket")
501
388
  return polymarketOrder(order);
502
- if (order.venue === "kalshi_dflow")
503
- return dflowOrder(order);
504
389
  if (order.venue === "hyperliquid")
505
390
  return hyperliquidOrder(order);
506
391
  throw new RouteError(`venue: one of ${Object.keys(ROUTE_FIELDS).join(", ")}`);
@@ -3,4 +3,4 @@
3
3
  * patch is this package's own (ADR-0015). release-sdks.yml sets package.json
4
4
  * from the api/vX.Y.Z tag; keep this constant equal to it.
5
5
  */
6
- export declare const VERSION = "0.1.5";
6
+ export declare const VERSION = "0.1.7";
@@ -3,4 +3,4 @@
3
3
  * patch is this package's own (ADR-0015). release-sdks.yml sets package.json
4
4
  * from the api/vX.Y.Z tag; keep this constant equal to it.
5
5
  */
6
- export const VERSION = "0.1.5";
6
+ export const VERSION = "0.1.7";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "skewtape",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "description": "Skewtape API client: prediction-market data across venues in one schema, with matched events.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/client.ts CHANGED
@@ -78,11 +78,26 @@ export interface MarketsOptions {
78
78
  venue?: string;
79
79
  marketId?: string[];
80
80
  updatedSince?: Date | string;
81
+ /** Only markets in one of these statuses. */
82
+ status?: Array<"open" | "closed" | "resolved" | "voided">;
83
+ /** Only markets whose category label is exactly one of these (at most 20). */
84
+ category?: string[];
85
+ /** Only the markets of this venue event; needs venue, since event ids are per venue. */
86
+ venueEventId?: string;
87
+ /** Only markets whose close_at is at or after this time. */
88
+ closeAfter?: Date | string;
89
+ /** Only markets whose close_at is before this time. */
90
+ closeBefore?: Date | string;
91
+ /** Keyword search on the question, 1 to 100 characters. */
92
+ q?: string;
93
+ /** venue (the default), close_at, updated_at or first_seen_at. */
94
+ sort?: "venue" | "close_at" | "updated_at" | "first_seen_at";
95
+ /** asc (the default) or desc. */
96
+ order?: "asc" | "desc";
81
97
  /**
82
- * Keeps the markets whose status is (or is not) resolved; applied on the
83
- * client, so every page is still fetched, each a metered call: pass a venue
84
- * or marketId with it. TODO(decision): a server-side status filter on
85
- * /v1/markets would make it one request per page of results.
98
+ * true is status ["resolved"], false the three others (open, closed,
99
+ * voided): filtered on the server like status, so one request per page of
100
+ * results. Pass resolved or status, not both (a ConfigurationError).
86
101
  */
87
102
  resolved?: boolean;
88
103
  limit?: number;
@@ -93,6 +108,10 @@ export interface EventsOptions {
93
108
  resolutionEqual?: boolean;
94
109
  venue?: string;
95
110
  status?: "approved" | "needs_rereview" | "retired";
111
+ /** event_id (the default) or published_at. */
112
+ sort?: "event_id" | "published_at";
113
+ /** asc (the default) or desc. */
114
+ order?: "asc" | "desc";
96
115
  limit?: number;
97
116
  }
98
117
 
@@ -123,6 +142,14 @@ export interface ResolutionsOptions {
123
142
  /** Up to 100 market ids. */
124
143
  marketId?: string[];
125
144
  createdSince?: Date | string;
145
+ /** Only events whose resolved_at is at or after this time. */
146
+ resolvedAfter?: Date | string;
147
+ /** Only events whose resolved_at is before this time. */
148
+ resolvedBefore?: Date | string;
149
+ /** venue (the default) or resolved_at. */
150
+ sort?: "venue" | "resolved_at";
151
+ /** asc (the default) or desc. */
152
+ order?: "asc" | "desc";
126
153
  limit?: number;
127
154
  }
128
155
 
@@ -177,6 +204,13 @@ function iso(v: Date | string | undefined): string | undefined {
177
204
  return v instanceof Date ? v.toISOString() : v;
178
205
  }
179
206
 
207
+ /** The status filter sk.markets sends: status as given, or resolved's (true is resolved, false the three others). */
208
+ function marketStatus(options: MarketsOptions): MarketsOptions["status"] {
209
+ if (options.resolved === undefined) return options.status;
210
+ if (options.status !== undefined) throw new ConfigurationError('pass resolved or status, not both: resolved true is status ["resolved"], false the three others');
211
+ return options.resolved ? ["resolved"] : ["open", "closed", "voided"];
212
+ }
213
+
180
214
  function defaultSleep(seconds: number): Promise<void> {
181
215
  return new Promise((resolve) => setTimeout(resolve, seconds * 1000));
182
216
  }
@@ -260,23 +294,34 @@ export class Skewtape {
260
294
  }
261
295
  }
262
296
 
263
- /** sk.markets({venue, resolved}) lists markets; sk.markets.get(venue, marketId) reads one. */
297
+ /**
298
+ * sk.markets({venue, status, q}) lists markets; sk.markets.get(venue,
299
+ * marketId) reads one. Every filter is the API's, resolved included (true
300
+ * is status ["resolved"], false the three others), so one request per page.
301
+ */
264
302
  readonly markets = Object.assign(
265
- (options: MarketsOptions = {}): Paginated<Market> =>
266
- new Paginated(
267
- async (cursor) => {
268
- const query: Query<"/v1/markets"> = {
269
- venue: options.venue,
270
- market_id: options.marketId,
271
- updated_since: iso(options.updatedSince),
272
- limit: options.limit ?? 100,
273
- cursor,
274
- };
275
- const data = await this.call(() => this.api.GET("/v1/markets", { params: { query } }));
276
- return { items: data.data, nextCursor: data.next_cursor ?? null };
277
- },
278
- options.resolved === undefined ? undefined : (m) => (m.status === "resolved") === options.resolved,
279
- ),
303
+ (options: MarketsOptions = {}): Paginated<Market> => {
304
+ const status = marketStatus(options);
305
+ return new Paginated(async (cursor) => {
306
+ const query: Query<"/v1/markets"> = {
307
+ venue: options.venue,
308
+ market_id: options.marketId,
309
+ updated_since: iso(options.updatedSince),
310
+ status,
311
+ category: options.category,
312
+ venue_event_id: options.venueEventId,
313
+ close_after: iso(options.closeAfter),
314
+ close_before: iso(options.closeBefore),
315
+ q: options.q,
316
+ sort: options.sort,
317
+ order: options.order,
318
+ limit: options.limit ?? 100,
319
+ cursor,
320
+ };
321
+ const data = await this.call(() => this.api.GET("/v1/markets", { params: { query } }));
322
+ return { items: data.data, nextCursor: data.next_cursor ?? null };
323
+ });
324
+ },
280
325
  {
281
326
  get: (venue: string, marketId: string): Promise<Market> =>
282
327
  this.call(() => this.api.GET("/v1/markets/{venue}/{market_id}", { params: { path: { venue, market_id: marketId } } })),
@@ -312,6 +357,8 @@ export class Skewtape {
312
357
  resolution_equal: options.resolutionEqual,
313
358
  venue: options.venue,
314
359
  status: options.status,
360
+ sort: options.sort,
361
+ order: options.order,
315
362
  limit: options.limit ?? 100,
316
363
  cursor,
317
364
  };
@@ -358,13 +405,17 @@ export class Skewtape {
358
405
  });
359
406
  }
360
407
 
361
- /** sk.resolutions({venue, marketId, createdSince}) lists resolution events, of up to 100 markets when marketId is given. */
408
+ /** sk.resolutions({venue, marketId, createdSince, resolvedAfter, resolvedBefore}) lists resolution events, of up to 100 markets when marketId is given. */
362
409
  resolutions(options: ResolutionsOptions = {}): Paginated<Resolution> {
363
410
  return new Paginated(async (cursor) => {
364
411
  const query: Query<"/v1/resolutions"> = {
365
412
  venue: options.venue,
366
413
  market_id: options.marketId,
367
414
  created_since: iso(options.createdSince),
415
+ resolved_after: iso(options.resolvedAfter),
416
+ resolved_before: iso(options.resolvedBefore),
417
+ sort: options.sort,
418
+ order: options.order,
368
419
  limit: options.limit ?? 100,
369
420
  cursor,
370
421
  };
package/src/fees.ts CHANGED
@@ -12,6 +12,13 @@ import { Rat, parseInt64, parseMicros } from "./exact.js";
12
12
 
13
13
  export const COLLATERAL_MICROS_DECIMALS = 6;
14
14
  export const FALLBACK_CATEGORY = "*";
15
+ /**
16
+ * A Polymarket fee_category joins several rows' names ("finance|mentions")
17
+ * when those rows charge alike and the venue's data does not say which is the
18
+ * market's.
19
+ */
20
+ const JOINED_VENUE = "polymarket";
21
+ const JOINED_SEPARATOR = "|";
15
22
  const MICROS_PER_UNIT = 1_000_000n;
16
23
 
17
24
  /** A fee that cannot be computed: an unknown formula or rounding, a missing parameter, a size out of range. */
@@ -171,19 +178,52 @@ function inForce(r: FeeRow, at: bigint): boolean {
171
178
  /**
172
179
  * The row in force for a fill of venue at time at (microseconds, a Date or
173
180
  * an ISO string): the market's fee_category if a row has it, else the row
174
- * with category *; of several, the latest effective_from. Undefined when no
175
- * row applies.
181
+ * with category *; of several, the latest effective_from. A Polymarket
182
+ * fee_category that joins names ("finance|mentions") gives the terms its rows
183
+ * share, under the joined name, while every one of them is in force and
184
+ * charges alike, and never the * row. Undefined when no row applies.
176
185
  */
177
186
  export function selectFeeRow(rows: Iterable<FeeRowInput>, venue: string, category: string | null | undefined, at: bigint | Date | string): FeeRow | undefined {
178
187
  const t = typeof at === "bigint" ? at : parseMicros(at, "at");
179
- const all = [...rows].map(feeRowOf);
188
+ const all = [...rows].map(feeRowOf).filter((r) => r.venue === venue);
189
+ if (venue === JOINED_VENUE && category && category.includes(JOINED_SEPARATOR)) return joinedRow(all, category, t);
180
190
  const wanted = category && category !== FALLBACK_CATEGORY ? [category, FALLBACK_CATEGORY] : [FALLBACK_CATEGORY];
181
191
  for (const cat of wanted) {
182
- let best: FeeRow | undefined;
183
- for (const r of all) {
184
- if (r.venue === venue && r.category === cat && inForce(r, t) && (best === undefined || r.effectiveFrom > best.effectiveFrom)) best = r;
185
- }
192
+ const best = rowInForce(all, cat, t);
186
193
  if (best) return best;
187
194
  }
188
195
  return undefined;
189
196
  }
197
+
198
+ function rowInForce(rows: FeeRow[], category: string, at: bigint): FeeRow | undefined {
199
+ let best: FeeRow | undefined;
200
+ for (const r of rows) {
201
+ if (r.category === category && inForce(r, at) && (best === undefined || r.effectiveFrom > best.effectiveFrom)) best = r;
202
+ }
203
+ return best;
204
+ }
205
+
206
+ function joinedRow(rows: FeeRow[], key: string, at: bigint): FeeRow | undefined {
207
+ let out: FeeRow | undefined;
208
+ for (const name of key.split(JOINED_SEPARATOR)) {
209
+ const r = rowInForce(rows, name, at);
210
+ if (r === undefined || (out !== undefined && !sameTerms(out, r))) return undefined;
211
+ if (out === undefined) {
212
+ out = { ...r, category: key };
213
+ continue;
214
+ }
215
+ if (r.effectiveFrom > out.effectiveFrom) out.effectiveFrom = r.effectiveFrom;
216
+ if (r.effectiveTo !== null && (out.effectiveTo === null || r.effectiveTo < out.effectiveTo)) out.effectiveTo = r.effectiveTo;
217
+ }
218
+ return out;
219
+ }
220
+
221
+ /** Whether two rows charge alike: everything but the name, period and source. */
222
+ function sameTerms(a: FeeRow, b: FeeRow): boolean {
223
+ return a.formula === b.formula && a.rounding === b.rounding && a.minFeeMicros === b.minFeeMicros && sameParams(a.takerParams, b.takerParams) && sameParams(a.makerRebateParams, b.makerRebateParams);
224
+ }
225
+
226
+ function sameParams(a: Record<string, bigint>, b: Record<string, bigint>): boolean {
227
+ const keys = Object.keys(a);
228
+ return keys.length === Object.keys(b).length && keys.every((k) => a[k] === b[k]);
229
+ }