@pod-network/trade-sdk 0.1.0-rc.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.
Files changed (102) hide show
  1. package/README.md +113 -0
  2. package/dist/client.d.ts +93 -0
  3. package/dist/client.d.ts.map +1 -0
  4. package/dist/client.js +168 -0
  5. package/dist/client.js.map +1 -0
  6. package/dist/codec/decode.d.ts +22 -0
  7. package/dist/codec/decode.d.ts.map +1 -0
  8. package/dist/codec/decode.js +251 -0
  9. package/dist/codec/decode.js.map +1 -0
  10. package/dist/codec/fixed.d.ts +11 -0
  11. package/dist/codec/fixed.d.ts.map +1 -0
  12. package/dist/codec/fixed.js +37 -0
  13. package/dist/codec/fixed.js.map +1 -0
  14. package/dist/codec/resolution.d.ts +14 -0
  15. package/dist/codec/resolution.d.ts.map +1 -0
  16. package/dist/codec/resolution.js +35 -0
  17. package/dist/codec/resolution.js.map +1 -0
  18. package/dist/codec/units.d.ts +35 -0
  19. package/dist/codec/units.d.ts.map +1 -0
  20. package/dist/codec/units.js +86 -0
  21. package/dist/codec/units.js.map +1 -0
  22. package/dist/datafeed.d.ts +4 -0
  23. package/dist/datafeed.d.ts.map +1 -0
  24. package/dist/datafeed.js +73 -0
  25. package/dist/datafeed.js.map +1 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +19 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/stores/resource.d.ts +50 -0
  31. package/dist/stores/resource.d.ts.map +1 -0
  32. package/dist/stores/resource.js +154 -0
  33. package/dist/stores/resource.js.map +1 -0
  34. package/dist/sync/account-metrics.d.ts +26 -0
  35. package/dist/sync/account-metrics.d.ts.map +1 -0
  36. package/dist/sync/account-metrics.js +41 -0
  37. package/dist/sync/account-metrics.js.map +1 -0
  38. package/dist/sync/candles.d.ts +68 -0
  39. package/dist/sync/candles.d.ts.map +1 -0
  40. package/dist/sync/candles.js +318 -0
  41. package/dist/sync/candles.js.map +1 -0
  42. package/dist/sync/order-preview.d.ts +74 -0
  43. package/dist/sync/order-preview.d.ts.map +1 -0
  44. package/dist/sync/order-preview.js +86 -0
  45. package/dist/sync/order-preview.js.map +1 -0
  46. package/dist/sync/orders.d.ts +49 -0
  47. package/dist/sync/orders.d.ts.map +1 -0
  48. package/dist/sync/orders.js +210 -0
  49. package/dist/sync/orders.js.map +1 -0
  50. package/dist/sync/positions-live.d.ts +3 -0
  51. package/dist/sync/positions-live.d.ts.map +1 -0
  52. package/dist/sync/positions-live.js +86 -0
  53. package/dist/sync/positions-live.js.map +1 -0
  54. package/dist/sync/sources.d.ts +40 -0
  55. package/dist/sync/sources.d.ts.map +1 -0
  56. package/dist/sync/sources.js +197 -0
  57. package/dist/sync/sources.js.map +1 -0
  58. package/dist/transport/rest.d.ts +83 -0
  59. package/dist/transport/rest.d.ts.map +1 -0
  60. package/dist/transport/rest.js +146 -0
  61. package/dist/transport/rest.js.map +1 -0
  62. package/dist/transport/ws.d.ts +60 -0
  63. package/dist/transport/ws.d.ts.map +1 -0
  64. package/dist/transport/ws.js +235 -0
  65. package/dist/transport/ws.js.map +1 -0
  66. package/dist/types/public.d.ts +292 -0
  67. package/dist/types/public.d.ts.map +1 -0
  68. package/dist/types/public.js +4 -0
  69. package/dist/types/public.js.map +1 -0
  70. package/dist/types/wire.d.ts +283 -0
  71. package/dist/types/wire.d.ts.map +1 -0
  72. package/dist/types/wire.js +6 -0
  73. package/dist/types/wire.js.map +1 -0
  74. package/dist/write/delegation.d.ts +54 -0
  75. package/dist/write/delegation.d.ts.map +1 -0
  76. package/dist/write/delegation.js +81 -0
  77. package/dist/write/delegation.js.map +1 -0
  78. package/dist/write/index.d.ts +261 -0
  79. package/dist/write/index.d.ts.map +1 -0
  80. package/dist/write/index.js +428 -0
  81. package/dist/write/index.js.map +1 -0
  82. package/package.json +43 -0
  83. package/src/client.ts +229 -0
  84. package/src/codec/decode.ts +277 -0
  85. package/src/codec/fixed.ts +41 -0
  86. package/src/codec/resolution.ts +39 -0
  87. package/src/codec/units.ts +100 -0
  88. package/src/datafeed.ts +94 -0
  89. package/src/index.ts +49 -0
  90. package/src/stores/resource.ts +172 -0
  91. package/src/sync/account-metrics.ts +71 -0
  92. package/src/sync/candles.ts +326 -0
  93. package/src/sync/order-preview.ts +152 -0
  94. package/src/sync/orders.ts +205 -0
  95. package/src/sync/positions-live.ts +102 -0
  96. package/src/sync/sources.ts +239 -0
  97. package/src/transport/rest.ts +213 -0
  98. package/src/transport/ws.ts +255 -0
  99. package/src/types/public.ts +335 -0
  100. package/src/types/wire.ts +301 -0
  101. package/src/write/delegation.ts +113 -0
  102. package/src/write/index.ts +642 -0
