@pod-network/trade-sdk 0.15.0 → 0.17.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 +29 -0
- package/dist/client.d.ts +0 -1
- package/dist/client.d.ts.map +1 -1
- package/dist/client.js +0 -1
- package/dist/client.js.map +1 -1
- package/dist/codec/activity.d.ts.map +1 -1
- package/dist/codec/activity.js +6 -2
- package/dist/codec/activity.js.map +1 -1
- package/dist/codec/decode.d.ts.map +1 -1
- package/dist/codec/decode.js +3 -12
- package/dist/codec/decode.js.map +1 -1
- package/dist/codec/orders-v2.d.ts.map +1 -1
- package/dist/codec/orders-v2.js +10 -3
- package/dist/codec/orders-v2.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/stores/resource.d.ts +1 -0
- package/dist/stores/resource.d.ts.map +1 -1
- package/dist/stores/resource.js +1 -0
- package/dist/stores/resource.js.map +1 -1
- package/dist/sync/activity.d.ts +1 -1
- package/dist/sync/activity.d.ts.map +1 -1
- package/dist/sync/activity.js +4 -2
- package/dist/sync/activity.js.map +1 -1
- package/dist/sync/candles.d.ts +3 -1
- package/dist/sync/candles.d.ts.map +1 -1
- package/dist/sync/candles.js +13 -7
- package/dist/sync/candles.js.map +1 -1
- package/dist/sync/orders.d.ts +1 -1
- package/dist/sync/orders.d.ts.map +1 -1
- package/dist/sync/orders.js +11 -13
- package/dist/sync/orders.js.map +1 -1
- package/dist/sync/pnl-history.js +1 -1
- package/dist/sync/pnl-history.js.map +1 -1
- package/dist/sync/sources.d.ts +11 -1
- package/dist/sync/sources.d.ts.map +1 -1
- package/dist/sync/sources.js +117 -32
- package/dist/sync/sources.js.map +1 -1
- package/dist/sync/stream.d.ts.map +1 -1
- package/dist/sync/stream.js +2 -1
- package/dist/sync/stream.js.map +1 -1
- package/dist/sync/withdrawals.d.ts.map +1 -1
- package/dist/sync/withdrawals.js +32 -23
- package/dist/sync/withdrawals.js.map +1 -1
- package/dist/transport/rest.d.ts +19 -9
- package/dist/transport/rest.d.ts.map +1 -1
- package/dist/transport/rest.js +42 -18
- package/dist/transport/rest.js.map +1 -1
- package/dist/transport/ws.d.ts +1 -1
- package/dist/transport/ws.d.ts.map +1 -1
- package/dist/transport/ws.js +5 -4
- package/dist/transport/ws.js.map +1 -1
- package/dist/types/public.d.ts +15 -14
- package/dist/types/public.d.ts.map +1 -1
- package/dist/types/wire.d.ts +14 -10
- package/dist/types/wire.d.ts.map +1 -1
- package/dist/write/delegation.d.ts +7 -0
- package/dist/write/delegation.d.ts.map +1 -1
- package/dist/write/delegation.js +86 -8
- package/dist/write/delegation.js.map +1 -1
- package/dist/write/index.d.ts +2 -3
- package/dist/write/index.d.ts.map +1 -1
- package/dist/write/index.js +9 -12
- package/dist/write/index.js.map +1 -1
- package/package.json +2 -1
- package/src/client.ts +1 -2
- package/src/codec/activity.ts +7 -2
- package/src/codec/decode.ts +3 -12
- package/src/codec/orders-v2.ts +9 -3
- package/src/index.ts +2 -2
- package/src/stores/resource.ts +2 -0
- package/src/sync/activity.ts +7 -3
- package/src/sync/candles.ts +12 -8
- package/src/sync/orders.ts +14 -14
- package/src/sync/pnl-history.ts +1 -1
- package/src/sync/sources.ts +112 -30
- package/src/sync/stream.ts +2 -1
- package/src/sync/withdrawals.ts +35 -25
- package/src/transport/rest.ts +40 -19
- package/src/transport/ws.ts +8 -6
- package/src/types/public.ts +15 -14
- package/src/types/wire.ts +15 -10
- package/src/write/delegation.ts +82 -8
- package/src/write/index.ts +15 -23
package/src/transport/ws.ts
CHANGED
|
@@ -122,9 +122,11 @@ export class PodSubscriptionClosedError extends Error {
|
|
|
122
122
|
}
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
const resolve = (p: SubParams | (() => SubParams)): SubParams => (typeof p === "function" ? p() : p);
|
|
126
|
+
|
|
125
127
|
interface LogicalSub {
|
|
126
128
|
channel: Channel;
|
|
127
|
-
params: SubParams;
|
|
129
|
+
params: SubParams | (() => SubParams);
|
|
128
130
|
onMessage: (result: unknown) => void;
|
|
129
131
|
/**
|
|
130
132
|
* `eth_subscribe` was rejected (e.g. `since` too old), or the server closed a
|
|
@@ -201,17 +203,17 @@ export class PodWsClient {
|
|
|
201
203
|
|
|
202
204
|
subscribe(
|
|
203
205
|
channel: Channel,
|
|
204
|
-
params: SubParams,
|
|
206
|
+
params: SubParams | (() => SubParams),
|
|
205
207
|
onMessage: (result: unknown) => void,
|
|
206
208
|
onError?: (err: unknown) => void,
|
|
207
209
|
): Subscription {
|
|
208
|
-
const sub: LogicalSub = { channel, params: { ...params }, onMessage, onError };
|
|
210
|
+
const sub: LogicalSub = { channel, params: typeof params === "function" ? params : { ...params }, onMessage, onError };
|
|
209
211
|
this.subs.add(sub);
|
|
210
212
|
this.connect();
|
|
211
213
|
if (this._state === "open") this.sendSubscribe(sub);
|
|
212
214
|
return {
|
|
213
215
|
unsubscribe: () => this.removeSub(sub),
|
|
214
|
-
update: (p) => { sub.params = { ...sub.params, ...p }; },
|
|
216
|
+
update: (p) => { sub.params = { ...resolve(sub.params), ...p }; },
|
|
215
217
|
resubscribe: () => {
|
|
216
218
|
if (this._state !== "open") return;
|
|
217
219
|
if (sub.subId) { this.bySubId.delete(sub.subId); sub.subId = undefined; }
|
|
@@ -293,7 +295,7 @@ export class PodWsClient {
|
|
|
293
295
|
}
|
|
294
296
|
|
|
295
297
|
private sendSubscribe(sub: LogicalSub): void {
|
|
296
|
-
this.send("eth_subscribe", [sub.channel, this.wireParams(sub.params)], (result, error) => {
|
|
298
|
+
this.send("eth_subscribe", [sub.channel, this.wireParams(resolve(sub.params))], (result, error) => {
|
|
297
299
|
if (error || typeof result !== "string") {
|
|
298
300
|
const err = error ?? new Error("eth_subscribe failed");
|
|
299
301
|
if (sub.onError) sub.onError(err); // owner can re-seed + resubscribe (e.g. `since` too old)
|
|
@@ -346,7 +348,7 @@ export class PodWsClient {
|
|
|
346
348
|
// batch landed whole, so the stored book must be cleared rather than
|
|
347
349
|
// carried over: it belongs to an older batch, and leaving it would
|
|
348
350
|
// ask the server to skip books inside the new one.
|
|
349
|
-
sub.params = { ...sub.params, since: closed.resumeSince, sinceBook: closed.resumeSinceBook };
|
|
351
|
+
sub.params = { ...resolve(sub.params), since: closed.resumeSince, sinceBook: closed.resumeSinceBook };
|
|
350
352
|
}
|
|
351
353
|
if (sub.onError) sub.onError(closed);
|
|
352
354
|
else this.emit("error", closed);
|
package/src/types/public.ts
CHANGED
|
@@ -113,6 +113,11 @@ export interface OrderEventFill extends PartialFill {
|
|
|
113
113
|
closedAs?: TerminalStatus;
|
|
114
114
|
/** This fill's fee; absent on activity rows stored before it was recorded. */
|
|
115
115
|
fee?: bigint;
|
|
116
|
+
/** PnL realized by this fill alone (signed); absent when it closed nothing. */
|
|
117
|
+
realizedPnl?: bigint;
|
|
118
|
+
/** The owner's position in this market before and after this fill (signed). Perp only. */
|
|
119
|
+
positionBefore?: bigint;
|
|
120
|
+
positionAfter?: bigint;
|
|
116
121
|
}
|
|
117
122
|
|
|
118
123
|
/**
|
|
@@ -299,25 +304,16 @@ export interface Order {
|
|
|
299
304
|
triggerType?: TriggerType;
|
|
300
305
|
/**
|
|
301
306
|
* Realized PnL across the slices this order's fills closed (signed, 1e18 USD). Absent on
|
|
302
|
-
* spot
|
|
303
|
-
* does not carry it for; a REST row the stream later updates keeps the value it was fetched with.
|
|
307
|
+
* spot and on orders that never closed exposure. Set by REST rows and summed from streamed fills.
|
|
304
308
|
*/
|
|
305
309
|
realizedPnl?: bigint;
|
|
306
310
|
}
|
|
307
311
|
|
|
308
312
|
export type Position = SpotPosition | PerpPosition;
|
|
309
313
|
|
|
310
|
-
|
|
314
|
+
/** A spot holding as an entry of {@link PositionsSnapshot.positions}. */
|
|
315
|
+
export interface SpotPosition extends SpotHolding {
|
|
311
316
|
kind: "spot";
|
|
312
|
-
orderbookId?: MarketId;
|
|
313
|
-
token: Address;
|
|
314
|
-
balance: bigint;
|
|
315
|
-
freeBalance: bigint;
|
|
316
|
-
lockedBalance: bigint;
|
|
317
|
-
costBasis: bigint;
|
|
318
|
-
markPrice: bigint;
|
|
319
|
-
unrealizedPnl: bigint;
|
|
320
|
-
realizedPnl: bigint;
|
|
321
317
|
}
|
|
322
318
|
|
|
323
319
|
export interface PerpPosition {
|
|
@@ -352,6 +348,8 @@ export interface PositionsSnapshot {
|
|
|
352
348
|
cash: bigint;
|
|
353
349
|
withdrawableCash: bigint;
|
|
354
350
|
maintenanceMargin?: bigint;
|
|
351
|
+
/** Deadline (µs) of the last tick the answering node executed. */
|
|
352
|
+
timestampUs?: number;
|
|
355
353
|
}
|
|
356
354
|
|
|
357
355
|
export interface Trigger {
|
|
@@ -436,8 +434,7 @@ export interface TxExplorer {
|
|
|
436
434
|
[k: string]: unknown;
|
|
437
435
|
}
|
|
438
436
|
|
|
439
|
-
/** A spot token holding (`/clob/balances`).
|
|
440
|
-
* market + symbols rather than token address. */
|
|
437
|
+
/** A spot token holding for one market (`/clob/balances`). */
|
|
441
438
|
export interface SpotHolding {
|
|
442
439
|
orderbookId: MarketId;
|
|
443
440
|
baseSymbol: string;
|
|
@@ -458,6 +455,8 @@ export interface Balances {
|
|
|
458
455
|
cash: bigint;
|
|
459
456
|
withdrawableCash: bigint;
|
|
460
457
|
netDeposits: bigint;
|
|
458
|
+
/** Deadline (µs) of the last tick the answering node executed. */
|
|
459
|
+
timestampUs?: number;
|
|
461
460
|
}
|
|
462
461
|
|
|
463
462
|
// --- query / paging types ---
|
|
@@ -494,6 +493,8 @@ export type ActivityEntry =
|
|
|
494
493
|
totalFee?: bigint;
|
|
495
494
|
/** This fill's fee; absent on rows stored before it was recorded. */
|
|
496
495
|
fee?: bigint;
|
|
496
|
+
/** PnL realized by this fill alone (signed); absent when it closed nothing. */
|
|
497
|
+
realizedPnl?: bigint;
|
|
497
498
|
closedAs?: TerminalStatus;
|
|
498
499
|
/** Perp only; signed. */
|
|
499
500
|
positionAfter?: bigint;
|
package/src/types/wire.ts
CHANGED
|
@@ -58,6 +58,7 @@ export interface WireMarketDynamics {
|
|
|
58
58
|
/** pod_markets push uses `orderbook` instead of `orderbook_id`. */
|
|
59
59
|
export interface WireMarketDynamicsPush extends Omit<WireMarketDynamics, "orderbook_id"> {
|
|
60
60
|
orderbook: Hex;
|
|
61
|
+
timestamp?: number;
|
|
61
62
|
}
|
|
62
63
|
|
|
63
64
|
export interface WireMarketStatsPage {
|
|
@@ -149,17 +150,8 @@ export interface WireOrderbook {
|
|
|
149
150
|
funding_last_updated?: number | null;
|
|
150
151
|
}
|
|
151
152
|
|
|
152
|
-
export interface WireSpotPosition {
|
|
153
|
+
export interface WireSpotPosition extends WireSpotHolding {
|
|
153
154
|
kind: "spot";
|
|
154
|
-
orderbook_id?: Hex;
|
|
155
|
-
token: Hex;
|
|
156
|
-
balance: WireDecimal;
|
|
157
|
-
free_balance: WireDecimal;
|
|
158
|
-
locked_balance: WireDecimal;
|
|
159
|
-
cost_basis: WireDecimal;
|
|
160
|
-
mark_price: WireDecimal;
|
|
161
|
-
unrealized_pnl: WireDecimal;
|
|
162
|
-
realized_pnl: WireDecimal;
|
|
163
155
|
}
|
|
164
156
|
|
|
165
157
|
export interface WirePerpPosition {
|
|
@@ -193,6 +185,8 @@ export interface WirePositionsSnapshot {
|
|
|
193
185
|
account_value: WireDecimal;
|
|
194
186
|
cash: WireDecimal;
|
|
195
187
|
withdrawable_cash: WireDecimal;
|
|
188
|
+
net_deposits: WireDecimal;
|
|
189
|
+
timestamp?: number;
|
|
196
190
|
}
|
|
197
191
|
|
|
198
192
|
export interface WireSpotHolding {
|
|
@@ -213,6 +207,7 @@ export interface WireBalances {
|
|
|
213
207
|
cash: WireDecimal;
|
|
214
208
|
withdrawable_cash: WireDecimal;
|
|
215
209
|
net_deposits: WireDecimal;
|
|
210
|
+
timestamp?: number;
|
|
216
211
|
}
|
|
217
212
|
|
|
218
213
|
export interface WireTrigger {
|
|
@@ -235,6 +230,7 @@ export interface WireTriggersPage {
|
|
|
235
230
|
triggers: WireTrigger[];
|
|
236
231
|
total_count: number;
|
|
237
232
|
next_cursor: string | null;
|
|
233
|
+
timestamp?: number;
|
|
238
234
|
}
|
|
239
235
|
|
|
240
236
|
export interface WireBackstopTransfer {
|
|
@@ -367,6 +363,8 @@ export interface WireOrderEvent {
|
|
|
367
363
|
* or flipped the position.
|
|
368
364
|
*/
|
|
369
365
|
pa?: WireDecimal;
|
|
366
|
+
/** `fill`: PnL realized by this fill alone, signed and 1e18-scaled; absent when it closed nothing. */
|
|
367
|
+
pnl?: WireDecimal;
|
|
370
368
|
/** `modify`: the price after the change. */
|
|
371
369
|
px?: WireDecimal;
|
|
372
370
|
/** `modify`: the size after the change, as an **unsigned magnitude**. */
|
|
@@ -383,6 +381,7 @@ export interface WireTriggersPush {
|
|
|
383
381
|
triggers: WireTrigger[];
|
|
384
382
|
total_count: number;
|
|
385
383
|
next_cursor: string | null;
|
|
384
|
+
timestamp?: number;
|
|
386
385
|
}
|
|
387
386
|
|
|
388
387
|
// --- bridge / withdrawals (ADR 0033) ---
|
|
@@ -418,6 +417,11 @@ export interface WireWithdrawal {
|
|
|
418
417
|
timestamp_us: number;
|
|
419
418
|
}
|
|
420
419
|
|
|
420
|
+
export interface WireWithdrawalsPage {
|
|
421
|
+
withdrawals: WireWithdrawal[];
|
|
422
|
+
timestamp: number; // micros, newest tick whose outcomes the answering node can serve
|
|
423
|
+
}
|
|
424
|
+
|
|
421
425
|
/** `GET /v1/bridge/withdrawals/by-id/{id}`. Nested rather than flattened because
|
|
422
426
|
* `WithdrawalUpdate` carries a u128 and serde's `flatten` cannot round-trip one.
|
|
423
427
|
*
|
|
@@ -484,6 +488,7 @@ export type WireActivityEntry =
|
|
|
484
488
|
f?: WireDecimal;
|
|
485
489
|
st?: WireTerminalStatus;
|
|
486
490
|
pa?: WireDecimal;
|
|
491
|
+
pnl?: WireDecimal;
|
|
487
492
|
}
|
|
488
493
|
| { k: "modify"; id: Hex; book: Hex; px: WireDecimal; sz: WireDecimal; old_px: WireDecimal; old_sz: WireDecimal }
|
|
489
494
|
| {
|
package/src/write/delegation.ts
CHANGED
|
@@ -10,11 +10,15 @@
|
|
|
10
10
|
// DelegatedWallet exposes is submit(); "logging out" is dropping the object.
|
|
11
11
|
// Keep it that way.
|
|
12
12
|
|
|
13
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
BaseError, RpcRequestError, createWalletClient, defineChain, encodeFunctionData, http, keccak256, parseAbi, recoverTypedDataAddress,
|
|
15
|
+
} from "viem";
|
|
14
16
|
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
|
|
15
17
|
import type { Address, Hash, Hex } from "../types/public.js";
|
|
16
|
-
import { rpc } from "../transport/jsonrpc.js";
|
|
17
|
-
import {
|
|
18
|
+
import { PodRpcError, rpc } from "../transport/jsonrpc.js";
|
|
19
|
+
import {
|
|
20
|
+
CLOB_ADDRESS, PodTxRevertError, sendRawTransaction, waitForReceipt, type PodTxRequest,
|
|
21
|
+
} from "./index.js";
|
|
18
22
|
|
|
19
23
|
/** EIP-712 payload the master signs (domain "pod delegation" v1). */
|
|
20
24
|
export function delegationTypedData(delegate: Address, validUntil: bigint, chainId: number) {
|
|
@@ -35,6 +39,21 @@ const DELEGATED_ABI = parseAbi([
|
|
|
35
39
|
"function delegated(address master, uint64 validUntil, bytes signature, bytes inner)",
|
|
36
40
|
]);
|
|
37
41
|
|
|
42
|
+
// Past nonce, future nonce or account pending: a pre-validation rejection that a fresh nonce can fix.
|
|
43
|
+
const RETRYABLE_REJECTION_CODE = 996;
|
|
44
|
+
const SUBMIT_RETRY_MS = 250;
|
|
45
|
+
const SUBMIT_GIVE_UP_MS = 10_000;
|
|
46
|
+
// A node that never attests holds a send for its whole wait; the rest of the budget is for the receipt poll.
|
|
47
|
+
const SEND_ATTEMPT_MS = SUBMIT_GIVE_UP_MS / 2;
|
|
48
|
+
|
|
49
|
+
/** `submit` could not tell whether its transaction reached the chain. */
|
|
50
|
+
export class PodDeliveryUnknownError extends Error {
|
|
51
|
+
constructor(readonly txHash: Hash, options?: { cause?: unknown }) {
|
|
52
|
+
super(`submit: delivery unknown for ${txHash} after ${SUBMIT_GIVE_UP_MS / 1000}s`, options);
|
|
53
|
+
this.name = "PodDeliveryUnknownError";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
38
57
|
/** A trading session: public cert facts + the one capability, submit(). */
|
|
39
58
|
export interface DelegatedWallet {
|
|
40
59
|
readonly master: Address;
|
|
@@ -79,10 +98,18 @@ export async function createDelegatedWallet(p: CreateDelegatedWalletParams): Pro
|
|
|
79
98
|
nativeCurrency: { name: "pETH", symbol: "pETH", decimals: 18 },
|
|
80
99
|
rpcUrls: { default: { http: [p.rpcUrl] } },
|
|
81
100
|
});
|
|
82
|
-
const client = createWalletClient({ account, chain, transport: http(p.rpcUrl) });
|
|
101
|
+
const client = createWalletClient({ account, chain, transport: http(p.rpcUrl, { fetchFn: p.fetch }) });
|
|
83
102
|
const doFetch = p.fetch ?? fetch;
|
|
84
103
|
|
|
85
104
|
const submit = async (tx: PodTxRequest): Promise<Hash> => {
|
|
105
|
+
const giveUpAt = Date.now() + SUBMIT_GIVE_UP_MS;
|
|
106
|
+
const inBudget = <T>(work: Promise<T>): Promise<T> => {
|
|
107
|
+
let stall: ReturnType<typeof setTimeout> | undefined;
|
|
108
|
+
const outOfTime = new Promise<never>((_, reject) => {
|
|
109
|
+
stall = setTimeout(() => reject(new Error("out of time")), Math.max(0, giveUpAt - Date.now()));
|
|
110
|
+
});
|
|
111
|
+
return Promise.race([work, outOfTime]).finally(() => clearTimeout(stall));
|
|
112
|
+
};
|
|
86
113
|
if (tx.to.toLowerCase() !== CLOB_ADDRESS) {
|
|
87
114
|
throw new Error(`delegation covers CLOB calls only, not ${tx.to} — sign this with the master wallet`);
|
|
88
115
|
}
|
|
@@ -96,10 +123,57 @@ export async function createDelegatedWallet(p: CreateDelegatedWalletParams): Pro
|
|
|
96
123
|
functionName: "delegated",
|
|
97
124
|
args: [p.master, validUntil, signature, tx.data],
|
|
98
125
|
});
|
|
99
|
-
const
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
126
|
+
const sign = async () => {
|
|
127
|
+
const maxFeePerGas = BigInt(await rpc<string>(p.rpcUrl, "eth_gasPrice", [], { fetch: doFetch }));
|
|
128
|
+
const prepared = await client.prepareTransactionRequest({ ...tx, data, account, chain, maxFeePerGas });
|
|
129
|
+
return client.signTransaction(prepared as never);
|
|
130
|
+
};
|
|
131
|
+
let serialized: Hex | undefined;
|
|
132
|
+
// Set once an attempt may have reached a node; from then on the bytes are never re-signed.
|
|
133
|
+
let maybeDelivered: Hash | undefined;
|
|
134
|
+
let err: unknown;
|
|
135
|
+
for (let attempt = 0; ; attempt++) {
|
|
136
|
+
let sending = false;
|
|
137
|
+
try {
|
|
138
|
+
serialized ??= await inBudget(sign());
|
|
139
|
+
sending = true;
|
|
140
|
+
// Not AbortSignal.timeout: its clock is not the one setTimeout runs on, which fake timers replace.
|
|
141
|
+
const ctl = new AbortController();
|
|
142
|
+
const stall = setTimeout(() => ctl.abort(), Math.max(1, Math.min(SEND_ATTEMPT_MS, giveUpAt - Date.now())));
|
|
143
|
+
try {
|
|
144
|
+
return await sendRawTransaction(p.rpcUrl, serialized, { fetch: doFetch, signal: ctl.signal });
|
|
145
|
+
} finally {
|
|
146
|
+
clearTimeout(stall);
|
|
147
|
+
}
|
|
148
|
+
} catch (e) {
|
|
149
|
+
err = e;
|
|
150
|
+
}
|
|
151
|
+
if (!sending && (err instanceof PodRpcError
|
|
152
|
+
|| (err instanceof BaseError && err.walk((c) => c instanceof RpcRequestError) !== null))) throw err;
|
|
153
|
+
if (err instanceof PodTxRevertError) {
|
|
154
|
+
if (err.code !== RETRYABLE_REJECTION_CODE) throw err;
|
|
155
|
+
if (maybeDelivered) break;
|
|
156
|
+
// Rejected by the node's pre-validation, so nothing was broadcast.
|
|
157
|
+
serialized = undefined;
|
|
158
|
+
} else if (sending) {
|
|
159
|
+
maybeDelivered = keccak256(serialized!);
|
|
160
|
+
}
|
|
161
|
+
const backoff = Math.min(1_000, SUBMIT_RETRY_MS * 2 ** attempt);
|
|
162
|
+
if (Date.now() + backoff > giveUpAt) {
|
|
163
|
+
if (maybeDelivered) break;
|
|
164
|
+
throw new Error(`submit gave up after ${SUBMIT_GIVE_UP_MS / 1000}s: ${(err as Error).message}`, { cause: err });
|
|
165
|
+
}
|
|
166
|
+
await new Promise((r) => setTimeout(r, backoff));
|
|
167
|
+
}
|
|
168
|
+
const hash = maybeDelivered;
|
|
169
|
+
try {
|
|
170
|
+
await inBudget(waitForReceipt(p.rpcUrl, hash, {
|
|
171
|
+
fetch: doFetch, pollMs: SUBMIT_RETRY_MS, timeoutMs: Math.max(0, giveUpAt - Date.now()),
|
|
172
|
+
}));
|
|
173
|
+
return hash;
|
|
174
|
+
} catch {
|
|
175
|
+
throw new PodDeliveryUnknownError(hash, { cause: err });
|
|
176
|
+
}
|
|
103
177
|
};
|
|
104
178
|
|
|
105
179
|
return Object.freeze({ master: p.master, delegate: account.address, validUntil, submit });
|
package/src/write/index.ts
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
import { decodeAbiParameters, encodeAbiParameters, encodeFunctionData, keccak256, parseAbi } from "viem";
|
|
14
14
|
import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
|
|
15
15
|
import type { Address, Hash, Hex, MarketId } from "../types/public.js";
|
|
16
|
-
import { rpc } from "../transport/jsonrpc.js";
|
|
16
|
+
import { rpc, tryRpc } from "../transport/jsonrpc.js";
|
|
17
17
|
// In codec/ so the read entry reaches it too; re-exported so all three align* are here.
|
|
18
18
|
import { alignSize } from "../codec/units.js";
|
|
19
19
|
|
|
@@ -195,20 +195,22 @@ export function decodeRevertReason(data: unknown): string | undefined {
|
|
|
195
195
|
export async function sendRawTransaction(
|
|
196
196
|
rpcUrl: string,
|
|
197
197
|
signedTx: Hex,
|
|
198
|
-
opts?: { fetch?: typeof fetch },
|
|
198
|
+
opts?: { fetch?: typeof fetch; signal?: AbortSignal },
|
|
199
199
|
): Promise<Hash> {
|
|
200
200
|
const doFetch = opts?.fetch ?? fetch;
|
|
201
201
|
const res = await doFetch(rpcUrl, {
|
|
202
202
|
method: "POST",
|
|
203
203
|
headers: { "content-type": "application/json" },
|
|
204
204
|
body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_sendRawTransaction", params: [signedTx] }),
|
|
205
|
+
signal: opts?.signal,
|
|
205
206
|
});
|
|
206
207
|
const json = (await res.json()) as { result?: Hash; error?: { code?: number; message?: string; data?: unknown } };
|
|
207
208
|
if (json.error) {
|
|
208
209
|
const reason = decodeRevertReason(json.error.data) ?? json.error.message ?? "transaction failed";
|
|
209
210
|
throw new PodTxRevertError(reason, json.error.data, json.error.code);
|
|
210
211
|
}
|
|
211
|
-
|
|
212
|
+
if (!res.ok || !json.result) throw new Error(`eth_sendRawTransaction: HTTP ${res.status}, no result`);
|
|
213
|
+
return json.result;
|
|
212
214
|
}
|
|
213
215
|
|
|
214
216
|
export interface UpdateOrderParams {
|
|
@@ -579,25 +581,16 @@ export async function waitForReceipt(
|
|
|
579
581
|
hash: Hash,
|
|
580
582
|
opts?: { fetch?: typeof fetch; timeoutMs?: number; pollMs?: number },
|
|
581
583
|
): Promise<TxReceipt> {
|
|
582
|
-
const doFetch = opts?.fetch ?? fetch;
|
|
583
584
|
const timeoutMs = opts?.timeoutMs ?? 30_000;
|
|
584
585
|
const pollMs = opts?.pollMs ?? 250;
|
|
585
586
|
const deadline = Date.now() + timeoutMs;
|
|
586
587
|
for (;;) {
|
|
587
|
-
const
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
result?: {
|
|
594
|
-
status: string;
|
|
595
|
-
transactionHash: Hash;
|
|
596
|
-
blockNumber?: string | null;
|
|
597
|
-
gasUsed: string;
|
|
598
|
-
} | null;
|
|
599
|
-
};
|
|
600
|
-
const r = json.result;
|
|
588
|
+
const r = await tryRpc<{
|
|
589
|
+
status: string;
|
|
590
|
+
transactionHash: Hash;
|
|
591
|
+
blockNumber?: string | null;
|
|
592
|
+
gasUsed: string;
|
|
593
|
+
} | null>(rpcUrl, "eth_getTransactionReceipt", [hash], { fetch: opts?.fetch });
|
|
601
594
|
if (r) {
|
|
602
595
|
return {
|
|
603
596
|
status: r.status === "0x1" ? "success" : "reverted",
|
|
@@ -624,7 +617,7 @@ export const MINT_ADDRESS: Address = "0x00000000000000000000000000000000000fFFFf
|
|
|
624
617
|
export const NATIVE_USD_ADDRESS: Address = "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE";
|
|
625
618
|
|
|
626
619
|
const MINT_ABI = parseAbi([
|
|
627
|
-
"function mint(address to, (address token, uint256 amount)[] tokens,
|
|
620
|
+
"function mint(address to, (address token, uint256 amount)[] tokens, uint128 deadline)",
|
|
628
621
|
]);
|
|
629
622
|
|
|
630
623
|
export interface MintParams {
|
|
@@ -634,8 +627,6 @@ export interface MintParams {
|
|
|
634
627
|
to: Address;
|
|
635
628
|
/** 1e18-scaled amounts; `token` defaults to the native USD (cash) token. */
|
|
636
629
|
tokens: Array<{ token?: Address; amount: bigint }>;
|
|
637
|
-
/** Deposit into the CLOB balance (default) instead of crediting the EOA. */
|
|
638
|
-
depositToClob?: boolean;
|
|
639
630
|
/** Called with the tx hash once the node accepts it (before confirmation). */
|
|
640
631
|
onSubmitted?: (hash: Hash) => void;
|
|
641
632
|
fetch?: typeof fetch;
|
|
@@ -655,7 +646,8 @@ export async function mint(p: MintParams): Promise<TxReceipt> {
|
|
|
655
646
|
args: [
|
|
656
647
|
p.to,
|
|
657
648
|
p.tokens.map((t) => ({ token: t.token ?? NATIVE_USD_ADDRESS, amount: t.amount })),
|
|
658
|
-
|
|
649
|
+
// Only bounds how long the node holds the intent; it executes in the first batch after it finalizes.
|
|
650
|
+
BigInt(Date.now() + 60_000) * 1000n,
|
|
659
651
|
],
|
|
660
652
|
});
|
|
661
653
|
const serialized = await signer.signTransaction({
|
|
@@ -835,6 +827,6 @@ export function deriveOrderId(signer: Address, nonce: number, sequence = 0): Has
|
|
|
835
827
|
}
|
|
836
828
|
|
|
837
829
|
export {
|
|
838
|
-
createDelegatedWallet, delegationTypedData,
|
|
830
|
+
createDelegatedWallet, delegationTypedData, PodDeliveryUnknownError,
|
|
839
831
|
type CreateDelegatedWalletParams, type DelegatedWallet, type DelegationTypedData,
|
|
840
832
|
} from "./delegation.js";
|