@pod-network/trade-sdk 0.14.0 → 0.16.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 +4 -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 +7 -1
- 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 +16 -12
- package/dist/types/public.d.ts.map +1 -1
- package/dist/types/wire.d.ts +15 -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 +4 -12
- package/src/codec/orders-v2.ts +6 -1
- 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 +16 -12
- package/src/types/wire.ts +16 -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,8 @@ 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;
|
|
116
118
|
}
|
|
117
119
|
|
|
118
120
|
/**
|
|
@@ -297,21 +299,18 @@ export interface Order {
|
|
|
297
299
|
ioc?: boolean;
|
|
298
300
|
direction?: OrderDirection;
|
|
299
301
|
triggerType?: TriggerType;
|
|
302
|
+
/**
|
|
303
|
+
* Realized PnL across the slices this order's fills closed (signed, 1e18 USD). Absent on
|
|
304
|
+
* spot and on orders that never closed exposure. Set by REST rows and summed from streamed fills.
|
|
305
|
+
*/
|
|
306
|
+
realizedPnl?: bigint;
|
|
300
307
|
}
|
|
301
308
|
|
|
302
309
|
export type Position = SpotPosition | PerpPosition;
|
|
303
310
|
|
|
304
|
-
|
|
311
|
+
/** A spot holding as an entry of {@link PositionsSnapshot.positions}. */
|
|
312
|
+
export interface SpotPosition extends SpotHolding {
|
|
305
313
|
kind: "spot";
|
|
306
|
-
orderbookId?: MarketId;
|
|
307
|
-
token: Address;
|
|
308
|
-
balance: bigint;
|
|
309
|
-
freeBalance: bigint;
|
|
310
|
-
lockedBalance: bigint;
|
|
311
|
-
costBasis: bigint;
|
|
312
|
-
markPrice: bigint;
|
|
313
|
-
unrealizedPnl: bigint;
|
|
314
|
-
realizedPnl: bigint;
|
|
315
314
|
}
|
|
316
315
|
|
|
317
316
|
export interface PerpPosition {
|
|
@@ -346,6 +345,8 @@ export interface PositionsSnapshot {
|
|
|
346
345
|
cash: bigint;
|
|
347
346
|
withdrawableCash: bigint;
|
|
348
347
|
maintenanceMargin?: bigint;
|
|
348
|
+
/** Deadline (µs) of the last tick the answering node executed. */
|
|
349
|
+
timestampUs?: number;
|
|
349
350
|
}
|
|
350
351
|
|
|
351
352
|
export interface Trigger {
|
|
@@ -430,8 +431,7 @@ export interface TxExplorer {
|
|
|
430
431
|
[k: string]: unknown;
|
|
431
432
|
}
|
|
432
433
|
|
|
433
|
-
/** A spot token holding (`/clob/balances`).
|
|
434
|
-
* market + symbols rather than token address. */
|
|
434
|
+
/** A spot token holding for one market (`/clob/balances`). */
|
|
435
435
|
export interface SpotHolding {
|
|
436
436
|
orderbookId: MarketId;
|
|
437
437
|
baseSymbol: string;
|
|
@@ -452,6 +452,8 @@ export interface Balances {
|
|
|
452
452
|
cash: bigint;
|
|
453
453
|
withdrawableCash: bigint;
|
|
454
454
|
netDeposits: bigint;
|
|
455
|
+
/** Deadline (µs) of the last tick the answering node executed. */
|
|
456
|
+
timestampUs?: number;
|
|
455
457
|
}
|
|
456
458
|
|
|
457
459
|
// --- query / paging types ---
|
|
@@ -488,6 +490,8 @@ export type ActivityEntry =
|
|
|
488
490
|
totalFee?: bigint;
|
|
489
491
|
/** This fill's fee; absent on rows stored before it was recorded. */
|
|
490
492
|
fee?: bigint;
|
|
493
|
+
/** PnL realized by this fill alone (signed); absent when it closed nothing. */
|
|
494
|
+
realizedPnl?: bigint;
|
|
491
495
|
closedAs?: TerminalStatus;
|
|
492
496
|
/** Perp only; signed. */
|
|
493
497
|
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 {
|
|
@@ -115,6 +116,7 @@ export interface WireOrder {
|
|
|
115
116
|
reduce_only?: boolean;
|
|
116
117
|
ioc?: boolean;
|
|
117
118
|
direction?: string;
|
|
119
|
+
realized_pnl?: WireDecimal; // signed, perp only
|
|
118
120
|
grouping?: WireDecimal;
|
|
119
121
|
trigger_type?: string | null;
|
|
120
122
|
invalid_reason?: string;
|
|
@@ -148,17 +150,8 @@ export interface WireOrderbook {
|
|
|
148
150
|
funding_last_updated?: number | null;
|
|
149
151
|
}
|
|
150
152
|
|
|
151
|
-
export interface WireSpotPosition {
|
|
153
|
+
export interface WireSpotPosition extends WireSpotHolding {
|
|
152
154
|
kind: "spot";
|
|
153
|
-
orderbook_id?: Hex;
|
|
154
|
-
token: Hex;
|
|
155
|
-
balance: WireDecimal;
|
|
156
|
-
free_balance: WireDecimal;
|
|
157
|
-
locked_balance: WireDecimal;
|
|
158
|
-
cost_basis: WireDecimal;
|
|
159
|
-
mark_price: WireDecimal;
|
|
160
|
-
unrealized_pnl: WireDecimal;
|
|
161
|
-
realized_pnl: WireDecimal;
|
|
162
155
|
}
|
|
163
156
|
|
|
164
157
|
export interface WirePerpPosition {
|
|
@@ -192,6 +185,8 @@ export interface WirePositionsSnapshot {
|
|
|
192
185
|
account_value: WireDecimal;
|
|
193
186
|
cash: WireDecimal;
|
|
194
187
|
withdrawable_cash: WireDecimal;
|
|
188
|
+
net_deposits: WireDecimal;
|
|
189
|
+
timestamp?: number;
|
|
195
190
|
}
|
|
196
191
|
|
|
197
192
|
export interface WireSpotHolding {
|
|
@@ -212,6 +207,7 @@ export interface WireBalances {
|
|
|
212
207
|
cash: WireDecimal;
|
|
213
208
|
withdrawable_cash: WireDecimal;
|
|
214
209
|
net_deposits: WireDecimal;
|
|
210
|
+
timestamp?: number;
|
|
215
211
|
}
|
|
216
212
|
|
|
217
213
|
export interface WireTrigger {
|
|
@@ -234,6 +230,7 @@ export interface WireTriggersPage {
|
|
|
234
230
|
triggers: WireTrigger[];
|
|
235
231
|
total_count: number;
|
|
236
232
|
next_cursor: string | null;
|
|
233
|
+
timestamp?: number;
|
|
237
234
|
}
|
|
238
235
|
|
|
239
236
|
export interface WireBackstopTransfer {
|
|
@@ -366,6 +363,8 @@ export interface WireOrderEvent {
|
|
|
366
363
|
* or flipped the position.
|
|
367
364
|
*/
|
|
368
365
|
pa?: WireDecimal;
|
|
366
|
+
/** `fill`: PnL realized by this fill alone, signed and 1e18-scaled; absent when it closed nothing. */
|
|
367
|
+
pnl?: WireDecimal;
|
|
369
368
|
/** `modify`: the price after the change. */
|
|
370
369
|
px?: WireDecimal;
|
|
371
370
|
/** `modify`: the size after the change, as an **unsigned magnitude**. */
|
|
@@ -382,6 +381,7 @@ export interface WireTriggersPush {
|
|
|
382
381
|
triggers: WireTrigger[];
|
|
383
382
|
total_count: number;
|
|
384
383
|
next_cursor: string | null;
|
|
384
|
+
timestamp?: number;
|
|
385
385
|
}
|
|
386
386
|
|
|
387
387
|
// --- bridge / withdrawals (ADR 0033) ---
|
|
@@ -417,6 +417,11 @@ export interface WireWithdrawal {
|
|
|
417
417
|
timestamp_us: number;
|
|
418
418
|
}
|
|
419
419
|
|
|
420
|
+
export interface WireWithdrawalsPage {
|
|
421
|
+
withdrawals: WireWithdrawal[];
|
|
422
|
+
timestamp: number; // micros, newest tick whose outcomes the answering node can serve
|
|
423
|
+
}
|
|
424
|
+
|
|
420
425
|
/** `GET /v1/bridge/withdrawals/by-id/{id}`. Nested rather than flattened because
|
|
421
426
|
* `WithdrawalUpdate` carries a u128 and serde's `flatten` cannot round-trip one.
|
|
422
427
|
*
|
|
@@ -483,6 +488,7 @@ export type WireActivityEntry =
|
|
|
483
488
|
f?: WireDecimal;
|
|
484
489
|
st?: WireTerminalStatus;
|
|
485
490
|
pa?: WireDecimal;
|
|
491
|
+
pnl?: WireDecimal;
|
|
486
492
|
}
|
|
487
493
|
| { k: "modify"; id: Hex; book: Hex; px: WireDecimal; sz: WireDecimal; old_px: WireDecimal; old_sz: WireDecimal }
|
|
488
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";
|