@pod-network/trade-sdk 0.3.0 → 0.4.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 (70) hide show
  1. package/README.md +94 -2
  2. package/dist/client.d.ts +19 -1
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +24 -1
  5. package/dist/client.js.map +1 -1
  6. package/dist/codec/bridge.d.ts +82 -0
  7. package/dist/codec/bridge.d.ts.map +1 -0
  8. package/dist/codec/bridge.js +114 -0
  9. package/dist/codec/bridge.js.map +1 -0
  10. package/dist/codec/decode.d.ts +15 -2
  11. package/dist/codec/decode.d.ts.map +1 -1
  12. package/dist/codec/decode.js +39 -0
  13. package/dist/codec/decode.js.map +1 -1
  14. package/dist/codec/units.d.ts.map +1 -1
  15. package/dist/codec/units.js +9 -1
  16. package/dist/codec/units.js.map +1 -1
  17. package/dist/index.d.ts +3 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +5 -0
  20. package/dist/index.js.map +1 -1
  21. package/dist/sync/sources.d.ts +5 -1
  22. package/dist/sync/sources.d.ts.map +1 -1
  23. package/dist/sync/sources.js +16 -0
  24. package/dist/sync/sources.js.map +1 -1
  25. package/dist/sync/withdrawals.d.ts +5 -0
  26. package/dist/sync/withdrawals.d.ts.map +1 -0
  27. package/dist/sync/withdrawals.js +172 -0
  28. package/dist/sync/withdrawals.js.map +1 -0
  29. package/dist/transport/claim.d.ts +160 -0
  30. package/dist/transport/claim.d.ts.map +1 -0
  31. package/dist/transport/claim.js +341 -0
  32. package/dist/transport/claim.js.map +1 -0
  33. package/dist/transport/jsonrpc.d.ts +16 -0
  34. package/dist/transport/jsonrpc.d.ts.map +1 -0
  35. package/dist/transport/jsonrpc.js +42 -0
  36. package/dist/transport/jsonrpc.js.map +1 -0
  37. package/dist/transport/rest.d.ts +15 -1
  38. package/dist/transport/rest.d.ts.map +1 -1
  39. package/dist/transport/rest.js +25 -1
  40. package/dist/transport/rest.js.map +1 -1
  41. package/dist/transport/ws.d.ts +4 -1
  42. package/dist/transport/ws.d.ts.map +1 -1
  43. package/dist/transport/ws.js.map +1 -1
  44. package/dist/types/public.d.ts +87 -0
  45. package/dist/types/public.d.ts.map +1 -1
  46. package/dist/types/wire.d.ts +43 -1
  47. package/dist/types/wire.d.ts.map +1 -1
  48. package/dist/write/delegation.d.ts.map +1 -1
  49. package/dist/write/delegation.js +2 -12
  50. package/dist/write/delegation.js.map +1 -1
  51. package/dist/write/index.d.ts +25 -0
  52. package/dist/write/index.d.ts.map +1 -1
  53. package/dist/write/index.js +20 -13
  54. package/dist/write/index.js.map +1 -1
  55. package/package.json +1 -1
  56. package/src/client.ts +32 -4
  57. package/src/codec/bridge.ts +138 -0
  58. package/src/codec/decode.ts +47 -4
  59. package/src/codec/units.ts +8 -1
  60. package/src/index.ts +16 -0
  61. package/src/sync/sources.ts +16 -1
  62. package/src/sync/withdrawals.ts +177 -0
  63. package/src/transport/claim.ts +434 -0
  64. package/src/transport/jsonrpc.ts +54 -0
  65. package/src/transport/rest.ts +35 -7
  66. package/src/transport/ws.ts +4 -1
  67. package/src/types/public.ts +94 -0
  68. package/src/types/wire.ts +47 -1
  69. package/src/write/delegation.ts +2 -12
  70. package/src/write/index.ts +58 -12
