@qntx/wallet-engine 0.12.0 → 0.14.0
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/README.md +1057 -20
- package/dist/apps-fiat24.d.mts +202 -0
- package/dist/apps-fiat24.mjs +1378 -0
- package/dist/apps-fiat24.mjs.map +1 -0
- package/dist/apps-hyperliquid.d.mts +549 -0
- package/dist/apps-hyperliquid.mjs +2742 -0
- package/dist/apps-hyperliquid.mjs.map +1 -0
- package/dist/apps-polymarket.d.mts +729 -0
- package/dist/apps-polymarket.mjs +3786 -0
- package/dist/apps-polymarket.mjs.map +1 -0
- package/dist/apps.d.mts +136 -0
- package/dist/apps.mjs +535 -0
- package/dist/apps.mjs.map +1 -0
- package/dist/connect-BY1C5ZRI.mjs +210 -0
- package/dist/connect-BY1C5ZRI.mjs.map +1 -0
- package/dist/connect.d.mts +17 -9
- package/dist/connect.mjs +3 -185
- package/dist/controller-DpNVHVsj.d.mts +2295 -0
- package/dist/controller-rMnaxKAH.mjs +46 -0
- package/dist/controller-rMnaxKAH.mjs.map +1 -0
- package/dist/decimal-COJ4g8qy.mjs +38 -0
- package/dist/decimal-COJ4g8qy.mjs.map +1 -0
- package/dist/eligibility-BfM9ybYZ.mjs +48 -0
- package/dist/eligibility-BfM9ybYZ.mjs.map +1 -0
- package/dist/engine-Dic_kkEr.d.mts +1829 -0
- package/dist/errors-B8W-hoYW.d.mts +7 -0
- package/dist/errors-horUy5k1.mjs +24 -0
- package/dist/errors-horUy5k1.mjs.map +1 -0
- package/dist/gateway-contract.d.mts +3 -362
- package/dist/gateway-contract.mjs +1531 -81
- package/dist/gateway-contract.mjs.map +1 -1
- package/dist/idb.d.mts +5 -0
- package/dist/idb.mjs +122 -46
- package/dist/idb.mjs.map +1 -1
- package/dist/index-vBgfOFIh.d.mts +2227 -0
- package/dist/index.d.mts +58 -515
- package/dist/index.mjs +22314 -4901
- package/dist/index.mjs.map +1 -1
- package/dist/json-BDwV38cj.mjs +15 -0
- package/dist/json-BDwV38cj.mjs.map +1 -0
- package/dist/link-Ceq8Dggp.mjs +139 -0
- package/dist/link-Ceq8Dggp.mjs.map +1 -0
- package/dist/primitives-DbSHLZKq.mjs +31 -0
- package/dist/primitives-DbSHLZKq.mjs.map +1 -0
- package/dist/push-message-AQuzoNFY.d.mts +84 -0
- package/dist/push-message-kbnH1A5w.mjs +142 -0
- package/dist/push-message-kbnH1A5w.mjs.map +1 -0
- package/dist/push.d.mts +13 -0
- package/dist/push.mjs +70 -0
- package/dist/push.mjs.map +1 -0
- package/dist/qr.d.mts +292 -0
- package/dist/qr.mjs +1725 -0
- package/dist/qr.mjs.map +1 -0
- package/dist/registry-CbtwcxkX.mjs +374 -0
- package/dist/registry-CbtwcxkX.mjs.map +1 -0
- package/dist/risk-DyABgg4W.mjs +757 -0
- package/dist/risk-DyABgg4W.mjs.map +1 -0
- package/dist/session-CNJFLarP.mjs +18 -0
- package/dist/session-CNJFLarP.mjs.map +1 -0
- package/dist/socket-ChG9JRT_.mjs +110 -0
- package/dist/socket-ChG9JRT_.mjs.map +1 -0
- package/dist/spi-BrTw5s98.d.mts +3 -0
- package/dist/timer-Cdk5rGM2.mjs +43 -0
- package/dist/timer-Cdk5rGM2.mjs.map +1 -0
- package/dist/types-BpvioFGo.d.mts +258 -0
- package/dist/types-DbftVZ3I.mjs +90 -0
- package/dist/types-DbftVZ3I.mjs.map +1 -0
- package/dist/walletconnect.d.mts +86 -0
- package/dist/walletconnect.mjs +1507 -0
- package/dist/walletconnect.mjs.map +1 -0
- package/dist/webln-BgrtPXpG.mjs +2593 -0
- package/dist/webln-BgrtPXpG.mjs.map +1 -0
- package/dist/webln-Bllk_xJ2.d.mts +666 -0
- package/package.json +94 -19
- package/dist/connect.mjs.map +0 -1
- package/dist/errors-DpkJneDe.d.mts +0 -1696
- package/dist/registry-Deo5WQe1.d.mts +0 -25
- package/dist/registry-wYrcuFNc.mjs +0 -99
- package/dist/registry-wYrcuFNc.mjs.map +0 -1
- package/dist/webln-DzsI7jVb.mjs +0 -3629
- package/dist/webln-DzsI7jVb.mjs.map +0 -1
|
@@ -0,0 +1,3786 @@
|
|
|
1
|
+
import { t as EngineStoreError } from "./errors-horUy5k1.mjs";
|
|
2
|
+
import { n as formatDecimal, r as parseDecimal } from "./decimal-COJ4g8qy.mjs";
|
|
3
|
+
import { t as readJson } from "./json-BDwV38cj.mjs";
|
|
4
|
+
import { n as timeoutSignal } from "./timer-Cdk5rGM2.mjs";
|
|
5
|
+
import { i as RequestEndedError } from "./types-DbftVZ3I.mjs";
|
|
6
|
+
import { t as createAppSocketCore } from "./socket-ChG9JRT_.mjs";
|
|
7
|
+
import { concat, encodeAbiParameters, getAddress, getCreate2Address, hashTypedData, keccak256, numberToHex, padHex, toHex } from "viem";
|
|
8
|
+
import * as z$1 from "zod/mini";
|
|
9
|
+
import { utf8ToBytes } from "@noble/hashes/utils.js";
|
|
10
|
+
import { sha256 } from "@noble/hashes/sha2.js";
|
|
11
|
+
import { base64, base64url } from "@scure/base";
|
|
12
|
+
import { WalletError } from "@qntx/wallet";
|
|
13
|
+
import { hmac } from "@noble/hashes/hmac.js";
|
|
14
|
+
// src/apps/polymarket/errors.ts
|
|
15
|
+
var PolymarketError = class extends Error {
|
|
16
|
+
category;
|
|
17
|
+
/**
|
|
18
|
+
* The HTTP status — set on `unavailable` only. Callers distinguish a definitive 4xx (the request
|
|
19
|
+
* never ran as asked) from a 5xx/timeout (the outcome is unknown).
|
|
20
|
+
*/
|
|
21
|
+
status;
|
|
22
|
+
/** The server's parsed JSON error body when it was an object — `unavailable` only. */
|
|
23
|
+
body;
|
|
24
|
+
constructor(category, message, options) {
|
|
25
|
+
super(message, { cause: options?.cause });
|
|
26
|
+
this.name = "PolymarketError";
|
|
27
|
+
this.category = category;
|
|
28
|
+
if (options?.status !== void 0) this.status = options.status;
|
|
29
|
+
if (options?.body !== void 0) this.body = options.body;
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
// src/apps/polymarket/credentials.ts
|
|
33
|
+
/**
|
|
34
|
+
* The group's CLOB L2 credentials in the apps store — `{owner, apiKey, secret, passphrase}` under
|
|
35
|
+
* the `eip155:137` record name (Polymarket trades on Polygon only), encrypted with the session data
|
|
36
|
+
* key like every engine record (design.md §返工). A locked vault throws
|
|
37
|
+
* `PolymarketError("unlock-required")`; a record that is not strict JSON with exactly those four
|
|
38
|
+
* keys and valid field formats reads as absent, with one content-free warning — the enable flow
|
|
39
|
+
* then re-derives rather than trusting it. The record's `owner` is the `evm.bip44` signer that
|
|
40
|
+
* imported it; `l2.ts` re-checks it against the group's live signer on every request, so another
|
|
41
|
+
* account's record can never sign. `onDelete` notifies after a `delete` lands — a live account view
|
|
42
|
+
* stops on it rather than re-sending the deleted credentials on its next reconnect.
|
|
43
|
+
*/
|
|
44
|
+
/** The record name — the signature chain's CAIP-2. */
|
|
45
|
+
const NAME = "eip155:137";
|
|
46
|
+
const ADDRESS$1 = /^0x[0-9a-fA-F]{40}$/;
|
|
47
|
+
const API_KEY = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
48
|
+
/** The alphabet import accepts — standard or url-safe base64, padding optional. */
|
|
49
|
+
const SECRET_CHARS = /^[A-Za-z0-9+/=_-]+$/;
|
|
50
|
+
/** Printable ASCII 0x21–0x7e, like the CLOB issues it. */
|
|
51
|
+
const PASSPHRASE = /^[\u0021-\u007E]{1,128}$/;
|
|
52
|
+
const SECRET_MAX_CHARS = 128;
|
|
53
|
+
const SECRET_MIN_BYTES = 16;
|
|
54
|
+
const SECRET_MAX_BYTES = 64;
|
|
55
|
+
/**
|
|
56
|
+
* The secret decoded to HMAC key bytes, or undefined when the string is not within bounds or does
|
|
57
|
+
* not decode. Mirrors clob-client-v2 `src/signing/hmac.ts` `decodeBase64Secret`: the url-safe
|
|
58
|
+
* alphabet is normalized to the standard one and `=` padding is optional; a length-`%4 == 1`
|
|
59
|
+
* remainder or a stray `=` fails the decode, never produces wrong bytes.
|
|
60
|
+
*/
|
|
61
|
+
function decodeSecret(secret) {
|
|
62
|
+
if (secret.length === 0 || secret.length > SECRET_MAX_CHARS || !SECRET_CHARS.test(secret)) return;
|
|
63
|
+
const normalized = secret.replaceAll("-", "+").replaceAll("_", "/");
|
|
64
|
+
const padded = normalized + "=".repeat((4 - normalized.length % 4) % 4);
|
|
65
|
+
try {
|
|
66
|
+
const bytes = base64.decode(padded);
|
|
67
|
+
return bytes.length >= SECRET_MIN_BYTES && bytes.length <= SECRET_MAX_BYTES ? bytes : void 0;
|
|
68
|
+
} catch {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
const isAddress$1 = (value) => typeof value === "string" && ADDRESS$1.test(value);
|
|
73
|
+
/** Field formats, minus `owner` — shared by `put` validation and the strict record parse. */
|
|
74
|
+
const fieldsValid = (value) => typeof value.apiKey === "string" && API_KEY.test(value.apiKey) && typeof value.secret === "string" && decodeSecret(value.secret) !== void 0 && typeof value.passphrase === "string" && PASSPHRASE.test(value.passphrase);
|
|
75
|
+
const isRecord$1 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
76
|
+
/** The strict record shape: exactly the four keys, each with a valid format. */
|
|
77
|
+
const parse = (raw) => {
|
|
78
|
+
const value = readJson(raw);
|
|
79
|
+
if (!isRecord$1(value)) return;
|
|
80
|
+
if (Object.keys(value).some((key) => key !== "owner" && key !== "apiKey" && key !== "secret" && key !== "passphrase")) return;
|
|
81
|
+
const { owner } = value;
|
|
82
|
+
if (!isAddress$1(owner) || !fieldsValid(value)) return;
|
|
83
|
+
return {
|
|
84
|
+
owner,
|
|
85
|
+
apiKey: value.apiKey,
|
|
86
|
+
secret: value.secret,
|
|
87
|
+
passphrase: value.passphrase
|
|
88
|
+
};
|
|
89
|
+
};
|
|
90
|
+
const read = async (run) => {
|
|
91
|
+
try {
|
|
92
|
+
return await run();
|
|
93
|
+
} catch (error) {
|
|
94
|
+
if (error instanceof EngineStoreError && error.code === "closed") throw new PolymarketError("unlock-required", "the vault is locked", { cause: error });
|
|
95
|
+
throw error;
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
function createPolymarketCredentials(options) {
|
|
99
|
+
const deleteListeners = /* @__PURE__ */ new Set();
|
|
100
|
+
return {
|
|
101
|
+
get: async (group) => {
|
|
102
|
+
const raw = await read(async () => options.storage.get(group, NAME));
|
|
103
|
+
if (raw === void 0) return;
|
|
104
|
+
const parsed = parse(raw);
|
|
105
|
+
if (parsed === void 0) options.logger.warn(`polymarket credentials ${group.walletId}/${group.groupIndex} skipped: malformed`);
|
|
106
|
+
return parsed;
|
|
107
|
+
},
|
|
108
|
+
put: async (group, value) => {
|
|
109
|
+
const normalized = {
|
|
110
|
+
owner: value.owner,
|
|
111
|
+
apiKey: value.apiKey.toLowerCase(),
|
|
112
|
+
secret: value.secret,
|
|
113
|
+
passphrase: value.passphrase
|
|
114
|
+
};
|
|
115
|
+
if (!isAddress$1(normalized.owner) || !fieldsValid(normalized)) throw new PolymarketError("malformed", "the credential fields failed validation");
|
|
116
|
+
await read(async () => options.storage.put(group, NAME, utf8ToBytes(JSON.stringify(normalized))));
|
|
117
|
+
},
|
|
118
|
+
delete: async (group) => {
|
|
119
|
+
await read(async () => options.storage.delete(group, NAME));
|
|
120
|
+
for (const listener of deleteListeners) try {
|
|
121
|
+
listener(group);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
options.logger.warn("polymarket credentials delete listener threw", error);
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
onDelete: (listener) => {
|
|
127
|
+
deleteListeners.add(listener);
|
|
128
|
+
return () => {
|
|
129
|
+
deleteListeners.delete(listener);
|
|
130
|
+
};
|
|
131
|
+
},
|
|
132
|
+
groups: async () => read(options.storage.groups)
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
// src/apps/polymarket/constants.ts
|
|
136
|
+
/**
|
|
137
|
+
* Polymarket hosts (docs.polymarket.com getting-started/api.md; research.md §5). Every request goes
|
|
138
|
+
* to one of these over the injected fetch — nothing else is a valid base.
|
|
139
|
+
*/
|
|
140
|
+
/** Gamma API — market/event metadata (events, markets, search). */
|
|
141
|
+
const GAMMA_HOST = "https://gamma-api.polymarket.com";
|
|
142
|
+
/** CLOB REST — order book, prices, fees, server time, L2-authenticated trading. */
|
|
143
|
+
const CLOB_HOST = "https://clob.polymarket.com";
|
|
144
|
+
/** Data API v2 — positions, activity, resolutions, approvals. */
|
|
145
|
+
const DATA_HOST = "https://data-api.polymarket.com";
|
|
146
|
+
/** Relayer — deposit-wallet deploy, batched approvals, Safe transactions. */
|
|
147
|
+
const RELAYER_HOST = "https://relayer-v2.polymarket.com";
|
|
148
|
+
/** Market-channel WebSocket (`/ws/market`) — book/price/trade events. */
|
|
149
|
+
const MARKET_WS_URL = "wss://ws-subscriptions-clob.polymarket.com/ws/market";
|
|
150
|
+
/** User-channel WebSocket (`/ws/user`) — authenticated order/trade events (asyncapi user.json). */
|
|
151
|
+
const USER_WS_URL = "wss://ws-subscriptions-clob.polymarket.com/ws/user";
|
|
152
|
+
/**
|
|
153
|
+
* Deposit-wallet CREATE2 factory — every deposit wallet is `CREATE2(factory, keccak256(
|
|
154
|
+
* abi.encode(factory, bytes32(signer))), initCodeHash)` (docs trading/wallets-auth.md §Derive a
|
|
155
|
+
* Deposit Wallet Address + resources/contracts.md).
|
|
156
|
+
*/
|
|
157
|
+
const DEPOSIT_WALLET_FACTORY = "0x00000000000Fb5C9ADea0298D729A0CB3823Cc07";
|
|
158
|
+
/** The beacon the current deposit-wallet proxy template points at (resources/contracts.md). */
|
|
159
|
+
const DEPOSIT_WALLET_BEACON = "0x7A18EDfe055488A3128f01F563e5B479D92ffc3a";
|
|
160
|
+
/**
|
|
161
|
+
* The UUPS implementation the pre-beacon deposit-wallet template points at (wallets deployed before
|
|
162
|
+
* 2026-06-29 — resources/contracts.md; `@polymarket/client@0.18.0` walletDerivation).
|
|
163
|
+
*/
|
|
164
|
+
const DEPOSIT_WALLET_IMPLEMENTATION = "0x58CA52ebe0DadfdF531Cde7062e76746de4Db1eB";
|
|
165
|
+
/** The Safe proxy factory legacy accounts deployed through (resources/contracts.md). */
|
|
166
|
+
const SAFE_FACTORY = "0xaacFeEa03eb1561C4e67d661e40682Bd20E3541b";
|
|
167
|
+
/**
|
|
168
|
+
* Keccak256 of the Safe proxy init code Polymarket deployed legacy accounts with
|
|
169
|
+
* (`@polymarket/client@0.18.0` `walletDerivation.safeInitCodeHash` — checked on-chain, research.md
|
|
170
|
+
* §1a).
|
|
171
|
+
*/
|
|
172
|
+
const SAFE_INIT_CODE_HASH = "0x2bce2127ff07fb632d16c8347c4ebf501f4841168bed00d9e6ef715ddb6fcecf";
|
|
173
|
+
/** The shared EIP-712 domain name of the CTF exchanges (docs §Order Domain). */
|
|
174
|
+
const CTF_EXCHANGE_NAME = "Polymarket CTF Exchange";
|
|
175
|
+
/** CTF Exchange v2 — non-neg-risk V1 markets (docs §Order Domain; contracts.md). */
|
|
176
|
+
const CTF_EXCHANGE_V2 = "0xE111180000d2663C0091e4f400237545B87B996B";
|
|
177
|
+
/** CTF Exchange v2 — neg-risk V1 markets (docs §Order Domain; contracts.md). */
|
|
178
|
+
const NEG_RISK_EXCHANGE_V2 = "0xe2222d279d744050d28e00520010520000310F59";
|
|
179
|
+
/** CTF Exchange v3 — `version: "v2"` markets (docs §Order Domain; contracts.md). */
|
|
180
|
+
const CTF_EXCHANGE_V3 = "0xe3333700cA9d93003F00f0F71f8515005F6c00Aa";
|
|
181
|
+
/** PUSD — the 6-decimal collateral every approval batch approves first (concepts/pusd.md). */
|
|
182
|
+
const PUSD = "0xC011a7E12a19f7B1f670d46F03B03f3342E82DFB";
|
|
183
|
+
/** PositionManager — V2 outcome-token ledger (trading/wallets-auth.md §Set Up Trading Approvals). */
|
|
184
|
+
const POSITION_MANAGER = "0x006F54F7f9A22e0000CC2AB60031000000ae9fEF";
|
|
185
|
+
/** Conditional Tokens — V1 outcome-token ledger (trading/wallets-auth.md; contracts.md). */
|
|
186
|
+
const CONDITIONAL_TOKENS = "0x4D97DCd97eC945f40cF65F87097ACe5EA0476045";
|
|
187
|
+
/** Neg Risk Adapter — converts/merges neg-risk positions (trading/wallets-auth.md; contracts.md). */
|
|
188
|
+
const NEG_RISK_ADAPTER = "0xd91E80cF2E7be2e162c6513ceD06f1dD0dA35296";
|
|
189
|
+
/** `path` may be absolute-joined only onto `host` — the URL keeps the host's origin+path. */
|
|
190
|
+
const buildUrl = (request) => {
|
|
191
|
+
const url = new URL(`${request.host}${request.path}`);
|
|
192
|
+
for (const [key, value] of Object.entries(request.query ?? {})) url.searchParams.set(key, String(value));
|
|
193
|
+
return url.toString();
|
|
194
|
+
};
|
|
195
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
196
|
+
/** The server's parsed error body when it is a JSON object — a non-JSON body carries none. */
|
|
197
|
+
const errorBody = async (response) => {
|
|
198
|
+
try {
|
|
199
|
+
const body = await response.json();
|
|
200
|
+
if (isRecord(body)) return body;
|
|
201
|
+
} catch {}
|
|
202
|
+
};
|
|
203
|
+
function createPolymarketHttp(options) {
|
|
204
|
+
const timeoutMs = options.timeoutMs ?? 1e4;
|
|
205
|
+
const request = async (input, schema) => {
|
|
206
|
+
const bound = timeoutSignal(timeoutMs, options.setTimer);
|
|
207
|
+
const url = buildUrl(input);
|
|
208
|
+
try {
|
|
209
|
+
const response = await options.fetch(url, {
|
|
210
|
+
method: input.method,
|
|
211
|
+
...input.headers === void 0 ? {} : { headers: input.headers },
|
|
212
|
+
...input.body === void 0 ? {} : { body: input.body },
|
|
213
|
+
signal: bound.signal
|
|
214
|
+
});
|
|
215
|
+
if (!response.ok) {
|
|
216
|
+
const body = await errorBody(response);
|
|
217
|
+
const detail = body?.["error"];
|
|
218
|
+
throw new PolymarketError("unavailable", `${input.method} ${input.path} answered ${response.status}${typeof detail === "string" ? `: ${detail.slice(0, 200)}` : ""}`, {
|
|
219
|
+
status: response.status,
|
|
220
|
+
...body === void 0 ? {} : { body }
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
let body;
|
|
224
|
+
try {
|
|
225
|
+
body = await response.json();
|
|
226
|
+
} catch (error) {
|
|
227
|
+
throw new PolymarketError("malformed", `${input.method} ${input.path} answered non-JSON`, { cause: error });
|
|
228
|
+
}
|
|
229
|
+
const parsed = z$1.safeParse(schema, body);
|
|
230
|
+
if (!parsed.success) throw new PolymarketError("malformed", `${input.method} ${input.path} failed its schema`, { cause: parsed.error });
|
|
231
|
+
return parsed.data;
|
|
232
|
+
} catch (error) {
|
|
233
|
+
if (error instanceof PolymarketError) throw error;
|
|
234
|
+
if (bound.signal.aborted) throw new PolymarketError("timeout", `${input.method} ${input.path} timed out`, { cause: error });
|
|
235
|
+
throw new PolymarketError("network", `${input.method} ${input.path} failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
236
|
+
} finally {
|
|
237
|
+
bound.cancel();
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
return {
|
|
241
|
+
request,
|
|
242
|
+
time: async () => {
|
|
243
|
+
const start = options.now();
|
|
244
|
+
const seconds = await request({
|
|
245
|
+
host: CLOB_HOST,
|
|
246
|
+
method: "GET",
|
|
247
|
+
path: "/time"
|
|
248
|
+
}, z$1.int());
|
|
249
|
+
const midpoint = (start + options.now()) / 2;
|
|
250
|
+
return {
|
|
251
|
+
serverSeconds: seconds,
|
|
252
|
+
skewMs: seconds * 1e3 - midpoint
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
}
|
|
257
|
+
// src/apps/polymarket/schemas.ts
|
|
258
|
+
/**
|
|
259
|
+
* Zod/mini schemas for the Gamma/CLOB/Data answers the provider reads (design.md 不变量 7) — exactly
|
|
260
|
+
* the fields we consume, unknown keys ignored (`looseObject`), bounded lengths so a hostile answer
|
|
261
|
+
* cannot balloon memory. Field shapes follow the archived specs
|
|
262
|
+
* (evidence/specs/{gamma,clob,data-api-v2}-openapi) and the live recordings.
|
|
263
|
+
*
|
|
264
|
+
* Wire quirks handled here: money/price/size fields arrive as numbers OR decimal strings and
|
|
265
|
+
* normalise to strings; Gamma carries `outcomes`/`clobTokenIds`/`outcomePrices` as JSON _text_
|
|
266
|
+
* (parsed strictly in markets.ts — the schema only bounds the string); `version` absent means
|
|
267
|
+
* "v1".
|
|
268
|
+
*/
|
|
269
|
+
const MAX_TEXT = 8192;
|
|
270
|
+
const MAX_ITEMS = 512;
|
|
271
|
+
const MAX_MARKETS = 256;
|
|
272
|
+
/** `0x` + 64 hex — a condition/question/order id. */
|
|
273
|
+
const conditionId = z$1.string().check(z$1.regex(/^0x[0-9a-fA-F]{64}$/));
|
|
274
|
+
/** A uint256 as decimal text — token/asset ids. */
|
|
275
|
+
const uint256 = z$1.string().check(z$1.regex(/^[0-9]{1,78}$/));
|
|
276
|
+
/** Decimal-looking text or a finite number, normalised to its string form. */
|
|
277
|
+
const wireDecimal = z$1.pipe(z$1.union([z$1.string().check(z$1.maxLength(64)), z$1.number()]), z$1.transform((value) => typeof value === "number" ? String(value) : value));
|
|
278
|
+
const wireDecimalOrNull = z$1.union([wireDecimal, z$1.null()]);
|
|
279
|
+
const boolOrNull = z$1.union([z$1.boolean(), z$1.null()]);
|
|
280
|
+
const textOrNull = z$1.union([z$1.string().check(z$1.maxLength(MAX_TEXT)), z$1.null()]);
|
|
281
|
+
/** Specs/gamma-openapi.yaml `Market` — the fields we read, nullable per the spec where noted. */
|
|
282
|
+
const gammaMarket = z$1.looseObject({
|
|
283
|
+
id: z$1.string().check(z$1.maxLength(32)),
|
|
284
|
+
conditionId,
|
|
285
|
+
slug: z$1.string().check(z$1.maxLength(512)),
|
|
286
|
+
question: textOrNull,
|
|
287
|
+
questionID: z$1.optional(z$1.union([conditionId, z$1.null()])),
|
|
288
|
+
questionId: z$1.optional(z$1.union([conditionId, z$1.null()])),
|
|
289
|
+
outcomes: z$1.string().check(z$1.maxLength(MAX_TEXT)),
|
|
290
|
+
clobTokenIds: z$1.optional(textOrNull),
|
|
291
|
+
positionIds: z$1.optional(z$1.union([z$1.array(uint256).check(z$1.maxLength(16)), z$1.null()])),
|
|
292
|
+
version: z$1.optional(textOrNull),
|
|
293
|
+
negRisk: z$1.optional(boolOrNull),
|
|
294
|
+
orderPriceMinTickSize: z$1.optional(wireDecimalOrNull),
|
|
295
|
+
orderMinSize: z$1.optional(wireDecimalOrNull),
|
|
296
|
+
acceptingOrders: z$1.optional(boolOrNull),
|
|
297
|
+
active: z$1.optional(boolOrNull),
|
|
298
|
+
closed: z$1.optional(boolOrNull),
|
|
299
|
+
endDate: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(64)), z$1.null()])),
|
|
300
|
+
outcomePrices: z$1.optional(textOrNull),
|
|
301
|
+
volume: z$1.optional(wireDecimalOrNull),
|
|
302
|
+
liquidity: z$1.optional(wireDecimalOrNull),
|
|
303
|
+
makerBaseFee: z$1.optional(z$1.union([z$1.number(), z$1.null()])),
|
|
304
|
+
takerBaseFee: z$1.optional(z$1.union([z$1.number(), z$1.null()]))
|
|
305
|
+
});
|
|
306
|
+
const gammaMarketList = z$1.array(gammaMarket).check(z$1.maxLength(MAX_MARKETS));
|
|
307
|
+
/** Specs/gamma-openapi.yaml `Event` — `markets` embeds full Market rows. */
|
|
308
|
+
const gammaEvent = z$1.looseObject({
|
|
309
|
+
id: z$1.string().check(z$1.maxLength(32)),
|
|
310
|
+
slug: z$1.string().check(z$1.maxLength(512)),
|
|
311
|
+
title: textOrNull,
|
|
312
|
+
active: z$1.optional(boolOrNull),
|
|
313
|
+
closed: z$1.optional(boolOrNull),
|
|
314
|
+
negRisk: z$1.optional(boolOrNull),
|
|
315
|
+
endDate: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(64)), z$1.null()])),
|
|
316
|
+
markets: z$1.optional(z$1.union([gammaMarketList, z$1.null()]))
|
|
317
|
+
});
|
|
318
|
+
const gammaEventList = z$1.array(gammaEvent).check(z$1.maxLength(MAX_ITEMS));
|
|
319
|
+
/** `/public-search` `Search` — events only; tags/profiles are ignored. */
|
|
320
|
+
const gammaSearch = z$1.looseObject({ events: z$1.optional(z$1.union([gammaEventList, z$1.null()])) });
|
|
321
|
+
const orderSummary = z$1.looseObject({
|
|
322
|
+
price: z$1.string().check(z$1.maxLength(32)),
|
|
323
|
+
size: z$1.string().check(z$1.maxLength(64))
|
|
324
|
+
});
|
|
325
|
+
/** `OrderBookSummary` — bids desc / asks asc per the spec; markets.ts re-sorts defensively. */
|
|
326
|
+
const clobBook = z$1.looseObject({
|
|
327
|
+
market: conditionId,
|
|
328
|
+
asset_id: uint256,
|
|
329
|
+
timestamp: z$1.string().check(z$1.maxLength(32)),
|
|
330
|
+
hash: z$1.string().check(z$1.maxLength(128)),
|
|
331
|
+
bids: z$1.array(orderSummary).check(z$1.maxLength(MAX_ITEMS)),
|
|
332
|
+
asks: z$1.array(orderSummary).check(z$1.maxLength(MAX_ITEMS)),
|
|
333
|
+
min_order_size: wireDecimal,
|
|
334
|
+
tick_size: wireDecimal,
|
|
335
|
+
neg_risk: z$1.boolean(),
|
|
336
|
+
last_trade_price: z$1.optional(wireDecimalOrNull),
|
|
337
|
+
version: z$1.optional(textOrNull)
|
|
338
|
+
});
|
|
339
|
+
const clobPrice = z$1.looseObject({ price: wireDecimal });
|
|
340
|
+
/** The spec documents `mid_price`; the live key is `mid` (recording `midpoint-primary.json`). */
|
|
341
|
+
const clobMidpoint = z$1.looseObject({ mid: wireDecimal });
|
|
342
|
+
const clobFeeRate = z$1.looseObject({ base_fee: z$1.number() });
|
|
343
|
+
const clobPricesHistory = z$1.looseObject({ history: z$1.array(z$1.looseObject({
|
|
344
|
+
t: z$1.number(),
|
|
345
|
+
p: wireDecimal
|
|
346
|
+
})).check(z$1.maxLength(1e4)) });
|
|
347
|
+
const clobToken = z$1.looseObject({
|
|
348
|
+
t: uint256,
|
|
349
|
+
o: z$1.optional(textOrNull)
|
|
350
|
+
});
|
|
351
|
+
/**
|
|
352
|
+
* `ClobMarketDetails` — live abbreviated keys (recording `clob-market-primary.json`): `c`
|
|
353
|
+
* conditionId, `t` tokens, `mos`/`mts` order minimums, `ao` accepting orders, `cbos` closed
|
|
354
|
+
* buy-only, `aot` accepting-orders timestamp, `ibce` Blockaid check, `v` version, `r` rewards (`e`
|
|
355
|
+
* enabled, `mi`/`ma` incentive bounds, `moas` min order age). The archived spec's
|
|
356
|
+
* `mbf`/`tbf`/`rfqe`/`itode`/`oas` fields do not appear on live answers.
|
|
357
|
+
*/
|
|
358
|
+
const clobRewards = z$1.looseObject({
|
|
359
|
+
e: z$1.optional(boolOrNull),
|
|
360
|
+
mi: z$1.optional(wireDecimalOrNull),
|
|
361
|
+
ma: z$1.optional(wireDecimalOrNull),
|
|
362
|
+
moas: z$1.optional(z$1.union([z$1.number(), z$1.null()]))
|
|
363
|
+
});
|
|
364
|
+
const clobMarketDetails = z$1.looseObject({
|
|
365
|
+
c: z$1.optional(z$1.union([conditionId, z$1.null()])),
|
|
366
|
+
t: z$1.array(clobToken).check(z$1.maxLength(16)),
|
|
367
|
+
mos: z$1.optional(wireDecimalOrNull),
|
|
368
|
+
mts: z$1.optional(wireDecimalOrNull),
|
|
369
|
+
ao: z$1.optional(boolOrNull),
|
|
370
|
+
cbos: z$1.optional(boolOrNull),
|
|
371
|
+
aot: z$1.optional(textOrNull),
|
|
372
|
+
ibce: z$1.optional(boolOrNull),
|
|
373
|
+
r: z$1.optional(z$1.union([clobRewards, z$1.null()])),
|
|
374
|
+
v: z$1.optional(textOrNull)
|
|
375
|
+
});
|
|
376
|
+
/** `/v2/resolutions` rows — UMA/V2 lifecycle fields; `payouts` in micro-USDC per share. */
|
|
377
|
+
const resolutionRow = z$1.looseObject({
|
|
378
|
+
condition_id: z$1.optional(z$1.union([conditionId, z$1.null()])),
|
|
379
|
+
question_id: z$1.optional(z$1.union([conditionId, z$1.null()])),
|
|
380
|
+
status: z$1.string().check(z$1.maxLength(32)),
|
|
381
|
+
market_type: z$1.optional(textOrNull),
|
|
382
|
+
reporter: z$1.optional(textOrNull),
|
|
383
|
+
was_disputed: z$1.boolean(),
|
|
384
|
+
extended_review: z$1.boolean(),
|
|
385
|
+
resolved_at: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(64)), z$1.null()])),
|
|
386
|
+
payouts: z$1.optional(z$1.union([z$1.array(z$1.number()).check(z$1.maxLength(16)), z$1.null()])),
|
|
387
|
+
price: z$1.optional(wireDecimalOrNull)
|
|
388
|
+
});
|
|
389
|
+
const dataResolutions = z$1.looseObject({ data: z$1.array(resolutionRow).check(z$1.maxLength(64)) });
|
|
390
|
+
/** `0x` + 40 hex — an EVM address; the output keeps the template type. */
|
|
391
|
+
const evmAddress = z$1.custom((value) => typeof value === "string" && /^0x[0-9a-fA-F]{40}$/.test(value));
|
|
392
|
+
/** Relayer `GET /deployed` — the only field the locate step reads. */
|
|
393
|
+
const relayerDeployed = z$1.looseObject({ deployed: z$1.boolean() });
|
|
394
|
+
/** The Data-v2 paged envelope — `next_cursor` is the only page token callers follow. */
|
|
395
|
+
const dataPagination = z$1.looseObject({
|
|
396
|
+
has_more: z$1.boolean(),
|
|
397
|
+
next_cursor: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(4096)), z$1.null()]))
|
|
398
|
+
});
|
|
399
|
+
/**
|
|
400
|
+
* `/v2/positions` rows (specs/data-api-v2-openapi.json `Position`, plus the live record
|
|
401
|
+
* `account-positions.json`): money/size/PnL fields are numbers on the wire and normalise to strings
|
|
402
|
+
* — a `null` numeric means unavailable, never zero.
|
|
403
|
+
*/
|
|
404
|
+
const dataPosition = z$1.looseObject({
|
|
405
|
+
proxy_wallet: evmAddress,
|
|
406
|
+
token_id: uint256,
|
|
407
|
+
condition_id: conditionId,
|
|
408
|
+
current_size: wireDecimal,
|
|
409
|
+
avg_price: z$1.optional(wireDecimalOrNull),
|
|
410
|
+
entry_cost_usdc: z$1.optional(wireDecimalOrNull),
|
|
411
|
+
entry_fees_usdc: z$1.optional(wireDecimalOrNull),
|
|
412
|
+
total_cost_usdc: z$1.optional(wireDecimalOrNull),
|
|
413
|
+
current_price: z$1.optional(wireDecimalOrNull),
|
|
414
|
+
current_value: z$1.optional(wireDecimalOrNull),
|
|
415
|
+
total_size: z$1.optional(wireDecimalOrNull),
|
|
416
|
+
realized_pnl: z$1.optional(wireDecimalOrNull),
|
|
417
|
+
unrealized_pnl: z$1.optional(wireDecimalOrNull),
|
|
418
|
+
total_pnl: z$1.optional(wireDecimalOrNull),
|
|
419
|
+
percent_pnl: z$1.optional(wireDecimalOrNull),
|
|
420
|
+
percent_realized_pnl: z$1.optional(wireDecimalOrNull),
|
|
421
|
+
status: z$1.string().check(z$1.maxLength(32)),
|
|
422
|
+
redeemable: z$1.optional(boolOrNull),
|
|
423
|
+
mergeable: z$1.optional(boolOrNull),
|
|
424
|
+
negative_risk: z$1.optional(boolOrNull),
|
|
425
|
+
archived: z$1.optional(boolOrNull),
|
|
426
|
+
title: z$1.optional(textOrNull),
|
|
427
|
+
slug: z$1.optional(textOrNull),
|
|
428
|
+
outcome: z$1.optional(textOrNull),
|
|
429
|
+
outcome_index: z$1.optional(z$1.union([z$1.number(), z$1.null()])),
|
|
430
|
+
opposite_outcome: z$1.optional(textOrNull),
|
|
431
|
+
opposite_token_id: z$1.optional(z$1.union([uint256, z$1.null()])),
|
|
432
|
+
end_date: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(64)), z$1.null()]))
|
|
433
|
+
});
|
|
434
|
+
const dataPositions = z$1.looseObject({
|
|
435
|
+
data: z$1.array(dataPosition).check(z$1.maxLength(MAX_ITEMS)),
|
|
436
|
+
pagination: dataPagination
|
|
437
|
+
});
|
|
438
|
+
/** `/v2/value` — exactly one row; an empty book still answers `{proxy_wallet, value: 0}`. */
|
|
439
|
+
const dataValue = z$1.looseObject({ data: z$1.looseObject({
|
|
440
|
+
proxy_wallet: evmAddress,
|
|
441
|
+
value: wireDecimal
|
|
442
|
+
}) });
|
|
443
|
+
/** `/v2/activity` rows — the feed fields the account view reads. */
|
|
444
|
+
const dataActivityItem = z$1.looseObject({
|
|
445
|
+
proxy_wallet: evmAddress,
|
|
446
|
+
timestamp: z$1.number(),
|
|
447
|
+
condition_id: z$1.string().check(z$1.maxLength(128)),
|
|
448
|
+
type: z$1.string().check(z$1.maxLength(32)),
|
|
449
|
+
size: z$1.optional(wireDecimalOrNull),
|
|
450
|
+
usdc_size: z$1.optional(wireDecimalOrNull),
|
|
451
|
+
transaction_hash: z$1.string().check(z$1.maxLength(128)),
|
|
452
|
+
price: z$1.optional(wireDecimalOrNull),
|
|
453
|
+
token_id: z$1.string().check(z$1.maxLength(128)),
|
|
454
|
+
side: z$1.optional(z$1.string().check(z$1.maxLength(16))),
|
|
455
|
+
outcome_index: z$1.optional(z$1.union([z$1.number(), z$1.null()])),
|
|
456
|
+
outcome: z$1.optional(textOrNull),
|
|
457
|
+
title: z$1.optional(textOrNull),
|
|
458
|
+
slug: z$1.optional(textOrNull)
|
|
459
|
+
});
|
|
460
|
+
const dataActivity = z$1.looseObject({
|
|
461
|
+
data: z$1.array(dataActivityItem).check(z$1.maxLength(MAX_ITEMS)),
|
|
462
|
+
pagination: dataPagination
|
|
463
|
+
});
|
|
464
|
+
/** `/v2/user-pnl` — dense cumulative points; nullable atoms mean unavailable, not zero. */
|
|
465
|
+
const dataPnlPoint = z$1.looseObject({
|
|
466
|
+
timestamp: z$1.number(),
|
|
467
|
+
source_block: z$1.optional(z$1.union([z$1.number(), z$1.null()])),
|
|
468
|
+
realized_pnl: wireDecimal,
|
|
469
|
+
position_pnl: z$1.optional(wireDecimalOrNull),
|
|
470
|
+
economic_pnl: z$1.optional(wireDecimalOrNull),
|
|
471
|
+
settled_pnl: z$1.optional(wireDecimalOrNull),
|
|
472
|
+
volume: z$1.optional(wireDecimalOrNull),
|
|
473
|
+
volume_usdc: z$1.optional(wireDecimalOrNull),
|
|
474
|
+
trade_count: z$1.optional(z$1.union([z$1.number(), z$1.null()]))
|
|
475
|
+
});
|
|
476
|
+
const dataUserPnl = z$1.looseObject({ data: z$1.looseObject({
|
|
477
|
+
proxy_wallet: evmAddress,
|
|
478
|
+
interval: z$1.string().check(z$1.maxLength(16)),
|
|
479
|
+
fidelity: z$1.string().check(z$1.maxLength(16)),
|
|
480
|
+
points: z$1.array(dataPnlPoint).check(z$1.maxLength(1e4))
|
|
481
|
+
}) });
|
|
482
|
+
/** `/v2/approvals` — the served catalog of token/operator approvals, canonical order. */
|
|
483
|
+
const approvalContract = z$1.looseObject({
|
|
484
|
+
id: z$1.string().check(z$1.maxLength(128)),
|
|
485
|
+
feature: z$1.string().check(z$1.maxLength(64)),
|
|
486
|
+
token: evmAddress,
|
|
487
|
+
spender: evmAddress,
|
|
488
|
+
standard: z$1.string().check(z$1.maxLength(16)),
|
|
489
|
+
amount: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(80)), z$1.null()])),
|
|
490
|
+
approved: z$1.boolean()
|
|
491
|
+
});
|
|
492
|
+
const dataApprovals = z$1.looseObject({ data: z$1.looseObject({
|
|
493
|
+
address: evmAddress,
|
|
494
|
+
chain_id: z$1.number(),
|
|
495
|
+
checked_at: z$1.string().check(z$1.maxLength(64)),
|
|
496
|
+
contracts: z$1.array(approvalContract).check(z$1.maxLength(128))
|
|
497
|
+
}) });
|
|
498
|
+
const clobBoundedText = z$1.string().check(z$1.maxLength(128));
|
|
499
|
+
/**
|
|
500
|
+
* `OpenOrder` — the `/data/orders` row and the `/data/order/{id}` answer (specs/clob-openapi.yaml;
|
|
501
|
+
* docs fixture `l2-orders.json`). Sizes/prices arrive as decimal strings already normalised.
|
|
502
|
+
*/
|
|
503
|
+
const clobOpenOrder = z$1.looseObject({
|
|
504
|
+
id: clobBoundedText,
|
|
505
|
+
status: z$1.string().check(z$1.maxLength(64)),
|
|
506
|
+
owner: clobBoundedText,
|
|
507
|
+
maker_address: evmAddress,
|
|
508
|
+
market: clobBoundedText,
|
|
509
|
+
asset_id: clobBoundedText,
|
|
510
|
+
side: z$1.string().check(z$1.maxLength(8)),
|
|
511
|
+
original_size: z$1.string().check(z$1.maxLength(64)),
|
|
512
|
+
size_matched: z$1.string().check(z$1.maxLength(64)),
|
|
513
|
+
price: z$1.string().check(z$1.maxLength(32)),
|
|
514
|
+
outcome: z$1.optional(textOrNull),
|
|
515
|
+
expiration: z$1.string().check(z$1.maxLength(32)),
|
|
516
|
+
order_type: z$1.string().check(z$1.maxLength(8)),
|
|
517
|
+
created_at: z$1.number()
|
|
518
|
+
});
|
|
519
|
+
/** `DELETE /auth/api-key` answers the bare string "OK" (specs/clob-openapi.yaml /auth/api-key). */
|
|
520
|
+
const clobApiKeyDelete = z$1.string().check(z$1.maxLength(64));
|
|
521
|
+
/**
|
|
522
|
+
* `POST`/`GET /auth/api-key|derive-api-key` — the L1 credentials answer (specs/clob-openapi.yaml
|
|
523
|
+
* `ApiKeyResponse`; getting-started/api.md §Create or Derive API Keys). Held only until the
|
|
524
|
+
* credential store seals it — never logged.
|
|
525
|
+
*/
|
|
526
|
+
const clobApiKeyResponse = z$1.looseObject({
|
|
527
|
+
apiKey: z$1.string().check(z$1.maxLength(64)),
|
|
528
|
+
secret: z$1.string().check(z$1.maxLength(256)),
|
|
529
|
+
passphrase: z$1.string().check(z$1.maxLength(128))
|
|
530
|
+
});
|
|
531
|
+
/** `POST /submit` — the immediate `{transactionID, state}` (specs/relayer-openapi.yaml). */
|
|
532
|
+
const relayerSubmitResponse = z$1.looseObject({
|
|
533
|
+
transactionID: z$1.string().check(z$1.maxLength(64)),
|
|
534
|
+
state: z$1.string().check(z$1.maxLength(32))
|
|
535
|
+
});
|
|
536
|
+
/** `GET /transaction?id=` row — the array the poll reads (specs/relayer-openapi.yaml). */
|
|
537
|
+
const relayerTransaction = z$1.looseObject({
|
|
538
|
+
transactionID: z$1.string().check(z$1.maxLength(64)),
|
|
539
|
+
state: z$1.string().check(z$1.maxLength(32)),
|
|
540
|
+
transactionHash: z$1.optional(z$1.string().check(z$1.maxLength(80))),
|
|
541
|
+
proxyAddress: z$1.optional(evmAddress)
|
|
542
|
+
});
|
|
543
|
+
const relayerTransactions = z$1.array(relayerTransaction).check(z$1.maxLength(16));
|
|
544
|
+
/** `GET /nonce?type=WALLET` — the wallet's batch nonce (specs/relayer-openapi.yaml). */
|
|
545
|
+
const relayerNonce = z$1.looseObject({ nonce: z$1.string().check(z$1.maxLength(32)) });
|
|
546
|
+
/** `OrdersResponse` — `next_cursor` is empty when the page is the last. */
|
|
547
|
+
const clobOrdersPage = z$1.looseObject({
|
|
548
|
+
limit: z$1.number(),
|
|
549
|
+
next_cursor: z$1.string().check(z$1.maxLength(4096)),
|
|
550
|
+
count: z$1.number(),
|
|
551
|
+
data: z$1.array(clobOpenOrder).check(z$1.maxLength(MAX_ITEMS))
|
|
552
|
+
});
|
|
553
|
+
const clobMakerOrder = z$1.looseObject({
|
|
554
|
+
order_id: clobBoundedText,
|
|
555
|
+
owner: z$1.optional(clobBoundedText),
|
|
556
|
+
maker_address: z$1.optional(clobBoundedText),
|
|
557
|
+
matched_amount: z$1.string().check(z$1.maxLength(64)),
|
|
558
|
+
price: z$1.string().check(z$1.maxLength(32)),
|
|
559
|
+
fee_rate_bps: z$1.optional(z$1.union([clobBoundedText, z$1.null()])),
|
|
560
|
+
asset_id: z$1.optional(clobBoundedText),
|
|
561
|
+
outcome: z$1.optional(textOrNull),
|
|
562
|
+
side: z$1.optional(z$1.string().check(z$1.maxLength(8)))
|
|
563
|
+
});
|
|
564
|
+
/** `Trade` — the `/data/trades` row; `maker_orders` may be `[]`. */
|
|
565
|
+
const clobTrade = z$1.looseObject({
|
|
566
|
+
id: clobBoundedText,
|
|
567
|
+
taker_order_id: clobBoundedText,
|
|
568
|
+
market: clobBoundedText,
|
|
569
|
+
asset_id: clobBoundedText,
|
|
570
|
+
side: z$1.string().check(z$1.maxLength(8)),
|
|
571
|
+
size: z$1.string().check(z$1.maxLength(64)),
|
|
572
|
+
price: z$1.string().check(z$1.maxLength(32)),
|
|
573
|
+
status: z$1.string().check(z$1.maxLength(64)),
|
|
574
|
+
match_time: z$1.string().check(z$1.maxLength(32)),
|
|
575
|
+
last_update: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(32)), z$1.null()])),
|
|
576
|
+
outcome: z$1.optional(textOrNull),
|
|
577
|
+
bucket_index: z$1.optional(z$1.union([z$1.number(), z$1.null()])),
|
|
578
|
+
owner: z$1.optional(clobBoundedText),
|
|
579
|
+
maker_address: z$1.optional(clobBoundedText),
|
|
580
|
+
transaction_hash: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(128)), z$1.null()])),
|
|
581
|
+
fee_rate_bps: z$1.optional(z$1.union([clobBoundedText, z$1.null()])),
|
|
582
|
+
err_msg: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(512)), z$1.null()])),
|
|
583
|
+
maker_orders: z$1.optional(z$1.union([z$1.array(clobMakerOrder).check(z$1.maxLength(64)), z$1.null()])),
|
|
584
|
+
trader_side: z$1.string().check(z$1.maxLength(8))
|
|
585
|
+
});
|
|
586
|
+
/** `TradesResponse` — `next_cursor` of `LTE=` (base64 `-1`) means no more pages. */
|
|
587
|
+
const clobTradesPage = z$1.looseObject({
|
|
588
|
+
limit: z$1.number(),
|
|
589
|
+
next_cursor: z$1.string().check(z$1.maxLength(4096)),
|
|
590
|
+
count: z$1.number(),
|
|
591
|
+
data: z$1.array(clobTrade).check(z$1.maxLength(MAX_ITEMS))
|
|
592
|
+
});
|
|
593
|
+
/** `BalanceAllowanceResponse` — `balance`/`allowances` are raw 6-decimal integer strings. */
|
|
594
|
+
const clobBalanceAllowance = z$1.looseObject({
|
|
595
|
+
balance: z$1.string().check(z$1.maxLength(80)),
|
|
596
|
+
allowances: z$1.record(z$1.string().check(z$1.maxLength(64)), z$1.string().check(z$1.maxLength(80))).check(z$1.refine((map) => Object.keys(map).length <= 128))
|
|
597
|
+
});
|
|
598
|
+
/** `ClosedOnlyResponse` — a 404 (no record) normalises to `false` in account.ts. */
|
|
599
|
+
const clobClosedOnly = z$1.looseObject({ closed_only: z$1.boolean() });
|
|
600
|
+
const clobHashList = z$1.array(z$1.string().check(z$1.maxLength(80))).check(z$1.maxLength(64));
|
|
601
|
+
/**
|
|
602
|
+
* `SendOrderResponse` — the `POST /order` answer (specs/clob-openapi.yaml). `orderID`/`status` are
|
|
603
|
+
* validated against what we sent in trade.ts — a mismatched answer is never trusted.
|
|
604
|
+
*/
|
|
605
|
+
const clobPostOrderResponse = z$1.looseObject({
|
|
606
|
+
success: z$1.boolean(),
|
|
607
|
+
errorMsg: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(2048)), z$1.null()])),
|
|
608
|
+
orderID: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(80)), z$1.null()])),
|
|
609
|
+
status: z$1.optional(z$1.union([z$1.string().check(z$1.maxLength(32)), z$1.null()])),
|
|
610
|
+
makingAmount: z$1.optional(wireDecimalOrNull),
|
|
611
|
+
takingAmount: z$1.optional(wireDecimalOrNull),
|
|
612
|
+
transactionsHashes: z$1.optional(z$1.union([clobHashList, z$1.null()])),
|
|
613
|
+
tradeIDs: z$1.optional(z$1.union([z$1.array(clobBoundedText).check(z$1.maxLength(64)), z$1.null()]))
|
|
614
|
+
});
|
|
615
|
+
/**
|
|
616
|
+
* The cancel answers (`DELETE /order`, `/orders`, `/cancel-all`, `/cancel-market-orders`;
|
|
617
|
+
* specs/clob-openapi.yaml): `canceled` lists ids that were dropped, `not_canceled` maps id →
|
|
618
|
+
* reason.
|
|
619
|
+
*/
|
|
620
|
+
const clobCancelResponse = z$1.looseObject({
|
|
621
|
+
canceled: z$1.optional(z$1.union([z$1.array(clobBoundedText).check(z$1.maxLength(3e3)), z$1.null()])),
|
|
622
|
+
not_canceled: z$1.optional(z$1.union([z$1.record(clobBoundedText, z$1.string().check(z$1.maxLength(1024))).check(z$1.refine((map) => Object.keys(map).length <= 3e3)), z$1.null()]))
|
|
623
|
+
});
|
|
624
|
+
/** A `{"price","size"}` book level — `OrderSummary` in the spec. */
|
|
625
|
+
const wsLevel = z$1.looseObject({
|
|
626
|
+
price: z$1.string().check(z$1.maxLength(64)),
|
|
627
|
+
size: z$1.string().check(z$1.maxLength(64))
|
|
628
|
+
});
|
|
629
|
+
const wsAssetId = z$1.string().check(z$1.minLength(1), z$1.maxLength(80));
|
|
630
|
+
const wsTimestamp = z$1.optional(z$1.string().check(z$1.maxLength(20)));
|
|
631
|
+
/** `book` — a full orderbook snapshot for one asset. */
|
|
632
|
+
const wsBookEvent = z$1.looseObject({
|
|
633
|
+
event_type: z$1.literal("book"),
|
|
634
|
+
asset_id: wsAssetId,
|
|
635
|
+
market: z$1.string().check(z$1.maxLength(80)),
|
|
636
|
+
bids: z$1.array(wsLevel).check(z$1.maxLength(1e3)),
|
|
637
|
+
asks: z$1.array(wsLevel).check(z$1.maxLength(1e3)),
|
|
638
|
+
timestamp: wsTimestamp,
|
|
639
|
+
hash: z$1.optional(z$1.string().check(z$1.maxLength(200))),
|
|
640
|
+
tick_size: z$1.optional(z$1.string().check(z$1.maxLength(64)))
|
|
641
|
+
});
|
|
642
|
+
/** `price_change` — level deltas; `size` "0" removes the level. */
|
|
643
|
+
const wsPriceChangeEvent = z$1.looseObject({
|
|
644
|
+
event_type: z$1.literal("price_change"),
|
|
645
|
+
market: z$1.string().check(z$1.maxLength(80)),
|
|
646
|
+
price_changes: z$1.array(z$1.looseObject({
|
|
647
|
+
asset_id: wsAssetId,
|
|
648
|
+
price: z$1.string().check(z$1.maxLength(64)),
|
|
649
|
+
size: z$1.string().check(z$1.maxLength(64)),
|
|
650
|
+
side: z$1.enum(["BUY", "SELL"])
|
|
651
|
+
})).check(z$1.maxLength(1e3)),
|
|
652
|
+
timestamp: wsTimestamp
|
|
653
|
+
});
|
|
654
|
+
/** `last_trade_price` — the last matched trade on one asset. */
|
|
655
|
+
const wsLastTradePriceEvent = z$1.looseObject({
|
|
656
|
+
event_type: z$1.literal("last_trade_price"),
|
|
657
|
+
asset_id: wsAssetId,
|
|
658
|
+
market: z$1.string().check(z$1.maxLength(80)),
|
|
659
|
+
price: z$1.string().check(z$1.maxLength(64)),
|
|
660
|
+
size: z$1.string().check(z$1.maxLength(64)),
|
|
661
|
+
side: z$1.enum(["BUY", "SELL"]),
|
|
662
|
+
timestamp: wsTimestamp
|
|
663
|
+
});
|
|
664
|
+
/** `best_bid_ask` — needs `custom_feature_enabled` on subscribe. */
|
|
665
|
+
const wsBestBidAskEvent = z$1.looseObject({
|
|
666
|
+
event_type: z$1.literal("best_bid_ask"),
|
|
667
|
+
asset_id: wsAssetId,
|
|
668
|
+
market: z$1.string().check(z$1.maxLength(80)),
|
|
669
|
+
best_bid: z$1.string().check(z$1.maxLength(64)),
|
|
670
|
+
best_ask: z$1.string().check(z$1.maxLength(64)),
|
|
671
|
+
spread: z$1.string().check(z$1.maxLength(64)),
|
|
672
|
+
timestamp: wsTimestamp
|
|
673
|
+
});
|
|
674
|
+
/** `tick_size_change` — the market's minimum tick moved. */
|
|
675
|
+
const wsTickSizeChangeEvent = z$1.looseObject({
|
|
676
|
+
event_type: z$1.literal("tick_size_change"),
|
|
677
|
+
asset_id: wsAssetId,
|
|
678
|
+
market: z$1.string().check(z$1.maxLength(80)),
|
|
679
|
+
old_tick_size: z$1.string().check(z$1.maxLength(64)),
|
|
680
|
+
new_tick_size: z$1.string().check(z$1.maxLength(64)),
|
|
681
|
+
timestamp: wsTimestamp
|
|
682
|
+
});
|
|
683
|
+
/** `market_resolved` — needs `custom_feature_enabled` on subscribe. */
|
|
684
|
+
const wsMarketResolvedEvent = z$1.looseObject({
|
|
685
|
+
event_type: z$1.literal("market_resolved"),
|
|
686
|
+
id: z$1.optional(z$1.string().check(z$1.maxLength(80))),
|
|
687
|
+
market: z$1.string().check(z$1.maxLength(80)),
|
|
688
|
+
assets_ids: z$1.array(wsAssetId).check(z$1.maxLength(100)),
|
|
689
|
+
winning_asset_id: z$1.string().check(z$1.maxLength(80)),
|
|
690
|
+
winning_outcome: z$1.string().check(z$1.maxLength(200)),
|
|
691
|
+
timestamp: wsTimestamp
|
|
692
|
+
});
|
|
693
|
+
/**
|
|
694
|
+
* `order` — a placement/update/cancellation for the authenticated user. The spec requires only `id` +
|
|
695
|
+
* `type`; every field the upsert needs is optional here and checked by the caller.
|
|
696
|
+
* `owner`/`order_owner` carry the API key — parsed, never copied into view data.
|
|
697
|
+
*/
|
|
698
|
+
const wsUserOrderEvent = z$1.looseObject({
|
|
699
|
+
event_type: z$1.literal("order"),
|
|
700
|
+
id: z$1.string().check(z$1.maxLength(128)),
|
|
701
|
+
type: z$1.enum([
|
|
702
|
+
"PLACEMENT",
|
|
703
|
+
"UPDATE",
|
|
704
|
+
"CANCELLATION"
|
|
705
|
+
]),
|
|
706
|
+
status: z$1.optional(z$1.string().check(z$1.maxLength(32))),
|
|
707
|
+
market: z$1.optional(z$1.string().check(z$1.maxLength(80))),
|
|
708
|
+
asset_id: z$1.optional(z$1.string().check(z$1.maxLength(80))),
|
|
709
|
+
side: z$1.optional(z$1.string().check(z$1.maxLength(8))),
|
|
710
|
+
original_size: z$1.optional(z$1.string().check(z$1.maxLength(64))),
|
|
711
|
+
size_matched: z$1.optional(z$1.string().check(z$1.maxLength(64))),
|
|
712
|
+
price: z$1.optional(z$1.string().check(z$1.maxLength(32))),
|
|
713
|
+
outcome: z$1.optional(textOrNull),
|
|
714
|
+
order_type: z$1.optional(z$1.string().check(z$1.maxLength(8))),
|
|
715
|
+
expiration: z$1.optional(z$1.string().check(z$1.maxLength(32))),
|
|
716
|
+
created_at: z$1.optional(z$1.string().check(z$1.maxLength(32))),
|
|
717
|
+
maker_address: z$1.optional(z$1.string().check(z$1.maxLength(64))),
|
|
718
|
+
owner: z$1.optional(z$1.string().check(z$1.maxLength(64))),
|
|
719
|
+
order_owner: z$1.optional(z$1.string().check(z$1.maxLength(64))),
|
|
720
|
+
associate_trades: z$1.optional(z$1.union([z$1.array(z$1.string().check(z$1.maxLength(128))).check(z$1.maxLength(64)), z$1.null()])),
|
|
721
|
+
timestamp: wsTimestamp
|
|
722
|
+
});
|
|
723
|
+
/** `trade` — a match for the authenticated user; only its arrival matters (debounced re-read). */
|
|
724
|
+
const wsUserTradeEvent = z$1.looseObject({
|
|
725
|
+
event_type: z$1.literal("trade"),
|
|
726
|
+
type: z$1.literal("TRADE")
|
|
727
|
+
});
|
|
728
|
+
// src/apps/polymarket/relayer.ts
|
|
729
|
+
/** `/transaction` is polled every 2 s for up to 120 s (docs trading/wallets-auth.md §Deploy). */
|
|
730
|
+
const POLL_MS = 2e3;
|
|
731
|
+
const POLL_TIMEOUT_MS = 12e4;
|
|
732
|
+
/** The relayer's stale-nonce refusal (SDK `Ts()` — research.md §1). */
|
|
733
|
+
const NONCE_MISMATCH = /batch nonce\s+\d+\s+does not match on-chain nonce\s+\d+/i;
|
|
734
|
+
const isHeaders = (value) => {
|
|
735
|
+
if (typeof value !== "object" || value === null) return false;
|
|
736
|
+
return "POLY_BUILDER_API_KEY" in value && typeof value.POLY_BUILDER_API_KEY === "string" && value.POLY_BUILDER_API_KEY !== "" && "POLY_BUILDER_PASSPHRASE" in value && typeof value.POLY_BUILDER_PASSPHRASE === "string" && value.POLY_BUILDER_PASSPHRASE !== "" && "POLY_BUILDER_SIGNATURE" in value && typeof value.POLY_BUILDER_SIGNATURE === "string" && value.POLY_BUILDER_SIGNATURE !== "" && "POLY_BUILDER_TIMESTAMP" in value && typeof value.POLY_BUILDER_TIMESTAMP === "string" && /^[0-9]+$/.test(value.POLY_BUILDER_TIMESTAMP);
|
|
737
|
+
};
|
|
738
|
+
function createPolymarketRelayer(options) {
|
|
739
|
+
const sleep = async (ms) => new Promise((resolve) => {
|
|
740
|
+
options.setTimer(ms, resolve);
|
|
741
|
+
});
|
|
742
|
+
/** The builder oracle must answer exactly the four header fields — anything else is refused. */
|
|
743
|
+
const builderHeaders = async (body) => {
|
|
744
|
+
if (options.builder === void 0) throw new PolymarketError("builder-required", "this step submits through the relayer, which needs the host's builder signer");
|
|
745
|
+
const headers = await options.builder.sign({
|
|
746
|
+
method: "POST",
|
|
747
|
+
path: "/submit",
|
|
748
|
+
body
|
|
749
|
+
}).catch((error) => {
|
|
750
|
+
throw new PolymarketError("unavailable", "the builder signer failed", { cause: error });
|
|
751
|
+
});
|
|
752
|
+
if (!isHeaders(headers)) throw new PolymarketError("unavailable", "the builder signer returned malformed POLY_BUILDER_* headers");
|
|
753
|
+
return headers;
|
|
754
|
+
};
|
|
755
|
+
/** POST `/submit` with the exact `body` the builder just signed — never reserialized. */
|
|
756
|
+
const submit = async (body) => {
|
|
757
|
+
const headers = await builderHeaders(body);
|
|
758
|
+
try {
|
|
759
|
+
return await options.http.request({
|
|
760
|
+
host: RELAYER_HOST,
|
|
761
|
+
method: "POST",
|
|
762
|
+
path: "/submit",
|
|
763
|
+
headers: {
|
|
764
|
+
...headers,
|
|
765
|
+
"content-type": "application/json"
|
|
766
|
+
},
|
|
767
|
+
body
|
|
768
|
+
}, relayerSubmitResponse);
|
|
769
|
+
} catch (error) {
|
|
770
|
+
if (error instanceof PolymarketError && error.category === "unavailable" && error.status === 400 && typeof error.body?.["error"] === "string" && NONCE_MISMATCH.test(error.body["error"])) throw new PolymarketError("rejected", error.body["error"], { cause: error });
|
|
771
|
+
throw error;
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
/** Poll `GET /transaction?id=` to a terminal state; a lapse is `unavailable` (resumable). */
|
|
775
|
+
const confirm = async (transactionID) => {
|
|
776
|
+
const deadline = options.now() + POLL_TIMEOUT_MS;
|
|
777
|
+
for (;;) {
|
|
778
|
+
const row = (await options.http.request({
|
|
779
|
+
host: RELAYER_HOST,
|
|
780
|
+
method: "GET",
|
|
781
|
+
path: "/transaction",
|
|
782
|
+
query: { id: transactionID }
|
|
783
|
+
}, relayerTransactions)).find((r) => r.transactionID === transactionID);
|
|
784
|
+
if (row !== void 0 && row.state === "STATE_CONFIRMED") return row;
|
|
785
|
+
if (row !== void 0 && (row.state === "STATE_FAILED" || row.state === "STATE_INVALID")) throw new PolymarketError("rejected", `the relayer ${row.state === "STATE_FAILED" ? "failed" : "invalidated"} the transaction`);
|
|
786
|
+
if (options.now() >= deadline) throw new PolymarketError("unavailable", "the relayer transaction did not confirm in time — retry to resume");
|
|
787
|
+
await sleep(POLL_MS);
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
return {
|
|
791
|
+
nonce: async (signer) => {
|
|
792
|
+
const answer = await options.http.request({
|
|
793
|
+
host: RELAYER_HOST,
|
|
794
|
+
method: "GET",
|
|
795
|
+
path: "/nonce",
|
|
796
|
+
query: {
|
|
797
|
+
address: signer,
|
|
798
|
+
type: "WALLET"
|
|
799
|
+
}
|
|
800
|
+
}, relayerNonce);
|
|
801
|
+
return BigInt(answer.nonce);
|
|
802
|
+
},
|
|
803
|
+
deploy: async (signer, expected) => {
|
|
804
|
+
const body = JSON.stringify({
|
|
805
|
+
type: "WALLET-CREATE",
|
|
806
|
+
from: signer,
|
|
807
|
+
to: DEPOSIT_WALLET_FACTORY,
|
|
808
|
+
metadata: "Deploy Deposit Wallet"
|
|
809
|
+
});
|
|
810
|
+
const { transactionID } = await submit(body);
|
|
811
|
+
if ((await confirm(transactionID)).proxyAddress?.toLowerCase() !== expected.toLowerCase()) throw new PolymarketError("unavailable", "the relayer reported a different deposit wallet than our derivation — refusing it");
|
|
812
|
+
},
|
|
813
|
+
submitBatch: async (input) => {
|
|
814
|
+
const body = JSON.stringify({
|
|
815
|
+
type: "WALLET",
|
|
816
|
+
from: input.signer,
|
|
817
|
+
to: DEPOSIT_WALLET_FACTORY,
|
|
818
|
+
nonce: input.nonce.toString(10),
|
|
819
|
+
signature: input.signature,
|
|
820
|
+
metadata: input.metadata,
|
|
821
|
+
depositWalletParams: {
|
|
822
|
+
depositWallet: input.wallet,
|
|
823
|
+
deadline: String(input.deadline),
|
|
824
|
+
calls: input.calls.map((call) => ({
|
|
825
|
+
target: call.target,
|
|
826
|
+
value: call.value,
|
|
827
|
+
data: call.data
|
|
828
|
+
}))
|
|
829
|
+
}
|
|
830
|
+
});
|
|
831
|
+
const { transactionID } = await submit(body);
|
|
832
|
+
await confirm(transactionID);
|
|
833
|
+
}
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* The `DepositWallet` `Batch` typed-data document the owner signs — the exact shape the kernel's
|
|
838
|
+
* `polymarket` recognizer describes (vectors/chains/polymarket.json Batch cases; docs
|
|
839
|
+
* trading/wallets-auth.md "Create the Batch Typed Data").
|
|
840
|
+
*/
|
|
841
|
+
const batchTypedData = (input) => JSON.stringify({
|
|
842
|
+
types: {
|
|
843
|
+
EIP712Domain: [
|
|
844
|
+
{
|
|
845
|
+
name: "name",
|
|
846
|
+
type: "string"
|
|
847
|
+
},
|
|
848
|
+
{
|
|
849
|
+
name: "version",
|
|
850
|
+
type: "string"
|
|
851
|
+
},
|
|
852
|
+
{
|
|
853
|
+
name: "chainId",
|
|
854
|
+
type: "uint256"
|
|
855
|
+
},
|
|
856
|
+
{
|
|
857
|
+
name: "verifyingContract",
|
|
858
|
+
type: "address"
|
|
859
|
+
}
|
|
860
|
+
],
|
|
861
|
+
Batch: [
|
|
862
|
+
{
|
|
863
|
+
name: "wallet",
|
|
864
|
+
type: "address"
|
|
865
|
+
},
|
|
866
|
+
{
|
|
867
|
+
name: "nonce",
|
|
868
|
+
type: "uint256"
|
|
869
|
+
},
|
|
870
|
+
{
|
|
871
|
+
name: "deadline",
|
|
872
|
+
type: "uint256"
|
|
873
|
+
},
|
|
874
|
+
{
|
|
875
|
+
name: "calls",
|
|
876
|
+
type: "Call[]"
|
|
877
|
+
}
|
|
878
|
+
],
|
|
879
|
+
Call: [
|
|
880
|
+
{
|
|
881
|
+
name: "target",
|
|
882
|
+
type: "address"
|
|
883
|
+
},
|
|
884
|
+
{
|
|
885
|
+
name: "value",
|
|
886
|
+
type: "uint256"
|
|
887
|
+
},
|
|
888
|
+
{
|
|
889
|
+
name: "data",
|
|
890
|
+
type: "bytes"
|
|
891
|
+
}
|
|
892
|
+
]
|
|
893
|
+
},
|
|
894
|
+
primaryType: "Batch",
|
|
895
|
+
domain: {
|
|
896
|
+
name: "DepositWallet",
|
|
897
|
+
version: "1",
|
|
898
|
+
chainId: 137,
|
|
899
|
+
verifyingContract: input.wallet
|
|
900
|
+
},
|
|
901
|
+
message: {
|
|
902
|
+
wallet: input.wallet,
|
|
903
|
+
nonce: Number(input.nonce),
|
|
904
|
+
deadline: input.deadline,
|
|
905
|
+
calls: input.calls.map((call) => ({
|
|
906
|
+
target: call.target,
|
|
907
|
+
value: Number(call.value),
|
|
908
|
+
data: call.data
|
|
909
|
+
}))
|
|
910
|
+
}
|
|
911
|
+
});
|
|
912
|
+
// src/apps/polymarket/wallets.ts
|
|
913
|
+
const BEACON_PREFIX = 458075474873290183227763n;
|
|
914
|
+
const BEACON_RUNTIME = [
|
|
915
|
+
"0x60195155f3363d3d373d3d363d602036600436635c60da",
|
|
916
|
+
"0x1b60e01b36527fa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6c",
|
|
917
|
+
"0xb3582b35133d50545afa5036515af43d6000803e604d573d6000fd5b3d6000f3"
|
|
918
|
+
];
|
|
919
|
+
const UUPS_PREFIX = 458073961663815386741107n;
|
|
920
|
+
const UUPS_RUNTIME = [
|
|
921
|
+
"0x6009",
|
|
922
|
+
"0x5155f3363d3d373d3d363d7f360894a13ba1a3210667c828492db98dca3e2076",
|
|
923
|
+
"0xcc3735a920a3ca505d382bbc545af43d6000803e6038573d6000fd5b3d6000f3"
|
|
924
|
+
];
|
|
925
|
+
const isSigner = (signer) => /^0x[0-9a-fA-F]{40}$/.test(signer);
|
|
926
|
+
/** `1 << 56` as a multiplier — the args length lands in the prefix's third byte. */
|
|
927
|
+
const BYTE56 = 72057594037927936n;
|
|
928
|
+
/**
|
|
929
|
+
* The PUSH2 length prefix: the constant already encodes the runtime size, and the args length is
|
|
930
|
+
* added into its top bytes — `uint80BE(prefix + (len << 56))` per the Solady formula.
|
|
931
|
+
*/
|
|
932
|
+
const prefixFor = (prefix, argsBytes) => numberToHex(prefix + BigInt(argsBytes) * BYTE56, { size: 10 });
|
|
933
|
+
const depositArgs = (signer) => encodeAbiParameters([{ type: "address" }, { type: "bytes32" }], [DEPOSIT_WALLET_FACTORY, padHex(signer, { size: 32 })]);
|
|
934
|
+
/**
|
|
935
|
+
* The runtime the deployed deposit-wallet proxy carries: the init code minus its creation part —
|
|
936
|
+
* the runtime segments concatenated with `args`, dropping the first 5 bytes (the constructor tail
|
|
937
|
+
* `PUSH1 slot-offset; MLOAD; SSTORE; RETURN` that stores the template in the ERC-1967 slot: `60 19
|
|
938
|
+
* 51 55 f3` beacon, `60 09 51 55 f3` UUPS).
|
|
939
|
+
*/
|
|
940
|
+
const expectedPolymarketWalletRuntime = (kind, signer) => {
|
|
941
|
+
return `0x${concat([...kind === "beacon" ? BEACON_RUNTIME : UUPS_RUNTIME, depositArgs(signer)]).slice(12)}`;
|
|
942
|
+
};
|
|
943
|
+
const derivePolymarketWallets = (signer) => {
|
|
944
|
+
const given = signer;
|
|
945
|
+
if (!isSigner(given)) throw new PolymarketError("invalid-input", `bad signer address ${given}`);
|
|
946
|
+
const args = depositArgs(signer);
|
|
947
|
+
const salt = keccak256(args);
|
|
948
|
+
const argsBytes = (args.length - 2) / 2;
|
|
949
|
+
return {
|
|
950
|
+
beacon: getCreate2Address({
|
|
951
|
+
from: DEPOSIT_WALLET_FACTORY,
|
|
952
|
+
salt,
|
|
953
|
+
bytecodeHash: keccak256(concat([
|
|
954
|
+
prefixFor(BEACON_PREFIX, argsBytes),
|
|
955
|
+
DEPOSIT_WALLET_BEACON,
|
|
956
|
+
...BEACON_RUNTIME,
|
|
957
|
+
args
|
|
958
|
+
]))
|
|
959
|
+
}),
|
|
960
|
+
uups: getCreate2Address({
|
|
961
|
+
from: DEPOSIT_WALLET_FACTORY,
|
|
962
|
+
salt,
|
|
963
|
+
bytecodeHash: keccak256(concat([
|
|
964
|
+
prefixFor(UUPS_PREFIX, argsBytes),
|
|
965
|
+
DEPOSIT_WALLET_IMPLEMENTATION,
|
|
966
|
+
...UUPS_RUNTIME,
|
|
967
|
+
args
|
|
968
|
+
]))
|
|
969
|
+
}),
|
|
970
|
+
safe: getCreate2Address({
|
|
971
|
+
from: SAFE_FACTORY,
|
|
972
|
+
salt: keccak256(encodeAbiParameters([{ type: "address" }], [signer])),
|
|
973
|
+
bytecodeHash: SAFE_INIT_CODE_HASH
|
|
974
|
+
})
|
|
975
|
+
};
|
|
976
|
+
};
|
|
977
|
+
const NETWORK$2 = "eip155:137";
|
|
978
|
+
const codeAt = async (client, address) => {
|
|
979
|
+
const code = await client.transport.request({
|
|
980
|
+
method: "eth_getCode",
|
|
981
|
+
params: [address, "latest"]
|
|
982
|
+
});
|
|
983
|
+
if (typeof code !== "string") throw new TypeError("eth_getCode returned a malformed result");
|
|
984
|
+
return code;
|
|
985
|
+
};
|
|
986
|
+
const emptyCode = (code) => code === void 0 || code === "0x" || code === "";
|
|
987
|
+
function createPolymarketWallets(http, networks) {
|
|
988
|
+
const deployed = async (address, type) => {
|
|
989
|
+
return (await http.request({
|
|
990
|
+
host: RELAYER_HOST,
|
|
991
|
+
method: "GET",
|
|
992
|
+
path: "/deployed",
|
|
993
|
+
query: {
|
|
994
|
+
address,
|
|
995
|
+
type
|
|
996
|
+
}
|
|
997
|
+
}, relayerDeployed)).deployed;
|
|
998
|
+
};
|
|
999
|
+
return {
|
|
1000
|
+
derive: derivePolymarketWallets,
|
|
1001
|
+
locate: async (signer) => {
|
|
1002
|
+
const candidates = derivePolymarketWallets(signer);
|
|
1003
|
+
const chainCode = async (address) => codeAt(networks.client(NETWORK$2), address);
|
|
1004
|
+
const independent = networks.independentClient(NETWORK$2);
|
|
1005
|
+
const [uupsHint, beaconHint, safeHint, codes, other] = await Promise.all([
|
|
1006
|
+
deployed(candidates.uups, "WALLET"),
|
|
1007
|
+
deployed(candidates.beacon, "WALLET"),
|
|
1008
|
+
deployed(candidates.safe, "SAFE"),
|
|
1009
|
+
Promise.all([
|
|
1010
|
+
chainCode(candidates.uups),
|
|
1011
|
+
chainCode(candidates.beacon),
|
|
1012
|
+
chainCode(candidates.safe)
|
|
1013
|
+
]),
|
|
1014
|
+
independent.kind === "available" ? Promise.all([
|
|
1015
|
+
codeAt(independent.client, candidates.uups),
|
|
1016
|
+
codeAt(independent.client, candidates.beacon),
|
|
1017
|
+
codeAt(independent.client, candidates.safe)
|
|
1018
|
+
]).catch((error) => {
|
|
1019
|
+
throw new PolymarketError("unavailable", "the host endpoint could not read the account wallets", { cause: error });
|
|
1020
|
+
}) : Promise.resolve(void 0)
|
|
1021
|
+
]);
|
|
1022
|
+
const codeOf = (index) => {
|
|
1023
|
+
const primary = codes[index];
|
|
1024
|
+
const secondary = other?.[index];
|
|
1025
|
+
if (secondary !== void 0 && primary?.toLowerCase() !== secondary.toLowerCase()) throw new PolymarketError("deployment-mismatch", "the chain RPC and the host endpoint disagree on the account wallet's code");
|
|
1026
|
+
return primary;
|
|
1027
|
+
};
|
|
1028
|
+
const deployedByChain = (index, kind) => {
|
|
1029
|
+
const code = codeOf(index);
|
|
1030
|
+
if (emptyCode(code)) return false;
|
|
1031
|
+
if (code !== void 0 && code.toLowerCase() !== expectedPolymarketWalletRuntime(kind, signer).toLowerCase()) throw new PolymarketError("deployment-mismatch", `the code at the ${kind} candidate is not the deposit-wallet template`);
|
|
1032
|
+
return true;
|
|
1033
|
+
};
|
|
1034
|
+
const uupsUp = deployedByChain(0, "uups");
|
|
1035
|
+
const beaconUp = deployedByChain(1, "beacon");
|
|
1036
|
+
const safeUp = !emptyCode(codeOf(2));
|
|
1037
|
+
const hints = [
|
|
1038
|
+
[
|
|
1039
|
+
"uups",
|
|
1040
|
+
uupsHint,
|
|
1041
|
+
uupsUp
|
|
1042
|
+
],
|
|
1043
|
+
[
|
|
1044
|
+
"beacon",
|
|
1045
|
+
beaconHint,
|
|
1046
|
+
beaconUp
|
|
1047
|
+
],
|
|
1048
|
+
[
|
|
1049
|
+
"safe",
|
|
1050
|
+
safeHint,
|
|
1051
|
+
safeUp
|
|
1052
|
+
]
|
|
1053
|
+
];
|
|
1054
|
+
for (const [name, hint, chain] of hints) if (hint !== chain) throw new PolymarketError("deployment-mismatch", `the relayer claims the ${name} candidate is ${hint ? "" : "not "}deployed but the chain disagrees`);
|
|
1055
|
+
const legacySafe = safeUp ? { legacySafe: candidates.safe } : {};
|
|
1056
|
+
if (uupsUp) return {
|
|
1057
|
+
signer,
|
|
1058
|
+
wallet: candidates.uups,
|
|
1059
|
+
kind: "deposit-wallet",
|
|
1060
|
+
deployed: true,
|
|
1061
|
+
...legacySafe
|
|
1062
|
+
};
|
|
1063
|
+
if (beaconUp) return {
|
|
1064
|
+
signer,
|
|
1065
|
+
wallet: candidates.beacon,
|
|
1066
|
+
kind: "deposit-wallet",
|
|
1067
|
+
deployed: true,
|
|
1068
|
+
...legacySafe
|
|
1069
|
+
};
|
|
1070
|
+
if (safeUp) return {
|
|
1071
|
+
signer,
|
|
1072
|
+
wallet: candidates.safe,
|
|
1073
|
+
kind: "safe",
|
|
1074
|
+
deployed: true
|
|
1075
|
+
};
|
|
1076
|
+
return {
|
|
1077
|
+
signer,
|
|
1078
|
+
wallet: candidates.beacon,
|
|
1079
|
+
kind: "deposit-wallet",
|
|
1080
|
+
deployed: false
|
|
1081
|
+
};
|
|
1082
|
+
}
|
|
1083
|
+
};
|
|
1084
|
+
}
|
|
1085
|
+
// src/apps/polymarket/enable.ts
|
|
1086
|
+
/**
|
|
1087
|
+
* The Polymarket `AppProvider`: locate → deploy → credentials → approvals → verify as one resumable
|
|
1088
|
+
* state machine (design.md §启用状态机). Facts live in the apps store's credential records, the relayer
|
|
1089
|
+
* (`/deployed`) and the Data API (`/v2/approvals`); the engine persists only the terms flag. Every
|
|
1090
|
+
* step writes through the flow so a lock or crash resumes — each step is idempotent and re-derives
|
|
1091
|
+
* its precondition from the facts rather than trusting the recorded step.
|
|
1092
|
+
*
|
|
1093
|
+
* Secret hygiene: the `POST /auth/api-key` answer's `secret` is stored through the credential store
|
|
1094
|
+
* inside the credentials step and goes out of scope with it — it never reaches controller state,
|
|
1095
|
+
* the logger, or an error.
|
|
1096
|
+
*/
|
|
1097
|
+
const NETWORK$1 = "eip155:137";
|
|
1098
|
+
/** The SDK's batch deadline window (research.md §1 — `Ul = 600` seconds). */
|
|
1099
|
+
const BATCH_DEADLINE_SECONDS = 600;
|
|
1100
|
+
/** The kernel signing window — enable refuses to start on a device clock beyond it. */
|
|
1101
|
+
const MAX_SKEW_MS$1 = 3e4;
|
|
1102
|
+
/**
|
|
1103
|
+
* The eight trading approvals a deposit wallet needs (docs trading/wallets-auth.md §Set Up Trading
|
|
1104
|
+
* Approvals): pUSD `approve(spender, maxUint256)` for the two exchanges + adapter, and
|
|
1105
|
+
* `setApprovalForAll(spender, true)` on the outcome-token ledgers. The batch is built only from
|
|
1106
|
+
* this table — never from API data — so a hostile `/v2/approvals` cannot inject a call.
|
|
1107
|
+
*/
|
|
1108
|
+
const UINT256_MAX = 2n ** 256n - 1n;
|
|
1109
|
+
const pad32$1 = (hex) => hex.slice(2).toLowerCase().padStart(64, "0");
|
|
1110
|
+
const approveData = (spender) => `0x095ea7b3${pad32$1(spender)}${UINT256_MAX.toString(16).padStart(64, "0")}`;
|
|
1111
|
+
const approveAllData = (operator) => `0xa22cb465${pad32$1(operator)}${"1".padStart(64, "0")}`;
|
|
1112
|
+
const APPROVALS = [
|
|
1113
|
+
{
|
|
1114
|
+
token: PUSD,
|
|
1115
|
+
spender: CTF_EXCHANGE_V3,
|
|
1116
|
+
data: approveData(CTF_EXCHANGE_V3)
|
|
1117
|
+
},
|
|
1118
|
+
{
|
|
1119
|
+
token: PUSD,
|
|
1120
|
+
spender: CTF_EXCHANGE_V2,
|
|
1121
|
+
data: approveData(CTF_EXCHANGE_V2)
|
|
1122
|
+
},
|
|
1123
|
+
{
|
|
1124
|
+
token: PUSD,
|
|
1125
|
+
spender: NEG_RISK_EXCHANGE_V2,
|
|
1126
|
+
data: approveData(NEG_RISK_EXCHANGE_V2)
|
|
1127
|
+
},
|
|
1128
|
+
{
|
|
1129
|
+
token: PUSD,
|
|
1130
|
+
spender: NEG_RISK_ADAPTER,
|
|
1131
|
+
data: approveData(NEG_RISK_ADAPTER)
|
|
1132
|
+
},
|
|
1133
|
+
{
|
|
1134
|
+
token: POSITION_MANAGER,
|
|
1135
|
+
spender: CTF_EXCHANGE_V3,
|
|
1136
|
+
data: approveAllData(CTF_EXCHANGE_V3)
|
|
1137
|
+
},
|
|
1138
|
+
{
|
|
1139
|
+
token: CONDITIONAL_TOKENS,
|
|
1140
|
+
spender: CTF_EXCHANGE_V2,
|
|
1141
|
+
data: approveAllData(CTF_EXCHANGE_V2)
|
|
1142
|
+
},
|
|
1143
|
+
{
|
|
1144
|
+
token: CONDITIONAL_TOKENS,
|
|
1145
|
+
spender: NEG_RISK_EXCHANGE_V2,
|
|
1146
|
+
data: approveAllData(NEG_RISK_EXCHANGE_V2)
|
|
1147
|
+
},
|
|
1148
|
+
{
|
|
1149
|
+
token: CONDITIONAL_TOKENS,
|
|
1150
|
+
spender: NEG_RISK_ADAPTER,
|
|
1151
|
+
data: approveAllData(NEG_RISK_ADAPTER)
|
|
1152
|
+
}
|
|
1153
|
+
];
|
|
1154
|
+
const CLOB_AUTH_MESSAGE = "This message attests that I control the given wallet";
|
|
1155
|
+
/**
|
|
1156
|
+
* The `ClobAuth` typed data — the L1 signature that creates or derives the group's CLOB API
|
|
1157
|
+
* credentials (getting-started/api.md §Authentication; phase-1 vectors' `ClobAuth` case). The
|
|
1158
|
+
* kernel's recognizer describes it (`kind: "auth"`) rather than blind-signing.
|
|
1159
|
+
*/
|
|
1160
|
+
const clobAuthTypedData = (signer, timestamp) => JSON.stringify({
|
|
1161
|
+
types: {
|
|
1162
|
+
EIP712Domain: [
|
|
1163
|
+
{
|
|
1164
|
+
name: "name",
|
|
1165
|
+
type: "string"
|
|
1166
|
+
},
|
|
1167
|
+
{
|
|
1168
|
+
name: "version",
|
|
1169
|
+
type: "string"
|
|
1170
|
+
},
|
|
1171
|
+
{
|
|
1172
|
+
name: "chainId",
|
|
1173
|
+
type: "uint256"
|
|
1174
|
+
}
|
|
1175
|
+
],
|
|
1176
|
+
ClobAuth: [
|
|
1177
|
+
{
|
|
1178
|
+
name: "address",
|
|
1179
|
+
type: "address"
|
|
1180
|
+
},
|
|
1181
|
+
{
|
|
1182
|
+
name: "timestamp",
|
|
1183
|
+
type: "string"
|
|
1184
|
+
},
|
|
1185
|
+
{
|
|
1186
|
+
name: "nonce",
|
|
1187
|
+
type: "uint256"
|
|
1188
|
+
},
|
|
1189
|
+
{
|
|
1190
|
+
name: "message",
|
|
1191
|
+
type: "string"
|
|
1192
|
+
}
|
|
1193
|
+
]
|
|
1194
|
+
},
|
|
1195
|
+
primaryType: "ClobAuth",
|
|
1196
|
+
domain: {
|
|
1197
|
+
name: "ClobAuthDomain",
|
|
1198
|
+
version: "1",
|
|
1199
|
+
chainId: 137
|
|
1200
|
+
},
|
|
1201
|
+
message: {
|
|
1202
|
+
address: signer,
|
|
1203
|
+
timestamp,
|
|
1204
|
+
nonce: 0,
|
|
1205
|
+
message: CLOB_AUTH_MESSAGE
|
|
1206
|
+
}
|
|
1207
|
+
});
|
|
1208
|
+
/** Which table approvals `/v2/approvals` is missing — the batch's call list, in table order. */
|
|
1209
|
+
const missingApprovals = (contracts) => {
|
|
1210
|
+
const have = new Set(contracts.filter((c) => c.approved).map((c) => `${c.token.toLowerCase()}/${c.spender.toLowerCase()}`));
|
|
1211
|
+
return APPROVALS.filter((row) => !have.has(`${row.token}/${row.spender}`.toLowerCase()));
|
|
1212
|
+
};
|
|
1213
|
+
const accountRef$2 = (group) => ({
|
|
1214
|
+
kind: "hd",
|
|
1215
|
+
walletId: group.walletId,
|
|
1216
|
+
groupIndex: group.groupIndex,
|
|
1217
|
+
template: "evm.bip44"
|
|
1218
|
+
});
|
|
1219
|
+
/** The state's `account` view of a locate result — positions reads scope to `wallet`. */
|
|
1220
|
+
const stateAccount = (account) => ({
|
|
1221
|
+
wallet: account.wallet,
|
|
1222
|
+
kind: account.kind,
|
|
1223
|
+
deployed: account.deployed,
|
|
1224
|
+
...account.legacySafe === void 0 ? {} : { legacySafe: account.legacySafe }
|
|
1225
|
+
});
|
|
1226
|
+
const errorOf = (error) => error instanceof PolymarketError ? {
|
|
1227
|
+
category: error.category,
|
|
1228
|
+
message: error.message
|
|
1229
|
+
} : {
|
|
1230
|
+
category: "unavailable",
|
|
1231
|
+
message: error instanceof Error ? error.message : String(error)
|
|
1232
|
+
};
|
|
1233
|
+
const fail = (flow, category, message) => {
|
|
1234
|
+
flow.write({ error: {
|
|
1235
|
+
category,
|
|
1236
|
+
message
|
|
1237
|
+
} });
|
|
1238
|
+
throw new PolymarketError(category, message);
|
|
1239
|
+
};
|
|
1240
|
+
/** Run `body`; a stale flow stops writing but a thrown error still surfaces to the caller. */
|
|
1241
|
+
const guard = async (flow, body) => {
|
|
1242
|
+
try {
|
|
1243
|
+
await body();
|
|
1244
|
+
} catch (error) {
|
|
1245
|
+
if (!flow.stale() && flow.current().status === "enabling") flow.write({
|
|
1246
|
+
error: errorOf(error),
|
|
1247
|
+
requestId: void 0
|
|
1248
|
+
});
|
|
1249
|
+
throw error;
|
|
1250
|
+
}
|
|
1251
|
+
};
|
|
1252
|
+
function createPolymarketEnable(options) {
|
|
1253
|
+
const http = createPolymarketHttp({
|
|
1254
|
+
fetch: options.fetch,
|
|
1255
|
+
setTimer: options.setTimer,
|
|
1256
|
+
now: options.now
|
|
1257
|
+
});
|
|
1258
|
+
const relayer = createPolymarketRelayer({
|
|
1259
|
+
http,
|
|
1260
|
+
...options.builder === void 0 ? {} : { builder: options.builder },
|
|
1261
|
+
now: options.now,
|
|
1262
|
+
setTimer: options.setTimer
|
|
1263
|
+
});
|
|
1264
|
+
/** The group's stored credential set — the engine's own fact for the credentials step. */
|
|
1265
|
+
const hasCredentials = async (group) => await options.credentials.get(group) !== void 0;
|
|
1266
|
+
/**
|
|
1267
|
+
* Open an `evm-sign` request for `typedData` and await the 65-byte owner signature —
|
|
1268
|
+
* refused/expired requests are `approval-rejected`, a non-signature result `unavailable` (the
|
|
1269
|
+
* same contract `trade.ts` posts under).
|
|
1270
|
+
*/
|
|
1271
|
+
const signTypedData = async (group, flow, typedData) => {
|
|
1272
|
+
const pending = await options.requests.prepare({
|
|
1273
|
+
method: "evm-sign",
|
|
1274
|
+
account: accountRef$2(group),
|
|
1275
|
+
network: NETWORK$1,
|
|
1276
|
+
request: {
|
|
1277
|
+
kind: "evm.typed-data",
|
|
1278
|
+
network: NETWORK$1,
|
|
1279
|
+
account: accountRef$2(group),
|
|
1280
|
+
typedData
|
|
1281
|
+
}
|
|
1282
|
+
});
|
|
1283
|
+
flow.write({ requestId: pending.id });
|
|
1284
|
+
try {
|
|
1285
|
+
const result = await options.requests.outcome(pending.id);
|
|
1286
|
+
if (!("kind" in result) || result.kind !== "evm.typed-data" || result.signature.length !== 65) throw new PolymarketError("unavailable", "the request resolved without a typed-data signature");
|
|
1287
|
+
return toHex(result.signature);
|
|
1288
|
+
} catch (error) {
|
|
1289
|
+
if (error instanceof RequestEndedError) throw new PolymarketError("approval-rejected", `the request was ${error.stage}`, { cause: error });
|
|
1290
|
+
throw error;
|
|
1291
|
+
} finally {
|
|
1292
|
+
flow.write({ requestId: void 0 });
|
|
1293
|
+
}
|
|
1294
|
+
};
|
|
1295
|
+
/**
|
|
1296
|
+
* `POST /auth/api-key`, then `GET /auth/derive-api-key` under the same L1 headers when create
|
|
1297
|
+
* fails or answers without credentials — one user signature serves both (getting-started/api.md
|
|
1298
|
+
* §Create or Derive API Keys).
|
|
1299
|
+
*/
|
|
1300
|
+
const createOrDeriveCredentials = async (signer, signature, timestamp) => {
|
|
1301
|
+
const headers = {
|
|
1302
|
+
POLY_ADDRESS: signer,
|
|
1303
|
+
POLY_SIGNATURE: signature,
|
|
1304
|
+
POLY_TIMESTAMP: timestamp,
|
|
1305
|
+
POLY_NONCE: "0"
|
|
1306
|
+
};
|
|
1307
|
+
let credentials;
|
|
1308
|
+
try {
|
|
1309
|
+
credentials = await http.request({
|
|
1310
|
+
host: CLOB_HOST,
|
|
1311
|
+
method: "POST",
|
|
1312
|
+
path: "/auth/api-key",
|
|
1313
|
+
headers
|
|
1314
|
+
}, clobApiKeyResponse);
|
|
1315
|
+
} catch {}
|
|
1316
|
+
if (credentials !== void 0) return credentials;
|
|
1317
|
+
return http.request({
|
|
1318
|
+
host: CLOB_HOST,
|
|
1319
|
+
method: "GET",
|
|
1320
|
+
path: "/auth/derive-api-key",
|
|
1321
|
+
headers
|
|
1322
|
+
}, clobApiKeyResponse);
|
|
1323
|
+
};
|
|
1324
|
+
/** The enable state machine — every step writes; a failure leaves a resumable state. */
|
|
1325
|
+
const enableFlow = async (group, flow) => {
|
|
1326
|
+
if (flow.current().status !== "enabling") flow.write({
|
|
1327
|
+
status: "enabling",
|
|
1328
|
+
step: "locate-wallet",
|
|
1329
|
+
error: void 0
|
|
1330
|
+
});
|
|
1331
|
+
if (!flow.current().termsAcknowledged) fail(flow, "invalid-input", "Polymarket terms have not been acknowledged");
|
|
1332
|
+
const { skewMs } = await http.time();
|
|
1333
|
+
if (Math.abs(skewMs) > MAX_SKEW_MS$1) fail(flow, "clock-skew", `the device clock is ${Math.round(skewMs)} ms off the CLOB's`);
|
|
1334
|
+
flow.write({ step: "locate-wallet" });
|
|
1335
|
+
let account = await options.account.locate(group);
|
|
1336
|
+
flow.write({ account: stateAccount(account) });
|
|
1337
|
+
if (account.kind === "safe") {
|
|
1338
|
+
flow.write({
|
|
1339
|
+
status: "needs-migration",
|
|
1340
|
+
step: void 0,
|
|
1341
|
+
requestId: void 0
|
|
1342
|
+
});
|
|
1343
|
+
throw new PolymarketError("needs-migration", "the group only has a legacy Safe — migrate it to a deposit wallet first");
|
|
1344
|
+
}
|
|
1345
|
+
if (!account.deployed) {
|
|
1346
|
+
flow.write({ step: "deploy-wallet" });
|
|
1347
|
+
await relayer.deploy(account.signer, derivePolymarketWallets(account.signer).beacon);
|
|
1348
|
+
account = {
|
|
1349
|
+
...account,
|
|
1350
|
+
deployed: true
|
|
1351
|
+
};
|
|
1352
|
+
flow.write({ account: stateAccount(account) });
|
|
1353
|
+
}
|
|
1354
|
+
if (!await hasCredentials(group)) {
|
|
1355
|
+
flow.write({ step: "credentials" });
|
|
1356
|
+
const timestamp = String(Math.floor(options.now() / 1e3));
|
|
1357
|
+
const signature = await signTypedData(group, flow, clobAuthTypedData(account.signer, timestamp));
|
|
1358
|
+
const credentials = await createOrDeriveCredentials(account.signer, signature, timestamp);
|
|
1359
|
+
await options.credentials.put(group, {
|
|
1360
|
+
owner: account.signer,
|
|
1361
|
+
apiKey: credentials.apiKey,
|
|
1362
|
+
secret: credentials.secret,
|
|
1363
|
+
passphrase: credentials.passphrase
|
|
1364
|
+
});
|
|
1365
|
+
}
|
|
1366
|
+
const approvals = await options.account.approvals(account.wallet);
|
|
1367
|
+
const calls = missingApprovals(approvals.contracts).map((row) => ({
|
|
1368
|
+
target: row.token,
|
|
1369
|
+
value: "0",
|
|
1370
|
+
data: row.data
|
|
1371
|
+
}));
|
|
1372
|
+
if (calls.length > 0) {
|
|
1373
|
+
flow.write({ step: "approvals" });
|
|
1374
|
+
if (options.builder === void 0) fail(flow, "builder-required", "approving the trading contracts submits through the relayer, which needs the host's builder signer");
|
|
1375
|
+
const nonce = await relayer.nonce(account.signer);
|
|
1376
|
+
const deadline = Math.floor(options.now() / 1e3) + BATCH_DEADLINE_SECONDS;
|
|
1377
|
+
const signature = await signTypedData(group, flow, batchTypedData({
|
|
1378
|
+
wallet: account.wallet,
|
|
1379
|
+
nonce,
|
|
1380
|
+
deadline,
|
|
1381
|
+
calls
|
|
1382
|
+
}));
|
|
1383
|
+
await relayer.submitBatch({
|
|
1384
|
+
signer: account.signer,
|
|
1385
|
+
wallet: account.wallet,
|
|
1386
|
+
calls,
|
|
1387
|
+
signature,
|
|
1388
|
+
nonce,
|
|
1389
|
+
deadline,
|
|
1390
|
+
metadata: "Approve trading"
|
|
1391
|
+
});
|
|
1392
|
+
}
|
|
1393
|
+
flow.write({ step: "verify" });
|
|
1394
|
+
await options.account.refreshAllowance(group, { assetType: "COLLATERAL" });
|
|
1395
|
+
flow.write({
|
|
1396
|
+
status: "enabled",
|
|
1397
|
+
step: void 0,
|
|
1398
|
+
requestId: void 0,
|
|
1399
|
+
error: void 0
|
|
1400
|
+
});
|
|
1401
|
+
};
|
|
1402
|
+
/** The facts-only status reconcile derives — never opens a request. */
|
|
1403
|
+
const reconcileFlow = async (group, flow) => {
|
|
1404
|
+
const account = await options.account.locate(group);
|
|
1405
|
+
const written = stateAccount(account);
|
|
1406
|
+
if (account.kind === "safe") {
|
|
1407
|
+
flow.write({
|
|
1408
|
+
status: "needs-migration",
|
|
1409
|
+
step: void 0,
|
|
1410
|
+
requestId: void 0,
|
|
1411
|
+
account: written,
|
|
1412
|
+
error: void 0
|
|
1413
|
+
});
|
|
1414
|
+
return;
|
|
1415
|
+
}
|
|
1416
|
+
if (!account.deployed || !await hasCredentials(group)) {
|
|
1417
|
+
flow.write({
|
|
1418
|
+
status: "disabled",
|
|
1419
|
+
step: void 0,
|
|
1420
|
+
requestId: void 0,
|
|
1421
|
+
account: written,
|
|
1422
|
+
error: void 0
|
|
1423
|
+
});
|
|
1424
|
+
return;
|
|
1425
|
+
}
|
|
1426
|
+
const approvals = await options.account.approvals(account.wallet);
|
|
1427
|
+
if (missingApprovals(approvals.contracts).length > 0) {
|
|
1428
|
+
flow.write({
|
|
1429
|
+
status: "enabling",
|
|
1430
|
+
step: "approvals",
|
|
1431
|
+
account: written,
|
|
1432
|
+
error: void 0
|
|
1433
|
+
});
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
flow.write({
|
|
1437
|
+
status: "enabled",
|
|
1438
|
+
step: void 0,
|
|
1439
|
+
requestId: void 0,
|
|
1440
|
+
account: written,
|
|
1441
|
+
error: void 0
|
|
1442
|
+
});
|
|
1443
|
+
};
|
|
1444
|
+
return {
|
|
1445
|
+
error: (category, message) => new PolymarketError(category === "unavailable" ? "blocked" : category, message),
|
|
1446
|
+
groups: options.credentials.groups,
|
|
1447
|
+
reconcile: async (group, flow) => guard(flow, async () => reconcileFlow(group, flow)),
|
|
1448
|
+
enable: async (group, flow) => guard(flow, async () => enableFlow(group, flow)),
|
|
1449
|
+
renew: async () => {
|
|
1450
|
+
await Promise.resolve();
|
|
1451
|
+
throw new PolymarketError("invalid-input", "Polymarket credentials do not expire — there is nothing to renew");
|
|
1452
|
+
},
|
|
1453
|
+
disable: async (group, { revoke }, flow) => guard(flow, async () => {
|
|
1454
|
+
if (revoke) try {
|
|
1455
|
+
await options.account.revokeApiKey(group);
|
|
1456
|
+
} catch (error) {
|
|
1457
|
+
flow.write({ error: errorOf(error) });
|
|
1458
|
+
options.logger.warn("polymarket api-key revoke failed", error);
|
|
1459
|
+
}
|
|
1460
|
+
await options.credentials.delete(group);
|
|
1461
|
+
flow.write({
|
|
1462
|
+
status: "disabled",
|
|
1463
|
+
step: void 0,
|
|
1464
|
+
requestId: void 0
|
|
1465
|
+
});
|
|
1466
|
+
}),
|
|
1467
|
+
cancel: async (group, flow) => {
|
|
1468
|
+
const { requestId } = flow.current();
|
|
1469
|
+
if (requestId !== void 0) options.requests.reject(requestId);
|
|
1470
|
+
await reconcileFlow(group, flow);
|
|
1471
|
+
},
|
|
1472
|
+
authorities: async (group) => {
|
|
1473
|
+
const account = await options.account.locate(group);
|
|
1474
|
+
if (account.kind !== "deposit-wallet" || !account.deployed) return [];
|
|
1475
|
+
const { contracts } = await options.account.approvals(account.wallet);
|
|
1476
|
+
const approved = new Map(contracts.filter((contract) => contract.approved).map((contract) => [`${contract.token.toLowerCase()}/${contract.spender.toLowerCase()}`, contract]));
|
|
1477
|
+
return APPROVALS.flatMap((row) => {
|
|
1478
|
+
const hit = approved.get(`${row.token}/${row.spender}`.toLowerCase());
|
|
1479
|
+
if (hit === void 0) return [];
|
|
1480
|
+
const base = {
|
|
1481
|
+
network: "eip155:137",
|
|
1482
|
+
account: account.wallet,
|
|
1483
|
+
holder: row.spender,
|
|
1484
|
+
asset: row.token,
|
|
1485
|
+
revoke: "none"
|
|
1486
|
+
};
|
|
1487
|
+
return row.data.startsWith("0x095ea7b3") ? [{
|
|
1488
|
+
kind: "token-allowance",
|
|
1489
|
+
...base,
|
|
1490
|
+
...hit.amount === void 0 || hit.amount === "max" ? {} : { limit: hit.amount }
|
|
1491
|
+
}] : [{
|
|
1492
|
+
kind: "operator",
|
|
1493
|
+
...base
|
|
1494
|
+
}];
|
|
1495
|
+
});
|
|
1496
|
+
}
|
|
1497
|
+
};
|
|
1498
|
+
}
|
|
1499
|
+
// src/apps/polymarket/account.ts
|
|
1500
|
+
const POSITIONS_LIMIT = 100;
|
|
1501
|
+
const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
|
|
1502
|
+
const ORDER_ID$1 = /^0x[0-9a-fA-F]{64}$/;
|
|
1503
|
+
const isWallet = (wallet) => ADDRESS.test(wallet);
|
|
1504
|
+
const checkWallet = (wallet) => {
|
|
1505
|
+
if (!isWallet(wallet)) throw new PolymarketError("invalid-input", `bad wallet address ${wallet}`);
|
|
1506
|
+
return wallet;
|
|
1507
|
+
};
|
|
1508
|
+
const checkLimit = (limit) => {
|
|
1509
|
+
if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > POSITIONS_LIMIT)) throw new PolymarketError("invalid-input", `limit must be an integer in 1..${POSITIONS_LIMIT}`);
|
|
1510
|
+
};
|
|
1511
|
+
/** The documented absence answers: a 404 `unavailable` becomes `absent`, anything else throws. */
|
|
1512
|
+
const absentOn404 = (error) => {
|
|
1513
|
+
if (error instanceof PolymarketError && error.category === "unavailable" && error.status === 404) return "absent";
|
|
1514
|
+
throw error;
|
|
1515
|
+
};
|
|
1516
|
+
/** CLOB page cursors mark the end with `LTE=` (base64 `-1`) or an empty string. */
|
|
1517
|
+
const clobCursor = (next) => next === "" || next === "LTE=" ? void 0 : next;
|
|
1518
|
+
const normalizePosition = (row) => ({
|
|
1519
|
+
assetId: row.token_id,
|
|
1520
|
+
conditionId: row.condition_id,
|
|
1521
|
+
size: row.current_size,
|
|
1522
|
+
...row.avg_price === void 0 || row.avg_price === null ? {} : { avgPrice: row.avg_price },
|
|
1523
|
+
...row.current_price === void 0 || row.current_price === null ? {} : { price: row.current_price },
|
|
1524
|
+
...row.current_value === void 0 || row.current_value === null ? {} : { value: row.current_value },
|
|
1525
|
+
...row.entry_cost_usdc === void 0 || row.entry_cost_usdc === null ? {} : { entryCost: row.entry_cost_usdc },
|
|
1526
|
+
...row.realized_pnl === void 0 || row.realized_pnl === null ? {} : { realizedPnl: row.realized_pnl },
|
|
1527
|
+
...row.unrealized_pnl === void 0 || row.unrealized_pnl === null ? {} : { unrealizedPnl: row.unrealized_pnl },
|
|
1528
|
+
...row.total_pnl === void 0 || row.total_pnl === null ? {} : { totalPnl: row.total_pnl },
|
|
1529
|
+
status: row.status,
|
|
1530
|
+
redeemable: row.redeemable ?? false,
|
|
1531
|
+
mergeable: row.mergeable ?? false,
|
|
1532
|
+
negRisk: row.negative_risk ?? false,
|
|
1533
|
+
...row.title === void 0 || row.title === null ? {} : { title: row.title },
|
|
1534
|
+
...row.slug === void 0 || row.slug === null ? {} : { slug: row.slug },
|
|
1535
|
+
...row.outcome === void 0 || row.outcome === null ? {} : { outcome: row.outcome },
|
|
1536
|
+
...row.outcome_index === void 0 || row.outcome_index === null ? {} : { outcomeIndex: row.outcome_index },
|
|
1537
|
+
...row.end_date === void 0 || row.end_date === null ? {} : { endDate: row.end_date }
|
|
1538
|
+
});
|
|
1539
|
+
const normalizeActivity = (row) => ({
|
|
1540
|
+
type: row.type,
|
|
1541
|
+
timestamp: row.timestamp,
|
|
1542
|
+
conditionId: row.condition_id,
|
|
1543
|
+
assetId: row.token_id,
|
|
1544
|
+
...row.side === void 0 || row.side === "" ? {} : { side: row.side },
|
|
1545
|
+
...row.size === void 0 || row.size === null ? {} : { size: row.size },
|
|
1546
|
+
...row.usdc_size === void 0 || row.usdc_size === null ? {} : { usdcSize: row.usdc_size },
|
|
1547
|
+
...row.price === void 0 || row.price === null ? {} : { price: row.price },
|
|
1548
|
+
transactionHash: row.transaction_hash,
|
|
1549
|
+
...row.outcome === void 0 || row.outcome === null ? {} : { outcome: row.outcome },
|
|
1550
|
+
...row.outcome_index === void 0 || row.outcome_index === null ? {} : { outcomeIndex: row.outcome_index }
|
|
1551
|
+
});
|
|
1552
|
+
const normalizeOrder = (row) => ({
|
|
1553
|
+
id: row.id,
|
|
1554
|
+
status: row.status,
|
|
1555
|
+
conditionId: row.market,
|
|
1556
|
+
assetId: row.asset_id,
|
|
1557
|
+
side: row.side,
|
|
1558
|
+
price: row.price,
|
|
1559
|
+
originalSize: row.original_size,
|
|
1560
|
+
sizeMatched: row.size_matched,
|
|
1561
|
+
...row.outcome === void 0 || row.outcome === null ? {} : { outcome: row.outcome },
|
|
1562
|
+
orderType: row.order_type,
|
|
1563
|
+
expiration: row.expiration,
|
|
1564
|
+
createdAt: row.created_at,
|
|
1565
|
+
makerAddress: row.maker_address
|
|
1566
|
+
});
|
|
1567
|
+
const normalizeTrade = (row) => ({
|
|
1568
|
+
id: row.id,
|
|
1569
|
+
takerOrderId: row.taker_order_id,
|
|
1570
|
+
conditionId: row.market,
|
|
1571
|
+
assetId: row.asset_id,
|
|
1572
|
+
side: row.side,
|
|
1573
|
+
size: row.size,
|
|
1574
|
+
price: row.price,
|
|
1575
|
+
status: row.status,
|
|
1576
|
+
matchTime: row.match_time,
|
|
1577
|
+
...row.outcome === void 0 || row.outcome === null ? {} : { outcome: row.outcome },
|
|
1578
|
+
...row.transaction_hash === void 0 || row.transaction_hash === null ? {} : { transactionHash: row.transaction_hash },
|
|
1579
|
+
traderSide: row.trader_side,
|
|
1580
|
+
makerOrders: (row.maker_orders ?? []).map((order) => ({
|
|
1581
|
+
orderId: order.order_id,
|
|
1582
|
+
matchedAmount: order.matched_amount,
|
|
1583
|
+
price: order.price
|
|
1584
|
+
}))
|
|
1585
|
+
});
|
|
1586
|
+
const normalizePnlPoint = (point) => ({
|
|
1587
|
+
timestamp: point.timestamp,
|
|
1588
|
+
realizedPnl: point.realized_pnl,
|
|
1589
|
+
...point.position_pnl === void 0 || point.position_pnl === null ? {} : { positionPnl: point.position_pnl },
|
|
1590
|
+
...point.economic_pnl === void 0 || point.economic_pnl === null ? {} : { economicPnl: point.economic_pnl },
|
|
1591
|
+
...point.volume_usdc === void 0 || point.volume_usdc === null ? {} : { volume: point.volume_usdc },
|
|
1592
|
+
...point.trade_count === void 0 || point.trade_count === null ? {} : { tradeCount: point.trade_count }
|
|
1593
|
+
});
|
|
1594
|
+
const normalizeApproval = (contract) => ({
|
|
1595
|
+
id: contract.id,
|
|
1596
|
+
feature: contract.feature,
|
|
1597
|
+
token: contract.token,
|
|
1598
|
+
spender: contract.spender,
|
|
1599
|
+
standard: contract.standard,
|
|
1600
|
+
...contract.amount === void 0 || contract.amount === null ? {} : { amount: contract.amount },
|
|
1601
|
+
approved: contract.approved
|
|
1602
|
+
});
|
|
1603
|
+
function createPolymarketAccount(options) {
|
|
1604
|
+
/** Group key → the locate call — one relayer probe per group per session. */
|
|
1605
|
+
const located = /* @__PURE__ */ new Map();
|
|
1606
|
+
const locate = async (group) => {
|
|
1607
|
+
const key = `${group.walletId}/${group.groupIndex}`;
|
|
1608
|
+
let pending = located.get(key);
|
|
1609
|
+
if (pending === void 0) {
|
|
1610
|
+
const run = async () => options.wallets.locate(await options.signerOf(group));
|
|
1611
|
+
pending = run();
|
|
1612
|
+
located.set(key, pending);
|
|
1613
|
+
}
|
|
1614
|
+
const account = await pending;
|
|
1615
|
+
if (!account.deployed && located.get(key) === pending) located.delete(key);
|
|
1616
|
+
return account;
|
|
1617
|
+
};
|
|
1618
|
+
return {
|
|
1619
|
+
locate,
|
|
1620
|
+
positions: async (wallet, params) => {
|
|
1621
|
+
checkWallet(wallet);
|
|
1622
|
+
checkLimit(params?.limit);
|
|
1623
|
+
const page = await options.http.request({
|
|
1624
|
+
host: DATA_HOST,
|
|
1625
|
+
method: "GET",
|
|
1626
|
+
path: "/v2/positions",
|
|
1627
|
+
query: {
|
|
1628
|
+
user: wallet,
|
|
1629
|
+
...params?.limit === void 0 ? {} : { limit: params.limit },
|
|
1630
|
+
...params?.cursor === void 0 ? {} : { cursor: params.cursor }
|
|
1631
|
+
}
|
|
1632
|
+
}, dataPositions);
|
|
1633
|
+
return {
|
|
1634
|
+
items: page.data.map(normalizePosition),
|
|
1635
|
+
...page.pagination.next_cursor === void 0 || page.pagination.next_cursor === null || page.pagination.next_cursor === "" ? {} : { nextCursor: page.pagination.next_cursor }
|
|
1636
|
+
};
|
|
1637
|
+
},
|
|
1638
|
+
value: async (wallet) => {
|
|
1639
|
+
checkWallet(wallet);
|
|
1640
|
+
return (await options.http.request({
|
|
1641
|
+
host: DATA_HOST,
|
|
1642
|
+
method: "GET",
|
|
1643
|
+
path: "/v2/value",
|
|
1644
|
+
query: { user: wallet }
|
|
1645
|
+
}, dataValue)).data.value;
|
|
1646
|
+
},
|
|
1647
|
+
activity: async (wallet, params) => {
|
|
1648
|
+
checkWallet(wallet);
|
|
1649
|
+
checkLimit(params?.limit);
|
|
1650
|
+
const page = await options.http.request({
|
|
1651
|
+
host: DATA_HOST,
|
|
1652
|
+
method: "GET",
|
|
1653
|
+
path: "/v2/activity",
|
|
1654
|
+
query: {
|
|
1655
|
+
user: wallet,
|
|
1656
|
+
...params?.limit === void 0 ? {} : { limit: params.limit },
|
|
1657
|
+
...params?.cursor === void 0 ? {} : { cursor: params.cursor },
|
|
1658
|
+
...params?.start === void 0 ? {} : { start: params.start },
|
|
1659
|
+
...params?.end === void 0 ? {} : { end: params.end },
|
|
1660
|
+
...params?.sortDirection === void 0 ? {} : { sort_direction: params.sortDirection }
|
|
1661
|
+
}
|
|
1662
|
+
}, dataActivity);
|
|
1663
|
+
return {
|
|
1664
|
+
items: page.data.map(normalizeActivity),
|
|
1665
|
+
...page.pagination.next_cursor === void 0 || page.pagination.next_cursor === null || page.pagination.next_cursor === "" ? {} : { nextCursor: page.pagination.next_cursor }
|
|
1666
|
+
};
|
|
1667
|
+
},
|
|
1668
|
+
pnl: async (wallet, params) => {
|
|
1669
|
+
checkWallet(wallet);
|
|
1670
|
+
const answer = await options.http.request({
|
|
1671
|
+
host: DATA_HOST,
|
|
1672
|
+
method: "GET",
|
|
1673
|
+
path: "/v2/user-pnl",
|
|
1674
|
+
query: {
|
|
1675
|
+
user: wallet,
|
|
1676
|
+
...params?.interval === void 0 ? {} : { interval: params.interval },
|
|
1677
|
+
...params?.fidelity === void 0 ? {} : { fidelity: params.fidelity }
|
|
1678
|
+
}
|
|
1679
|
+
}, dataUserPnl);
|
|
1680
|
+
return {
|
|
1681
|
+
wallet: answer.data.proxy_wallet,
|
|
1682
|
+
interval: answer.data.interval,
|
|
1683
|
+
fidelity: answer.data.fidelity,
|
|
1684
|
+
points: answer.data.points.map(normalizePnlPoint)
|
|
1685
|
+
};
|
|
1686
|
+
},
|
|
1687
|
+
approvals: async (wallet) => {
|
|
1688
|
+
checkWallet(wallet);
|
|
1689
|
+
const answer = await options.http.request({
|
|
1690
|
+
host: DATA_HOST,
|
|
1691
|
+
method: "GET",
|
|
1692
|
+
path: "/v2/approvals",
|
|
1693
|
+
query: { user: wallet }
|
|
1694
|
+
}, dataApprovals);
|
|
1695
|
+
return {
|
|
1696
|
+
address: answer.data.address,
|
|
1697
|
+
checkedAt: answer.data.checked_at,
|
|
1698
|
+
contracts: answer.data.contracts.map(normalizeApproval)
|
|
1699
|
+
};
|
|
1700
|
+
},
|
|
1701
|
+
openOrders: async (group, params) => {
|
|
1702
|
+
if (params?.assetId !== void 0 && params.market === void 0) throw new PolymarketError("invalid-input", "assetId requires market");
|
|
1703
|
+
const page = await options.l2.request(group, {
|
|
1704
|
+
method: "GET",
|
|
1705
|
+
path: "/data/orders",
|
|
1706
|
+
query: {
|
|
1707
|
+
...params?.market === void 0 ? {} : { market: params.market },
|
|
1708
|
+
...params?.assetId === void 0 ? {} : { asset_id: params.assetId },
|
|
1709
|
+
...params?.cursor === void 0 ? {} : { next_cursor: params.cursor }
|
|
1710
|
+
}
|
|
1711
|
+
}, clobOrdersPage);
|
|
1712
|
+
const nextCursor = clobCursor(page.next_cursor);
|
|
1713
|
+
return {
|
|
1714
|
+
items: page.data.map(normalizeOrder),
|
|
1715
|
+
...nextCursor === void 0 ? {} : { nextCursor }
|
|
1716
|
+
};
|
|
1717
|
+
},
|
|
1718
|
+
order: async (group, orderId) => {
|
|
1719
|
+
if (!ORDER_ID$1.test(orderId)) throw new PolymarketError("invalid-input", `bad order id ${orderId}`);
|
|
1720
|
+
const row = await options.l2.request(group, {
|
|
1721
|
+
method: "GET",
|
|
1722
|
+
path: `/data/order/${orderId}`
|
|
1723
|
+
}, clobOpenOrder).catch(absentOn404);
|
|
1724
|
+
return row === "absent" ? void 0 : normalizeOrder(row);
|
|
1725
|
+
},
|
|
1726
|
+
trades: async (group, params) => {
|
|
1727
|
+
const maker = (await locate(group)).wallet;
|
|
1728
|
+
const page = await options.l2.request(group, {
|
|
1729
|
+
method: "GET",
|
|
1730
|
+
path: "/data/trades",
|
|
1731
|
+
query: {
|
|
1732
|
+
maker_address: maker,
|
|
1733
|
+
...params?.market === void 0 ? {} : { market: params.market },
|
|
1734
|
+
...params?.assetId === void 0 ? {} : { asset_id: params.assetId },
|
|
1735
|
+
...params?.before === void 0 ? {} : { before: params.before },
|
|
1736
|
+
...params?.after === void 0 ? {} : { after: params.after },
|
|
1737
|
+
...params?.cursor === void 0 ? {} : { next_cursor: params.cursor }
|
|
1738
|
+
}
|
|
1739
|
+
}, clobTradesPage);
|
|
1740
|
+
const nextCursor = clobCursor(page.next_cursor);
|
|
1741
|
+
return {
|
|
1742
|
+
items: page.data.map(normalizeTrade),
|
|
1743
|
+
...nextCursor === void 0 ? {} : { nextCursor }
|
|
1744
|
+
};
|
|
1745
|
+
},
|
|
1746
|
+
balance: async (group) => {
|
|
1747
|
+
const answer = await options.l2.request(group, {
|
|
1748
|
+
method: "GET",
|
|
1749
|
+
path: "/balance-allowance",
|
|
1750
|
+
query: {
|
|
1751
|
+
asset_type: "COLLATERAL",
|
|
1752
|
+
signature_type: 3
|
|
1753
|
+
}
|
|
1754
|
+
}, clobBalanceAllowance);
|
|
1755
|
+
return {
|
|
1756
|
+
balance: answer.balance,
|
|
1757
|
+
allowances: answer.allowances
|
|
1758
|
+
};
|
|
1759
|
+
},
|
|
1760
|
+
refreshAllowance: async (group, params) => {
|
|
1761
|
+
const answer = await options.l2.request(group, {
|
|
1762
|
+
method: "GET",
|
|
1763
|
+
path: "/balance-allowance/update",
|
|
1764
|
+
query: {
|
|
1765
|
+
asset_type: params.assetType,
|
|
1766
|
+
signature_type: 3,
|
|
1767
|
+
...params.tokenId === void 0 ? {} : { token_id: params.tokenId }
|
|
1768
|
+
}
|
|
1769
|
+
}, clobBalanceAllowance);
|
|
1770
|
+
return {
|
|
1771
|
+
balance: answer.balance,
|
|
1772
|
+
allowances: answer.allowances
|
|
1773
|
+
};
|
|
1774
|
+
},
|
|
1775
|
+
closedOnly: async (group) => {
|
|
1776
|
+
const answer = await options.l2.request(group, {
|
|
1777
|
+
method: "GET",
|
|
1778
|
+
path: "/auth/ban-status/closed-only"
|
|
1779
|
+
}, clobClosedOnly).catch(absentOn404);
|
|
1780
|
+
return answer === "absent" ? false : answer.closed_only;
|
|
1781
|
+
},
|
|
1782
|
+
revokeApiKey: async (group) => {
|
|
1783
|
+
await options.l2.request(group, {
|
|
1784
|
+
method: "DELETE",
|
|
1785
|
+
path: "/auth/api-key"
|
|
1786
|
+
}, clobApiKeyDelete);
|
|
1787
|
+
}
|
|
1788
|
+
};
|
|
1789
|
+
}
|
|
1790
|
+
// src/apps/polymarket/funding.ts
|
|
1791
|
+
/**
|
|
1792
|
+
* Polymarket funding — the only two movements this app offers (research.md §4):
|
|
1793
|
+
*
|
|
1794
|
+
* - `deposit`: a pUSD `send` request from the owner's EOA to the located **deployed** deposit wallet.
|
|
1795
|
+
* It is not eligibility-gated — a deposit opens nothing on the exchange.
|
|
1796
|
+
* - `withdraw`: a one-call relayer `Batch` `pUSD.transfer(owner, amount)` — the destination is always
|
|
1797
|
+
* the owner's own EOA, so a lost submit is `unknown` and a user retry can never move funds out of
|
|
1798
|
+
* the owner's control (the batch is never auto-resubmitted; the kernel-described request makes a
|
|
1799
|
+
* duplicate deliberate, not accidental).
|
|
1800
|
+
*
|
|
1801
|
+
* USDC/USDC.e wrapping and cross-chain bridging are not offered: Polymarket's collateral is pUSD on
|
|
1802
|
+
* Polygon, and wrapping paths belong to the swap/bridge flows, not this app.
|
|
1803
|
+
*/
|
|
1804
|
+
const BATCH_DEADLINE_S = 600;
|
|
1805
|
+
const pad32 = (hex) => hex.slice(2).toLowerCase().padStart(64, "0");
|
|
1806
|
+
/** `transfer(address,uint256)` — the withdraw call's only spend. */
|
|
1807
|
+
const transferData = (to, amount) => `0xa9059cbb${pad32(to)}${amount.toString(16).padStart(64, "0")}`;
|
|
1808
|
+
const accountRef$1 = (group) => ({
|
|
1809
|
+
kind: "hd",
|
|
1810
|
+
walletId: group.walletId,
|
|
1811
|
+
groupIndex: group.groupIndex,
|
|
1812
|
+
template: "evm.bip44"
|
|
1813
|
+
});
|
|
1814
|
+
const requireAmount = (amount) => {
|
|
1815
|
+
if (amount <= 0n) throw new PolymarketError("invalid-input", "the amount must be a positive pUSD quantity");
|
|
1816
|
+
};
|
|
1817
|
+
function createPolymarketFunding(options) {
|
|
1818
|
+
const requirePipeline = () => {
|
|
1819
|
+
if (options.requests === void 0) throw new PolymarketError("not-enabled", "this provider has no request pipeline");
|
|
1820
|
+
return options.requests;
|
|
1821
|
+
};
|
|
1822
|
+
/** A located, deployed deposit wallet is the only account funding moves for. */
|
|
1823
|
+
const requireWallet = async (group) => {
|
|
1824
|
+
const located = await options.account.locate(group);
|
|
1825
|
+
if (located.kind === "safe") throw new PolymarketError("needs-migration", "this account only has a legacy Safe — migrate it to a deposit wallet first");
|
|
1826
|
+
if (!located.deployed) throw new PolymarketError("not-enabled", "the deposit wallet is not deployed yet");
|
|
1827
|
+
return located;
|
|
1828
|
+
};
|
|
1829
|
+
const wrapOutcome = async (requestId) => {
|
|
1830
|
+
const requests = requirePipeline();
|
|
1831
|
+
try {
|
|
1832
|
+
const result = await requests.outcome(requestId);
|
|
1833
|
+
if (!("family" in result) && !("kind" in result)) throw new PolymarketError("unavailable", "the funding request resolved without a result");
|
|
1834
|
+
return { kind: "ok" };
|
|
1835
|
+
} catch (error) {
|
|
1836
|
+
if (error instanceof RequestEndedError) throw new PolymarketError("approval-rejected", `the request was ${error.stage}`, error);
|
|
1837
|
+
throw error;
|
|
1838
|
+
}
|
|
1839
|
+
};
|
|
1840
|
+
return {
|
|
1841
|
+
deposit: async (group, { amount, fee }) => {
|
|
1842
|
+
const requests = requirePipeline();
|
|
1843
|
+
requireAmount(amount);
|
|
1844
|
+
const located = await requireWallet(group);
|
|
1845
|
+
const pending = await requests.prepare({
|
|
1846
|
+
method: "send",
|
|
1847
|
+
account: accountRef$1(group),
|
|
1848
|
+
network: "eip155:137",
|
|
1849
|
+
to: located.wallet,
|
|
1850
|
+
amount,
|
|
1851
|
+
token: PUSD,
|
|
1852
|
+
fee
|
|
1853
|
+
});
|
|
1854
|
+
return {
|
|
1855
|
+
requestId: pending.id,
|
|
1856
|
+
outcome: wrapOutcome(pending.id)
|
|
1857
|
+
};
|
|
1858
|
+
},
|
|
1859
|
+
withdraw: async (group, { amount }) => {
|
|
1860
|
+
const requests = requirePipeline();
|
|
1861
|
+
requireAmount(amount);
|
|
1862
|
+
if (!options.hasBuilder) throw new PolymarketError("builder-required", "withdrawing submits through the relayer, which needs the host's builder signer");
|
|
1863
|
+
const located = await requireWallet(group);
|
|
1864
|
+
const nonce = await options.relayer.nonce(located.signer);
|
|
1865
|
+
const deadline = Math.floor(options.now() / 1e3) + BATCH_DEADLINE_S;
|
|
1866
|
+
const calls = [{
|
|
1867
|
+
target: PUSD,
|
|
1868
|
+
value: "0",
|
|
1869
|
+
data: transferData(located.signer, amount)
|
|
1870
|
+
}];
|
|
1871
|
+
const pending = await requests.prepare({
|
|
1872
|
+
method: "evm-sign",
|
|
1873
|
+
account: accountRef$1(group),
|
|
1874
|
+
network: "eip155:137",
|
|
1875
|
+
request: {
|
|
1876
|
+
kind: "evm.typed-data",
|
|
1877
|
+
network: "eip155:137",
|
|
1878
|
+
account: accountRef$1(group),
|
|
1879
|
+
typedData: batchTypedData({
|
|
1880
|
+
wallet: located.wallet,
|
|
1881
|
+
nonce,
|
|
1882
|
+
deadline,
|
|
1883
|
+
calls
|
|
1884
|
+
})
|
|
1885
|
+
}
|
|
1886
|
+
});
|
|
1887
|
+
const outcome = (async () => {
|
|
1888
|
+
let signature;
|
|
1889
|
+
try {
|
|
1890
|
+
const result = await requests.outcome(pending.id);
|
|
1891
|
+
if (!("kind" in result) || result.kind !== "evm.typed-data" || result.signature.length !== 65) throw new PolymarketError("unavailable", "the request resolved without a typed-data signature");
|
|
1892
|
+
signature = toHex(result.signature);
|
|
1893
|
+
} catch (error) {
|
|
1894
|
+
if (error instanceof RequestEndedError) throw new PolymarketError("approval-rejected", `the request was ${error.stage}`, error);
|
|
1895
|
+
throw error;
|
|
1896
|
+
}
|
|
1897
|
+
try {
|
|
1898
|
+
await options.relayer.submitBatch({
|
|
1899
|
+
signer: located.signer,
|
|
1900
|
+
wallet: located.wallet,
|
|
1901
|
+
calls,
|
|
1902
|
+
signature,
|
|
1903
|
+
nonce,
|
|
1904
|
+
deadline,
|
|
1905
|
+
metadata: "Withdraw pUSD"
|
|
1906
|
+
});
|
|
1907
|
+
return { kind: "ok" };
|
|
1908
|
+
} catch (error) {
|
|
1909
|
+
if (error instanceof PolymarketError && error.category === "rejected") throw error;
|
|
1910
|
+
return { kind: "unknown" };
|
|
1911
|
+
}
|
|
1912
|
+
})();
|
|
1913
|
+
return {
|
|
1914
|
+
requestId: pending.id,
|
|
1915
|
+
outcome
|
|
1916
|
+
};
|
|
1917
|
+
}
|
|
1918
|
+
};
|
|
1919
|
+
}
|
|
1920
|
+
const SKEW_REFRESH_MS = 6e5;
|
|
1921
|
+
/**
|
|
1922
|
+
* The five `POLY_*` headers for one request — the oracle of vectors/chains/polymarket-l2.json:
|
|
1923
|
+
* `POLY_SIGNATURE` is the url-safe base64 (padding kept) HMAC-SHA256 over
|
|
1924
|
+
* `${timestamp}${method}${path}${body ?? ""}` keyed by the decoded secret.
|
|
1925
|
+
*/
|
|
1926
|
+
function l2Headers(credentials, input) {
|
|
1927
|
+
const key = decodeSecret(credentials.secret);
|
|
1928
|
+
if (key === void 0) throw new PolymarketError("malformed", "the stored credential secret does not decode");
|
|
1929
|
+
return {
|
|
1930
|
+
POLY_ADDRESS: credentials.owner,
|
|
1931
|
+
POLY_SIGNATURE: base64url.encode(hmac(sha256, key, utf8ToBytes(`${input.timestamp}${input.method}${input.path}${input.body ?? ""}`))),
|
|
1932
|
+
POLY_TIMESTAMP: `${input.timestamp}`,
|
|
1933
|
+
POLY_API_KEY: credentials.apiKey,
|
|
1934
|
+
POLY_PASSPHRASE: credentials.passphrase
|
|
1935
|
+
};
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* A hostile CLOB can reflect the issued credentials back inside an error — the thrown error is
|
|
1939
|
+
* re-derived with every occurrence of the three values in the message/body/cause chain replaced or
|
|
1940
|
+
* dropped, preserving category and status. Errors free of them pass through untouched.
|
|
1941
|
+
*/
|
|
1942
|
+
const scrub = (error, credentials) => {
|
|
1943
|
+
const secrets = [
|
|
1944
|
+
credentials.apiKey,
|
|
1945
|
+
credentials.secret,
|
|
1946
|
+
credentials.passphrase
|
|
1947
|
+
].filter((value) => value !== "");
|
|
1948
|
+
const texts = [];
|
|
1949
|
+
let cause = error;
|
|
1950
|
+
while (cause instanceof Error) {
|
|
1951
|
+
texts.push(cause.message);
|
|
1952
|
+
({cause} = cause);
|
|
1953
|
+
}
|
|
1954
|
+
if (error instanceof PolymarketError && error.body !== void 0) texts.push(JSON.stringify(error.body));
|
|
1955
|
+
const leaks = (text) => secrets.some((secret) => text.includes(secret));
|
|
1956
|
+
if (!texts.some(leaks)) return error;
|
|
1957
|
+
const redact = (text) => {
|
|
1958
|
+
let next = text;
|
|
1959
|
+
for (const secret of secrets) next = next.replaceAll(secret, "[redacted]");
|
|
1960
|
+
return next;
|
|
1961
|
+
};
|
|
1962
|
+
if (error instanceof PolymarketError) {
|
|
1963
|
+
const options = error.status === void 0 ? {} : { status: error.status };
|
|
1964
|
+
return new PolymarketError(error.category, redact(error.message), options);
|
|
1965
|
+
}
|
|
1966
|
+
return new PolymarketError("unavailable", redact(error instanceof Error ? error.message : String(error)));
|
|
1967
|
+
};
|
|
1968
|
+
function createPolymarketL2(options) {
|
|
1969
|
+
/** Last `now()` a skew check passed — one `/time` per session plus a refresh every 10 min. */
|
|
1970
|
+
let checkedAt;
|
|
1971
|
+
const assertClock = async () => {
|
|
1972
|
+
if (checkedAt !== void 0 && options.now() - checkedAt <= SKEW_REFRESH_MS) return;
|
|
1973
|
+
const { skewMs } = await options.http.time();
|
|
1974
|
+
checkedAt = options.now();
|
|
1975
|
+
if (Math.abs(skewMs) > 3e4) throw new PolymarketError("clock-skew", `the device clock is ${Math.round(skewMs)} ms off the CLOB's`);
|
|
1976
|
+
};
|
|
1977
|
+
return {
|
|
1978
|
+
request: async (group, input, schema) => {
|
|
1979
|
+
const credentials = await options.credentials.get(group);
|
|
1980
|
+
if (credentials === void 0) throw new PolymarketError("not-enabled", "the group has no Polymarket credentials");
|
|
1981
|
+
if ((await options.signerOf(group)).toLowerCase() !== credentials.owner.toLowerCase()) throw new PolymarketError("not-enabled", "the group's signer no longer matches its credentials");
|
|
1982
|
+
await assertClock();
|
|
1983
|
+
const timestamp = Math.floor(options.now() / 1e3);
|
|
1984
|
+
const headers = l2Headers(credentials, {
|
|
1985
|
+
method: input.method,
|
|
1986
|
+
path: input.path,
|
|
1987
|
+
...input.body === void 0 ? {} : { body: input.body },
|
|
1988
|
+
timestamp
|
|
1989
|
+
});
|
|
1990
|
+
try {
|
|
1991
|
+
return await options.http.request({
|
|
1992
|
+
host: CLOB_HOST,
|
|
1993
|
+
method: input.method,
|
|
1994
|
+
path: input.path,
|
|
1995
|
+
...input.query === void 0 ? {} : { query: input.query },
|
|
1996
|
+
headers: {
|
|
1997
|
+
...headers,
|
|
1998
|
+
...input.body === void 0 ? {} : { "content-type": "application/json" }
|
|
1999
|
+
},
|
|
2000
|
+
...input.body === void 0 ? {} : { body: input.body }
|
|
2001
|
+
}, schema);
|
|
2002
|
+
} catch (error) {
|
|
2003
|
+
throw scrub(error, credentials);
|
|
2004
|
+
}
|
|
2005
|
+
},
|
|
2006
|
+
credentials: async (group) => options.credentials.get(group)
|
|
2007
|
+
};
|
|
2008
|
+
}
|
|
2009
|
+
// src/apps/polymarket/live.ts
|
|
2010
|
+
const PING_MS = 1e4;
|
|
2011
|
+
const PONG_TIMEOUT_MS = 5e3;
|
|
2012
|
+
const ACCOUNT_POLL_MS = 1e4;
|
|
2013
|
+
const TRADE_REFRESH_MS = 1e3;
|
|
2014
|
+
/** A single frame carries at most this many events — anything bigger is dropped whole. */
|
|
2015
|
+
const MAX_FRAME_EVENTS = 256;
|
|
2016
|
+
const sortLevels = (levels, desc) => [...levels].sort((a, b) => {
|
|
2017
|
+
const cmp = Number(a.price) - Number(b.price);
|
|
2018
|
+
return desc ? -cmp : cmp;
|
|
2019
|
+
});
|
|
2020
|
+
const initialFrame = (ids) => `{"assets_ids":${JSON.stringify(ids)},"type":"market","custom_feature_enabled":true}`;
|
|
2021
|
+
const fatal = (error) => error instanceof PolymarketError && (error.category === "unlock-required" || error.category === "not-enabled");
|
|
2022
|
+
const authFrame = (credentials) => JSON.stringify({
|
|
2023
|
+
auth: {
|
|
2024
|
+
apiKey: credentials.apiKey,
|
|
2025
|
+
secret: credentials.secret,
|
|
2026
|
+
passphrase: credentials.passphrase
|
|
2027
|
+
},
|
|
2028
|
+
type: "user"
|
|
2029
|
+
});
|
|
2030
|
+
const updateFrame = (operation, ids) => `{"operation":"${operation}","assets_ids":${JSON.stringify(ids)}}`;
|
|
2031
|
+
function createPolymarketLive(options) {
|
|
2032
|
+
const views = /* @__PURE__ */ new Map();
|
|
2033
|
+
const viewByAsset = (assetId) => {
|
|
2034
|
+
const set = views.get(assetId);
|
|
2035
|
+
if (set === void 0) {
|
|
2036
|
+
const next = /* @__PURE__ */ new Set();
|
|
2037
|
+
views.set(assetId, next);
|
|
2038
|
+
return next;
|
|
2039
|
+
}
|
|
2040
|
+
return set;
|
|
2041
|
+
};
|
|
2042
|
+
let malformed = 0;
|
|
2043
|
+
const notify = (view) => {
|
|
2044
|
+
for (const listener of view.listeners) listener(view.state);
|
|
2045
|
+
};
|
|
2046
|
+
const setState = (view, next) => {
|
|
2047
|
+
view.state = next;
|
|
2048
|
+
notify(view);
|
|
2049
|
+
};
|
|
2050
|
+
const eachView = (assetId, fn) => {
|
|
2051
|
+
for (const view of views.get(assetId) ?? []) fn(view);
|
|
2052
|
+
};
|
|
2053
|
+
const applyBook = (view, event) => {
|
|
2054
|
+
const book = {
|
|
2055
|
+
bids: sortLevels(event.bids, true),
|
|
2056
|
+
asks: sortLevels(event.asks, false),
|
|
2057
|
+
tickSize: event.tick_size ?? view.state.data?.book?.tickSize,
|
|
2058
|
+
timestamp: event.timestamp,
|
|
2059
|
+
hash: event.hash
|
|
2060
|
+
};
|
|
2061
|
+
setState(view, {
|
|
2062
|
+
status: "live",
|
|
2063
|
+
error: void 0,
|
|
2064
|
+
updatedAt: options.now(),
|
|
2065
|
+
data: {
|
|
2066
|
+
...view.state.data,
|
|
2067
|
+
book,
|
|
2068
|
+
resolved: view.state.data?.resolved
|
|
2069
|
+
}
|
|
2070
|
+
});
|
|
2071
|
+
};
|
|
2072
|
+
const applyPriceChange = (view, event) => {
|
|
2073
|
+
const book = view.state.data?.book;
|
|
2074
|
+
if (book === void 0) return;
|
|
2075
|
+
let bids = [...book.bids];
|
|
2076
|
+
let asks = [...book.asks];
|
|
2077
|
+
let sawAsset = false;
|
|
2078
|
+
for (const change of event.price_changes) {
|
|
2079
|
+
if (change.asset_id !== view.assetId) continue;
|
|
2080
|
+
sawAsset = true;
|
|
2081
|
+
const side = change.side === "BUY" ? "bids" : "asks";
|
|
2082
|
+
const levels = side === "bids" ? bids : asks;
|
|
2083
|
+
const idx = levels.findIndex((l) => l.price === change.price);
|
|
2084
|
+
const next = [...levels];
|
|
2085
|
+
if (change.size === "0") {
|
|
2086
|
+
if (idx !== -1) next.splice(idx, 1);
|
|
2087
|
+
} else if (idx === -1) next.push({
|
|
2088
|
+
price: change.price,
|
|
2089
|
+
size: change.size
|
|
2090
|
+
});
|
|
2091
|
+
else next[idx] = {
|
|
2092
|
+
price: change.price,
|
|
2093
|
+
size: change.size
|
|
2094
|
+
};
|
|
2095
|
+
if (side === "bids") bids = sortLevels(next, true);
|
|
2096
|
+
else asks = sortLevels(next, false);
|
|
2097
|
+
}
|
|
2098
|
+
if (!sawAsset) return;
|
|
2099
|
+
setState(view, {
|
|
2100
|
+
...view.state,
|
|
2101
|
+
updatedAt: options.now(),
|
|
2102
|
+
data: {
|
|
2103
|
+
...view.state.data,
|
|
2104
|
+
book: {
|
|
2105
|
+
...book,
|
|
2106
|
+
bids,
|
|
2107
|
+
asks
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
});
|
|
2111
|
+
};
|
|
2112
|
+
const dispatch = (raw) => {
|
|
2113
|
+
let parsed;
|
|
2114
|
+
try {
|
|
2115
|
+
parsed = JSON.parse(raw);
|
|
2116
|
+
} catch {
|
|
2117
|
+
malformed += 1;
|
|
2118
|
+
options.logger.warn("apps.polymarket.live: dropped a malformed frame");
|
|
2119
|
+
return;
|
|
2120
|
+
}
|
|
2121
|
+
const events = Array.isArray(parsed) ? parsed : [parsed];
|
|
2122
|
+
for (const event of events) {
|
|
2123
|
+
const book = wsBookEvent.safeParse(event);
|
|
2124
|
+
if (book.success) {
|
|
2125
|
+
eachView(book.data.asset_id, (view) => applyBook(view, book.data));
|
|
2126
|
+
continue;
|
|
2127
|
+
}
|
|
2128
|
+
const change = wsPriceChangeEvent.safeParse(event);
|
|
2129
|
+
if (change.success) {
|
|
2130
|
+
for (const assetId of views.keys()) eachView(assetId, (view) => applyPriceChange(view, change.data));
|
|
2131
|
+
continue;
|
|
2132
|
+
}
|
|
2133
|
+
const trade = wsLastTradePriceEvent.safeParse(event);
|
|
2134
|
+
if (trade.success) {
|
|
2135
|
+
eachView(trade.data.asset_id, (view) => setState(view, {
|
|
2136
|
+
...view.state,
|
|
2137
|
+
updatedAt: options.now(),
|
|
2138
|
+
data: {
|
|
2139
|
+
...view.state.data,
|
|
2140
|
+
lastTrade: {
|
|
2141
|
+
price: trade.data.price,
|
|
2142
|
+
size: trade.data.size,
|
|
2143
|
+
side: trade.data.side
|
|
2144
|
+
}
|
|
2145
|
+
}
|
|
2146
|
+
}));
|
|
2147
|
+
continue;
|
|
2148
|
+
}
|
|
2149
|
+
const best = wsBestBidAskEvent.safeParse(event);
|
|
2150
|
+
if (best.success) {
|
|
2151
|
+
eachView(best.data.asset_id, (view) => setState(view, {
|
|
2152
|
+
...view.state,
|
|
2153
|
+
updatedAt: options.now(),
|
|
2154
|
+
data: {
|
|
2155
|
+
...view.state.data,
|
|
2156
|
+
bestBidAsk: {
|
|
2157
|
+
bestBid: best.data.best_bid,
|
|
2158
|
+
bestAsk: best.data.best_ask,
|
|
2159
|
+
spread: best.data.spread
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
}));
|
|
2163
|
+
continue;
|
|
2164
|
+
}
|
|
2165
|
+
const tick = wsTickSizeChangeEvent.safeParse(event);
|
|
2166
|
+
if (tick.success) {
|
|
2167
|
+
eachView(tick.data.asset_id, (view) => {
|
|
2168
|
+
const book = view.state.data?.book;
|
|
2169
|
+
if (book === void 0) return;
|
|
2170
|
+
setState(view, {
|
|
2171
|
+
...view.state,
|
|
2172
|
+
updatedAt: options.now(),
|
|
2173
|
+
data: {
|
|
2174
|
+
...view.state.data,
|
|
2175
|
+
book: {
|
|
2176
|
+
...book,
|
|
2177
|
+
tickSize: tick.data.new_tick_size
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
});
|
|
2181
|
+
});
|
|
2182
|
+
continue;
|
|
2183
|
+
}
|
|
2184
|
+
const resolved = wsMarketResolvedEvent.safeParse(event);
|
|
2185
|
+
if (resolved.success) {
|
|
2186
|
+
for (const assetId of resolved.data.assets_ids) eachView(assetId, (view) => setState(view, {
|
|
2187
|
+
...view.state,
|
|
2188
|
+
updatedAt: options.now(),
|
|
2189
|
+
data: {
|
|
2190
|
+
...view.state.data,
|
|
2191
|
+
resolved: {
|
|
2192
|
+
winningAssetId: resolved.data.winning_asset_id,
|
|
2193
|
+
winningOutcome: resolved.data.winning_outcome
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
}));
|
|
2197
|
+
continue;
|
|
2198
|
+
}
|
|
2199
|
+
malformed += 1;
|
|
2200
|
+
options.logger.warn("apps.polymarket.live: dropped an unparsed event");
|
|
2201
|
+
}
|
|
2202
|
+
};
|
|
2203
|
+
const core = createAppSocketCore({
|
|
2204
|
+
url: MARKET_WS_URL,
|
|
2205
|
+
socket: options.socket,
|
|
2206
|
+
setTimer: options.setTimer,
|
|
2207
|
+
random: options.random,
|
|
2208
|
+
heartbeat: {
|
|
2209
|
+
intervalMs: PING_MS,
|
|
2210
|
+
pongTimeoutMs: PONG_TIMEOUT_MS,
|
|
2211
|
+
ping: "PING",
|
|
2212
|
+
isPong: (raw) => raw === "PONG"
|
|
2213
|
+
},
|
|
2214
|
+
onOpen: () => {
|
|
2215
|
+
const ids = [...views.keys()];
|
|
2216
|
+
if (ids.length > 0) core.send(initialFrame(ids));
|
|
2217
|
+
for (const set of views.values()) for (const view of set) setState(view, {
|
|
2218
|
+
...view.state,
|
|
2219
|
+
status: "connecting"
|
|
2220
|
+
});
|
|
2221
|
+
},
|
|
2222
|
+
onMessage: dispatch,
|
|
2223
|
+
onUserClose: () => {
|
|
2224
|
+
for (const set of views.values()) for (const view of set) setState(view, {
|
|
2225
|
+
...view.state,
|
|
2226
|
+
status: "stale"
|
|
2227
|
+
});
|
|
2228
|
+
}
|
|
2229
|
+
});
|
|
2230
|
+
core.onStatus((status) => {
|
|
2231
|
+
if (status === "closed" && !core.closedByUser()) for (const set of views.values()) for (const view of set) setState(view, {
|
|
2232
|
+
...view.state,
|
|
2233
|
+
status: "stale"
|
|
2234
|
+
});
|
|
2235
|
+
else if (status === "connecting") for (const set of views.values()) for (const view of set) setState(view, {
|
|
2236
|
+
...view.state,
|
|
2237
|
+
status: "connecting"
|
|
2238
|
+
});
|
|
2239
|
+
});
|
|
2240
|
+
const book = (assetId) => {
|
|
2241
|
+
const view = {
|
|
2242
|
+
assetId,
|
|
2243
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
2244
|
+
state: {
|
|
2245
|
+
status: "connecting",
|
|
2246
|
+
error: void 0,
|
|
2247
|
+
updatedAt: void 0,
|
|
2248
|
+
data: {
|
|
2249
|
+
book: void 0,
|
|
2250
|
+
lastTrade: void 0,
|
|
2251
|
+
bestBidAsk: void 0,
|
|
2252
|
+
resolved: void 0
|
|
2253
|
+
}
|
|
2254
|
+
}
|
|
2255
|
+
};
|
|
2256
|
+
viewByAsset(assetId).add(view);
|
|
2257
|
+
if (core.status() === "open") core.send(updateFrame("subscribe", [assetId]));
|
|
2258
|
+
core.connect();
|
|
2259
|
+
return {
|
|
2260
|
+
getState: () => view.state,
|
|
2261
|
+
subscribe: (listener) => {
|
|
2262
|
+
view.listeners.add(listener);
|
|
2263
|
+
return () => {
|
|
2264
|
+
view.listeners.delete(listener);
|
|
2265
|
+
};
|
|
2266
|
+
},
|
|
2267
|
+
close: async () => {
|
|
2268
|
+
const owners = views.get(assetId);
|
|
2269
|
+
owners?.delete(view);
|
|
2270
|
+
if (owners !== void 0 && owners.size === 0) {
|
|
2271
|
+
views.delete(assetId);
|
|
2272
|
+
if (core.status() === "open") core.send(updateFrame("unsubscribe", [assetId]));
|
|
2273
|
+
}
|
|
2274
|
+
if (views.size === 0) core.close();
|
|
2275
|
+
await Promise.resolve();
|
|
2276
|
+
}
|
|
2277
|
+
};
|
|
2278
|
+
};
|
|
2279
|
+
const accountViews = /* @__PURE__ */ new Set();
|
|
2280
|
+
let unsubscribeWallet;
|
|
2281
|
+
const followLock = () => {
|
|
2282
|
+
unsubscribeWallet ??= options.wallet.subscribe(() => {
|
|
2283
|
+
const snapshot = options.wallet.getSnapshot();
|
|
2284
|
+
if (snapshot.vault !== "unlocked") {
|
|
2285
|
+
for (const view of Array.from(accountViews)) view.stop("unlock-required");
|
|
2286
|
+
return;
|
|
2287
|
+
}
|
|
2288
|
+
const wallets = new Set(snapshot.wallets.map((w) => w.walletId));
|
|
2289
|
+
for (const view of Array.from(accountViews)) if (!wallets.has(view.group.walletId)) view.stop("not-enabled");
|
|
2290
|
+
});
|
|
2291
|
+
};
|
|
2292
|
+
const account = (group) => {
|
|
2293
|
+
followLock();
|
|
2294
|
+
let credentials;
|
|
2295
|
+
let core;
|
|
2296
|
+
let snapshotting = false;
|
|
2297
|
+
const queued = [];
|
|
2298
|
+
let pollCancel;
|
|
2299
|
+
let tradeCancel;
|
|
2300
|
+
let unsubscribeDelete;
|
|
2301
|
+
const view = {
|
|
2302
|
+
group,
|
|
2303
|
+
listeners: /* @__PURE__ */ new Set(),
|
|
2304
|
+
closed: false,
|
|
2305
|
+
state: {
|
|
2306
|
+
status: "connecting",
|
|
2307
|
+
error: void 0,
|
|
2308
|
+
updatedAt: void 0,
|
|
2309
|
+
data: void 0
|
|
2310
|
+
},
|
|
2311
|
+
stop: (error) => {
|
|
2312
|
+
if (view.closed) return;
|
|
2313
|
+
view.closed = true;
|
|
2314
|
+
credentials = void 0;
|
|
2315
|
+
queued.length = 0;
|
|
2316
|
+
pollCancel?.();
|
|
2317
|
+
pollCancel = void 0;
|
|
2318
|
+
tradeCancel?.();
|
|
2319
|
+
tradeCancel = void 0;
|
|
2320
|
+
core?.close();
|
|
2321
|
+
core = void 0;
|
|
2322
|
+
unsubscribeDelete?.();
|
|
2323
|
+
unsubscribeDelete = void 0;
|
|
2324
|
+
accountViews.delete(view);
|
|
2325
|
+
if (accountViews.size === 0) {
|
|
2326
|
+
unsubscribeWallet?.();
|
|
2327
|
+
unsubscribeWallet = void 0;
|
|
2328
|
+
}
|
|
2329
|
+
view.state = {
|
|
2330
|
+
...view.state,
|
|
2331
|
+
status: "stale",
|
|
2332
|
+
error
|
|
2333
|
+
};
|
|
2334
|
+
for (const listener of view.listeners) listener(view.state);
|
|
2335
|
+
}
|
|
2336
|
+
};
|
|
2337
|
+
unsubscribeDelete = options.credentials.onDelete((deleted) => {
|
|
2338
|
+
if (deleted.walletId === group.walletId && deleted.groupIndex === group.groupIndex) view.stop("not-enabled");
|
|
2339
|
+
});
|
|
2340
|
+
const emit = (next) => {
|
|
2341
|
+
view.state = next;
|
|
2342
|
+
for (const listener of view.listeners) listener(next);
|
|
2343
|
+
};
|
|
2344
|
+
const snapshot = async () => {
|
|
2345
|
+
const located = await options.account.locate(group);
|
|
2346
|
+
const [orders, positions, trades] = await Promise.all([
|
|
2347
|
+
options.account.openOrders(group, {}),
|
|
2348
|
+
options.account.positions(located.wallet, {}),
|
|
2349
|
+
options.account.trades(group, {})
|
|
2350
|
+
]);
|
|
2351
|
+
return {
|
|
2352
|
+
wallet: located.wallet,
|
|
2353
|
+
openOrders: orders.items,
|
|
2354
|
+
positions: positions.items,
|
|
2355
|
+
trades: trades.items
|
|
2356
|
+
};
|
|
2357
|
+
};
|
|
2358
|
+
const applyOrder = (event) => {
|
|
2359
|
+
const { data } = view.state;
|
|
2360
|
+
if (data === void 0) return;
|
|
2361
|
+
if (event.type === "CANCELLATION" || event.status !== void 0 && event.status !== "LIVE") {
|
|
2362
|
+
emit({
|
|
2363
|
+
...view.state,
|
|
2364
|
+
updatedAt: options.now(),
|
|
2365
|
+
data: {
|
|
2366
|
+
...data,
|
|
2367
|
+
openOrders: data.openOrders.filter((order) => order.id !== event.id)
|
|
2368
|
+
}
|
|
2369
|
+
});
|
|
2370
|
+
return;
|
|
2371
|
+
}
|
|
2372
|
+
const createdAt = event.created_at === void 0 ? NaN : Number(event.created_at);
|
|
2373
|
+
if (event.market === void 0 || event.asset_id === void 0 || event.side === void 0 || event.original_size === void 0 || event.size_matched === void 0 || event.price === void 0 || event.order_type === void 0 || event.expiration === void 0 || event.maker_address === void 0 || !Number.isFinite(createdAt)) {
|
|
2374
|
+
malformed += 1;
|
|
2375
|
+
options.logger.warn("apps.polymarket.live: dropped an unmappable order event");
|
|
2376
|
+
return;
|
|
2377
|
+
}
|
|
2378
|
+
const order = {
|
|
2379
|
+
id: event.id,
|
|
2380
|
+
status: event.status ?? "LIVE",
|
|
2381
|
+
conditionId: event.market,
|
|
2382
|
+
assetId: event.asset_id,
|
|
2383
|
+
side: event.side,
|
|
2384
|
+
price: event.price,
|
|
2385
|
+
originalSize: event.original_size,
|
|
2386
|
+
sizeMatched: event.size_matched,
|
|
2387
|
+
...event.outcome === void 0 || event.outcome === null ? {} : { outcome: event.outcome },
|
|
2388
|
+
orderType: event.order_type,
|
|
2389
|
+
expiration: event.expiration,
|
|
2390
|
+
createdAt,
|
|
2391
|
+
makerAddress: event.maker_address
|
|
2392
|
+
};
|
|
2393
|
+
const index = data.openOrders.findIndex((existing) => existing.id === order.id);
|
|
2394
|
+
const openOrders = index === -1 ? [...data.openOrders, order] : data.openOrders.map((existing, at) => at === index ? order : existing);
|
|
2395
|
+
emit({
|
|
2396
|
+
...view.state,
|
|
2397
|
+
updatedAt: options.now(),
|
|
2398
|
+
data: {
|
|
2399
|
+
...data,
|
|
2400
|
+
openOrders
|
|
2401
|
+
}
|
|
2402
|
+
});
|
|
2403
|
+
};
|
|
2404
|
+
const scheduleTradeRead = () => {
|
|
2405
|
+
if (tradeCancel !== void 0 || view.closed) return;
|
|
2406
|
+
tradeCancel = options.setTimer(TRADE_REFRESH_MS, () => {
|
|
2407
|
+
tradeCancel = void 0;
|
|
2408
|
+
(async () => {
|
|
2409
|
+
const wallet = view.state.data?.wallet;
|
|
2410
|
+
if (wallet === void 0 || view.closed) return;
|
|
2411
|
+
try {
|
|
2412
|
+
const [positions, trades] = await Promise.all([options.account.positions(wallet, {}), options.account.trades(group, {})]);
|
|
2413
|
+
const { data } = view.state;
|
|
2414
|
+
if (view.closed || data === void 0) return;
|
|
2415
|
+
emit({
|
|
2416
|
+
...view.state,
|
|
2417
|
+
updatedAt: options.now(),
|
|
2418
|
+
data: {
|
|
2419
|
+
...data,
|
|
2420
|
+
positions: positions.items,
|
|
2421
|
+
trades: trades.items
|
|
2422
|
+
}
|
|
2423
|
+
});
|
|
2424
|
+
} catch (error) {
|
|
2425
|
+
if (view.closed) return;
|
|
2426
|
+
if (fatal(error)) view.stop(error.category);
|
|
2427
|
+
}
|
|
2428
|
+
})();
|
|
2429
|
+
});
|
|
2430
|
+
};
|
|
2431
|
+
const applyFrame = (raw) => {
|
|
2432
|
+
let parsed;
|
|
2433
|
+
try {
|
|
2434
|
+
parsed = JSON.parse(raw);
|
|
2435
|
+
} catch {
|
|
2436
|
+
malformed += 1;
|
|
2437
|
+
options.logger.warn("apps.polymarket.live: dropped a malformed user frame");
|
|
2438
|
+
return;
|
|
2439
|
+
}
|
|
2440
|
+
const events = Array.isArray(parsed) ? parsed : [parsed];
|
|
2441
|
+
if (events.length > MAX_FRAME_EVENTS) {
|
|
2442
|
+
malformed += 1;
|
|
2443
|
+
options.logger.warn("apps.polymarket.live: dropped an oversized user frame");
|
|
2444
|
+
return;
|
|
2445
|
+
}
|
|
2446
|
+
for (const event of events) {
|
|
2447
|
+
const order = wsUserOrderEvent.safeParse(event);
|
|
2448
|
+
if (order.success) {
|
|
2449
|
+
applyOrder(order.data);
|
|
2450
|
+
continue;
|
|
2451
|
+
}
|
|
2452
|
+
if (wsUserTradeEvent.safeParse(event).success) {
|
|
2453
|
+
scheduleTradeRead();
|
|
2454
|
+
continue;
|
|
2455
|
+
}
|
|
2456
|
+
malformed += 1;
|
|
2457
|
+
options.logger.warn("apps.polymarket.live: dropped an unparsed user event");
|
|
2458
|
+
}
|
|
2459
|
+
};
|
|
2460
|
+
const startPoll = () => {
|
|
2461
|
+
if (pollCancel !== void 0 || view.closed) return;
|
|
2462
|
+
const tick = async () => {
|
|
2463
|
+
pollCancel = void 0;
|
|
2464
|
+
try {
|
|
2465
|
+
const data = await snapshot();
|
|
2466
|
+
if (view.closed) return;
|
|
2467
|
+
emit({
|
|
2468
|
+
...view.state,
|
|
2469
|
+
updatedAt: options.now(),
|
|
2470
|
+
data: {
|
|
2471
|
+
...data,
|
|
2472
|
+
source: "poll"
|
|
2473
|
+
}
|
|
2474
|
+
});
|
|
2475
|
+
} catch (error) {
|
|
2476
|
+
if (view.closed) return;
|
|
2477
|
+
if (fatal(error)) {
|
|
2478
|
+
view.stop(error.category);
|
|
2479
|
+
return;
|
|
2480
|
+
}
|
|
2481
|
+
}
|
|
2482
|
+
if (!view.closed) pollCancel = options.setTimer(ACCOUNT_POLL_MS, () => void tick());
|
|
2483
|
+
};
|
|
2484
|
+
pollCancel = options.setTimer(ACCOUNT_POLL_MS, () => void tick());
|
|
2485
|
+
};
|
|
2486
|
+
const runSnapshot = async () => {
|
|
2487
|
+
snapshotting = true;
|
|
2488
|
+
let degraded = false;
|
|
2489
|
+
try {
|
|
2490
|
+
const data = await snapshot();
|
|
2491
|
+
if (view.closed) return;
|
|
2492
|
+
pollCancel?.();
|
|
2493
|
+
pollCancel = void 0;
|
|
2494
|
+
emit({
|
|
2495
|
+
status: "live",
|
|
2496
|
+
error: void 0,
|
|
2497
|
+
updatedAt: options.now(),
|
|
2498
|
+
data: {
|
|
2499
|
+
...data,
|
|
2500
|
+
source: "stream"
|
|
2501
|
+
}
|
|
2502
|
+
});
|
|
2503
|
+
} catch (error) {
|
|
2504
|
+
if (view.closed) return;
|
|
2505
|
+
if (fatal(error)) {
|
|
2506
|
+
view.stop(error.category);
|
|
2507
|
+
return;
|
|
2508
|
+
}
|
|
2509
|
+
degraded = true;
|
|
2510
|
+
emit({
|
|
2511
|
+
...view.state,
|
|
2512
|
+
status: "stale",
|
|
2513
|
+
error: void 0
|
|
2514
|
+
});
|
|
2515
|
+
} finally {
|
|
2516
|
+
snapshotting = false;
|
|
2517
|
+
for (const raw of queued.splice(0)) if (!view.closed) applyFrame(raw);
|
|
2518
|
+
}
|
|
2519
|
+
if (degraded && !view.closed) startPoll();
|
|
2520
|
+
};
|
|
2521
|
+
const onUserMessage = (raw) => {
|
|
2522
|
+
if (view.closed) return;
|
|
2523
|
+
if (snapshotting) {
|
|
2524
|
+
if (queued.length < MAX_FRAME_EVENTS) queued.push(raw);
|
|
2525
|
+
return;
|
|
2526
|
+
}
|
|
2527
|
+
applyFrame(raw);
|
|
2528
|
+
};
|
|
2529
|
+
(async () => {
|
|
2530
|
+
try {
|
|
2531
|
+
credentials = await options.credentials.get(group);
|
|
2532
|
+
} catch (error) {
|
|
2533
|
+
view.stop(error instanceof PolymarketError ? error.category : "unavailable");
|
|
2534
|
+
return;
|
|
2535
|
+
}
|
|
2536
|
+
if (view.closed) return;
|
|
2537
|
+
if (credentials === void 0) {
|
|
2538
|
+
view.stop("not-enabled");
|
|
2539
|
+
return;
|
|
2540
|
+
}
|
|
2541
|
+
const next = createAppSocketCore({
|
|
2542
|
+
url: USER_WS_URL,
|
|
2543
|
+
socket: options.socket,
|
|
2544
|
+
setTimer: options.setTimer,
|
|
2545
|
+
random: options.random,
|
|
2546
|
+
heartbeat: {
|
|
2547
|
+
intervalMs: PING_MS,
|
|
2548
|
+
pongTimeoutMs: PONG_TIMEOUT_MS,
|
|
2549
|
+
ping: "PING",
|
|
2550
|
+
isPong: (raw) => raw === "PONG"
|
|
2551
|
+
},
|
|
2552
|
+
onOpen: () => {
|
|
2553
|
+
if (credentials !== void 0) next.send(authFrame(credentials));
|
|
2554
|
+
runSnapshot();
|
|
2555
|
+
},
|
|
2556
|
+
onMessage: onUserMessage
|
|
2557
|
+
});
|
|
2558
|
+
next.onStatus((status) => {
|
|
2559
|
+
if (view.closed) return;
|
|
2560
|
+
if (status === "closed" && !next.closedByUser()) {
|
|
2561
|
+
emit({
|
|
2562
|
+
...view.state,
|
|
2563
|
+
status: "stale"
|
|
2564
|
+
});
|
|
2565
|
+
startPoll();
|
|
2566
|
+
} else if (status === "connecting") emit({
|
|
2567
|
+
...view.state,
|
|
2568
|
+
status: "connecting"
|
|
2569
|
+
});
|
|
2570
|
+
});
|
|
2571
|
+
core = next;
|
|
2572
|
+
next.connect();
|
|
2573
|
+
})();
|
|
2574
|
+
accountViews.add(view);
|
|
2575
|
+
return {
|
|
2576
|
+
getState: () => view.state,
|
|
2577
|
+
subscribe: (listener) => {
|
|
2578
|
+
view.listeners.add(listener);
|
|
2579
|
+
return () => {
|
|
2580
|
+
view.listeners.delete(listener);
|
|
2581
|
+
};
|
|
2582
|
+
},
|
|
2583
|
+
close: async () => {
|
|
2584
|
+
view.stop(view.state.error);
|
|
2585
|
+
await Promise.resolve();
|
|
2586
|
+
}
|
|
2587
|
+
};
|
|
2588
|
+
};
|
|
2589
|
+
return {
|
|
2590
|
+
book,
|
|
2591
|
+
account
|
|
2592
|
+
};
|
|
2593
|
+
}
|
|
2594
|
+
// src/apps/polymarket/markets.ts
|
|
2595
|
+
const EVENTS_LIMIT = 100;
|
|
2596
|
+
const malformed = (where, what) => new PolymarketError("malformed", `${where}: ${what}`);
|
|
2597
|
+
/** A Gamma JSON-text field: a strict JSON array, every item run through `check`. */
|
|
2598
|
+
const jsonArray = (text, check, where) => {
|
|
2599
|
+
let parsed;
|
|
2600
|
+
try {
|
|
2601
|
+
parsed = JSON.parse(text);
|
|
2602
|
+
} catch {
|
|
2603
|
+
throw malformed(where, "field is not JSON text");
|
|
2604
|
+
}
|
|
2605
|
+
if (!Array.isArray(parsed) || parsed.length > 64 || !parsed.every(check)) throw malformed(where, "field is not the expected JSON array");
|
|
2606
|
+
return parsed;
|
|
2607
|
+
};
|
|
2608
|
+
const isString = (value) => typeof value === "string";
|
|
2609
|
+
const isUint256 = (value) => typeof value === "string" && /^[0-9]{1,78}$/.test(value);
|
|
2610
|
+
const normalizeMarket = (raw) => {
|
|
2611
|
+
const outcomes = jsonArray(raw.outcomes, isString, `market ${raw.id} outcomes`);
|
|
2612
|
+
const version = raw.version === "v2" ? "v2" : "v1";
|
|
2613
|
+
const assetIds = version === "v2" ? (raw.positionIds ?? []).filter(isUint256) : raw.clobTokenIds === void 0 || raw.clobTokenIds === null ? (() => {
|
|
2614
|
+
throw malformed(`market ${raw.id}`, "v1 market has no clobTokenIds");
|
|
2615
|
+
})() : jsonArray(raw.clobTokenIds, isUint256, `market ${raw.id} clobTokenIds`);
|
|
2616
|
+
if (version === "v2" && assetIds.length === 0) throw malformed(`market ${raw.id}`, "v2 market has no positionIds");
|
|
2617
|
+
if (assetIds.length !== outcomes.length) throw malformed(`market ${raw.id}`, "asset id count does not match outcomes");
|
|
2618
|
+
const outcomePrices = raw.outcomePrices === void 0 || raw.outcomePrices === null ? void 0 : jsonArray(raw.outcomePrices, isString, `market ${raw.id} outcomePrices`);
|
|
2619
|
+
const questionId = raw.questionID ?? raw.questionId ?? void 0;
|
|
2620
|
+
return {
|
|
2621
|
+
id: raw.id,
|
|
2622
|
+
conditionId: raw.conditionId,
|
|
2623
|
+
...questionId === void 0 || questionId === null ? {} : { questionId },
|
|
2624
|
+
question: raw.question ?? "",
|
|
2625
|
+
slug: raw.slug,
|
|
2626
|
+
outcomes,
|
|
2627
|
+
assetIds,
|
|
2628
|
+
version,
|
|
2629
|
+
negRisk: raw.negRisk ?? false,
|
|
2630
|
+
tickSize: raw.orderPriceMinTickSize ?? "0.01",
|
|
2631
|
+
minOrderSize: raw.orderMinSize ?? "1",
|
|
2632
|
+
acceptingOrders: raw.acceptingOrders ?? false,
|
|
2633
|
+
active: raw.active ?? false,
|
|
2634
|
+
closed: raw.closed ?? false,
|
|
2635
|
+
...raw.endDate === void 0 || raw.endDate === null ? {} : { endDate: raw.endDate },
|
|
2636
|
+
...outcomePrices === void 0 ? {} : { outcomePrices },
|
|
2637
|
+
...raw.volume === void 0 || raw.volume === null ? {} : { volume: raw.volume },
|
|
2638
|
+
...raw.liquidity === void 0 || raw.liquidity === null ? {} : { liquidity: raw.liquidity },
|
|
2639
|
+
...raw.makerBaseFee === void 0 && raw.takerBaseFee === void 0 ? {} : { fees: {
|
|
2640
|
+
...raw.makerBaseFee === void 0 || raw.makerBaseFee === null ? {} : { makerBaseFee: raw.makerBaseFee },
|
|
2641
|
+
...raw.takerBaseFee === void 0 || raw.takerBaseFee === null ? {} : { takerBaseFee: raw.takerBaseFee }
|
|
2642
|
+
} }
|
|
2643
|
+
};
|
|
2644
|
+
};
|
|
2645
|
+
const normalizeEvent = (raw) => ({
|
|
2646
|
+
id: raw.id,
|
|
2647
|
+
slug: raw.slug,
|
|
2648
|
+
title: raw.title ?? "",
|
|
2649
|
+
active: raw.active ?? false,
|
|
2650
|
+
closed: raw.closed ?? false,
|
|
2651
|
+
...raw.negRisk === void 0 || raw.negRisk === null ? {} : { negRisk: raw.negRisk },
|
|
2652
|
+
...raw.endDate === void 0 || raw.endDate === null ? {} : { endDate: raw.endDate },
|
|
2653
|
+
markets: (raw.markets ?? []).map(normalizeMarket)
|
|
2654
|
+
});
|
|
2655
|
+
const normalizeResolution = (row) => ({
|
|
2656
|
+
...row.condition_id === void 0 || row.condition_id === null ? {} : { conditionId: row.condition_id },
|
|
2657
|
+
...row.question_id === void 0 || row.question_id === null ? {} : { questionId: row.question_id },
|
|
2658
|
+
status: row.status,
|
|
2659
|
+
resolved: row.status === "resolved",
|
|
2660
|
+
...row.market_type === void 0 || row.market_type === null ? {} : { marketType: row.market_type },
|
|
2661
|
+
...row.reporter === void 0 || row.reporter === null ? {} : { reporter: row.reporter },
|
|
2662
|
+
wasDisputed: row.was_disputed,
|
|
2663
|
+
extendedReview: row.extended_review,
|
|
2664
|
+
...row.resolved_at === void 0 || row.resolved_at === null ? {} : { resolvedAt: row.resolved_at },
|
|
2665
|
+
...row.payouts === void 0 || row.payouts === null ? {} : { payouts: row.payouts },
|
|
2666
|
+
...row.price === void 0 || row.price === null ? {} : { price: row.price }
|
|
2667
|
+
});
|
|
2668
|
+
const eventsQuery = (params) => {
|
|
2669
|
+
if (params === void 0) return {};
|
|
2670
|
+
if (params.limit !== void 0 && (!Number.isInteger(params.limit) || params.limit < 1 || params.limit > EVENTS_LIMIT)) throw new PolymarketError("invalid-input", `limit must be an integer in 1..${EVENTS_LIMIT}`);
|
|
2671
|
+
return {
|
|
2672
|
+
...params.limit === void 0 ? {} : { limit: params.limit },
|
|
2673
|
+
...params.offset === void 0 ? {} : { offset: params.offset },
|
|
2674
|
+
...params.closed === void 0 ? {} : { closed: params.closed },
|
|
2675
|
+
...params.order === void 0 ? {} : { order: params.order },
|
|
2676
|
+
...params.ascending === void 0 ? {} : { ascending: params.ascending },
|
|
2677
|
+
...params.tag_id === void 0 ? {} : { tag_id: params.tag_id }
|
|
2678
|
+
};
|
|
2679
|
+
};
|
|
2680
|
+
const byPrice = (a, b) => Number(a.price) - Number(b.price);
|
|
2681
|
+
function createPolymarketMarkets(http) {
|
|
2682
|
+
return {
|
|
2683
|
+
events: async (params) => {
|
|
2684
|
+
return (await http.request({
|
|
2685
|
+
host: GAMMA_HOST,
|
|
2686
|
+
method: "GET",
|
|
2687
|
+
path: "/events",
|
|
2688
|
+
query: eventsQuery(params)
|
|
2689
|
+
}, gammaEventList)).map(normalizeEvent);
|
|
2690
|
+
},
|
|
2691
|
+
event: async (slug) => normalizeEvent(await http.request({
|
|
2692
|
+
host: GAMMA_HOST,
|
|
2693
|
+
method: "GET",
|
|
2694
|
+
path: `/events/slug/${slug}`
|
|
2695
|
+
}, gammaEvent)),
|
|
2696
|
+
markets: async (params) => {
|
|
2697
|
+
return (await http.request({
|
|
2698
|
+
host: GAMMA_HOST,
|
|
2699
|
+
method: "GET",
|
|
2700
|
+
path: "/markets",
|
|
2701
|
+
query: eventsQuery(params)
|
|
2702
|
+
}, gammaMarketList)).map(normalizeMarket);
|
|
2703
|
+
},
|
|
2704
|
+
market: async (slug) => normalizeMarket(await http.request({
|
|
2705
|
+
host: GAMMA_HOST,
|
|
2706
|
+
method: "GET",
|
|
2707
|
+
path: `/markets/slug/${slug}`
|
|
2708
|
+
}, gammaMarket)),
|
|
2709
|
+
search: async (query) => {
|
|
2710
|
+
return ((await http.request({
|
|
2711
|
+
host: "https://gamma-api.polymarket.com",
|
|
2712
|
+
method: "GET",
|
|
2713
|
+
path: "/public-search",
|
|
2714
|
+
query: { q: query }
|
|
2715
|
+
}, gammaSearch)).events ?? []).map(normalizeEvent);
|
|
2716
|
+
},
|
|
2717
|
+
book: async (assetId) => {
|
|
2718
|
+
const raw = await http.request({
|
|
2719
|
+
host: CLOB_HOST,
|
|
2720
|
+
method: "GET",
|
|
2721
|
+
path: "/book",
|
|
2722
|
+
query: { token_id: assetId }
|
|
2723
|
+
}, clobBook);
|
|
2724
|
+
return {
|
|
2725
|
+
assetId: raw.asset_id,
|
|
2726
|
+
conditionId: raw.market,
|
|
2727
|
+
version: raw.version === "v2" ? "v2" : "v1",
|
|
2728
|
+
bids: [...raw.bids].sort((a, b) => byPrice(b, a)),
|
|
2729
|
+
asks: [...raw.asks].sort(byPrice),
|
|
2730
|
+
tickSize: raw.tick_size,
|
|
2731
|
+
minOrderSize: raw.min_order_size,
|
|
2732
|
+
negRisk: raw.neg_risk,
|
|
2733
|
+
timestamp: raw.timestamp,
|
|
2734
|
+
hash: raw.hash
|
|
2735
|
+
};
|
|
2736
|
+
},
|
|
2737
|
+
price: async (assetId, side) => {
|
|
2738
|
+
return (await http.request({
|
|
2739
|
+
host: CLOB_HOST,
|
|
2740
|
+
method: "GET",
|
|
2741
|
+
path: "/price",
|
|
2742
|
+
query: {
|
|
2743
|
+
token_id: assetId,
|
|
2744
|
+
side
|
|
2745
|
+
}
|
|
2746
|
+
}, clobPrice)).price;
|
|
2747
|
+
},
|
|
2748
|
+
midpoint: async (assetId) => {
|
|
2749
|
+
return (await http.request({
|
|
2750
|
+
host: CLOB_HOST,
|
|
2751
|
+
method: "GET",
|
|
2752
|
+
path: "/midpoint",
|
|
2753
|
+
query: { token_id: assetId }
|
|
2754
|
+
}, clobMidpoint)).mid;
|
|
2755
|
+
},
|
|
2756
|
+
history: async (assetId, params) => {
|
|
2757
|
+
return (await http.request({
|
|
2758
|
+
host: CLOB_HOST,
|
|
2759
|
+
method: "GET",
|
|
2760
|
+
path: "/prices-history",
|
|
2761
|
+
query: {
|
|
2762
|
+
market: assetId,
|
|
2763
|
+
...params?.startTs === void 0 ? {} : { startTs: params.startTs },
|
|
2764
|
+
...params?.endTs === void 0 ? {} : { endTs: params.endTs },
|
|
2765
|
+
...params?.interval === void 0 ? {} : { interval: params.interval },
|
|
2766
|
+
...params?.fidelity === void 0 ? {} : { fidelity: params.fidelity }
|
|
2767
|
+
}
|
|
2768
|
+
}, clobPricesHistory)).history;
|
|
2769
|
+
},
|
|
2770
|
+
clobMarket: async (condition) => {
|
|
2771
|
+
const raw = await http.request({
|
|
2772
|
+
host: CLOB_HOST,
|
|
2773
|
+
method: "GET",
|
|
2774
|
+
path: `/clob-markets/${condition}`
|
|
2775
|
+
}, clobMarketDetails);
|
|
2776
|
+
return {
|
|
2777
|
+
...raw.c === void 0 || raw.c === null ? {} : { conditionId: raw.c },
|
|
2778
|
+
tokens: raw.t.map((token) => ({
|
|
2779
|
+
assetId: token.t,
|
|
2780
|
+
...token.o === void 0 || token.o === null ? {} : { outcome: token.o }
|
|
2781
|
+
})),
|
|
2782
|
+
...raw.mos === void 0 || raw.mos === null ? {} : { minOrderSize: raw.mos },
|
|
2783
|
+
...raw.mts === void 0 || raw.mts === null ? {} : { tickSize: raw.mts },
|
|
2784
|
+
...raw.ao === void 0 || raw.ao === null ? {} : { acceptingOrders: raw.ao },
|
|
2785
|
+
...raw.cbos === void 0 || raw.cbos === null ? {} : { buyOnly: raw.cbos },
|
|
2786
|
+
version: raw.v === "v2" ? "v2" : "v1",
|
|
2787
|
+
...raw.ibce === void 0 || raw.ibce === null ? {} : { blockaidEnabled: raw.ibce },
|
|
2788
|
+
...raw.r === void 0 || raw.r === null ? {} : { rewards: {
|
|
2789
|
+
...raw.r.e === void 0 || raw.r.e === null ? {} : { enabled: raw.r.e },
|
|
2790
|
+
...raw.r.mi === void 0 || raw.r.mi === null ? {} : { minIncentiveSize: raw.r.mi },
|
|
2791
|
+
...raw.r.ma === void 0 || raw.r.ma === null ? {} : { maxIncentiveRate: raw.r.ma },
|
|
2792
|
+
...raw.r.moas === void 0 || raw.r.moas === null ? {} : { minOrderAgeSec: raw.r.moas }
|
|
2793
|
+
} }
|
|
2794
|
+
};
|
|
2795
|
+
},
|
|
2796
|
+
feeRate: async (assetId) => {
|
|
2797
|
+
return (await http.request({
|
|
2798
|
+
host: CLOB_HOST,
|
|
2799
|
+
method: "GET",
|
|
2800
|
+
path: "/fee-rate",
|
|
2801
|
+
query: { token_id: assetId }
|
|
2802
|
+
}, clobFeeRate)).base_fee;
|
|
2803
|
+
},
|
|
2804
|
+
resolution: async (condition) => {
|
|
2805
|
+
return (await http.request({
|
|
2806
|
+
host: DATA_HOST,
|
|
2807
|
+
method: "GET",
|
|
2808
|
+
path: "/v2/resolutions",
|
|
2809
|
+
query: { condition }
|
|
2810
|
+
}, dataResolutions)).data.map(normalizeResolution);
|
|
2811
|
+
},
|
|
2812
|
+
time: http.time
|
|
2813
|
+
};
|
|
2814
|
+
}
|
|
2815
|
+
// src/apps/polymarket/orders.ts
|
|
2816
|
+
/**
|
|
2817
|
+
* Polymarket order math and EIP-712 construction (design.md §订单数学) — pure bigint arithmetic in
|
|
2818
|
+
* 6-decimal integer units (pUSD and shares are both 6-decimal assets); no float ever touches an
|
|
2819
|
+
* amount. Directional rounding only: a BUY limit price rounds down to the tick, a SELL up, sizes
|
|
2820
|
+
* round down to two decimals, and a market order's bound-side amount rounds the way that can only
|
|
2821
|
+
* improve the user's implied price — the signed order is never worse than the user's limit
|
|
2822
|
+
* (invariant 6). Sources: docs trading/place-orders.md §Calculate the Order Amounts for the
|
|
2823
|
+
* precision table (verified against `@polymarket/clob-client-v2` `roundingConfig.ts`) and §Create
|
|
2824
|
+
* the Order Typed Data for the `TypedDataSign` envelope — byte-identical to
|
|
2825
|
+
* `exchangeOrderBuilderV2.ts`, whose `Order` field order is ctf-exchange-v2 `Structs.sol`
|
|
2826
|
+
* ORDER_TYPEHASH. Domain by book (research.md §3): `version:"v2"` → ExchangeV3 v"3"; otherwise the
|
|
2827
|
+
* V2 exchanges by `neg_risk`, v"2".
|
|
2828
|
+
*/
|
|
2829
|
+
const SCALE = 1000000n;
|
|
2830
|
+
const ONE = SCALE;
|
|
2831
|
+
const SIZE_GRID = 10000n;
|
|
2832
|
+
const MAX_SLIPPAGE_BPS = 5e3;
|
|
2833
|
+
/**
|
|
2834
|
+
* Tick → {price, size, amount} decimals + the tick in 6-decimal units (docs trading/place-orders.md
|
|
2835
|
+
* §Calculate the Order Amounts; clob-client-v2 `roundingConfig.ts`).
|
|
2836
|
+
*/
|
|
2837
|
+
const TICKS = {
|
|
2838
|
+
"0.1": {
|
|
2839
|
+
price: 1,
|
|
2840
|
+
size: 2,
|
|
2841
|
+
amount: 3
|
|
2842
|
+
},
|
|
2843
|
+
"0.01": {
|
|
2844
|
+
price: 2,
|
|
2845
|
+
size: 2,
|
|
2846
|
+
amount: 4
|
|
2847
|
+
},
|
|
2848
|
+
"0.005": {
|
|
2849
|
+
price: 3,
|
|
2850
|
+
size: 2,
|
|
2851
|
+
amount: 5
|
|
2852
|
+
},
|
|
2853
|
+
"0.0025": {
|
|
2854
|
+
price: 4,
|
|
2855
|
+
size: 2,
|
|
2856
|
+
amount: 6
|
|
2857
|
+
},
|
|
2858
|
+
"0.001": {
|
|
2859
|
+
price: 3,
|
|
2860
|
+
size: 2,
|
|
2861
|
+
amount: 5
|
|
2862
|
+
},
|
|
2863
|
+
"0.0001": {
|
|
2864
|
+
price: 4,
|
|
2865
|
+
size: 2,
|
|
2866
|
+
amount: 6
|
|
2867
|
+
}
|
|
2868
|
+
};
|
|
2869
|
+
const tickOf = (tickSize) => {
|
|
2870
|
+
const config = TICKS[tickSize];
|
|
2871
|
+
if (config === void 0) throw new PolymarketError("invalid-input", `unsupported tick size ${tickSize}`);
|
|
2872
|
+
return {
|
|
2873
|
+
grid: toUnits(tickSize, "tick size"),
|
|
2874
|
+
amount: config.amount
|
|
2875
|
+
};
|
|
2876
|
+
};
|
|
2877
|
+
/** A decimal string in 6-decimal units — anything else or > 6 decimals is `invalid-input`. */
|
|
2878
|
+
const toUnits = (text, what) => {
|
|
2879
|
+
let decimal;
|
|
2880
|
+
try {
|
|
2881
|
+
decimal = parseDecimal(text);
|
|
2882
|
+
} catch {
|
|
2883
|
+
throw new PolymarketError("invalid-input", `${what} is not a decimal: ${text}`);
|
|
2884
|
+
}
|
|
2885
|
+
if (decimal.scale > 6 || decimal.units < 0n) throw new PolymarketError("invalid-input", `${what} ${text} does not fit 6 decimals`);
|
|
2886
|
+
return decimal.units * 10n ** BigInt(6 - decimal.scale);
|
|
2887
|
+
};
|
|
2888
|
+
const fromUnits = (units) => formatDecimal({
|
|
2889
|
+
units,
|
|
2890
|
+
scale: 6
|
|
2891
|
+
});
|
|
2892
|
+
const floorTo = (value, grid) => value - value % grid;
|
|
2893
|
+
const ceilTo = (value, grid) => {
|
|
2894
|
+
const rest = value % grid;
|
|
2895
|
+
return rest === 0n ? value : value + grid - rest;
|
|
2896
|
+
};
|
|
2897
|
+
const ceilDiv = (a, b) => (a + b - 1n) / b;
|
|
2898
|
+
/** `(a·b)/1e6` — exact or `invalid-input`; a product needing more decimals never rounds silently. */
|
|
2899
|
+
const mulUnits = (a, b) => {
|
|
2900
|
+
const product = a * b;
|
|
2901
|
+
if (product % SCALE !== 0n) throw new PolymarketError("invalid-input", "the order's amounts need more than 6 decimals to express");
|
|
2902
|
+
return product / SCALE;
|
|
2903
|
+
};
|
|
2904
|
+
const quoteFees = (market) => market?.fees === void 0 ? {} : { fees: market.fees };
|
|
2905
|
+
/**
|
|
2906
|
+
* The signed `[maker, taker]` amounts for a limit order — `size·price` exactly in 6-decimal units
|
|
2907
|
+
* (BUY pays notional/demands shares, SELL swapped); a product needing more than 6 decimals refuses.
|
|
2908
|
+
* Exported for the exactness test — the public path reaches it only through `quoteLimit`.
|
|
2909
|
+
*/
|
|
2910
|
+
const limitAmounts = (side, size, price) => {
|
|
2911
|
+
const notional = mulUnits(size, price);
|
|
2912
|
+
return side === "BUY" ? [notional, size] : [size, notional];
|
|
2913
|
+
};
|
|
2914
|
+
const minBig = (a, b) => a < b ? a : b;
|
|
2915
|
+
const maxBig = (a, b) => a > b ? a : b;
|
|
2916
|
+
/** `floor((a·b)/1e6)` for book-depth sums — an approximation is fine for coverage, never signed. */
|
|
2917
|
+
const mulFloor = (a, b) => a * b / SCALE;
|
|
2918
|
+
/** A limit quote — the book supplies tick and minimum; the price rounds in the user's favour. */
|
|
2919
|
+
const quoteLimit = (params, book, market) => {
|
|
2920
|
+
const tick = tickOf(book.tickSize);
|
|
2921
|
+
const aligned = params.side === "BUY" ? floorTo(toUnits(params.price, "price"), tick.grid) : ceilTo(toUnits(params.price, "price"), tick.grid);
|
|
2922
|
+
if (aligned < tick.grid || aligned > ONE - tick.grid) throw new PolymarketError("invalid-input", `price ${params.price} must stay within [${book.tickSize}, 1 − ${book.tickSize}]`);
|
|
2923
|
+
const size = floorTo(toUnits(params.size, "size"), SIZE_GRID);
|
|
2924
|
+
if (size <= 0n) throw new PolymarketError("invalid-input", "size rounds to zero");
|
|
2925
|
+
if (size < toUnits(book.minOrderSize, "minimum order size")) throw new PolymarketError("invalid-input", `size ${params.size} is below the market minimum ${book.minOrderSize}`);
|
|
2926
|
+
const [maker, taker] = limitAmounts(params.side, size, aligned);
|
|
2927
|
+
const notional = params.side === "BUY" ? maker : taker;
|
|
2928
|
+
return {
|
|
2929
|
+
kind: "limit",
|
|
2930
|
+
assetId: params.assetId,
|
|
2931
|
+
side: params.side,
|
|
2932
|
+
price: fromUnits(aligned),
|
|
2933
|
+
size: fromUnits(size),
|
|
2934
|
+
bound: fromUnits(aligned),
|
|
2935
|
+
makerAmount: maker.toString(10),
|
|
2936
|
+
takerAmount: taker.toString(10),
|
|
2937
|
+
impliedPrice: fromUnits(aligned),
|
|
2938
|
+
notional: fromUnits(notional),
|
|
2939
|
+
minOrderSize: book.minOrderSize,
|
|
2940
|
+
...quoteFees(market)
|
|
2941
|
+
};
|
|
2942
|
+
};
|
|
2943
|
+
/**
|
|
2944
|
+
* A market quote — walks the book's asks (BUY, notional accumulation) or bids (SELL, share
|
|
2945
|
+
* accumulation) to the last level the amount touches, then applies the slippage bound: BUY
|
|
2946
|
+
* `ceilToTick(w·(1+s))` capped at `1−tick`, SELL `floorToTick(w·(1−s))` floored at `tick`. The
|
|
2947
|
+
* bound-side amount is `ceil` — a BUY demands at least `amount/P` shares and a SELL at least
|
|
2948
|
+
* `shares·P` pUSD, so the implied price can never be worse than `P`. (clob-client-v2 floors both —
|
|
2949
|
+
* a strictly better bound for us, inside one unit of the last amount decimal.)
|
|
2950
|
+
*/
|
|
2951
|
+
const quoteMarket = (params, book, market) => {
|
|
2952
|
+
if (!Number.isInteger(params.slippageBps) || params.slippageBps < 0 || params.slippageBps > MAX_SLIPPAGE_BPS) throw new PolymarketError("invalid-input", "slippageBps must be an integer in 0..5000");
|
|
2953
|
+
const tick = tickOf(book.tickSize);
|
|
2954
|
+
const amount = floorTo(toUnits(params.amount, "amount"), SIZE_GRID);
|
|
2955
|
+
if (amount <= 0n) throw new PolymarketError("invalid-input", "amount rounds to zero");
|
|
2956
|
+
const minSize = toUnits(book.minOrderSize, "minimum order size");
|
|
2957
|
+
const buy = params.side === "BUY";
|
|
2958
|
+
const levels = buy ? book.asks : book.bids;
|
|
2959
|
+
let worst = 0n;
|
|
2960
|
+
let fillable = 0n;
|
|
2961
|
+
let covered = false;
|
|
2962
|
+
for (const level of levels) {
|
|
2963
|
+
const price = toUnits(level.price, "book price");
|
|
2964
|
+
const size = toUnits(level.size, "book size");
|
|
2965
|
+
worst = price;
|
|
2966
|
+
fillable += buy ? mulFloor(size, price) : size;
|
|
2967
|
+
if (fillable >= amount) {
|
|
2968
|
+
covered = true;
|
|
2969
|
+
break;
|
|
2970
|
+
}
|
|
2971
|
+
}
|
|
2972
|
+
if (!covered && params.orderType === "FOK") throw new PolymarketError("invalid-input", "insufficient liquidity for a fill-or-kill order");
|
|
2973
|
+
if (worst === 0n) throw new PolymarketError("invalid-input", "the book has no liquidity on this side");
|
|
2974
|
+
const carried = covered ? amount : floorTo(fillable, SIZE_GRID);
|
|
2975
|
+
if (carried <= 0n) throw new PolymarketError("invalid-input", "insufficient liquidity");
|
|
2976
|
+
const bound = buy ? minBig(ceilTo(ceilDiv(worst * (10000n + BigInt(params.slippageBps)), 10000n), tick.grid), ONE - tick.grid) : maxBig(floorTo(worst * (10000n - BigInt(params.slippageBps)) / 10000n, tick.grid), tick.grid);
|
|
2977
|
+
if (bound <= 0n || bound >= ONE) throw new PolymarketError("invalid-input", "the slippage bound leaves no valid price");
|
|
2978
|
+
const amountGrid = 10n ** BigInt(6 - tick.amount);
|
|
2979
|
+
const [maker, taker] = buy ? [carried, ceilDiv(carried * 10n ** BigInt(tick.amount), bound) * amountGrid] : [carried, ceilDiv(carried * bound * 10n ** BigInt(tick.amount), SCALE * SCALE) * amountGrid];
|
|
2980
|
+
if ((buy ? taker : maker) < minSize) throw new PolymarketError("invalid-input", `the order is below the market minimum ${book.minOrderSize} shares`);
|
|
2981
|
+
const notional = buy ? maker : taker;
|
|
2982
|
+
const impliedUnits = buy ? maker * SCALE / taker : taker * SCALE / maker;
|
|
2983
|
+
return {
|
|
2984
|
+
kind: "market",
|
|
2985
|
+
assetId: params.assetId,
|
|
2986
|
+
side: params.side,
|
|
2987
|
+
amount: fromUnits(carried),
|
|
2988
|
+
bound: fromUnits(bound),
|
|
2989
|
+
makerAmount: maker.toString(10),
|
|
2990
|
+
takerAmount: taker.toString(10),
|
|
2991
|
+
impliedPrice: fromUnits(impliedUnits),
|
|
2992
|
+
notional: fromUnits(notional),
|
|
2993
|
+
minOrderSize: book.minOrderSize,
|
|
2994
|
+
...covered ? {} : { partial: true },
|
|
2995
|
+
...quoteFees(market)
|
|
2996
|
+
};
|
|
2997
|
+
};
|
|
2998
|
+
const exchangeDomain = (book) => book.version === "v2" ? {
|
|
2999
|
+
verifyingContract: CTF_EXCHANGE_V3,
|
|
3000
|
+
version: "3"
|
|
3001
|
+
} : book.negRisk ? {
|
|
3002
|
+
verifyingContract: NEG_RISK_EXCHANGE_V2,
|
|
3003
|
+
version: "2"
|
|
3004
|
+
} : {
|
|
3005
|
+
verifyingContract: CTF_EXCHANGE_V2,
|
|
3006
|
+
version: "2"
|
|
3007
|
+
};
|
|
3008
|
+
const ZERO_BYTES32 = `0x${"0".repeat(64)}`;
|
|
3009
|
+
const buildPolymarketOrder = (input) => Object.freeze({
|
|
3010
|
+
salt: input.salt,
|
|
3011
|
+
maker: input.wallet,
|
|
3012
|
+
signer: input.wallet,
|
|
3013
|
+
tokenId: input.assetId,
|
|
3014
|
+
makerAmount: input.makerAmount,
|
|
3015
|
+
takerAmount: input.takerAmount,
|
|
3016
|
+
side: input.side === "BUY" ? 0 : 1,
|
|
3017
|
+
signatureType: 3,
|
|
3018
|
+
timestamp: Math.floor(input.timestampMs).toString(10),
|
|
3019
|
+
metadata: ZERO_BYTES32,
|
|
3020
|
+
builder: input.builderCode ?? ZERO_BYTES32,
|
|
3021
|
+
expiration: input.expiration ?? "0"
|
|
3022
|
+
});
|
|
3023
|
+
/** `Order`'s EIP-712 field list — ctf-exchange-v2 `Structs.sol` ORDER_TYPEHASH, verbatim order. */
|
|
3024
|
+
const ORDER_FIELDS = [
|
|
3025
|
+
{
|
|
3026
|
+
name: "salt",
|
|
3027
|
+
type: "uint256"
|
|
3028
|
+
},
|
|
3029
|
+
{
|
|
3030
|
+
name: "maker",
|
|
3031
|
+
type: "address"
|
|
3032
|
+
},
|
|
3033
|
+
{
|
|
3034
|
+
name: "signer",
|
|
3035
|
+
type: "address"
|
|
3036
|
+
},
|
|
3037
|
+
{
|
|
3038
|
+
name: "tokenId",
|
|
3039
|
+
type: "uint256"
|
|
3040
|
+
},
|
|
3041
|
+
{
|
|
3042
|
+
name: "makerAmount",
|
|
3043
|
+
type: "uint256"
|
|
3044
|
+
},
|
|
3045
|
+
{
|
|
3046
|
+
name: "takerAmount",
|
|
3047
|
+
type: "uint256"
|
|
3048
|
+
},
|
|
3049
|
+
{
|
|
3050
|
+
name: "side",
|
|
3051
|
+
type: "uint8"
|
|
3052
|
+
},
|
|
3053
|
+
{
|
|
3054
|
+
name: "signatureType",
|
|
3055
|
+
type: "uint8"
|
|
3056
|
+
},
|
|
3057
|
+
{
|
|
3058
|
+
name: "timestamp",
|
|
3059
|
+
type: "uint256"
|
|
3060
|
+
},
|
|
3061
|
+
{
|
|
3062
|
+
name: "metadata",
|
|
3063
|
+
type: "bytes32"
|
|
3064
|
+
},
|
|
3065
|
+
{
|
|
3066
|
+
name: "builder",
|
|
3067
|
+
type: "bytes32"
|
|
3068
|
+
}
|
|
3069
|
+
];
|
|
3070
|
+
const EIP712_DOMAIN_FIELDS = [
|
|
3071
|
+
{
|
|
3072
|
+
name: "name",
|
|
3073
|
+
type: "string"
|
|
3074
|
+
},
|
|
3075
|
+
{
|
|
3076
|
+
name: "version",
|
|
3077
|
+
type: "string"
|
|
3078
|
+
},
|
|
3079
|
+
{
|
|
3080
|
+
name: "chainId",
|
|
3081
|
+
type: "uint256"
|
|
3082
|
+
},
|
|
3083
|
+
{
|
|
3084
|
+
name: "verifyingContract",
|
|
3085
|
+
type: "address"
|
|
3086
|
+
}
|
|
3087
|
+
];
|
|
3088
|
+
/** `TypedDataSign` — the ERC-7739 envelope a deposit wallet's owner signs (phase-1 vectors). */
|
|
3089
|
+
const TYPED_DATA_SIGN_FIELDS = [
|
|
3090
|
+
{
|
|
3091
|
+
name: "contents",
|
|
3092
|
+
type: "Order"
|
|
3093
|
+
},
|
|
3094
|
+
{
|
|
3095
|
+
name: "name",
|
|
3096
|
+
type: "string"
|
|
3097
|
+
},
|
|
3098
|
+
{
|
|
3099
|
+
name: "version",
|
|
3100
|
+
type: "string"
|
|
3101
|
+
},
|
|
3102
|
+
{
|
|
3103
|
+
name: "chainId",
|
|
3104
|
+
type: "uint256"
|
|
3105
|
+
},
|
|
3106
|
+
{
|
|
3107
|
+
name: "verifyingContract",
|
|
3108
|
+
type: "address"
|
|
3109
|
+
},
|
|
3110
|
+
{
|
|
3111
|
+
name: "salt",
|
|
3112
|
+
type: "bytes32"
|
|
3113
|
+
}
|
|
3114
|
+
];
|
|
3115
|
+
const orderMessage = (draft) => ({
|
|
3116
|
+
salt: draft.salt,
|
|
3117
|
+
maker: draft.maker,
|
|
3118
|
+
signer: draft.signer,
|
|
3119
|
+
tokenId: draft.tokenId,
|
|
3120
|
+
makerAmount: draft.makerAmount,
|
|
3121
|
+
takerAmount: draft.takerAmount,
|
|
3122
|
+
side: draft.side,
|
|
3123
|
+
signatureType: draft.signatureType,
|
|
3124
|
+
timestamp: draft.timestamp,
|
|
3125
|
+
metadata: draft.metadata,
|
|
3126
|
+
builder: draft.builder
|
|
3127
|
+
});
|
|
3128
|
+
const domainOf = (domain) => ({
|
|
3129
|
+
name: CTF_EXCHANGE_NAME,
|
|
3130
|
+
version: domain.version,
|
|
3131
|
+
chainId: 137,
|
|
3132
|
+
verifyingContract: domain.verifyingContract
|
|
3133
|
+
});
|
|
3134
|
+
/** The `TypedDataSign` document the kernel signs — the phase-1 vector shape, `EIP712Domain` present. */
|
|
3135
|
+
const typedDataSignDocument = (draft, domain) => JSON.stringify({
|
|
3136
|
+
types: {
|
|
3137
|
+
EIP712Domain: EIP712_DOMAIN_FIELDS,
|
|
3138
|
+
TypedDataSign: TYPED_DATA_SIGN_FIELDS,
|
|
3139
|
+
Order: ORDER_FIELDS
|
|
3140
|
+
},
|
|
3141
|
+
primaryType: "TypedDataSign",
|
|
3142
|
+
domain: domainOf(domain),
|
|
3143
|
+
message: {
|
|
3144
|
+
contents: orderMessage(draft),
|
|
3145
|
+
name: "DepositWallet",
|
|
3146
|
+
version: "1",
|
|
3147
|
+
chainId: 137,
|
|
3148
|
+
verifyingContract: draft.signer,
|
|
3149
|
+
salt: ZERO_BYTES32
|
|
3150
|
+
}
|
|
3151
|
+
});
|
|
3152
|
+
/**
|
|
3153
|
+
* The order id — the EIP-712 hash of `Order` under the exchange domain (clob-client-v2
|
|
3154
|
+
* `buildOrderHash`; apiref get-order-by-id: "the order hash").
|
|
3155
|
+
*/
|
|
3156
|
+
const polymarketOrderId = (draft, domain) => hashTypedData({
|
|
3157
|
+
domain: domainOf(domain),
|
|
3158
|
+
types: { Order: ORDER_FIELDS },
|
|
3159
|
+
primaryType: "Order",
|
|
3160
|
+
message: {
|
|
3161
|
+
salt: BigInt(draft.salt),
|
|
3162
|
+
maker: getAddress(draft.maker),
|
|
3163
|
+
signer: getAddress(draft.signer),
|
|
3164
|
+
tokenId: BigInt(draft.tokenId),
|
|
3165
|
+
makerAmount: BigInt(draft.makerAmount),
|
|
3166
|
+
takerAmount: BigInt(draft.takerAmount),
|
|
3167
|
+
side: draft.side,
|
|
3168
|
+
signatureType: draft.signatureType,
|
|
3169
|
+
timestamp: BigInt(draft.timestamp),
|
|
3170
|
+
metadata: draft.metadata,
|
|
3171
|
+
builder: draft.builder
|
|
3172
|
+
}
|
|
3173
|
+
});
|
|
3174
|
+
const ORDER_TYPE_STRING = "Order(uint256 salt,address maker,address signer,uint256 tokenId,uint256 makerAmount,uint256 takerAmount,uint8 side,uint8 signatureType,uint256 timestamp,bytes32 metadata,bytes32 builder)";
|
|
3175
|
+
const ORDER_TYPE_HASH = keccak256(toHex(ORDER_TYPE_STRING));
|
|
3176
|
+
const DOMAIN_TYPE_HASH = keccak256(toHex("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"));
|
|
3177
|
+
const ORDER_TYPE_HEX = toHex(ORDER_TYPE_STRING);
|
|
3178
|
+
/** The type string's byte length as uint16BE — 0x00ba for the Order type. */
|
|
3179
|
+
const ORDER_TYPE_LENGTH = numberToHex(186, { size: 2 });
|
|
3180
|
+
const appDomainSeparator = (domain) => keccak256(encodeAbiParameters([
|
|
3181
|
+
{ type: "bytes32" },
|
|
3182
|
+
{ type: "bytes32" },
|
|
3183
|
+
{ type: "bytes32" },
|
|
3184
|
+
{ type: "uint256" },
|
|
3185
|
+
{ type: "address" }
|
|
3186
|
+
], [
|
|
3187
|
+
DOMAIN_TYPE_HASH,
|
|
3188
|
+
keccak256(toHex(CTF_EXCHANGE_NAME)),
|
|
3189
|
+
keccak256(toHex(domain.version)),
|
|
3190
|
+
BigInt(137),
|
|
3191
|
+
domain.verifyingContract
|
|
3192
|
+
]));
|
|
3193
|
+
const contentsHash = (draft) => keccak256(encodeAbiParameters([
|
|
3194
|
+
{ type: "bytes32" },
|
|
3195
|
+
{ type: "uint256" },
|
|
3196
|
+
{ type: "address" },
|
|
3197
|
+
{ type: "address" },
|
|
3198
|
+
{ type: "uint256" },
|
|
3199
|
+
{ type: "uint256" },
|
|
3200
|
+
{ type: "uint256" },
|
|
3201
|
+
{ type: "uint8" },
|
|
3202
|
+
{ type: "uint8" },
|
|
3203
|
+
{ type: "uint256" },
|
|
3204
|
+
{ type: "bytes32" },
|
|
3205
|
+
{ type: "bytes32" }
|
|
3206
|
+
], [
|
|
3207
|
+
ORDER_TYPE_HASH,
|
|
3208
|
+
BigInt(draft.salt),
|
|
3209
|
+
draft.maker,
|
|
3210
|
+
draft.signer,
|
|
3211
|
+
BigInt(draft.tokenId),
|
|
3212
|
+
BigInt(draft.makerAmount),
|
|
3213
|
+
BigInt(draft.takerAmount),
|
|
3214
|
+
draft.side,
|
|
3215
|
+
draft.signatureType,
|
|
3216
|
+
BigInt(draft.timestamp),
|
|
3217
|
+
draft.metadata,
|
|
3218
|
+
draft.builder
|
|
3219
|
+
]));
|
|
3220
|
+
/**
|
|
3221
|
+
* The wire signature: the owner's 65-byte `TypedDataSign` signature, then the 7739 trailer —
|
|
3222
|
+
* `appDomainSeparator ‖ contentsHash ‖ ORDER_TYPE utf-8 ‖ uint16BE(len)` — so the deposit wallet's
|
|
3223
|
+
* ERC-1271 `isValidSignature` can re-derive what the owner signed (docs §Create the Order Typed
|
|
3224
|
+
* Data; exchangeOrderBuilderV2.ts).
|
|
3225
|
+
*/
|
|
3226
|
+
const wireSignature = (inner, draft, domain) => concat([
|
|
3227
|
+
toHex(inner),
|
|
3228
|
+
appDomainSeparator(domain),
|
|
3229
|
+
contentsHash(draft),
|
|
3230
|
+
ORDER_TYPE_HEX,
|
|
3231
|
+
ORDER_TYPE_LENGTH
|
|
3232
|
+
]);
|
|
3233
|
+
/**
|
|
3234
|
+
* The exact `POST /order` body — serialized once, never reserialized after signing. Field set
|
|
3235
|
+
* matches clob-client-v2 `orderToJsonV2` (`taker` absent on V2 orders; `postOnly` always present so
|
|
3236
|
+
* the body parses equal to the oracle's output).
|
|
3237
|
+
*/
|
|
3238
|
+
const orderBody = (draft, signature, owner, orderType, postOnly) => JSON.stringify({
|
|
3239
|
+
deferExec: false,
|
|
3240
|
+
order: {
|
|
3241
|
+
builder: draft.builder,
|
|
3242
|
+
expiration: draft.expiration,
|
|
3243
|
+
maker: draft.maker,
|
|
3244
|
+
makerAmount: draft.makerAmount,
|
|
3245
|
+
metadata: draft.metadata,
|
|
3246
|
+
salt: Number(draft.salt),
|
|
3247
|
+
side: draft.side === 0 ? "BUY" : "SELL",
|
|
3248
|
+
signature,
|
|
3249
|
+
signatureType: draft.signatureType,
|
|
3250
|
+
signer: draft.signer,
|
|
3251
|
+
takerAmount: draft.takerAmount,
|
|
3252
|
+
timestamp: draft.timestamp,
|
|
3253
|
+
tokenId: draft.tokenId
|
|
3254
|
+
},
|
|
3255
|
+
orderType,
|
|
3256
|
+
owner,
|
|
3257
|
+
postOnly
|
|
3258
|
+
});
|
|
3259
|
+
// src/apps/polymarket/trade.ts
|
|
3260
|
+
const ORDER_ID = /^0x[0-9a-fA-F]{64}$/;
|
|
3261
|
+
const GTD_MIN_SECONDS = 180;
|
|
3262
|
+
const CANCEL_MANY_LIMIT = 500;
|
|
3263
|
+
const SALT_MOD = 2n ** 53n;
|
|
3264
|
+
/** Reconcile reads after an unknown POST answer — offsets from the answer. */
|
|
3265
|
+
const RECONCILE_MS = [
|
|
3266
|
+
0,
|
|
3267
|
+
2e3,
|
|
3268
|
+
5e3
|
|
3269
|
+
];
|
|
3270
|
+
const RECONCILE_LATE_POLL_MS = 1e4;
|
|
3271
|
+
const RECONCILE_LATE_WINDOW_MS = 6e5;
|
|
3272
|
+
const MAX_UNRESOLVED = 64;
|
|
3273
|
+
const NETWORK = "eip155:137";
|
|
3274
|
+
const reconcileStatus = (orderId, status, row) => {
|
|
3275
|
+
switch (status) {
|
|
3276
|
+
case "LIVE": return {
|
|
3277
|
+
kind: "resting",
|
|
3278
|
+
orderId
|
|
3279
|
+
};
|
|
3280
|
+
case "MATCHED": return {
|
|
3281
|
+
kind: "matched",
|
|
3282
|
+
orderId,
|
|
3283
|
+
making: row.sizeMatched
|
|
3284
|
+
};
|
|
3285
|
+
case "CANCELED": return {
|
|
3286
|
+
kind: "canceled",
|
|
3287
|
+
orderId,
|
|
3288
|
+
making: row.sizeMatched
|
|
3289
|
+
};
|
|
3290
|
+
case "DELAYED": return {
|
|
3291
|
+
kind: "delayed",
|
|
3292
|
+
orderId
|
|
3293
|
+
};
|
|
3294
|
+
case "UNMATCHED": return {
|
|
3295
|
+
kind: "unmatched",
|
|
3296
|
+
orderId
|
|
3297
|
+
};
|
|
3298
|
+
default: return {
|
|
3299
|
+
kind: "unknown",
|
|
3300
|
+
orderId
|
|
3301
|
+
};
|
|
3302
|
+
}
|
|
3303
|
+
};
|
|
3304
|
+
const accountRef = (group) => ({
|
|
3305
|
+
kind: "hd",
|
|
3306
|
+
walletId: group.walletId,
|
|
3307
|
+
groupIndex: group.groupIndex,
|
|
3308
|
+
template: "evm.bip44"
|
|
3309
|
+
});
|
|
3310
|
+
const pendingKey = (group, orderId) => `${group.walletId}|${group.groupIndex}|${orderId}`;
|
|
3311
|
+
/** A 53-bit salt — `Number(draft.salt)` must serialize exactly (salt rides the wire as a number). */
|
|
3312
|
+
const saltOf = (random) => {
|
|
3313
|
+
let salt = 0n;
|
|
3314
|
+
for (const byte of random(8)) salt = salt * 256n + BigInt(byte);
|
|
3315
|
+
return (salt % SALT_MOD).toString(10);
|
|
3316
|
+
};
|
|
3317
|
+
/** The errorMsg/error text → the refusal class (docs resources/error-codes.md). */
|
|
3318
|
+
const classify = (message, status) => {
|
|
3319
|
+
const m = (message ?? "").toLowerCase();
|
|
3320
|
+
if (status === 429 || m.includes("too many requests") || m.includes("rate limit")) return "rate-limited";
|
|
3321
|
+
if (m.includes("signature") || m.includes("signer address")) return "invalid-signature";
|
|
3322
|
+
if (m.includes("balance") || m.includes("allowance")) return "balance-or-allowance";
|
|
3323
|
+
if (m.includes("tick")) return "tick";
|
|
3324
|
+
if (m.includes("minimum") || m.includes("min size")) return "min-size";
|
|
3325
|
+
if (m.includes("closed only")) return "close-only";
|
|
3326
|
+
if (m.includes("post-only") || m.includes("crosses book") || m.includes("crosses the book")) return "post-only-cross";
|
|
3327
|
+
if (m.includes("fok") || m.includes("fully filled") || m.includes("filled or killed")) return "fok-unfilled";
|
|
3328
|
+
if (m.includes("not yet ready") || m.includes("not accepting") || m.includes("market is closed") || m.includes("cancel-only") || m.includes("trading is currently")) return "market-closed";
|
|
3329
|
+
return "other";
|
|
3330
|
+
};
|
|
3331
|
+
/** The message a non-2xx body carries — `{error}` or `{errorMsg}` strings only. */
|
|
3332
|
+
const bodyMessage = (body) => {
|
|
3333
|
+
const error = body["error"] ?? body["errorMsg"];
|
|
3334
|
+
return typeof error === "string" ? error.slice(0, 500) : void 0;
|
|
3335
|
+
};
|
|
3336
|
+
function createPolymarketTrade(options) {
|
|
3337
|
+
const wait = async (ms) => new Promise((resolve) => {
|
|
3338
|
+
options.setTimer(ms, resolve);
|
|
3339
|
+
});
|
|
3340
|
+
/** BUY refuses closed: unverified eligibility or a failed close-only read is a refusal. */
|
|
3341
|
+
const assertOpenable = async (group) => {
|
|
3342
|
+
const availability = options.availability();
|
|
3343
|
+
if (availability !== "available") throw new PolymarketError("close-only", availability === "close-only" ? "Polymarket is close-only in this jurisdiction" : "Polymarket availability is unverified — refusing to open a position");
|
|
3344
|
+
let closed;
|
|
3345
|
+
try {
|
|
3346
|
+
closed = await options.account.closedOnly(group);
|
|
3347
|
+
} catch (error) {
|
|
3348
|
+
throw new PolymarketError("close-only", "the account's close-only status could not be read — refusing to open a position", { cause: error });
|
|
3349
|
+
}
|
|
3350
|
+
if (closed) throw new PolymarketError("close-only", "the account is in close-only mode");
|
|
3351
|
+
};
|
|
3352
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
3353
|
+
const emit = (correction) => {
|
|
3354
|
+
for (const listener of listeners) listener(correction);
|
|
3355
|
+
};
|
|
3356
|
+
const pending = /* @__PURE__ */ new Map();
|
|
3357
|
+
let pollCancel;
|
|
3358
|
+
let lockWatch;
|
|
3359
|
+
let session = 0;
|
|
3360
|
+
const watchLock = () => {
|
|
3361
|
+
lockWatch ??= options.wallet.subscribe(() => {
|
|
3362
|
+
if (options.wallet.getSnapshot().vault !== "unlocked") {
|
|
3363
|
+
session += 1;
|
|
3364
|
+
pending.clear();
|
|
3365
|
+
pollCancel?.();
|
|
3366
|
+
pollCancel = void 0;
|
|
3367
|
+
}
|
|
3368
|
+
});
|
|
3369
|
+
};
|
|
3370
|
+
/** One `order` read for a pending id — a found row corrects and drops it. */
|
|
3371
|
+
const probe = async (entry) => {
|
|
3372
|
+
let outcome;
|
|
3373
|
+
try {
|
|
3374
|
+
const found = await options.account.order(entry.group, entry.orderId);
|
|
3375
|
+
if (found === void 0) return;
|
|
3376
|
+
outcome = reconcileStatus(entry.orderId, found.status, found);
|
|
3377
|
+
} catch {
|
|
3378
|
+
return;
|
|
3379
|
+
}
|
|
3380
|
+
if (outcome.kind === "unknown") return;
|
|
3381
|
+
const key = pendingKey(entry.group, entry.orderId);
|
|
3382
|
+
if (pending.get(key) === entry) {
|
|
3383
|
+
pending.delete(key);
|
|
3384
|
+
emit({
|
|
3385
|
+
group: entry.group,
|
|
3386
|
+
orderId: entry.orderId,
|
|
3387
|
+
outcome
|
|
3388
|
+
});
|
|
3389
|
+
}
|
|
3390
|
+
};
|
|
3391
|
+
const schedulePoll = () => {
|
|
3392
|
+
if (pollCancel === void 0 && pending.size > 0) pollCancel = options.setTimer(RECONCILE_LATE_POLL_MS, () => {
|
|
3393
|
+
pollCancel = void 0;
|
|
3394
|
+
(async () => {
|
|
3395
|
+
for (const entry of pending.values()) if (options.now() - entry.since >= RECONCILE_LATE_WINDOW_MS) pending.delete(pendingKey(entry.group, entry.orderId));
|
|
3396
|
+
else await probe(entry);
|
|
3397
|
+
schedulePoll();
|
|
3398
|
+
})();
|
|
3399
|
+
});
|
|
3400
|
+
};
|
|
3401
|
+
const registerPending = (group, orderId, signedIn) => {
|
|
3402
|
+
if (signedIn !== session || options.wallet.getSnapshot().vault !== "unlocked") return;
|
|
3403
|
+
const key = pendingKey(group, orderId);
|
|
3404
|
+
if (!pending.has(key) && pending.size >= MAX_UNRESOLVED) {
|
|
3405
|
+
const [oldest] = pending.keys();
|
|
3406
|
+
if (oldest !== void 0) pending.delete(oldest);
|
|
3407
|
+
}
|
|
3408
|
+
pending.set(key, {
|
|
3409
|
+
group,
|
|
3410
|
+
orderId,
|
|
3411
|
+
since: options.now()
|
|
3412
|
+
});
|
|
3413
|
+
schedulePoll();
|
|
3414
|
+
};
|
|
3415
|
+
/**
|
|
3416
|
+
* The best-effort `DELETE /order` for an order no read ever saw — same authenticated request the
|
|
3417
|
+
* explicit `cancel` sends. Never throws: the attempt's fate rides the `unknown` outcome.
|
|
3418
|
+
*/
|
|
3419
|
+
const cancelAttempt = async (group, orderId) => {
|
|
3420
|
+
try {
|
|
3421
|
+
const answer = await options.l2.request(group, {
|
|
3422
|
+
method: "DELETE",
|
|
3423
|
+
path: "/order",
|
|
3424
|
+
body: JSON.stringify({ orderID: orderId })
|
|
3425
|
+
}, clobCancelResponse);
|
|
3426
|
+
if ((answer.canceled ?? []).includes(orderId)) return { kind: "canceled" };
|
|
3427
|
+
return {
|
|
3428
|
+
kind: "not-canceled",
|
|
3429
|
+
reason: (answer.not_canceled ?? {})[orderId] ?? "the cancel answer lists the order in neither canceled nor not_canceled"
|
|
3430
|
+
};
|
|
3431
|
+
} catch (error) {
|
|
3432
|
+
return {
|
|
3433
|
+
kind: "failed",
|
|
3434
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3435
|
+
};
|
|
3436
|
+
}
|
|
3437
|
+
};
|
|
3438
|
+
/**
|
|
3439
|
+
* Ask the CLOB for the order at 0/+2 s/+5 s — never re-post: a V2 order signs no expiry, so a
|
|
3440
|
+
* lost order could still be submitted by whoever holds the signed body. An order no read saw is
|
|
3441
|
+
* NOT proven absent, so the answer is `unknown` after a best-effort cancel attempt; every
|
|
3442
|
+
* `unknown` registers for the late reconcile.
|
|
3443
|
+
*/
|
|
3444
|
+
const reconcile = async (group, orderId, signedIn) => {
|
|
3445
|
+
let waited = 0;
|
|
3446
|
+
for (const at of RECONCILE_MS) {
|
|
3447
|
+
if (at > waited) {
|
|
3448
|
+
await wait(at - waited);
|
|
3449
|
+
waited = at;
|
|
3450
|
+
}
|
|
3451
|
+
try {
|
|
3452
|
+
const found = await options.account.order(group, orderId);
|
|
3453
|
+
if (found !== void 0) {
|
|
3454
|
+
const outcome = reconcileStatus(orderId, found.status, found);
|
|
3455
|
+
if (outcome.kind === "unknown") registerPending(group, orderId, signedIn);
|
|
3456
|
+
return outcome;
|
|
3457
|
+
}
|
|
3458
|
+
} catch {}
|
|
3459
|
+
}
|
|
3460
|
+
const cancel = await cancelAttempt(group, orderId);
|
|
3461
|
+
registerPending(group, orderId, signedIn);
|
|
3462
|
+
return {
|
|
3463
|
+
kind: "unknown",
|
|
3464
|
+
orderId,
|
|
3465
|
+
cancel
|
|
3466
|
+
};
|
|
3467
|
+
};
|
|
3468
|
+
const settleAnswer = async (answer, group, orderId, signedIn) => {
|
|
3469
|
+
if (!answer.success) return {
|
|
3470
|
+
kind: "rejected",
|
|
3471
|
+
reason: classify(answer.errorMsg ?? void 0),
|
|
3472
|
+
message: answer.errorMsg ?? "the CLOB rejected the order"
|
|
3473
|
+
};
|
|
3474
|
+
if (answer.orderID !== orderId) return reconcile(group, orderId, signedIn);
|
|
3475
|
+
switch (answer.status) {
|
|
3476
|
+
case "live": return {
|
|
3477
|
+
kind: "resting",
|
|
3478
|
+
orderId
|
|
3479
|
+
};
|
|
3480
|
+
case "matched": return {
|
|
3481
|
+
kind: "matched",
|
|
3482
|
+
orderId,
|
|
3483
|
+
...answer.makingAmount === void 0 || answer.makingAmount === null ? {} : { making: answer.makingAmount },
|
|
3484
|
+
...answer.takingAmount === void 0 || answer.takingAmount === null ? {} : { taking: answer.takingAmount },
|
|
3485
|
+
...answer.tradeIDs === void 0 || answer.tradeIDs === null ? {} : { tradeIds: answer.tradeIDs }
|
|
3486
|
+
};
|
|
3487
|
+
case "delayed": return {
|
|
3488
|
+
kind: "delayed",
|
|
3489
|
+
orderId
|
|
3490
|
+
};
|
|
3491
|
+
case "unmatched": return {
|
|
3492
|
+
kind: "unmatched",
|
|
3493
|
+
orderId
|
|
3494
|
+
};
|
|
3495
|
+
default: return reconcile(group, orderId, signedIn);
|
|
3496
|
+
}
|
|
3497
|
+
};
|
|
3498
|
+
const settleError = async (error, group, orderId, signedIn) => {
|
|
3499
|
+
if (error instanceof PolymarketError) {
|
|
3500
|
+
if (error.category === "unavailable" && error.status !== void 0 && error.status >= 400 && error.status < 500 && error.body !== void 0) {
|
|
3501
|
+
const message = bodyMessage(error.body);
|
|
3502
|
+
return {
|
|
3503
|
+
kind: "rejected",
|
|
3504
|
+
reason: classify(message, error.status),
|
|
3505
|
+
message: message ?? `the CLOB answered ${error.status}`
|
|
3506
|
+
};
|
|
3507
|
+
}
|
|
3508
|
+
if (error.category === "network" || error.category === "timeout" || error.category === "unavailable" || error.category === "malformed") return reconcile(group, orderId, signedIn);
|
|
3509
|
+
}
|
|
3510
|
+
throw error;
|
|
3511
|
+
};
|
|
3512
|
+
const runOutcome = async (group, requestId, draft, domain, orderId, params, apiKey, signedIn) => {
|
|
3513
|
+
let inner;
|
|
3514
|
+
try {
|
|
3515
|
+
const result = await options.requests.outcome(requestId);
|
|
3516
|
+
if (!("kind" in result) || result.kind !== "evm.typed-data" || result.signature.length !== 65) throw new PolymarketError("unavailable", "the request resolved without a typed-data signature");
|
|
3517
|
+
inner = result.signature;
|
|
3518
|
+
} catch (error) {
|
|
3519
|
+
if (error instanceof RequestEndedError) throw new PolymarketError("approval-rejected", `the request was ${error.stage}`, { cause: error });
|
|
3520
|
+
throw error;
|
|
3521
|
+
}
|
|
3522
|
+
const signature = wireSignature(inner, draft, domain);
|
|
3523
|
+
const body = orderBody(draft, signature, apiKey, params.orderType, params.kind === "limit" && params.postOnly === true);
|
|
3524
|
+
try {
|
|
3525
|
+
const answer = await options.l2.request(group, {
|
|
3526
|
+
method: "POST",
|
|
3527
|
+
path: "/order",
|
|
3528
|
+
body
|
|
3529
|
+
}, clobPostOrderResponse);
|
|
3530
|
+
return await settleAnswer(answer, group, orderId, signedIn);
|
|
3531
|
+
} catch (error) {
|
|
3532
|
+
return settleError(error, group, orderId, signedIn);
|
|
3533
|
+
}
|
|
3534
|
+
};
|
|
3535
|
+
const validatePlace = (params) => {
|
|
3536
|
+
if (params.kind === "limit") {
|
|
3537
|
+
if (params.orderType !== "GTC" && params.orderType !== "GTD") throw new PolymarketError("invalid-input", "limit orders are GTC or GTD");
|
|
3538
|
+
if (params.orderType === "GTC" && params.expiration !== void 0) throw new PolymarketError("invalid-input", "expiration applies to GTD orders only");
|
|
3539
|
+
if (params.orderType === "GTD") {
|
|
3540
|
+
if (params.expiration === void 0) throw new PolymarketError("invalid-input", "GTD orders need an expiration");
|
|
3541
|
+
if (!Number.isInteger(params.expiration) || params.expiration < Math.floor(options.now() / 1e3) + GTD_MIN_SECONDS) throw new PolymarketError("invalid-input", "GTD expiration must be a unix time at least 3 minutes out");
|
|
3542
|
+
}
|
|
3543
|
+
} else if ("postOnly" in params || "expiration" in params) throw new PolymarketError("invalid-input", "postOnly/expiration apply to limit orders only");
|
|
3544
|
+
};
|
|
3545
|
+
return {
|
|
3546
|
+
quote: async (group, params) => {
|
|
3547
|
+
validatePlace(params);
|
|
3548
|
+
if (params.side === "BUY") await assertOpenable(group);
|
|
3549
|
+
const book = await options.markets.book(params.assetId);
|
|
3550
|
+
return params.kind === "limit" ? quoteLimit(params, book) : quoteMarket(params, book);
|
|
3551
|
+
},
|
|
3552
|
+
place: async (group, params) => {
|
|
3553
|
+
validatePlace(params);
|
|
3554
|
+
const creds = await options.l2.credentials(group);
|
|
3555
|
+
if (creds === void 0) throw new PolymarketError("not-enabled", "the group has no Polymarket credentials");
|
|
3556
|
+
const located = await options.account.locate(group);
|
|
3557
|
+
if (located.kind === "safe") throw new PolymarketError("needs-migration", "the account resolves to a legacy Safe — migrate to a deposit wallet to trade");
|
|
3558
|
+
if (!located.deployed) throw new PolymarketError("not-enabled", "the account wallet is not deployed yet");
|
|
3559
|
+
if (creds.owner.toLowerCase() !== located.signer.toLowerCase()) throw new PolymarketError("not-enabled", "the stored credentials belong to another signer — re-enable the account");
|
|
3560
|
+
if (params.side === "BUY") await assertOpenable(group);
|
|
3561
|
+
const book = await options.markets.book(params.assetId);
|
|
3562
|
+
const quote = params.kind === "limit" ? quoteLimit(params, book) : quoteMarket(params, book);
|
|
3563
|
+
const domain = exchangeDomain(book);
|
|
3564
|
+
const draft = buildPolymarketOrder({
|
|
3565
|
+
wallet: located.wallet,
|
|
3566
|
+
assetId: params.assetId,
|
|
3567
|
+
side: params.side,
|
|
3568
|
+
makerAmount: quote.makerAmount,
|
|
3569
|
+
takerAmount: quote.takerAmount,
|
|
3570
|
+
salt: saltOf(options.random),
|
|
3571
|
+
timestampMs: options.now(),
|
|
3572
|
+
...options.builder?.code === void 0 ? {} : { builderCode: options.builder.code },
|
|
3573
|
+
...params.kind === "limit" && params.orderType === "GTD" ? { expiration: String(params.expiration) } : {}
|
|
3574
|
+
});
|
|
3575
|
+
const orderId = polymarketOrderId(draft, domain);
|
|
3576
|
+
watchLock();
|
|
3577
|
+
const signedIn = session;
|
|
3578
|
+
const pending = await options.requests.prepare({
|
|
3579
|
+
method: "evm-sign",
|
|
3580
|
+
account: accountRef(group),
|
|
3581
|
+
network: NETWORK,
|
|
3582
|
+
request: {
|
|
3583
|
+
kind: "evm.typed-data",
|
|
3584
|
+
network: NETWORK,
|
|
3585
|
+
account: accountRef(group),
|
|
3586
|
+
typedData: typedDataSignDocument(draft, domain)
|
|
3587
|
+
}
|
|
3588
|
+
});
|
|
3589
|
+
const outcome = runOutcome(group, pending.id, draft, domain, orderId, params, creds.apiKey, signedIn);
|
|
3590
|
+
(async () => {
|
|
3591
|
+
try {
|
|
3592
|
+
await outcome;
|
|
3593
|
+
} catch {}
|
|
3594
|
+
})();
|
|
3595
|
+
return {
|
|
3596
|
+
requestId: pending.id,
|
|
3597
|
+
orderId,
|
|
3598
|
+
quote,
|
|
3599
|
+
outcome
|
|
3600
|
+
};
|
|
3601
|
+
},
|
|
3602
|
+
cancel: async (group, orderId) => {
|
|
3603
|
+
if (!ORDER_ID.test(orderId)) throw new PolymarketError("invalid-input", `bad order id ${orderId}`);
|
|
3604
|
+
const answer = await options.l2.request(group, {
|
|
3605
|
+
method: "DELETE",
|
|
3606
|
+
path: "/order",
|
|
3607
|
+
body: JSON.stringify({ orderID: orderId })
|
|
3608
|
+
}, clobCancelResponse);
|
|
3609
|
+
return {
|
|
3610
|
+
canceled: answer.canceled ?? [],
|
|
3611
|
+
notCanceled: answer.not_canceled ?? {}
|
|
3612
|
+
};
|
|
3613
|
+
},
|
|
3614
|
+
cancelMany: async (group, orderIds) => {
|
|
3615
|
+
if (orderIds.length === 0 || orderIds.length > CANCEL_MANY_LIMIT) throw new PolymarketError("invalid-input", "cancelMany takes 1..500 order ids");
|
|
3616
|
+
for (const orderId of orderIds) if (!ORDER_ID.test(orderId)) throw new PolymarketError("invalid-input", `bad order id ${orderId}`);
|
|
3617
|
+
const answer = await options.l2.request(group, {
|
|
3618
|
+
method: "DELETE",
|
|
3619
|
+
path: "/orders",
|
|
3620
|
+
body: JSON.stringify([...orderIds])
|
|
3621
|
+
}, clobCancelResponse);
|
|
3622
|
+
return {
|
|
3623
|
+
canceled: answer.canceled ?? [],
|
|
3624
|
+
notCanceled: answer.not_canceled ?? {}
|
|
3625
|
+
};
|
|
3626
|
+
},
|
|
3627
|
+
cancelAll: async (group) => {
|
|
3628
|
+
const answer = await options.l2.request(group, {
|
|
3629
|
+
method: "DELETE",
|
|
3630
|
+
path: "/cancel-all"
|
|
3631
|
+
}, clobCancelResponse);
|
|
3632
|
+
return {
|
|
3633
|
+
canceled: answer.canceled ?? [],
|
|
3634
|
+
notCanceled: answer.not_canceled ?? {}
|
|
3635
|
+
};
|
|
3636
|
+
},
|
|
3637
|
+
cancelMarket: async (group, params) => {
|
|
3638
|
+
if (params.market === void 0 && params.assetId === void 0) throw new PolymarketError("invalid-input", "cancelMarket needs a market or an assetId");
|
|
3639
|
+
const answer = await options.l2.request(group, {
|
|
3640
|
+
method: "DELETE",
|
|
3641
|
+
path: "/cancel-market-orders",
|
|
3642
|
+
body: JSON.stringify({
|
|
3643
|
+
...params.market === void 0 ? {} : { market: params.market },
|
|
3644
|
+
...params.assetId === void 0 ? {} : { asset_id: params.assetId }
|
|
3645
|
+
})
|
|
3646
|
+
}, clobCancelResponse);
|
|
3647
|
+
return {
|
|
3648
|
+
canceled: answer.canceled ?? [],
|
|
3649
|
+
notCanceled: answer.not_canceled ?? {}
|
|
3650
|
+
};
|
|
3651
|
+
},
|
|
3652
|
+
corrections: { subscribe: (listener) => {
|
|
3653
|
+
listeners.add(listener);
|
|
3654
|
+
return () => {
|
|
3655
|
+
listeners.delete(listener);
|
|
3656
|
+
};
|
|
3657
|
+
} }
|
|
3658
|
+
};
|
|
3659
|
+
}
|
|
3660
|
+
// src/apps/polymarket/provider.ts
|
|
3661
|
+
const isEvmAddress = (address) => /^0x[0-9a-fA-F]{40}$/.test(address);
|
|
3662
|
+
function createPolymarketProvider(options) {
|
|
3663
|
+
const http = createPolymarketHttp({
|
|
3664
|
+
fetch: options.fetch,
|
|
3665
|
+
setTimer: options.setTimer,
|
|
3666
|
+
now: options.now,
|
|
3667
|
+
...options.timeoutMs === void 0 ? {} : { timeoutMs: options.timeoutMs }
|
|
3668
|
+
});
|
|
3669
|
+
const signerOf = async (group) => {
|
|
3670
|
+
if (options.account === void 0) throw new PolymarketError("not-enabled", "this provider has no account api");
|
|
3671
|
+
let resolved;
|
|
3672
|
+
try {
|
|
3673
|
+
resolved = await options.account({
|
|
3674
|
+
walletId: group.walletId,
|
|
3675
|
+
groupIndex: group.groupIndex,
|
|
3676
|
+
template: "evm.bip44",
|
|
3677
|
+
network: "eip155:137"
|
|
3678
|
+
});
|
|
3679
|
+
} catch (error) {
|
|
3680
|
+
if (error instanceof WalletError && error.code === "locked") throw new PolymarketError("unlock-required", "the vault is locked", { cause: error });
|
|
3681
|
+
throw error;
|
|
3682
|
+
}
|
|
3683
|
+
if (!("address" in resolved) || !isEvmAddress(resolved.address)) throw new PolymarketError("unavailable", "the group has no EVM address");
|
|
3684
|
+
return resolved.address;
|
|
3685
|
+
};
|
|
3686
|
+
const l2 = createPolymarketL2({
|
|
3687
|
+
http,
|
|
3688
|
+
credentials: options.credentials,
|
|
3689
|
+
signerOf,
|
|
3690
|
+
now: options.now
|
|
3691
|
+
});
|
|
3692
|
+
const account = createPolymarketAccount({
|
|
3693
|
+
http,
|
|
3694
|
+
l2,
|
|
3695
|
+
wallets: createPolymarketWallets(http, options.networks),
|
|
3696
|
+
signerOf
|
|
3697
|
+
});
|
|
3698
|
+
const markets = createPolymarketMarkets(http);
|
|
3699
|
+
const trade = createPolymarketTrade({
|
|
3700
|
+
l2,
|
|
3701
|
+
account,
|
|
3702
|
+
markets,
|
|
3703
|
+
requests: options.requests,
|
|
3704
|
+
wallet: options.wallet,
|
|
3705
|
+
random: options.random,
|
|
3706
|
+
now: options.now,
|
|
3707
|
+
setTimer: options.setTimer,
|
|
3708
|
+
availability: options.availability,
|
|
3709
|
+
...options.builder === void 0 ? {} : { builder: options.builder }
|
|
3710
|
+
});
|
|
3711
|
+
const relayer = createPolymarketRelayer({
|
|
3712
|
+
http,
|
|
3713
|
+
setTimer: options.setTimer,
|
|
3714
|
+
now: options.now,
|
|
3715
|
+
...options.builder === void 0 ? {} : { builder: options.builder }
|
|
3716
|
+
});
|
|
3717
|
+
return {
|
|
3718
|
+
markets,
|
|
3719
|
+
account,
|
|
3720
|
+
trade,
|
|
3721
|
+
live: createPolymarketLive({
|
|
3722
|
+
account,
|
|
3723
|
+
credentials: options.credentials,
|
|
3724
|
+
socket: options.socket,
|
|
3725
|
+
setTimer: options.setTimer,
|
|
3726
|
+
now: options.now,
|
|
3727
|
+
random: options.random,
|
|
3728
|
+
wallet: options.wallet,
|
|
3729
|
+
logger: options.logger
|
|
3730
|
+
}),
|
|
3731
|
+
fund: createPolymarketFunding({
|
|
3732
|
+
account,
|
|
3733
|
+
relayer,
|
|
3734
|
+
requests: options.requests,
|
|
3735
|
+
hasBuilder: options.builder !== void 0,
|
|
3736
|
+
now: options.now,
|
|
3737
|
+
setTimer: options.setTimer
|
|
3738
|
+
})
|
|
3739
|
+
};
|
|
3740
|
+
}
|
|
3741
|
+
// src/apps/polymarket/app.ts
|
|
3742
|
+
function polymarket(config = {}) {
|
|
3743
|
+
const { builder } = config;
|
|
3744
|
+
if (builder?.code !== void 0 && !/^0x[0-9a-fA-F]{64}$/.test(builder.code)) throw new Error("polymarket builder.code must be a 32-byte hex string");
|
|
3745
|
+
return {
|
|
3746
|
+
id: "polymarket",
|
|
3747
|
+
enableWhen: ["available", "close-only"],
|
|
3748
|
+
create: (context) => {
|
|
3749
|
+
const credentials = createPolymarketCredentials({
|
|
3750
|
+
storage: context.storage,
|
|
3751
|
+
logger: context.logger
|
|
3752
|
+
});
|
|
3753
|
+
const provider = createPolymarketProvider({
|
|
3754
|
+
fetch: context.fetch,
|
|
3755
|
+
setTimer: context.setTimer,
|
|
3756
|
+
now: context.now,
|
|
3757
|
+
wallet: context.wallet,
|
|
3758
|
+
account: context.account,
|
|
3759
|
+
credentials,
|
|
3760
|
+
requests: context.requests,
|
|
3761
|
+
random: context.random,
|
|
3762
|
+
networks: context.networks,
|
|
3763
|
+
socket: context.socket,
|
|
3764
|
+
logger: context.logger,
|
|
3765
|
+
availability: context.availability,
|
|
3766
|
+
...builder === void 0 ? {} : { builder }
|
|
3767
|
+
});
|
|
3768
|
+
return {
|
|
3769
|
+
api: provider,
|
|
3770
|
+
provider: createPolymarketEnable({
|
|
3771
|
+
credentials,
|
|
3772
|
+
account: provider.account,
|
|
3773
|
+
requests: context.requests,
|
|
3774
|
+
fetch: context.fetch,
|
|
3775
|
+
setTimer: context.setTimer,
|
|
3776
|
+
now: context.now,
|
|
3777
|
+
...builder === void 0 ? {} : { builder },
|
|
3778
|
+
logger: context.logger
|
|
3779
|
+
})
|
|
3780
|
+
};
|
|
3781
|
+
}
|
|
3782
|
+
};
|
|
3783
|
+
}
|
|
3784
|
+
export { PolymarketError, polymarket };
|
|
3785
|
+
|
|
3786
|
+
//# sourceMappingURL=apps-polymarket.mjs.map
|