@@ -0,0 +1,642 @@
1
+ // Write helpers: build unsigned CLOB transactions and derive order ids. These
2
+ // are pure encoding — no wallet, no key, no nonce ownership. The consumer signs
3
+ // + broadcasts the returned request with whatever wallet it has
4
+ // (walletClient.sendTransaction / eth_sendTransaction / Privy).
5
+ //
6
+ // Two deliberate exceptions hold keys, both scoped to this `/write` entry so
7
+ // read-only consumers never bundle signing code:
8
+ // - `mint` (below): the faucet is gas-exempt and signer-irrelevant, so it
9
+ // signs with a one-shot throwaway key.
10
+ // - `createDelegatedWallet` (./delegation.js): custody of the ephemeral
11
+ // trading key, closed over — see the invariant there.
12
+
13
+ import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, keccak256, parseAbi } from "viem";
14
+ import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
15
+ import type { Address, Hash, Hex, MarketId } from "../types/public.js";
16
+
17
+ /** The CLOB precompile (chain id 1293 / 0x50d). */
18
+ export const CLOB_ADDRESS: Address = "0x50d0000000000000000000000000000000000002";
19
+
20
+ const CLOB_ABI = parseAbi([
21
+ "function submitOrder(bytes32 orderbookId, int256 size, uint256 price, uint8 orderType, uint128 deadline, uint128 ttl, bool reduceOnly, bool ioc)",
22
+ "function cancel(bytes32 orderbookId, bytes32 canceledOrder, uint128 deadline)",
23
+ "function update(bytes32 orderbookId, bytes32 updatedOrder, uint256 newSize, uint256 newPrice, address token, uint128 deadline)",
24
+ // TriggerType { TakeProfit=0, StopLoss=1 } ; TriggerGrouping { None=0, Position=1 }
25
+ "function submitTrigger(bytes32 orderbookId, int256 size, uint256 limitPrice, uint256 triggerPrice, uint8 triggerType, uint8 grouping, uint128 deadline, uint128 ttl, bool reduceOnly, bool ioc)",
26
+ "function cancelTrigger(bytes32 orderbookId, bytes32 triggerOrder, uint128 deadline)",
27
+ "function updateTrigger(bytes32 orderbookId, bytes32 triggerOrder, int256 newSize, uint256 newLimitPrice, uint256 newTriggerPrice, uint128 deadline)",
28
+ "function submitBatch(bytes[] inner)",
29
+ ]);
30
+
31
+ /** ~10 years in microseconds — default far-future expiry for resting orders. */
32
+ const FAR_US = 10n * 365n * 24n * 3600n * 1_000_000n;
33
+
34
+ export interface SubmitOrderParams {
35
+ orderbookId: MarketId;
36
+ side: "buy" | "sell"; // buy/long → +size, sell/short → −size
37
+ orderType: "limit" | "market";
38
+ price: bigint; // 1e18-scaled
39
+ size: bigint; // 1e18-scaled magnitude (sign is applied from `side`)
40
+ /**
41
+ * Market `tick_precision`. When given, `price` is floored to a multiple of it
42
+ * — the CLOB rejects prices that aren't tick-aligned (e.g. a raw oracle mark
43
+ * like 49999.99999999999). Pass `market.tickPrecision`.
44
+ */
45
+ tickPrecision?: bigint;
46
+ /**
47
+ * Market auction interval in microseconds (`market.auctionIntervalMs * 1000`).
48
+ * The CLOB requires `deadline` to be a multiple of it ("Deadline is not aligned
49
+ * to auction interval"); when given, deadline & ttl are floored to it.
50
+ */
51
+ auctionIntervalUs?: number;
52
+ reduceOnly?: boolean;
53
+ /**
54
+ * Immediate-or-cancel. Defaults to `true` for a market order and `false` for
55
+ * a limit order: a market order carries no resting price of its own, so the
56
+ * CLOB rejects one that could outlive its batch ("market orders must be
57
+ * immediate-or-cancel"). Only set this explicitly to make a *limit* order IOC.
58
+ */
59
+ ioc?: boolean;
60
+ deadline?: number; // ms; default far future
61
+ ttl?: number; // ms; default far future
62
+ }
63
+
64
+ /** Floor a price to a multiple of the tick. */
65
+ export function alignPrice(price: bigint, tick: bigint): bigint {
66
+ return tick > 0n ? (price / tick) * tick : price;
67
+ }
68
+
69
+ /** Floor a microsecond timestamp to a multiple of the auction interval. */
70
+ export function alignDeadline(us: bigint, intervalUs: bigint): bigint {
71
+ return intervalUs > 0n ? (us / intervalUs) * intervalUs : us;
72
+ }
73
+
74
+ /** An unsigned transaction request — hand to `walletClient.sendTransaction`. */
75
+ export interface PodTxRequest {
76
+ to: Address;
77
+ data: Hex;
78
+ value: bigint;
79
+ type: "eip1559";
80
+ maxPriorityFeePerGas: bigint;
81
+ gas: bigint;
82
+ // maxFeePerGas is supplied by the caller (pod base fee, from eth_maxFeePerGas).
83
+ }
84
+
85
+ function us(ms: number | undefined, fallback: bigint): bigint {
86
+ return ms === undefined ? fallback : BigInt(Math.trunc(ms)) * 1000n;
87
+ }
88
+
89
+ export function buildSubmitOrder(p: SubmitOrderParams): PodTxRequest {
90
+ const nowUs = BigInt(Date.now()) * 1000n;
91
+ const signedSize = p.side === "sell" ? -p.size : p.size;
92
+ const price = p.tickPrecision ? alignPrice(p.price, p.tickPrecision) : p.price;
93
+ const interval = p.auctionIntervalUs ? BigInt(p.auctionIntervalUs) : 0n;
94
+ const deadline = alignDeadline(us(p.deadline, nowUs + FAR_US), interval);
95
+ const ttl = alignDeadline(us(p.ttl, nowUs + FAR_US + 30n * 24n * 3600n * 1_000_000n), interval);
96
+ const data = encodeFunctionData({
97
+ abi: CLOB_ABI,
98
+ functionName: "submitOrder",
99
+ args: [
100
+ p.orderbookId,
101
+ signedSize,
102
+ price,
103
+ p.orderType === "market" ? 1 : 0, // OrderType { Limit=0, Market=1 }
104
+ deadline,
105
+ ttl,
106
+ p.reduceOnly ?? false,
107
+ // A market order must not outlive its batch — the CLOB rejects a non-IOC
108
+ // market order outright (`validate_order_shape`, trading/src/book.rs), so
109
+ // default it on rather than making every caller remember.
110
+ p.ioc ?? p.orderType === "market",
111
+ ],
112
+ }) as Hex;
113
+ return { to: CLOB_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
114
+ }
115
+
116
+ export function buildCancelOrder(
117
+ orderbookId: MarketId,
118
+ orderId: Hash,
119
+ opts?: { deadline?: number; auctionIntervalUs?: number },
120
+ ): PodTxRequest {
121
+ const nowUs = BigInt(Date.now()) * 1000n;
122
+ const interval = opts?.auctionIntervalUs ? BigInt(opts.auctionIntervalUs) : 0n;
123
+ const deadline = alignDeadline(us(opts?.deadline, nowUs + FAR_US), interval);
124
+ const data = encodeFunctionData({
125
+ abi: CLOB_ABI,
126
+ functionName: "cancel",
127
+ args: [orderbookId, orderId, deadline],
128
+ }) as Hex;
129
+ return { to: CLOB_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
130
+ }
131
+
132
+ // --- broadcasting ---
133
+ //
134
+ // Signing stays with the consumer's wallet (viem / Privy / MetaMask). What IS
135
+ // pod-specific — and worth centralizing — is how a reverted CLOB tx surfaces:
136
+ // the CLOB validates orders only on execution, so a high-level send returns
137
+ // "execution reverted for an unknown reason" with the revert data dropped. We
138
+ // broadcast the already-signed tx with a raw eth_sendRawTransaction (which
139
+ // preserves the Solidity `Error(string)` payload) and decode the real message.
140
+
141
+ /** Solidity `Error(string)` selector — `bytes4(keccak256("Error(string)"))`. */
142
+ const ERROR_SELECTOR = "0x08c379a0";
143
+
144
+ /** A reverted pod transaction, carrying the decoded CLOB reason. */
145
+ export class PodTxRevertError extends Error {
146
+ constructor(public reason: string, public data?: string) {
147
+ super(reason);
148
+ this.name = "PodTxRevertError";
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Decode a Solidity `Error(string)` revert payload into its message (e.g.
154
+ * "Deadline is not aligned to auction interval"). Returns undefined when `data`
155
+ * isn't an `Error(string)` payload — use this directly if you broadcast through
156
+ * your own provider and just want to translate the revert data.
157
+ */
158
+ export function decodeRevertReason(data: string | null | undefined): string | undefined {
159
+ if (!data || !data.startsWith(ERROR_SELECTOR)) return undefined;
160
+ try {
161
+ return decodeAbiParameters([{ type: "string" }], `0x${data.slice(10)}` as Hex)[0];
162
+ } catch {
163
+ return undefined;
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Broadcast a SIGNED, serialized transaction via raw `eth_sendRawTransaction`
169
+ * and return its hash, throwing a {@link PodTxRevertError} with the decoded CLOB
170
+ * reason on revert. Transport-only — the consumer signs with its own wallet
171
+ * (`walletClient.signTransaction(...)`), then hands the serialized tx here.
172
+ */
173
+ export async function sendRawTransaction(
174
+ rpcUrl: string,
175
+ signedTx: Hex,
176
+ opts?: { fetch?: typeof fetch },
177
+ ): Promise<Hash> {
178
+ const doFetch = opts?.fetch ?? fetch;
179
+ const res = await doFetch(rpcUrl, {
180
+ method: "POST",
181
+ headers: { "content-type": "application/json" },
182
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_sendRawTransaction", params: [signedTx] }),
183
+ });
184
+ const json = (await res.json()) as { result?: Hash; error?: { message?: string; data?: string } };
185
+ if (json.error) {
186
+ const reason = decodeRevertReason(json.error.data) ?? json.error.message ?? "transaction failed";
187
+ throw new PodTxRevertError(reason, json.error.data);
188
+ }
189
+ return json.result!;
190
+ }
191
+
192
+ export interface UpdateOrderParams {
193
+ orderbookId: MarketId;
194
+ /** The resting order's id (`Order.id`) — modified in place, keeps the same id. */
195
+ orderId: Hash;
196
+ /** New price, 1e18-scaled. Floored to `tickPrecision` when given. */
197
+ price: bigint;
198
+ /**
199
+ * New size MAGNITUDE, 1e18-scaled. The side is unchanged — the engine reuses
200
+ * the resting order's side — so the sign is ignored. Must be non-zero.
201
+ */
202
+ size: bigint;
203
+ /**
204
+ * Collateral/quote token. The engine derives the real side & token from the
205
+ * resting order, so this is effectively informational; pass `market.quote.address`
206
+ * (the native USD address for perps).
207
+ */
208
+ token: Address;
209
+ tickPrecision?: bigint;
210
+ auctionIntervalUs?: number;
211
+ deadline?: number; // ms; default far future
212
+ }
213
+
214
+ /**
215
+ * Amend a resting order's price and/or size in place via the CLOB's native
216
+ * `update` (no cancel+resubmit, so the order keeps its id and queue identity).
217
+ * Aligns price to the tick and deadline to the auction interval, like
218
+ * {@link buildSubmitOrder}.
219
+ */
220
+ export function buildUpdateOrder(p: UpdateOrderParams): PodTxRequest {
221
+ const nowUs = BigInt(Date.now()) * 1000n;
222
+ const price = p.tickPrecision ? alignPrice(p.price, p.tickPrecision) : p.price;
223
+ const size = p.size < 0n ? -p.size : p.size; // contract takes an unsigned magnitude
224
+ const interval = p.auctionIntervalUs ? BigInt(p.auctionIntervalUs) : 0n;
225
+ const deadline = alignDeadline(us(p.deadline, nowUs + FAR_US), interval);
226
+ const data = encodeFunctionData({
227
+ abi: CLOB_ABI,
228
+ functionName: "update",
229
+ args: [p.orderbookId, p.orderId, size, price, p.token, deadline],
230
+ }) as Hex;
231
+ return { to: CLOB_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
232
+ }
233
+
234
+ // --- TP/SL triggers (perp-only) ---------------------------------------------
235
+ //
236
+ // A trigger is an *armed* limit order: when the pair's mark price crosses
237
+ // `triggerPrice` in the direction implied by `triggerType` and the sign of the
238
+ // size, the venue emits a regular limit order. To attach a TP/SL to a position,
239
+ // the trigger's side is the CLOSING side (opposite the position), `reduceOnly`,
240
+ // and `grouping: "position"` so it's auto-cancelled when the position closes.
241
+ //
242
+ // Direction matrix (is_buy = size > 0):
243
+ // buy + take_profit → fires when mark <= triggerPrice
244
+ // buy + stop_loss → fires when mark >= triggerPrice
245
+ // sell + take_profit → fires when mark >= triggerPrice
246
+ // sell + stop_loss → fires when mark <= triggerPrice
247
+
248
+ /** Triggers expire at most this long after their deadline (CLOB TRIGGER_MAX_TTL). */
249
+ const TRIGGER_TTL_US = 29n * 24n * 3600n * 1_000_000n; // 29d, just under the 30d cap
250
+
251
+ export interface SubmitTriggerParams {
252
+ orderbookId: MarketId;
253
+ /** Side of the order that fires: buy → +size, sell → −size. */
254
+ side: "buy" | "sell";
255
+ size: bigint; // magnitude, 1e18-scaled (sign applied from `side`)
256
+ triggerType: "take_profit" | "stop_loss";
257
+ /** Mark-price level that arms the fire, 1e18-scaled. Floored to the tick. */
258
+ triggerPrice: bigint;
259
+ /** Limit price of the fired order; defaults to `triggerPrice`. Floored to the tick. */
260
+ limitPrice?: bigint;
261
+ /** "position" (default) auto-cancels with the position; "none" is standalone. */
262
+ grouping?: "none" | "position";
263
+ reduceOnly?: boolean; // default true
264
+ ioc?: boolean;
265
+ tickPrecision?: bigint;
266
+ auctionIntervalUs?: number;
267
+ deadline?: number; // ms; default far future
268
+ /** Armed lifetime as a duration in ms (capped at ~30d by the CLOB); default 29d. */
269
+ ttlMs?: number;
270
+ }
271
+
272
+ export function buildSubmitTrigger(p: SubmitTriggerParams): PodTxRequest {
273
+ const nowUs = BigInt(Date.now()) * 1000n;
274
+ const signedSize = p.side === "sell" ? -p.size : p.size;
275
+ const align = (v: bigint) => (p.tickPrecision ? alignPrice(v, p.tickPrecision) : v);
276
+ const triggerPrice = align(p.triggerPrice);
277
+ const limitPrice = align(p.limitPrice ?? p.triggerPrice);
278
+ const interval = p.auctionIntervalUs ? BigInt(p.auctionIntervalUs) : 0n;
279
+ const deadline = alignDeadline(us(p.deadline, nowUs + FAR_US), interval);
280
+ // ttl as a RELATIVE duration (< deadline ⇒ the CLOB reads it relative to the deadline).
281
+ const ttl = p.ttlMs !== undefined ? BigInt(Math.trunc(p.ttlMs)) * 1000n : TRIGGER_TTL_US;
282
+ const data = encodeFunctionData({
283
+ abi: CLOB_ABI,
284
+ functionName: "submitTrigger",
285
+ args: [
286
+ p.orderbookId,
287
+ signedSize,
288
+ limitPrice,
289
+ triggerPrice,
290
+ p.triggerType === "stop_loss" ? 1 : 0, // TriggerType
291
+ (p.grouping ?? "position") === "position" ? 1 : 0, // TriggerGrouping
292
+ deadline,
293
+ ttl,
294
+ p.reduceOnly ?? true,
295
+ p.ioc ?? false,
296
+ ],
297
+ }) as Hex;
298
+ return { to: CLOB_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
299
+ }
300
+
301
+ export function buildCancelTrigger(
302
+ orderbookId: MarketId,
303
+ triggerOrderId: Hash,
304
+ opts?: { deadline?: number; auctionIntervalUs?: number },
305
+ ): PodTxRequest {
306
+ const nowUs = BigInt(Date.now()) * 1000n;
307
+ const interval = opts?.auctionIntervalUs ? BigInt(opts.auctionIntervalUs) : 0n;
308
+ const deadline = alignDeadline(us(opts?.deadline, nowUs + FAR_US), interval);
309
+ const data = encodeFunctionData({
310
+ abi: CLOB_ABI,
311
+ functionName: "cancelTrigger",
312
+ args: [orderbookId, triggerOrderId, deadline],
313
+ }) as Hex;
314
+ return { to: CLOB_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
315
+ }
316
+
317
+ export interface UpdateTriggerParams {
318
+ orderbookId: MarketId;
319
+ triggerOrderId: Hash;
320
+ side: "buy" | "sell"; // sign of newSize; grouping can't change via update
321
+ size: bigint; // magnitude
322
+ triggerPrice: bigint;
323
+ limitPrice?: bigint;
324
+ tickPrecision?: bigint;
325
+ auctionIntervalUs?: number;
326
+ deadline?: number;
327
+ }
328
+
329
+ export function buildUpdateTrigger(p: UpdateTriggerParams): PodTxRequest {
330
+ const nowUs = BigInt(Date.now()) * 1000n;
331
+ const signedSize = p.side === "sell" ? -p.size : p.size;
332
+ const align = (v: bigint) => (p.tickPrecision ? alignPrice(v, p.tickPrecision) : v);
333
+ const interval = p.auctionIntervalUs ? BigInt(p.auctionIntervalUs) : 0n;
334
+ const deadline = alignDeadline(us(p.deadline, nowUs + FAR_US), interval);
335
+ const data = encodeFunctionData({
336
+ abi: CLOB_ABI,
337
+ functionName: "updateTrigger",
338
+ args: [p.orderbookId, p.triggerOrderId, signedSize, align(p.limitPrice ?? p.triggerPrice), align(p.triggerPrice), deadline],
339
+ }) as Hex;
340
+ return { to: CLOB_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
341
+ }
342
+
343
+ // --- batching (submitBatch) -------------------------------------------------
344
+ //
345
+ // `submitBatch(bytes[] inner)` carries several single-intent calls in ONE signed
346
+ // tx. Each `inner[i]` is the ABI-encoded calldata of an existing intent
347
+ // (submitOrder, submitTrigger, cancel, …); its `sequence` (the index in `inner`)
348
+ // feeds `OrderId::new(signer, nonce, sequence)`. The CLOB requires every
349
+ // deadline-bearing leg to share ONE deadline — build the legs with the same
350
+ // `deadline` (see `buildOrderWithTriggers`, which does this for you).
351
+
352
+ /** ~10 years in ms — default far-future deadline shared by batched legs. */
353
+ const FAR_MS = 10 * 365 * 24 * 3600 * 1000;
354
+
355
+ /** Scale a 1e18 size by a 0..1 fraction (e.g. close 50% of a position). */
356
+ function scaleSize(size: bigint, fraction: number): bigint {
357
+ const f = Math.max(0, Math.min(1, fraction));
358
+ return (size * BigInt(Math.round(f * 1_000_000))) / 1_000_000n;
359
+ }
360
+
361
+ /** Wrap already-built legs into one `submitBatch` tx. Pass leg requests (their
362
+ * `data` is used) or raw calldata. Legs must share a deadline (the CLOB enforces
363
+ * it). Gas scales with the leg count. */
364
+ export function buildSubmitBatch(
365
+ legs: Array<PodTxRequest | Hex>,
366
+ opts?: { gas?: bigint },
367
+ ): PodTxRequest {
368
+ const inner = legs.map((l) => (typeof l === "string" ? l : l.data));
369
+ const data = encodeFunctionData({
370
+ abi: CLOB_ABI,
371
+ functionName: "submitBatch",
372
+ args: [inner],
373
+ }) as Hex;
374
+ return {
375
+ to: CLOB_ADDRESS,
376
+ data,
377
+ value: 0n,
378
+ type: "eip1559",
379
+ maxPriorityFeePerGas: 0n,
380
+ gas: opts?.gas ?? BigInt(Math.max(1, inner.length)) * 1_000_000n,
381
+ };
382
+ }
383
+
384
+ export interface OrderTrigger {
385
+ /** Mark-price level that arms the fire (1e18). Floored to the tick. */
386
+ triggerPrice: bigint;
387
+ /** Fired limit price; defaults to `triggerPrice`. Floored to the tick. */
388
+ limitPrice?: bigint;
389
+ /** Fraction of the entry size to close, 0..1 (default 1 = whole position). */
390
+ sizeFraction?: number;
391
+ }
392
+
393
+ export interface OrderWithTriggersParams {
394
+ orderbookId: MarketId;
395
+ /** Entry side: buy → long, sell → short. */
396
+ side: "buy" | "sell";
397
+ orderType: "limit" | "market";
398
+ price: bigint; // entry price, 1e18
399
+ size: bigint; // entry size magnitude, 1e18
400
+ takeProfit?: OrderTrigger;
401
+ stopLoss?: OrderTrigger;
402
+ tickPrecision?: bigint;
403
+ auctionIntervalUs?: number;
404
+ reduceOnly?: boolean; // entry reduceOnly (rare); triggers are always reduceOnly
405
+ ioc?: boolean;
406
+ deadline?: number; // ms; shared by every leg (default far future)
407
+ orderTtl?: number; // ms
408
+ triggerTtlMs?: number; // ms; armed lifetime (capped ~30d)
409
+ }
410
+
411
+ /**
412
+ * Build ONE transaction that places an entry order and arms its TP/SL together.
413
+ * With either trigger present it batches `submitOrder` + `submitTrigger`(s) via
414
+ * `submitBatch` under a shared deadline; with neither it's a plain `submitOrder`.
415
+ *
416
+ * Triggers close the entry position: opposite side, `reduceOnly`,
417
+ * `grouping: "position"` (so a partial fill — and the eventual close — keep the
418
+ * triggers consistent), size = entry size × `sizeFraction`.
419
+ */
420
+ export function buildOrderWithTriggers(p: OrderWithTriggersParams): PodTxRequest {
421
+ const deadline = p.deadline ?? Date.now() + FAR_MS;
422
+ const order = buildSubmitOrder({
423
+ orderbookId: p.orderbookId,
424
+ side: p.side,
425
+ orderType: p.orderType,
426
+ price: p.price,
427
+ size: p.size,
428
+ tickPrecision: p.tickPrecision,
429
+ auctionIntervalUs: p.auctionIntervalUs,
430
+ reduceOnly: p.reduceOnly,
431
+ ioc: p.ioc,
432
+ deadline,
433
+ ttl: p.orderTtl,
434
+ });
435
+ const closeSide: "buy" | "sell" = p.side === "buy" ? "sell" : "buy";
436
+ const trigLeg = (t: OrderTrigger, triggerType: "take_profit" | "stop_loss") =>
437
+ buildSubmitTrigger({
438
+ orderbookId: p.orderbookId,
439
+ side: closeSide,
440
+ size: scaleSize(p.size, t.sizeFraction ?? 1),
441
+ triggerType,
442
+ triggerPrice: t.triggerPrice,
443
+ limitPrice: t.limitPrice,
444
+ grouping: "position",
445
+ reduceOnly: true,
446
+ tickPrecision: p.tickPrecision,
447
+ auctionIntervalUs: p.auctionIntervalUs,
448
+ deadline,
449
+ ttlMs: p.triggerTtlMs,
450
+ });
451
+ const legs: PodTxRequest[] = [order];
452
+ if (p.takeProfit) legs.push(trigLeg(p.takeProfit, "take_profit"));
453
+ if (p.stopLoss) legs.push(trigLeg(p.stopLoss, "stop_loss"));
454
+ return legs.length === 1 ? order : buildSubmitBatch(legs);
455
+ }
456
+
457
+ /**
458
+ * Protective bound for a market order: the worst price it may fill at. A CLOB
459
+ * market order's `price` IS its slippage bound, so submit at the reference
460
+ * price padded by `slippageBps` (buy pays up to +bps, sell accepts down to
461
+ * −bps) — tight enough to protect, loose enough to actually cross.
462
+ */
463
+ export function protectivePrice(price: bigint, side: "buy" | "sell", slippageBps: number): bigint {
464
+ const bps = BigInt(Math.trunc(slippageBps));
465
+ const SCALE = 10_000n;
466
+ return (price * (side === "buy" ? SCALE + bps : SCALE - bps)) / SCALE;
467
+ }
468
+
469
+ export interface ClosePositionParams {
470
+ orderbookId: MarketId;
471
+ /** The position's current side (long → close with a sell; short → buy). */
472
+ side: "long" | "short";
473
+ /** Position size magnitude to close (1e18). */
474
+ size: bigint;
475
+ /** Current mark price (1e18) — the protective price is derived from it. */
476
+ price: bigint;
477
+ /** Slippage bound in basis points for the market close. Default 500 (5%). */
478
+ slippageBps?: number;
479
+ tickPrecision?: bigint;
480
+ auctionIntervalUs?: number;
481
+ deadline?: number; // ms; pass a shared value when batching closes
482
+ }
483
+
484
+ /**
485
+ * Close (flatten) a perp position: a reduce-only **market** order on the
486
+ * opposite side for the full size. A market order's `price` is a slippage
487
+ * bound, so it's set to mark ∓ `slippageBps` (sell accepts lower, buy pays
488
+ * higher) to guarantee it crosses and fills. `reduceOnly` guarantees it only
489
+ * shrinks the position, never flips it. Batch several with
490
+ * {@link buildSubmitBatch} (shared `deadline`) to close everything in one tx.
491
+ */
492
+ export function buildClosePosition(p: ClosePositionParams): PodTxRequest {
493
+ const closeSide = p.side === "long" ? "sell" : "buy";
494
+ const price = protectivePrice(p.price, closeSide, p.slippageBps ?? 500); // tick-aligned in build
495
+ return buildSubmitOrder({
496
+ orderbookId: p.orderbookId,
497
+ side: closeSide,
498
+ orderType: "market",
499
+ price,
500
+ size: p.size < 0n ? -p.size : p.size,
501
+ reduceOnly: true,
502
+ tickPrecision: p.tickPrecision,
503
+ auctionIntervalUs: p.auctionIntervalUs,
504
+ deadline: p.deadline,
505
+ });
506
+ }
507
+
508
+ /** A mined transaction receipt (the fields a consumer typically needs). */
509
+ export interface TxReceipt {
510
+ /** `success` when the tx executed (status `0x1`); `reverted` on `0x0`. */
511
+ status: "success" | "reverted";
512
+ transactionHash: Hash;
513
+ blockNumber: bigint;
514
+ gasUsed: bigint;
515
+ }
516
+
517
+ /**
518
+ * Poll `eth_getTransactionReceipt` until the tx is mined, then report whether it
519
+ * executed or reverted. A hash from {@link sendRawTransaction} only means the
520
+ * node accepted the tx into its pool — it is NOT yet confirmed. Await this to
521
+ * know the on-chain outcome. Throws on timeout. Like the rest of this module
522
+ * it's transport-only (raw JSON-RPC), so it needs no viem client.
523
+ */
524
+ export async function waitForReceipt(
525
+ rpcUrl: string,
526
+ hash: Hash,
527
+ opts?: { fetch?: typeof fetch; timeoutMs?: number; pollMs?: number },
528
+ ): Promise<TxReceipt> {
529
+ const doFetch = opts?.fetch ?? fetch;
530
+ const timeoutMs = opts?.timeoutMs ?? 30_000;
531
+ const pollMs = opts?.pollMs ?? 250;
532
+ const deadline = Date.now() + timeoutMs;
533
+ for (;;) {
534
+ const res = await doFetch(rpcUrl, {
535
+ method: "POST",
536
+ headers: { "content-type": "application/json" },
537
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_getTransactionReceipt", params: [hash] }),
538
+ });
539
+ const json = (await res.json()) as {
540
+ result?: { status: string; transactionHash: Hash; blockNumber: string; gasUsed: string } | null;
541
+ };
542
+ const r = json.result;
543
+ if (r) {
544
+ return {
545
+ status: r.status === "0x1" ? "success" : "reverted",
546
+ transactionHash: r.transactionHash,
547
+ blockNumber: BigInt(r.blockNumber),
548
+ gasUsed: BigInt(r.gasUsed),
549
+ };
550
+ }
551
+ if (Date.now() > deadline) throw new Error(`timed out waiting for receipt ${hash}`);
552
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
553
+ }
554
+ }
555
+
556
+ // --- mint faucet (test environments — node/src/mint.rs) ----------------------
557
+ //
558
+ // Anyone may mint tokens to any address when the node's `minting_allowed` flag
559
+ // is set (and its mint-admin list is empty). Mint txs are gas-exempt and the
560
+ // signer is irrelevant — only the recipient matters — so this signs with a
561
+ // fresh throwaway key per call; no wallet, no funds, no delegation needed.
562
+
563
+ /** The Mint contract (`node/src/mint.rs`). */
564
+ export const MINT_ADDRESS: Address = "0x00000000000000000000000000000000000fFFFf";
565
+ /** The native USD (cash) token — `trading/src/constants.rs` NATIVE_ADDRESS. */
566
+ export const NATIVE_USD_ADDRESS: Address = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
567
+
568
+ const MINT_ABI = parseAbi([
569
+ "function mint(address to, (address token, uint256 amount)[] tokens, bool depositToClob)",
570
+ ]);
571
+
572
+ export interface MintParams {
573
+ rpcUrl: string;
574
+ /** Chain id for the tx; fetched via `eth_chainId` when omitted. */
575
+ chainId?: number;
576
+ to: Address;
577
+ /** 1e18-scaled amounts; `token` defaults to the native USD (cash) token. */
578
+ tokens: Array<{ token?: Address; amount: bigint }>;
579
+ /** Deposit into the CLOB balance (default) instead of crediting the EOA. */
580
+ depositToClob?: boolean;
581
+ /** Called with the tx hash once the node accepts it (before confirmation). */
582
+ onSubmitted?: (hash: Hash) => void;
583
+ fetch?: typeof fetch;
584
+ }
585
+
586
+ /** Mint tokens to `to` and wait for the receipt. Throws {@link PodTxRevertError}
587
+ * on rejection (e.g. "Minting is disabled") and Error on on-chain revert. */
588
+ export async function mint(p: MintParams): Promise<TxReceipt> {
589
+ const doFetch = p.fetch ?? fetch;
590
+ const rpc = async (method: string): Promise<string> => {
591
+ const res = await doFetch(p.rpcUrl, {
592
+ method: "POST",
593
+ headers: { "content-type": "application/json" },
594
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params: [] }),
595
+ });
596
+ const json = (await res.json()) as { result?: string; error?: { message?: string } };
597
+ if (json.error || json.result === undefined) throw new Error(json.error?.message ?? `${method} failed`);
598
+ return json.result;
599
+ };
600
+ const chainId = p.chainId ?? Number(await rpc("eth_chainId"));
601
+ const maxFeePerGas = BigInt(await rpc("eth_gasPrice"));
602
+ const signer = privateKeyToAccount(generatePrivateKey());
603
+ const data = encodeFunctionData({
604
+ abi: MINT_ABI,
605
+ functionName: "mint",
606
+ args: [
607
+ p.to,
608
+ p.tokens.map((t) => ({ token: t.token ?? NATIVE_USD_ADDRESS, amount: t.amount })),
609
+ p.depositToClob ?? true,
610
+ ],
611
+ });
612
+ const serialized = await signer.signTransaction({
613
+ to: MINT_ADDRESS, data, value: 0n, chainId, type: "eip1559",
614
+ maxFeePerGas, maxPriorityFeePerGas: 0n, gas: 1_000_000n, nonce: 0,
615
+ });
616
+ const hash = await sendRawTransaction(p.rpcUrl, serialized, { fetch: doFetch });
617
+ p.onSubmitted?.(hash);
618
+ const receipt = await waitForReceipt(p.rpcUrl, hash, { fetch: doFetch });
619
+ if (receipt.status === "reverted") throw new Error(`mint reverted on-chain (${hash.slice(0, 10)}…)`);
620
+ return receipt;
621
+ }
622
+
623
+ /**
624
+ * Deterministic order id: `keccak256(abi.encode(signer, nonce, sequence))`,
625
+ * matching the engine (`trading/src/lib.rs`). `sequence` is the 0-based index
626
+ * of the intent within a `submitBatch` (0 for a single-intent tx). Needs the
627
+ * nonce, so it's only known up-front in managed mode; in advisory mode reconcile
628
+ * by `tx_hash` from the `pod_orders` stream instead.
629
+ */
630
+ export function deriveOrderId(signer: Address, nonce: number, sequence = 0): Hash {
631
+ return keccak256(
632
+ encodeAbiParameters(
633
+ [{ type: "address" }, { type: "uint64" }, { type: "uint32" }],
634
+ [signer, BigInt(nonce), sequence],
635
+ ),
636
+ ) as Hash;
637
+ }
638
+
639
+ export {
640
+ createDelegatedWallet, delegationTypedData,
641
+ type CreateDelegatedWalletParams, type DelegatedWallet, type DelegationTypedData,
642
+ } from "./delegation.js";