package/src/types/wire.ts CHANGED
@@ -126,7 +126,6 @@ export interface WireOrdersPage {
126
126
 
127
127
  export interface WireTickSnapshot {
128
128
  volume: WireDecimal;
129
- minimum_expiry?: number;
130
129
  }
131
130
 
132
131
  export interface WireOrderbook {
@@ -385,3 +384,50 @@ export interface WireTriggersPush {
385
384
  total_count: number;
386
385
  next_cursor: string | null;
387
386
  }
387
+
388
+ // --- bridge / withdrawals (ADR 0033) ---
389
+
390
+ export interface WireBridgeToken {
391
+ pod_token: Hex;
392
+ l1_token: Hex;
393
+ decimals: number;
394
+ /** Hex-encoded U256, in claim-chain decimals. */
395
+ min: string;
396
+ max: string;
397
+ }
398
+
399
+ export interface WireBridgeConfig {
400
+ claim_chain_id: number;
401
+ source_contract: Hex;
402
+ version: number;
403
+ tokens: WireBridgeToken[];
404
+ }
405
+
406
+ /** `pod_withdrawals` delivers an ARRAY of these per tick; the REST backfill
407
+ * serves the identical shape, so a backfilled outcome is indistinguishable
408
+ * from one that arrived live. */
409
+ export interface WireWithdrawal {
410
+ withdrawal_id: Hex;
411
+ withdrawer: Hex;
412
+ to: Hex;
413
+ token: Hex;
414
+ /** Hex-encoded U256 in pod's 18 decimals — the amount as signed. */
415
+ amount: string;
416
+ /** Omitted (not null) when the withdrawal is claimable. */
417
+ error?: string | null;
418
+ timestamp_us: number;
419
+ }
420
+
421
+ /** `GET /v1/bridge/withdrawals/by-id/{id}`. Nested rather than flattened because
422
+ * `WithdrawalUpdate` carries a u128 and serde's `flatten` cannot round-trip one.
423
+ *
424
+ * `status` is always present, but it is NOT what a consumer decides on: `proof`
425
+ * takes precedence, including over a `status` this build has never seen, so an
426
+ * unfamiliar label cannot veto a certificate attached to the same response.
427
+ * `proof` is omitted (never null) until one can be assembled. `fetchClaimStatus`
428
+ * carries the full precedence. */
429
+ export interface WireWithdrawalDetail {
430
+ withdrawal: WireWithdrawal;
431
+ status: "claimable" | "pending" | "refused";
432
+ proof?: { claim_hash?: Hex | null };
433
+ }
@@ -13,6 +13,7 @@
13
13
  import { createWalletClient, defineChain, encodeFunctionData, http, parseAbi, recoverTypedDataAddress } from "viem";
14
14
  import { generatePrivateKey, privateKeyToAccount } from "viem/accounts";
15
15
  import type { Address, Hash, Hex } from "../types/public.js";
16
+ import { rpc } from "../transport/jsonrpc.js";
16
17
  import { sendRawTransaction, type PodTxRequest } from "./index.js";
17
18
 
18
19
  /** EIP-712 payload the master signs (domain "pod delegation" v1). */
@@ -92,7 +93,7 @@ export async function createDelegatedWallet(p: CreateDelegatedWalletParams): Pro
92
93
  functionName: "delegated",
93
94
  args: [p.master, validUntil, signature, tx.data],
94
95
  });
95
- const maxFeePerGas = BigInt(await rpc(p.rpcUrl, doFetch, "eth_gasPrice"));
96
+ const maxFeePerGas = BigInt(await rpc<string>(p.rpcUrl, "eth_gasPrice", [], { fetch: doFetch }));
96
97
  const prepared = await client.prepareTransactionRequest({ ...tx, data, account, chain, maxFeePerGas });
97
98
  const serialized = await client.signTransaction(prepared as never);
98
99
  return sendRawTransaction(p.rpcUrl, serialized, { fetch: doFetch });
@@ -100,14 +101,3 @@ export async function createDelegatedWallet(p: CreateDelegatedWalletParams): Pro
100
101
 
101
102
  return Object.freeze({ master: p.master, delegate: account.address, validUntil, submit });
102
103
  }
103
-
104
- async function rpc(rpcUrl: string, doFetch: typeof fetch, method: string): Promise<string> {
105
- const res = await doFetch(rpcUrl, {
106
- method: "POST",
107
- headers: { "content-type": "application/json" },
108
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params: [] }),
109
- });
110
- const json = (await res.json()) as { result?: string; error?: { message?: string } };
111
- if (json.error || json.result === undefined) throw new Error(json.error?.message ?? `${method} failed`);
112
- return json.result;
113
- }
@@ -13,6 +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
17
 
17
18
  /** The CLOB precompile (chain id 1293 / 0x50d). */
18
19
  export const CLOB_ADDRESS: Address = "0x50d0000000000000000000000000000000000002";
@@ -26,6 +27,7 @@ const CLOB_ABI = parseAbi([
26
27
  "function cancelTrigger(bytes32 orderbookId, bytes32 triggerOrder, uint128 deadline)",
27
28
  "function updateTrigger(bytes32 orderbookId, bytes32 triggerOrder, int256 newSize, uint256 newLimitPrice, uint256 newTriggerPrice, uint128 deadline)",
28
29
  "function submitBatch(bytes[] inner)",
30
+ "function withdraw(address token, address recipient, uint256 amount, uint128 deadline)",
29
31
  ]);
