@pod-network/trade-sdk 0.4.1 → 0.6.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.
@@ -1,4 +1,4 @@
1
- // Write helpers: build unsigned CLOB transactions and derive order ids. These
1
+ // Write helpers: build unsigned pod transactions and derive order ids. These
2
2
  // are pure encoding — no wallet, no key, no nonce ownership. The consumer signs
3
3
  // + broadcasts the returned request with whatever wallet it has
4
4
  // (walletClient.sendTransaction / eth_sendTransaction / Privy).
@@ -18,6 +18,9 @@ import { rpc } from "../transport/jsonrpc.js";
18
18
  /** The CLOB precompile (chain id 1293 / 0x50d). */
19
19
  export const CLOB_ADDRESS: Address = "0x50d0000000000000000000000000000000000002";
20
20
 
21
+ /** The bridge precompile. */
22
+ export const BRIDGE_ADDRESS: Address = "0x50d0000000000000000000000000000000000001";
23
+
21
24
  const CLOB_ABI = parseAbi([
22
25
  "function submitOrder(bytes32 orderbookId, int256 size, uint256 price, uint8 orderType, uint128 deadline, uint128 ttl, bool reduceOnly, bool ioc)",
23
26
  "function cancel(bytes32 orderbookId, bytes32 canceledOrder, uint128 deadline)",
@@ -27,7 +30,10 @@ const CLOB_ABI = parseAbi([
27
30
  "function cancelTrigger(bytes32 orderbookId, bytes32 triggerOrder, uint128 deadline)",
28
31
  "function updateTrigger(bytes32 orderbookId, bytes32 triggerOrder, int256 newSize, uint256 newLimitPrice, uint256 newTriggerPrice, uint128 deadline)",
29
32
  "function submitBatch(bytes[] inner)",
30
- "function withdraw(address token, address recipient, uint256 amount, uint128 deadline)",
33
+ ]);
34
+
35
+ const BRIDGE_ABI = parseAbi([
36
+ "function withdraw(address token, address to, uint256 amount, uint128 deadline)",
31
37
  ]);
32
38
 
33
39
  /** ~10 years in microseconds — default far-future expiry for resting orders. */
@@ -367,7 +373,13 @@ export function buildSubmitBatch(
367
373
  legs: Array<PodTxRequest | Hex>,
368
374
  opts?: { gas?: bigint },
369
375
  ): PodTxRequest {
370
- const inner = legs.map((l) => (typeof l === "string" ? l : l.data));
376
+ const inner = legs.map((l) => {
377
+ if (typeof l === "string") return l;
378
+ if (l.to.toLowerCase() !== CLOB_ADDRESS) {
379
+ throw new Error(`submitBatch carries CLOB calls only, not a call to ${l.to}`);
380
+ }
381
+ return l.data;
382
+ });
371
383
  const data = encodeFunctionData({
372
384
  abi: CLOB_ABI,
373
385
  functionName: "submitBatch",
@@ -507,18 +519,21 @@ export function buildClosePosition(p: ClosePositionParams): PodTxRequest {
507
519
  });
508
520
  }
509
521
 
510
- /** A mined transaction receipt (the fields a consumer typically needs). */
522
+ /** A transaction receipt (the fields a consumer typically needs). */
511
523
  export interface TxReceipt {
512
524
  /** `success` when the tx executed (status `0x1`); `reverted` on `0x0`. */
513
525
  status: "success" | "reverted";
514
526
  transactionHash: Hash;
515
- blockNumber: bigint;
527
+ /** The height the tx was sequenced at, or `null` when it is in no block —
528
+ * `submitSolutions`, recovery txs, and an intent whose auction tick has not
529
+ * run yet. A null height is not a pending state: the receipt is still final. */
530
+ blockNumber: bigint | null;
516
531
  gasUsed: bigint;
517
532
  }
518
533
 
519
534
  /**
520
- * Poll `eth_getTransactionReceipt` until the tx is mined, then report whether it
521
- * executed or reverted. A hash from {@link sendRawTransaction} only means the
535
+ * Poll `eth_getTransactionReceipt` until a receipt exists, then report whether
536
+ * the tx executed or reverted. A hash from {@link sendRawTransaction} only means the
522
537
  * node accepted the tx into its pool — it is NOT yet confirmed. Await this to
523
538
  * know the on-chain outcome. Throws on timeout. Like the rest of this module
524
539
  * it's transport-only (raw JSON-RPC), so it needs no viem client.
@@ -539,14 +554,19 @@ export async function waitForReceipt(
539
554
  body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_getTransactionReceipt", params: [hash] }),
540
555
  });
541
556
  const json = (await res.json()) as {
542
- result?: { status: string; transactionHash: Hash; blockNumber: string; gasUsed: string } | null;
557
+ result?: {
558
+ status: string;
559
+ transactionHash: Hash;
560
+ blockNumber?: string | null;
561
+ gasUsed: string;
562
+ } | null;
543
563
  };
544
564
  const r = json.result;
545
565
  if (r) {
546
566
  return {
547
567
  status: r.status === "0x1" ? "success" : "reverted",
548
568
  transactionHash: r.transactionHash,
549
- blockNumber: BigInt(r.blockNumber),
569
+ blockNumber: r.blockNumber == null ? null : BigInt(r.blockNumber),
550
570
  gasUsed: BigInt(r.gasUsed),
551
571
  };
552
572
  }
@@ -613,7 +633,7 @@ export async function mint(p: MintParams): Promise<TxReceipt> {
613
633
  return receipt;
614
634
  }
615
635
 
616
- // --- waitlist deposit (canary — real USDC on the source chain) ---------------
636
+ // --- waitlist deposit + withdraw (canary — real USDC on the source chain) ----
617
637
  //
618
638
  // Canary environments fund accounts with a real USDC deposit on the source
619
639
  // chain (Arbitrum One) instead of the faucet: approve the waitlist contract to
@@ -625,6 +645,7 @@ const ERC20_ABI = parseAbi(["function approve(address spender, uint256 value)"])
625
645
 
626
646
  const WAITLIST_ABI = parseAbi([
627
647
  "function deposit(address token, uint256 amount, address from, address to, address callContract, uint256 reserveBalance, bytes permit)",
648
+ "function withdraw(uint256 depositId, address token, uint256 amount, address from, address to, address callContract, uint256 reserveBalance)",
628
649
  ]);
629
650
 
630
651
  /** An unsigned call on the source chain — spread into
@@ -677,24 +698,60 @@ export function buildWaitlistDeposit(p: WaitlistDepositParams): SourceChainCall
677
698
  };
678
699
  }
679
700
 
680
- // --- withdrawals (ADR 0033) --------------------------------------------------
701
+ /** Arguments for {@link buildWaitlistWithdraw}. Every field is required — see the
702
+ * builder for why none of them may be defaulted. */
703
+ export interface WaitlistWithdrawParams {
704
+ /** The waitlist contract on the source chain — the one the deposit went to. */
705
+ waitlist: Address;
706
+ /** The contract's id for the deposit being taken back out. One call per
707
+ * deposit: the waitlist deliberately has no batch withdrawal. */
708
+ depositId: bigint;
709
+ token: Address;
710
+ amount: bigint;
711
+ /** The depositing address — only it may withdraw, so it must also be the
712
+ * sender of this call. */
713
+ from: Address;
714
+ to: Address;
715
+ callContract: Address;
716
+ reserveBalance: bigint;
717
+ }
718
+
719
+ /** Waitlist `withdraw(...)` — takes a confirmed deposit back out on the source
720
+ * chain, undoing a {@link buildWaitlistDeposit}.
721
+ *
722
+ * Unlike the deposit builder, this one defaults nothing, and must not start to.
723
+ * The waitlist keeps only a *hash* of the deposit's argument set and recomputes
724
+ * it here, so an argument that merely looks right — `to` filled in from `from`,
725
+ * the usual `callContract`, a tidied `reserveBalance` — hashes to something else
726
+ * and reverts, and the user pays gas for the failure. The caller reads all seven
727
+ * verbatim from the waitlist API's `/v1/waitlist/me` response and passes them
728
+ * straight through: no fallbacks, no normalising, no lowercasing. */
729
+ export function buildWaitlistWithdraw(p: WaitlistWithdrawParams): SourceChainCall {
730
+ return {
731
+ to: p.waitlist,
732
+ data: encodeFunctionData({
733
+ abi: WAITLIST_ABI,
734
+ functionName: "withdraw",
735
+ args: [p.depositId, p.token, p.amount, p.from, p.to, p.callContract, p.reserveBalance],
736
+ }),
737
+ value: 0n,
738
+ };
739
+ }
740
+
741
+ // --- withdrawals (ADR 0042) --------------------------------------------------
681
742
  //
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.
743
+ // `Bridge.withdraw` settles on L1 in ONE transaction: the CLOB balance is
744
+ // debited and N−F validators sign the L1 claim at solution execution. Nothing is
745
+ // credited to a pod account on the way, so `tx.value` is zero for every token,
746
+ // native included, and MAX is the whole withdrawable balance.
687
747
  //
688
748
  // 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 {
749
+ // - `recipient` is an address on the CLAIM chain, not on pod.
750
+ // - `amount` stays in pod's 18 decimals but must be a whole number of
751
+ // claim-chain units; size it with `maxWithdrawable` from `codec/bridge.ts`,
752
+ // because this builder rounds nothing of its own.
753
+
754
+ export interface WithdrawParams {
698
755
  /** Pod-side token address (native USD for cash). */
699
756
  token: Address;
700
757
  /** Recipient on the **claim chain**. */
@@ -714,15 +771,15 @@ export interface ClobWithdrawParams {
714
771
  deadline?: number; // ms; default far future
715
772
  }
716
773
 
717
- export function buildClobWithdraw(p: ClobWithdrawParams): PodTxRequest {
774
+ export function buildWithdraw(p: WithdrawParams): PodTxRequest {
718
775
  const nowUs = BigInt(Date.now()) * 1000n;
719
776
  const deadline = alignDeadline(us(p.deadline, nowUs + FAR_US), BigInt(p.auctionIntervalUs));
720
777
  const data = encodeFunctionData({
721
- abi: CLOB_ABI,
778
+ abi: BRIDGE_ABI,
722
779
  functionName: "withdraw",
723
780
  args: [p.token, p.recipient, p.amount, deadline],
724
781
  }) as Hex;
725
- return { to: CLOB_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
782
+ return { to: BRIDGE_ADDRESS, data, value: 0n, type: "eip1559", maxPriorityFeePerGas: 0n, gas: 1_000_000n };
726
783
  }
727
784
 
728
785
  /**
@@ -731,11 +788,6 @@ export function buildClobWithdraw(p: ClobWithdrawParams): PodTxRequest {
731
788
  * of the intent within a `submitBatch` (0 for a single-intent tx). Needs the
732
789
  * nonce, so it's only known up-front in managed mode; in advisory mode reconcile
733
790
  * 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.
739
791
  */
740
792
  export function deriveOrderId(signer: Address, nonce: number, sequence = 0): Hash {
741
793
  return keccak256(