pmxtjs 2.51.0 → 2.51.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.
@@ -105,6 +105,7 @@ export declare abstract class Exchange {
105
105
  private _wsClient;
106
106
  /** Sticky flag: true if the sidecar /ws endpoint is unavailable. */
107
107
  private _wsUnsupported;
108
+ private readonly _useSidecarLockBaseUrl;
108
109
  constructor(exchangeName: string, options?: ExchangeOptions);
109
110
  private initializeServer;
110
111
  protected handleResponse(response: any): any;
@@ -125,9 +126,9 @@ export declare abstract class Exchange {
125
126
  /**
126
127
  * Resolve the current sidecar base URL.
127
128
  *
128
- * For hosted mode the configured basePath is returned as-is.
129
- * For local mode the port is re-read from the lock file on every
130
- * call so we pick up sidecar restarts that land on a different port.
129
+ * Hosted mode and explicit baseUrl clients keep the configured basePath.
130
+ * Default local clients re-read the lock-file port on every call so they
131
+ * pick up sidecar restarts that land on a different port.
131
132
  */
132
133
  private resolveBaseUrl;
133
134
  /**
@@ -576,6 +577,14 @@ export interface PolymarketOptions {
576
577
  proxyAddress?: string;
577
578
  /** Optional signature type */
578
579
  signatureType?: 'eoa' | 'poly-proxy' | 'gnosis-safe' | number;
580
+ /**
581
+ * EVM wallet address used for hosted reads/writes.
582
+ */
583
+ walletAddress?: string;
584
+ /**
585
+ * External signer used for hosted writes.
586
+ */
587
+ signer?: Signer;
579
588
  }
580
589
  export declare class Polymarket extends Exchange {
581
590
  constructor(options?: PolymarketOptions);
@@ -856,6 +865,15 @@ export declare const Suibets: typeof SuiBets;
856
865
  export declare class Rain extends Exchange {
857
866
  constructor(options?: ExchangeOptions);
858
867
  }
868
+ /**
869
+ * Hunch exchange client.
870
+ *
871
+ * Hunch is a crypto-native prediction market. Reads are unauthenticated;
872
+ * trading requires an EVM private key.
873
+ */
874
+ export declare class Hunch extends Exchange {
875
+ constructor(options?: ExchangeOptions);
876
+ }
859
877
  /**
860
878
  * Mock exchange client.
861
879
  *
@@ -6,7 +6,7 @@
6
6
  * OpenAPI client, matching the Python API exactly.
7
7
  */
8
8
  Object.defineProperty(exports, "__esModule", { value: true });
9
- exports.Mock = exports.Rain = exports.Suibets = exports.SuiBets = exports.Hyperliquid = exports.GeminiTitan = exports.PolymarketUS = exports.Smarkets = exports.Metaculus = exports.Opinion = exports.Baozi = exports.Probable = exports.Myriad = exports.KalshiDemo = exports.Limitless = exports.Kalshi = exports.Polymarket = exports.Exchange = void 0;
9
+ exports.Mock = exports.Hunch = exports.Rain = exports.Suibets = exports.SuiBets = exports.Hyperliquid = exports.GeminiTitan = exports.PolymarketUS = exports.Smarkets = exports.Metaculus = exports.Opinion = exports.Baozi = exports.Probable = exports.Myriad = exports.KalshiDemo = exports.Limitless = exports.Kalshi = exports.Polymarket = exports.Exchange = void 0;
10
10
  const index_js_1 = require("../generated/src/index.js");
11
11
  const models_js_1 = require("./models.js");
12
12
  const server_manager_js_1 = require("./server-manager.js");
@@ -193,6 +193,7 @@ class Exchange {
193
193
  _wsClient = null;
194
194
  /** Sticky flag: true if the sidecar /ws endpoint is unavailable. */
195
195
  _wsUnsupported = false;
196
+ _useSidecarLockBaseUrl;
196
197
  constructor(exchangeName, options = {}) {
197
198
  this.exchangeName = exchangeName.toLowerCase();
198
199
  this.apiKey = options.apiKey;
@@ -210,6 +211,9 @@ class Exchange {
210
211
  const baseUrl = resolved.baseUrl;
211
212
  this.pmxtApiKey = resolved.pmxtApiKey;
212
213
  this.isHosted = resolved.isHosted;
214
+ const hasBaseUrlOverride = Boolean(options.baseUrl ||
215
+ (typeof process !== "undefined" && process.env[constants_js_1.ENV.BASE_URL]));
216
+ this._useSidecarLockBaseUrl = !this.isHosted && !hasBaseUrlOverride;
213
217
  // Hosted trading bridge: if the caller passed a privateKey but no
214
218
  // explicit signer, lazily wrap it in an EthersSigner so that
215
219
  // `pmxt.Polymarket(pmxtApiKey, privateKey)` just works without the
@@ -250,15 +254,17 @@ class Exchange {
250
254
  if (autoStartServer) {
251
255
  try {
252
256
  await this.serverManager.ensureServerRunning();
253
- // Get the actual port the server is running on
254
- // (may differ from default if default port was busy)
255
- const actualPort = this.serverManager.getRunningPort();
256
- const newBaseUrl = `http://localhost:${actualPort}`;
257
- // Update API client with actual base URL
258
- this.config = new index_js_1.Configuration({
259
- basePath: newBaseUrl,
260
- });
261
- this.api = new index_js_1.DefaultApi(this.config);
257
+ if (this._useSidecarLockBaseUrl) {
258
+ // Get the actual port the server is running on
259
+ // (may differ from default if default port was busy)
260
+ const actualPort = this.serverManager.getRunningPort();
261
+ const newBaseUrl = `http://localhost:${actualPort}`;
262
+ // Update API client with actual base URL
263
+ this.config = new index_js_1.Configuration({
264
+ basePath: newBaseUrl,
265
+ });
266
+ this.api = new index_js_1.DefaultApi(this.config);
267
+ }
262
268
  }
263
269
  catch (error) {
264
270
  const msg = `Failed to start PMXT server: ${error instanceof Error ? error.message : error}\n\n` +
@@ -332,12 +338,12 @@ class Exchange {
332
338
  /**
333
339
  * Resolve the current sidecar base URL.
334
340
  *
335
- * For hosted mode the configured basePath is returned as-is.
336
- * For local mode the port is re-read from the lock file on every
337
- * call so we pick up sidecar restarts that land on a different port.
341
+ * Hosted mode and explicit baseUrl clients keep the configured basePath.
342
+ * Default local clients re-read the lock-file port on every call so they
343
+ * pick up sidecar restarts that land on a different port.
338
344
  */
339
345
  resolveBaseUrl() {
340
- if (this.isHosted)
346
+ if (this.isHosted || !this._useSidecarLockBaseUrl)
341
347
  return this.config.basePath;
342
348
  const port = this.serverManager.getRunningPort();
343
349
  return `http://localhost:${port}`;
@@ -1021,7 +1027,10 @@ class Exchange {
1021
1027
  const route = hosted_routing_js_1.HOSTED_METHOD_ROUTES.get("fetchOrder");
1022
1028
  const path = (0, hosted_routing_js_1.formatRoutePath)(route, { order_id: orderId });
1023
1029
  const data = await (0, hosted_routing_js_1._tradingRequest)(this, { method: route.method, path });
1024
- return (0, hosted_mappers_js_1.orderFromV0)(data);
1030
+ const payload = data && typeof data === "object" && "order" in data
1031
+ ? data.order
1032
+ : data;
1033
+ return (0, hosted_mappers_js_1.orderFromV0)(payload);
1025
1034
  }
1026
1035
  try {
1027
1036
  const args = [];
@@ -1127,6 +1136,9 @@ class Exchange {
1127
1136
  }
1128
1137
  async fetchClosedOrders(params) {
1129
1138
  await this.initPromise;
1139
+ if (this.isHosted) {
1140
+ throw new errors_js_1.NotSupported("fetchClosedOrders is not available in hosted trading mode.");
1141
+ }
1130
1142
  try {
1131
1143
  const args = [];
1132
1144
  if (params !== undefined)
@@ -1155,6 +1167,9 @@ class Exchange {
1155
1167
  }
1156
1168
  async fetchAllOrders(params) {
1157
1169
  await this.initPromise;
1170
+ if (this.isHosted) {
1171
+ throw new errors_js_1.NotSupported("fetchAllOrders is not available in hosted trading mode.");
1172
+ }
1158
1173
  try {
1159
1174
  const args = [];
1160
1175
  if (params !== undefined)
@@ -1188,7 +1203,9 @@ class Exchange {
1188
1203
  const route = hosted_routing_js_1.HOSTED_METHOD_ROUTES.get("fetchPositions");
1189
1204
  const path = (0, hosted_routing_js_1.formatRoutePath)(route, { address: resolvedAddress });
1190
1205
  const data = await (0, hosted_routing_js_1._tradingRequest)(this, { method: route.method, path });
1191
- const list = Array.isArray(data) ? data : [];
1206
+ const list = Array.isArray(data)
1207
+ ? data
1208
+ : (data && Array.isArray(data.positions) ? data.positions : []);
1192
1209
  return list.map((p) => (0, hosted_mappers_js_1.positionFromV0)(p));
1193
1210
  }
1194
1211
  try {
@@ -1224,7 +1241,9 @@ class Exchange {
1224
1241
  const route = hosted_routing_js_1.HOSTED_METHOD_ROUTES.get("fetchBalance");
1225
1242
  const path = (0, hosted_routing_js_1.formatRoutePath)(route, { address: resolvedAddress });
1226
1243
  const data = await (0, hosted_routing_js_1._tradingRequest)(this, { method: route.method, path });
1227
- const list = Array.isArray(data) ? data : [];
1244
+ const list = Array.isArray(data)
1245
+ ? data
1246
+ : (data && Array.isArray(data.balances) ? data.balances : []);
1228
1247
  return list.map((b) => (0, hosted_mappers_js_1.balanceFromV0)(b));
1229
1248
  }
1230
1249
  try {
@@ -3053,6 +3072,18 @@ class Rain extends Exchange {
3053
3072
  }
3054
3073
  }
3055
3074
  exports.Rain = Rain;
3075
+ /**
3076
+ * Hunch exchange client.
3077
+ *
3078
+ * Hunch is a crypto-native prediction market. Reads are unauthenticated;
3079
+ * trading requires an EVM private key.
3080
+ */
3081
+ class Hunch extends Exchange {
3082
+ constructor(options = {}) {
3083
+ super("hunch", options);
3084
+ }
3085
+ }
3086
+ exports.Hunch = Hunch;
3056
3087
  /**
3057
3088
  * Mock exchange client.
3058
3089
  *
@@ -12,6 +12,80 @@
12
12
  Object.defineProperty(exports, "__esModule", { value: true });
13
13
  exports.Escrow = void 0;
14
14
  const hosted_routing_1 = require("./hosted-routing");
15
+ const errors_1 = require("./errors");
16
+ const APPROVAL_TOKENS = new Set(["usdc", "ctf"]);
17
+ const WITHDRAW_ACTIONS = new Set(["request", "claim", "cancel"]);
18
+ const USDC_SCALE = 1000000n;
19
+ function isDecimalTokenId(token) {
20
+ return /^[0-9]+$/.test(token);
21
+ }
22
+ function normalizeApprovalToken(token) {
23
+ if (typeof token !== "string") {
24
+ throw new errors_1.ValidationError("token must be 'usdc', 'ctf', or a decimal CTF token_id string", "token");
25
+ }
26
+ const candidate = token.trim();
27
+ const normalized = candidate.toLowerCase();
28
+ if (APPROVAL_TOKENS.has(normalized)) {
29
+ return normalized;
30
+ }
31
+ if (isDecimalTokenId(candidate)) {
32
+ return candidate;
33
+ }
34
+ throw new errors_1.ValidationError("token must be 'usdc', 'ctf', or a decimal CTF token_id string", "token");
35
+ }
36
+ function normalizeAmountWei(amountWei) {
37
+ if (amountWei === undefined) {
38
+ return undefined;
39
+ }
40
+ if (typeof amountWei !== "bigint") {
41
+ throw new errors_1.ValidationError("amount_wei must be a non-negative integer", "amount_wei");
42
+ }
43
+ if (amountWei < 0n) {
44
+ throw new errors_1.ValidationError("amount_wei must be non-negative", "amount_wei");
45
+ }
46
+ return amountWei.toString();
47
+ }
48
+ function validateUsdcDecimal(value, field) {
49
+ const match = /^([0-9]+)(?:\.([0-9]+))?$/.exec(value);
50
+ if (!match) {
51
+ throw new errors_1.ValidationError(`${field} must be a finite positive number`, field);
52
+ }
53
+ const fractional = match[2] ?? "";
54
+ if (fractional.length > 6) {
55
+ throw new errors_1.ValidationError(`${field} precision exceeds 6 decimals; max precision for USDC is 0.000001`, field);
56
+ }
57
+ const scaled = BigInt(match[1]) * USDC_SCALE + BigInt(fractional.padEnd(6, "0"));
58
+ if (scaled <= 0n) {
59
+ throw new errors_1.ValidationError(`${field} must be positive`, field);
60
+ }
61
+ }
62
+ function normalizeUsdcAmount(value, field = "amount") {
63
+ if (typeof value === "bigint") {
64
+ if (value <= 0n) {
65
+ throw new errors_1.ValidationError(`${field} must be positive`, field);
66
+ }
67
+ return value.toString();
68
+ }
69
+ if (typeof value === "number") {
70
+ if (!Number.isFinite(value)) {
71
+ throw new errors_1.ValidationError(`${field} must be a finite positive number`, field);
72
+ }
73
+ validateUsdcDecimal(String(value), field);
74
+ return value;
75
+ }
76
+ if (typeof value === "string") {
77
+ const trimmed = value.trim();
78
+ validateUsdcDecimal(trimmed, field);
79
+ return trimmed;
80
+ }
81
+ throw new errors_1.ValidationError(`${field} must be a finite positive number`, field);
82
+ }
83
+ function normalizeWithdrawAction(action) {
84
+ if (typeof action === "string" && WITHDRAW_ACTIONS.has(action)) {
85
+ return action;
86
+ }
87
+ throw new errors_1.ValidationError("action must be 'request', 'claim', or 'cancel'", "action");
88
+ }
15
89
  class Escrow {
16
90
  client;
17
91
  constructor(client) {
@@ -22,13 +96,16 @@ class Escrow {
22
96
  * `amountWei` is omitted, the server returns an unlimited approval.
23
97
  */
24
98
  async approveTx(token, amountWei) {
99
+ const address = (0, hosted_routing_1.resolveWalletAddress)(this.client);
100
+ const approvalAmount = normalizeAmountWei(amountWei);
25
101
  const route = hosted_routing_1.HOSTED_METHOD_ROUTES.get("escrowApproveTx");
26
102
  return (0, hosted_routing_1._tradingRequest)(this.client, {
27
103
  method: route.method,
28
104
  path: route.path,
29
105
  body: {
30
- token,
31
- amount_wei: amountWei === undefined ? null : amountWei.toString(),
106
+ token: normalizeApprovalToken(token),
107
+ user_address: address,
108
+ ...(approvalAmount === undefined ? {} : { amount_wei: approvalAmount }),
32
109
  },
33
110
  });
34
111
  }
@@ -37,12 +114,15 @@ class Escrow {
37
114
  * grid). Accepts number, decimal string, or BigInt in micro-units.
38
115
  */
39
116
  async depositTx(amount) {
117
+ const address = (0, hosted_routing_1.resolveWalletAddress)(this.client);
40
118
  const route = hosted_routing_1.HOSTED_METHOD_ROUTES.get("escrowDepositTx");
41
119
  return (0, hosted_routing_1._tradingRequest)(this.client, {
42
120
  method: route.method,
43
121
  path: route.path,
44
122
  body: {
45
- amount: typeof amount === "bigint" ? amount.toString() : amount,
123
+ token: "usdc",
124
+ amount: normalizeUsdcAmount(amount),
125
+ user_address: address,
46
126
  },
47
127
  });
48
128
  }
@@ -52,16 +132,31 @@ class Escrow {
52
132
  * the timelock, `cancel` aborts a pending request.
53
133
  */
54
134
  async withdrawTx(action, amount) {
135
+ const normalizedAction = normalizeWithdrawAction(action);
136
+ const address = (0, hosted_routing_1.resolveWalletAddress)(this.client);
55
137
  const route = hosted_routing_1.HOSTED_METHOD_ROUTES.get("escrowWithdrawTx");
56
- const normalizedAmount = amount === undefined
57
- ? null
58
- : typeof amount === "bigint"
59
- ? amount.toString()
60
- : amount;
138
+ if (normalizedAction === "request") {
139
+ if (amount === undefined) {
140
+ throw new errors_1.ValidationError("amount is required when action='request'", "amount");
141
+ }
142
+ return (0, hosted_routing_1._tradingRequest)(this.client, {
143
+ method: route.method,
144
+ path: route.path,
145
+ body: {
146
+ action: normalizedAction,
147
+ token: "usdc",
148
+ amount: normalizeUsdcAmount(amount),
149
+ user_address: address,
150
+ },
151
+ });
152
+ }
153
+ if (amount !== undefined) {
154
+ throw new errors_1.ValidationError(`amount must be omitted when action='${normalizedAction}'`, "amount");
155
+ }
61
156
  return (0, hosted_routing_1._tradingRequest)(this.client, {
62
157
  method: route.method,
63
158
  path: route.path,
64
- body: { action, amount: normalizedAmount },
159
+ body: { action: normalizedAction, token: "usdc", user_address: address },
65
160
  });
66
161
  }
67
162
  /**
@@ -70,12 +165,16 @@ class Escrow {
70
165
  */
71
166
  async withdrawals(opts = {}) {
72
167
  const address = (0, hosted_routing_1.resolveWalletAddress)(this.client, opts.address);
168
+ const include = (opts.include ?? "pending,events").trim();
169
+ if (!include) {
170
+ throw new errors_1.ValidationError("include must not be empty", "include");
171
+ }
73
172
  const route = hosted_routing_1.HOSTED_METHOD_ROUTES.get("escrowWithdrawals");
74
173
  const path = (0, hosted_routing_1.formatRoutePath)(route, { address });
75
174
  return (0, hosted_routing_1._tradingRequest)(this.client, {
76
175
  method: route.method,
77
176
  path,
78
- params: { include: opts.include ?? "pending,events" },
177
+ params: { include },
79
178
  });
80
179
  }
81
180
  }
@@ -117,12 +117,14 @@ class ServerManager {
117
117
  * Check if the server is running.
118
118
  */
119
119
  async isServerRunning() {
120
- // Read lock file to get current port
121
- const port = this.getRunningPort();
120
+ const info = this.getServerInfo();
121
+ if (!info?.port) {
122
+ return false;
123
+ }
122
124
  try {
123
125
  // Use native fetch to check health on the actual running port
124
126
  // This avoids issues where this.api is configured with the wrong port
125
- const response = await fetch(`http://localhost:${port}/health`, {
127
+ const response = await fetch(`http://localhost:${info.port}/health`, {
126
128
  signal: AbortSignal.timeout(5_000),
127
129
  });
128
130
  if (response.ok) {