30
32
 
31
33
  /** ~10 years in microseconds — default far-future expiry for resting orders. */
@@ -587,18 +589,9 @@ export interface MintParams {
587
589
  * on rejection (e.g. "Minting is disabled") and Error on on-chain revert. */
588
590
  export async function mint(p: MintParams): Promise<TxReceipt> {
589
591
  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"));
592
+ const read = (method: string) => rpc<string>(p.rpcUrl, method, [], { fetch: doFetch });
593
+ const chainId = p.chainId ?? Number(await read("eth_chainId"));
594
+ const maxFeePerGas = BigInt(await read("eth_gasPrice"));
602
595
  const signer = privateKeyToAccount(generatePrivateKey());
603
596
  const data = encodeFunctionData({
604
597
  abi: MINT_ABI,
@@ -684,12 +677,65 @@ export function buildWaitlistDeposit(p: WaitlistDepositParams): SourceChainCall
684
677
  };
685
678
  }
686
679
 
680
+ // --- withdrawals (ADR 0033) --------------------------------------------------
681
+ //
682
+ // `Clob.withdraw` settles on L1 in ONE transaction: the CLOB balance is debited
683
+ // straight to the bridge's custody and N−F validators sign the L1 claim at
684
+ // solution execution. Nothing is credited to a pod account on the way, so the
685
+ // legacy `Bridge.withdraw` rules — `tx.value == amount`, a gas reserve, a second
686
+ // signature — do not apply, and MAX is the whole withdrawable balance.
687
+ //
688
+ // Two fields mean something different from the same-named ones elsewhere:
689
+ // - `recipient` is an address on the CLAIM chain, not on pod. Delegated calls
690
+ // stay pinned to the master (ADR 0018), so a session key cannot redirect it.
691
+ // - `amount` stays in pod's 18 decimals, but must be a whole number of
692
+ // claim-chain units or admission rejects it. Size it with `maxWithdrawable`
693
+ // / `quantizeWithdrawAmount` from `codec/bridge.ts` — this builder encodes
694
+ // what it is given and does no rounding of its own, because silently
695
+ // changing an amount a user signed for is worse than a clear rejection.
696
+
697
+ export interface ClobWithdrawParams {
698
+ /** Pod-side token address (native USD for cash). */
699
+ token: Address;
700
+ /** Recipient on the **claim chain**. */
701
+ recipient: Address;
702
+ /** 1e18-scaled, and a whole number of claim-chain units. */
703
+ amount: bigint;
704
+ /**
705
+ * Auction interval in microseconds (`market.auctionIntervalMs * 1000`).
706
+ *
707
+ * **Required, unlike the order builders'.** Admission refuses a deadline that
708
+ * is not a multiple of it, and the default here is a far-future timestamp with
709
+ * no reason to land on one — so an optional interval would silently produce a
710
+ * transaction that is rejected unless the clock happened to be aligned, and
711
+ * the rare one that slipped through would be stranded a decade out.
712
+ */
713
+ auctionIntervalUs: number;
714
+ deadline?: number; // ms; default far future
715
+ }
716
+
717
+ export function buildClobWithdraw(p: ClobWithdrawParams): PodTxRequest {
718
+ const nowUs = BigInt(Date.now()) * 1000n;
719
+ const deadline = alignDeadline(us(p.deadline, nowUs + FAR_US), BigInt(p.auctionIntervalUs));
720
+ const data = encodeFunctionData({
721
+ abi: CLOB_ABI,
722
+ functionName: "withdraw",
723
+ args: [p.token, p.recipient, p.amount, deadline],
724
+ }) as Hex;
725
+ return { to: CLOB_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
726
+ }
727
+
687
728
  /**
688
729
  * Deterministic order id: `keccak256(abi.encode(signer, nonce, sequence))`,
689
730
  * matching the engine (`trading/src/lib.rs`). `sequence` is the 0-based index
690
731
  * of the intent within a `submitBatch` (0 for a single-intent tx). Needs the
691
732
  * nonce, so it's only known up-front in managed mode; in advisory mode reconcile
692
733
  * by `tx` from the `pod_orders_v2` stream instead.
734
+ *
735
+ * **This is also the `withdrawal_id`** that `pod_withdrawals` reports and that
736
+ * `GET /v1/bridge/withdrawals/by-id/{id}` is keyed on — same derivation, same
737
+ * intent identity (ADR 0033 §3). `signer` is whoever signed the transaction,
738
+ * i.e. the delegate under a session key, not the debited master.
693
739
  */
694
740
  export function deriveOrderId(signer: Address, nonce: number, sequence = 0): Hash {
695
741
  return keccak256(