@predictasiax/api 2.4.0 → 3.0.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/dist/index.d.cts CHANGED
@@ -329,17 +329,26 @@ interface RequestOptions {
329
329
  * - `Cache-Control: no-store` on every request — prevents intermediary caches
330
330
  * retaining authenticated responses
331
331
  * - `Referrer-Policy` compatible via `no-referrer` header
332
- * - HMAC clock skew adjustment via client option
332
+ * - HMAC (PAX-* headers) re-signed per attempt; clock offset via client option
333
333
  * - CR/LF injection on user headers rejected in mergeHeaders
334
334
  * - `redirect: manual` — refuses server-initiated redirects that could
335
335
  * downgrade to plaintext or cross-origin
336
336
  */
337
337
 
338
+ declare const DEFAULT_BASE_URL = "https://api.predictasiax.com";
339
+ /** Strip a trailing slash and a trailing `/v1` so paths never double to /v1/v1. */
340
+ declare function normalizeBaseUrl(url: string): string;
338
341
  interface HttpClientOptions {
342
+ /** `sk_live_...` key. Alone: sent as `Authorization: Bearer`. With `keyId`: HMAC signing key. */
339
343
  apiKey?: string;
344
+ /** Key id (`api_...`). Enables HMAC request signing with PAX-* headers. */
345
+ keyId?: string;
346
+ bearerToken?: string;
347
+ /** @deprecated Not part of the PAX API; passing it throws. Use `keyId` + `apiKey`. */
340
348
  secret?: string;
349
+ /** @deprecated Not part of the PAX API; passing it throws. Use `keyId` + `apiKey`. */
341
350
  passphrase?: string;
342
- bearerToken?: string;
351
+ /** Accepted for compatibility; every env uses the same host. */
343
352
  env?: Env;
344
353
  baseUrl?: string;
345
354
  timeoutMs?: number;
@@ -357,7 +366,7 @@ interface HttpClientOptions {
357
366
  */
358
367
  maxResponseBytes?: number;
359
368
  /**
360
- * Auto-generate `Idempotency-Key` on POST/PUT/PATCH when caller does not
369
+ * Auto-generate `Idempotency-Key` on POST/PUT/PATCH/DELETE when caller does not
361
370
  * provide one. Same key is reused across all retries of a single call.
362
371
  * Default: `true`. Set to `false` to require callers to always provide
363
372
  * their own key.
@@ -366,7 +375,7 @@ interface HttpClientOptions {
366
375
  /**
367
376
  * Milliseconds added to `Date.now()` when constructing HMAC timestamps.
368
377
  * Use to compensate for a locally-drifted clock (e.g. from `serverTime - Date.now()`).
369
- * Server accepts ±30 s skew, so a value beyond that will fail regardless.
378
+ * The gateway accepts ±300 s.
370
379
  */
371
380
  clockOffsetMs?: number;
372
381
  /**
@@ -385,9 +394,10 @@ interface RawResponse<T> {
385
394
  declare class HttpClient {
386
395
  readonly baseUrl: string;
387
396
  readonly userAgent: string;
397
+ /** "hmac" | "api_key" | "bearer" | "none" */
398
+ get authMode(): string;
388
399
  private readonly apiKey?;
389
- private readonly secret?;
390
- private readonly passphrase?;
400
+ private readonly keyId?;
391
401
  private readonly bearerToken?;
392
402
  private readonly timeoutMs;
393
403
  private readonly maxRetries;
@@ -562,29 +572,24 @@ declare abstract class Resource {
562
572
  }
563
573
 
564
574
  /**
565
- * Account resource — balances, positions, your trade history.
575
+ * Account resource (scope portfolio:read).
566
576
  *
567
- * GET /v1/account retrieve()
568
- * GET /v1/account/positions positions()
569
- * GET /v1/account/trades trades()
577
+ * GET /v1/balance balance()
578
+ * GET /v1/portfolio portfolio() positions + balances
579
+ * GET /v1/positions positions()
570
580
  */
571
581
 
572
- interface ListTradesParams {
573
- cursor?: string;
574
- limit?: number;
575
- marketId?: string;
576
- }
577
582
  declare class AccountResource extends Resource {
578
- retrieve(opts?: RequestOptions): APIPromise<Account>;
579
- positions(opts?: RequestOptions): APIPromise<Position[]>;
580
- trades(params?: ListTradesParams, opts?: RequestOptions): PagePromise<Trade>;
583
+ balance(opts?: RequestOptions): APIPromise<unknown>;
584
+ /** @deprecated Use balance(). Kept as an alias. */
585
+ retrieve(opts?: RequestOptions): APIPromise<unknown>;
586
+ portfolio(opts?: RequestOptions): APIPromise<unknown>;
587
+ positions(opts?: RequestOptions): APIPromise<unknown>;
581
588
  }
582
589
 
583
590
  /**
584
- * Audit resource — public no-auth verifier over PAX's hash-chained event
585
- * log + Merkle-batched anchor chain. Any third party (auditor, investor,
586
- * external verifier) can independently reconstruct + verify without trusting
587
- * PAX at all.
591
+ * Audit resource — public, no-auth access to the hash-chained event log and
592
+ * its Merkle batches, plus offline verifiers.
588
593
  *
589
594
  * GET /v1/audit/status status()
590
595
  * GET /v1/audit/batches/latest latestBatch()
@@ -592,42 +597,67 @@ declare class AccountResource extends Resource {
592
597
  * GET /v1/audit/events/{seq} getEvent(seq)
593
598
  * GET /v1/audit/proof/{seq} getProof(seq)
594
599
  * GET /v1/audit/anchor/{num} getAnchor(num)
600
+ * (client-side) verify(seq), verifyEvent(), verifyEventHash(), verifyProof()
601
+ *
602
+ * Checks:
603
+ * 1. event_hash == sha256_hex(utf8(prev_event_hash + canonical)); `canonical`
604
+ * is returned verbatim by getEvent().
605
+ * 2. Merkle inclusion: leaf = event_hash; each level is SHA-256 over the
606
+ * sorted pair of RAW 32-byte digests (not keccak256, not hex strings); an
607
+ * odd level duplicates its last node.
608
+ * 3. Proof length: a batch of n leaves needs exactly expectedProofLength(n)
609
+ * siblings. Any other length is rejected, so an interior node cannot be
610
+ * presented as a leaf (second-preimage).
595
611
  *
596
- * v2.2+ — Polymarket has no equivalent surface. Merkle algo is OpenZeppelin
597
- * sorted-pair sha256, so Solidity `MerkleProof.verify` can verify proofs
598
- * on-chain without changes.
612
+ * A root read from this API proves internal consistency only; compare it with
613
+ * the batch's external anchor (getAnchor) for an independent check.
599
614
  */
600
615
 
601
616
  interface AuditStatus {
602
617
  events: {
603
618
  total: number;
604
- first_at: string;
605
- last_at: string;
619
+ first_at_ms: number;
620
+ last_at_ms: number;
606
621
  };
607
622
  batches: {
608
623
  total: number;
609
624
  anchored: number;
610
625
  };
611
626
  latest_batch: AuditBatch | null;
612
- latest_anchor: Pick<AuditBatch, "batch_num" | "anchored_at" | "anchor_target" | "anchor_ref"> | null;
627
+ latest_anchor: {
628
+ batch_num: number;
629
+ anchored_at_ms: number | null;
630
+ anchor_target: string | null;
631
+ anchor_ref: string | null;
632
+ } | null;
613
633
  anchor_lag_seconds: number | null;
614
634
  publisher_mode: string;
615
635
  verify_docs: string;
616
636
  }
617
637
  interface AuditBatch {
618
638
  batch_num: number;
619
- batch_id: string;
639
+ batch_id?: string;
620
640
  first_seq: number;
621
641
  last_seq: number;
622
642
  event_count: number;
623
643
  merkle_root: string;
624
644
  prev_batch_hash: string | null;
625
- created_at: string;
626
- anchored_at: string | null;
645
+ created_at_ms: number;
646
+ anchored_at_ms: number | null;
647
+ anchor_target: string | null;
648
+ anchor_ref?: string | null;
649
+ anchor_proof?: Record<string, unknown> | null;
650
+ anchor_public_url?: string | null;
651
+ }
652
+ /** GET /v1/audit/anchor/{num} */
653
+ interface AuditAnchor {
654
+ batch_num: number;
655
+ merkle_root: string;
627
656
  anchor_target: string | null;
628
657
  anchor_ref: string | null;
658
+ anchored_at_ms: number | null;
629
659
  anchor_proof: Record<string, unknown> | null;
630
- anchor_public_url?: string | null;
660
+ anchor_public_url: string | null;
631
661
  }
632
662
  interface AuditEvent {
633
663
  event_id: string;
@@ -635,38 +665,80 @@ interface AuditEvent {
635
665
  event_type: string;
636
666
  prev_event_hash: string;
637
667
  event_hash: string;
668
+ /** Display copy of the payload; numbers may be stringified. Hash `canonical`, not this. */
638
669
  payload: unknown;
639
670
  idempotency_key: string;
640
- created_at: string;
671
+ created_at_ms: number;
641
672
  emitter: string;
642
673
  schema_version: number;
643
674
  batch_id: string | null;
644
675
  batch_seq: number | null;
676
+ /** The exact string that was hashed: event_hash = sha256(prev_event_hash + canonical). */
677
+ canonical: string;
678
+ hash_recipe?: string;
645
679
  }
646
680
  interface MerkleProof {
647
681
  seq: number;
648
682
  event_hash: string;
649
- batch: Pick<AuditBatch, "batch_num" | "merkle_root" | "first_seq" | "last_seq" | "anchored_at" | "anchor_target" | "anchor_ref">;
683
+ batch: {
684
+ batch_num: number;
685
+ merkle_root: string;
686
+ first_seq: number;
687
+ last_seq: number;
688
+ anchored_at_ms?: number | null;
689
+ anchor_target?: string | null;
690
+ anchor_public_url?: string | null;
691
+ };
650
692
  merkle_proof: string[];
651
- verify_algo: string;
652
- verify_snippet: string;
693
+ leaf_index?: number;
694
+ leaf_count?: number;
695
+ expected_proof_length?: number;
696
+ verify_algo?: string;
697
+ verify_snippet?: string;
698
+ }
699
+ interface AuditVerification {
700
+ ok: boolean;
701
+ checks: Record<string, boolean>;
702
+ leafCount?: number;
703
+ expectedProofLength?: number;
704
+ reason: string | null;
653
705
  }
706
+ /** Number of siblings in a valid proof for a batch of `leafCount` leaves. */
707
+ declare function expectedProofLength(leafCount: number): number;
654
708
  declare class AuditResource extends Resource {
655
709
  status(opts?: RequestOptions): APIPromise<AuditStatus>;
656
710
  latestBatch(opts?: RequestOptions): APIPromise<AuditBatch>;
657
711
  getBatch(batchNum: number, opts?: RequestOptions): APIPromise<AuditBatch>;
658
712
  getEvent(seq: number, opts?: RequestOptions): APIPromise<AuditEvent>;
659
713
  getProof(seq: number, opts?: RequestOptions): APIPromise<MerkleProof>;
660
- getAnchor(batchNum: number, opts?: RequestOptions): APIPromise<AuditBatch>;
714
+ getAnchor(batchNum: number, opts?: RequestOptions): APIPromise<AuditAnchor>;
661
715
  /**
662
- * Verify a Merkle inclusion proof locally (client-side). Mirrors
663
- * OpenZeppelin's sorted-pair sha256 algorithm — identical logic to the
664
- * server-side batcher, so callers can independently confirm inclusion
665
- * without trusting the API response.
716
+ * Fetch event + proof for `seq` and run every offline check (event hash,
717
+ * same event, seq in batch, proof length, Merkle root). Pass `root` (e.g.
718
+ * the anchored root) for a check independent of this API's batch record.
666
719
  */
667
- static verifyProof(leaf: string, root: string, proof: string[]): boolean;
668
- /** Async variant using WebCrypto — works in browsers, Deno, Bun, edge runtimes. */
669
- static verifyProofAsync(leaf: string, root: string, proof: string[]): Promise<boolean>;
720
+ verify(seq: number, options?: {
721
+ root?: string;
722
+ } & RequestOptions): Promise<AuditVerification>;
723
+ /** Number of siblings in a valid proof for a batch of `leafCount` leaves. */
724
+ static expectedProofLength(leafCount: number): number;
725
+ /** Recompute event_hash = sha256(prev_event_hash + canonical) and check canonical.seq. */
726
+ static verifyEventHash(event: Pick<AuditEvent, "seq" | "prev_event_hash" | "event_hash" | "canonical">): boolean;
727
+ /** Run all checks for one event given getEvent() + getProof() data. */
728
+ static verifyEvent(event: AuditEvent, proof: MerkleProof, root?: string): AuditVerification;
729
+ /**
730
+ * Verify a Merkle inclusion proof locally. Synchronous and isomorphic
731
+ * (node:crypto when a sync `require` exists, else a built-in SHA-256).
732
+ *
733
+ * @param leaf the event's event_hash (64 hex chars)
734
+ * @param root the batch merkle_root (64 hex chars)
735
+ * @param proof sibling hashes, leaf level first (64 hex chars each)
736
+ * @param expectedLength expectedProofLength(leafCount) — required; any other
737
+ * proof length is rejected (second-preimage guard)
738
+ */
739
+ static verifyProof(leaf: string, root: string, proof: string[], expectedLength: number): boolean;
740
+ /** WebCrypto variant of verifyProof (same rules, including expectedLength). */
741
+ static verifyProofAsync(leaf: string, root: string, proof: string[], expectedLength: number): Promise<boolean>;
670
742
  }
671
743
 
672
744
  /**
@@ -674,7 +746,7 @@ declare class AuditResource extends Resource {
674
746
  *
675
747
  * GET /v1/fees/estimate estimate()
676
748
  *
677
- * v2.1+ — Polymarket has no equivalent. Returns identical shape to the `fee`
749
+ * v2.1+ — Exposes the 5-actor split before order placement (matches the
678
750
  * block on post-trade responses (same 5-actor `splits` + `attribution` +
679
751
  * `breakdown` + `ledger_preview`). Powered server-side by `lib/fiveActorFees`
680
752
  * so env-tunable bps flow through automatically without SDK bumps.
@@ -769,174 +841,128 @@ declare class GrantsResource extends Resource {
769
841
  }
770
842
 
771
843
  /**
772
- * Keys resource — programmatic API-key management.
844
+ * Markets resource.
773
845
  *
774
- * POST /v1/keys create()
775
- * GET /v1/keys list()
776
- * DELETE /v1/keys/{id} revoke()
777
- *
778
- * `secret` is returned only on `create()` and is never shown again — store
779
- * it securely at that moment.
780
- */
781
-
782
- interface CreateKeyParams {
783
- name?: string;
784
- scopes?: KeyScope[];
785
- }
786
- declare class KeysResource extends Resource {
787
- create(params?: CreateKeyParams, opts?: RequestOptions): APIPromise<ApiKey>;
788
- list(opts?: RequestOptions): APIPromise<ApiKey[]>;
789
- revoke(keyId: string, opts?: RequestOptions): APIPromise<{
790
- revoked: boolean;
791
- }>;
792
- }
793
-
794
- /**
795
- * Markets resource — discovery, candles, orderbook, public trades, creation.
796
- *
797
- * Endpoints wrapped:
798
- * GET /v1/markets list()
846
+ * GET /v1/markets list() paginated
799
847
  * GET /v1/markets/{id} retrieve()
800
- * POST /v1/markets create()
801
- * GET /v1/candles/{market_id} candles()
802
- * GET /v1/orderbook/{market_id} orderbook()
803
- * GET /v1/trades/{market_id} trades() (public tape)
848
+ * GET /v1/markets/categories categories()
849
+ * GET /v1/markets/{id}/orderbook orderbook() public
850
+ * GET /v1/markets/{id}/price-history priceHistory() public
851
+ * GET /v1/markets/{id}/resolution resolution() public
852
+ * POST /v1/composer/markets create()
804
853
  */
805
854
 
806
855
  interface ListMarketsParams {
807
- category?: Category;
808
- marketType?: MarketType;
809
- status?: MarketStatus;
856
+ category?: string;
857
+ q?: string;
810
858
  cursor?: string;
811
859
  limit?: number;
812
860
  }
813
861
  interface CreateMarketParams {
814
- templateId: string;
815
- params: Record<string, unknown>;
816
- creatorMetadata?: Record<string, unknown>;
817
- }
818
- interface CandlesParams {
819
- outcomeId: string;
820
- interval?: CandleInterval;
821
- fromMs?: number;
822
- toMs?: number;
823
- limit?: number;
824
- }
825
- interface OrderbookParams {
826
- outcomeId: string;
827
- depth?: number;
828
- }
829
- interface MarketTradesParams {
830
- outcomeId?: string;
831
- cursor?: string;
832
- limit?: number;
862
+ title: string;
863
+ rulesText: string;
864
+ resolutionRule: string;
865
+ /** https:// URL of an allow-listed public data publisher. */
866
+ primarySourceUrl: string;
867
+ backupSourceUrls?: string[];
868
+ cutoffTimeMs: number;
869
+ resolutionDeadlineMs: number;
870
+ edgeCasesText?: string;
871
+ description?: string;
833
872
  }
873
+ type PriceHistoryRange = "1h" | "6h" | "1d" | "7d" | "30d" | "90d";
834
874
  declare class MarketsResource extends Resource {
835
- /** List markets — auto-paginates. Iterate with `for await (const m of ...)`. */
836
- list(params?: ListMarketsParams, opts?: RequestOptions): PagePromise<Market>;
837
- retrieve(marketId: string, opts?: RequestOptions): APIPromise<Market>;
838
- create(params: CreateMarketParams, opts?: RequestOptions): APIPromise<Market>;
839
- candles(marketId: string, params: CandlesParams, opts?: RequestOptions): APIPromise<Candle[]>;
840
- orderbook(marketId: string, params: OrderbookParams, opts?: RequestOptions): APIPromise<Orderbook>;
841
- /** Public trade tape for a market (all fills, not your fills). */
842
- trades(marketId: string, params?: MarketTradesParams, opts?: RequestOptions): PagePromise<Trade>;
843
- private _buildListQuery;
875
+ /** List markets; iterate every page with `for await (const m of pax.markets.list())`. */
876
+ list(params?: ListMarketsParams, opts?: RequestOptions): PagePromise<Record<string, unknown>>;
877
+ retrieve(marketId: string, opts?: RequestOptions): APIPromise<Record<string, unknown>>;
878
+ categories(opts?: RequestOptions): APIPromise<unknown>;
879
+ orderbook(marketId: string, opts?: RequestOptions): APIPromise<unknown>;
880
+ priceHistory(marketId: string, params?: {
881
+ range?: PriceHistoryRange;
882
+ }, opts?: RequestOptions): APIPromise<unknown>;
883
+ resolution(marketId: string, opts?: RequestOptions): APIPromise<unknown>;
884
+ create(params: CreateMarketParams, opts?: RequestOptions): APIPromise<unknown>;
844
885
  }
845
886
 
846
887
  /**
847
- * Orders resource — your orders (single + batch).
888
+ * Orders resource.
848
889
  *
849
- * POST /v1/orders place()
850
- * DELETE /v1/orders/{id} cancel()
851
- * GET /v1/account/orders list()
852
- * POST /v1/orders/batch placeBatch() — v2.1+, up to 25 orders
853
- * DELETE /v1/orders/batch cancelBatch() — v2.1+, up to 50 orders
890
+ * POST /v1/orders place() limit BUY of one outcome
891
+ * POST /v1/orders/batch placeBatch()
892
+ * GET /v1/orders list() your most recent orders
893
+ * GET /v1/orders/history history()
894
+ * DELETE /v1/orders/{id} cancel()
895
+ * POST /v1/orders/cancel-all cancelAll() all resting orders, or one market's
854
896
  */
855
897
 
856
898
  interface PlaceOrderParams {
857
899
  marketId: string;
858
- outcomeId: string;
859
- side: Side;
860
- orderType: OrderType;
900
+ /** The outcome to buy. */
901
+ side: "yes" | "no";
902
+ /** Limit price, 0.01..0.99. */
903
+ price: Decimal | number;
904
+ /** Shares, > 0. */
861
905
  size: Decimal | number;
862
- price?: Decimal | number;
906
+ /**
907
+ * Engine-side dedupe key. Generated once per call when omitted, so a retry
908
+ * of the same call can never place a second order.
909
+ */
863
910
  clientOrderId?: string;
864
- timeInForce?: TimeInForce;
911
+ fundingMode?: string;
865
912
  }
866
913
  interface ListOrdersParams {
867
- status?: OrderStatus;
868
- cursor?: string;
869
914
  limit?: number;
870
915
  }
871
- /** Per-item result inside a batch response — one entry per input order. */
916
+ interface OrderHistoryParams {
917
+ limit?: number;
918
+ cursor?: string;
919
+ }
920
+ interface OrderRow {
921
+ id: string;
922
+ market_id: string;
923
+ side: string;
924
+ action: string;
925
+ kind: string;
926
+ price: string;
927
+ size: string;
928
+ filled_size: string;
929
+ status: string;
930
+ created_at: string;
931
+ updated_at: string;
932
+ [k: string]: unknown;
933
+ }
934
+ interface OrderList {
935
+ orders: OrderRow[];
936
+ count: number;
937
+ }
872
938
  interface BatchOrderResultItem {
873
939
  ok: boolean;
874
940
  index: number;
875
941
  client_order_id: string | null;
876
942
  data?: unknown;
877
- attribution?: {
878
- execution_builder_id?: string;
879
- acquisition_builder_id?: string | null;
880
- order_id?: string | null;
881
- write?: {
882
- ok: boolean;
883
- rowCount?: number;
884
- reason?: string;
885
- };
886
- };
887
943
  error?: {
888
944
  code: string;
889
945
  message: string;
890
946
  };
891
947
  }
892
- interface BatchOrderSummary {
893
- submitted: number;
894
- succeeded: number;
895
- failed: number;
896
- duration_ms: number;
897
- }
898
948
  interface BatchOrdersResult {
899
949
  results: BatchOrderResultItem[];
900
- summary: BatchOrderSummary;
901
- }
902
- interface BatchCancelResultItem {
903
- ok: boolean;
904
- index: number;
905
- order_id?: string;
906
- data?: unknown;
907
- error?: {
908
- code: string;
909
- message: string;
950
+ summary: {
951
+ submitted: number;
952
+ succeeded: number;
953
+ failed: number;
954
+ duration_ms: number;
910
955
  };
911
956
  }
912
- interface BatchCancelResult {
913
- results: BatchCancelResultItem[];
914
- summary: BatchOrderSummary;
915
- }
916
957
  declare class OrdersResource extends Resource {
917
- place(params: PlaceOrderParams, opts?: RequestOptions): APIPromise<Order>;
918
- cancel(orderId: string, opts?: RequestOptions): APIPromise<Order>;
919
- list(params?: ListOrdersParams, opts?: RequestOptions): PagePromise<Order>;
920
- /**
921
- * Place multiple orders in a single request (up to 25 per batch).
922
- *
923
- * Each order is processed sequentially by the CLOB engine (single-writer per
924
- * market). Response contains a `results` array with one entry per input order
925
- * (indexed) plus a `summary` with counts + duration. One bad order does not
926
- * fail the whole batch — inspect `results[i].ok` per item.
927
- *
928
- * Batch cap is env-tunable server-side (BATCH_ORDERS_MAX, default 25). Exceeding
929
- * returns `413 BATCH_TOO_LARGE`.
930
- */
958
+ place(params: PlaceOrderParams, opts?: RequestOptions): APIPromise<unknown>;
931
959
  placeBatch(orders: PlaceOrderParams[], opts?: RequestOptions): APIPromise<BatchOrdersResult>;
932
- /**
933
- * Cancel multiple orders in a single request (up to 50 per batch).
934
- *
935
- * Each cancel is processed sequentially by the CLOB engine. Response mirrors
936
- * `placeBatch` shape — inspect `results[i].ok` per item. Batch cap env-tunable
937
- * server-side (BATCH_CANCEL_MAX, default 50).
938
- */
939
- cancelBatch(orderIds: string[], opts?: RequestOptions): APIPromise<BatchCancelResult>;
960
+ list(params?: ListOrdersParams, opts?: RequestOptions): APIPromise<OrderList>;
961
+ history(params?: OrderHistoryParams, opts?: RequestOptions): APIPromise<unknown>;
962
+ cancel(orderId: string, opts?: RequestOptions): APIPromise<unknown>;
963
+ cancelAll(params?: {
964
+ marketId?: string;
965
+ }, opts?: RequestOptions): APIPromise<unknown>;
940
966
  }
941
967
 
942
968
  /**
@@ -955,7 +981,7 @@ declare class OrdersResource extends Resource {
955
981
 
956
982
  interface SandboxKeyMintParams {
957
983
  orgName: string;
958
- contactEmail?: string;
984
+ contactHandle?: string;
959
985
  }
960
986
  interface ApplyCreateParams {
961
987
  /**
@@ -1002,15 +1028,10 @@ declare class SandboxResource extends Resource {
1002
1028
  /**
1003
1029
  * Settle resource — claim accrued fee revenue (v2.4+).
1004
1030
  *
1005
- * Three surfaces:
1006
- * - `me()` — builder self-serve claim of their own execution +
1007
- * acquisition builder fees. Uses api-key auth.
1008
- * - `adminBuilder()` — admin claim of a specific builder's accrued fees.
1009
- * Requires X-Admin-Key header.
1010
- * - `adminCreator()` — admin claim of a market creator's FEE_MARKET_CREATOR
1011
- * fees. Requires X-Admin-Key header.
1031
+ * - `me()` — POST /v1/builders/me/settle: builder self-serve claim of their
1032
+ * own execution + acquisition builder fees.
1012
1033
  *
1013
- * All three insert a `withdrawal_state` row with the appropriate source tag
1034
+ * Inserts a `withdrawal_state` row with the appropriate source tag
1014
1035
  * and mark the underlying `financial_event` rows settled. The existing
1015
1036
  * withdrawal pipeline delivers USDT to the provided address.
1016
1037
  */
@@ -1034,11 +1055,6 @@ interface SettleResult {
1034
1055
  declare class SettleResource extends Resource {
1035
1056
  /** Builder self-serve settle — POST /v1/builders/me/settle. */
1036
1057
  me(params: SettleParams, opts?: RequestOptions): APIPromise<SettleResult>;
1037
- /** Admin settle a specific builder's fees — POST /v1/admin/builders/{userId}/settle.
1038
- * Requires X-Admin-Key header. */
1039
- adminBuilder(userId: string, params: SettleParams, adminKey: string, opts?: RequestOptions): APIPromise<SettleResult>;
1040
- /** Admin settle a market creator's fees — POST /v1/admin/creators/{userId}/settle. */
1041
- adminCreator(userId: string, params: SettleParams, adminKey: string, opts?: RequestOptions): APIPromise<SettleResult>;
1042
1058
  }
1043
1059
 
1044
1060
  /**
@@ -1059,39 +1075,25 @@ declare class TemplatesResource extends Resource {
1059
1075
  }
1060
1076
 
1061
1077
  /**
1062
- * PaxClient — top-level entry point.
1078
+ * PaxClient — top-level entry point for https://api.predictasiax.com.
1063
1079
  *
1064
- * Auth modes (auto-detected from constructor):
1065
- * 1. HMAC — pass `apiKey` + `secret` + `passphrase`. Every request
1066
- * signed with 5 POLY_* headers. Use for high-security trading.
1067
- * 2. API Key — pass only `apiKey`. Sent via `X-Api-Key` header.
1068
- * 3. Bearer — pass `bearerToken`. Session-based, browser/mobile.
1069
- *
1070
- * Resources hang off the client, e.g. `pax.markets.list()`, following
1071
- * the Stripe/OpenAI/Anthropic convention.
1080
+ * Credentials (pick one; none is fine for public endpoints):
1081
+ * - `apiKey: "sk_live_..."` → Authorization: Bearer sk_live_...
1082
+ * - `apiKey: "sk_live_...", keyId: "api_..."` → HMAC request signing (PAX-* headers)
1083
+ * - `bearerToken: "..."` → session / OAuth token
1072
1084
  *
1073
1085
  * @example
1074
1086
  * import { PaxClient } from "@predictasiax/api";
1075
1087
  *
1076
- * // Mint an anonymous sandbox key first (30 sec, no email):
1077
- * // curl -X POST https://api.predictasiax.com/v1/sandbox-keys \
1078
- * // -H 'Content-Type: application/json' -d '{"org_name":"my-app"}'
1079
- * // → { api_key: "sk_live_...", tier: "self_serve", ... }
1080
- * const pax = new PaxClient({ apiKey: "sk_live_..." });
1081
- * const account = await pax.account.retrieve();
1082
- *
1083
- * for await (const market of pax.markets.list({ category: "crypto" })) {
1084
- * console.log(market.id, market.title);
1085
- * }
1088
+ * const pub = new PaxClient();
1089
+ * const check = await pub.audit.verify(1866215); // offline audit checks
1086
1090
  *
1087
- * const { data, response, requestId } =
1088
- * await pax.orders.place({
1089
- * marketId: "m_abc", outcomeId: "yes",
1090
- * side: "buy", orderType: "market", size: "10",
1091
- * }, { idempotencyKey: "ord_1" }).withResponse();
1091
+ * const pax = new PaxClient({ apiKey: "sk_live_...", keyId: "api_..." });
1092
+ * await pax.account.balance();
1093
+ * await pax.orders.place({ marketId: "hadjar-f1-2026", side: "yes", price: "0.05", size: "10" });
1092
1094
  */
1093
1095
 
1094
- declare const VERSION = "2.2.0";
1096
+ declare const VERSION = "3.0.0";
1095
1097
  type PaxClientOptions = HttpClientOptions;
1096
1098
  declare class PaxClient {
1097
1099
  private readonly _http;
@@ -1099,7 +1101,6 @@ declare class PaxClient {
1099
1101
  readonly templates: TemplatesResource;
1100
1102
  readonly orders: OrdersResource;
1101
1103
  readonly account: AccountResource;
1102
- readonly keys: KeysResource;
1103
1104
  readonly sandbox: SandboxResource;
1104
1105
  readonly sandboxKeys: SandboxKeysResource;
1105
1106
  readonly apply: ApplyResource;
@@ -1107,13 +1108,88 @@ declare class PaxClient {
1107
1108
  readonly fees: FeesResource;
1108
1109
  readonly audit: AuditResource;
1109
1110
  readonly settle: SettleResource;
1110
- constructor(opts: PaxClientOptions);
1111
+ constructor(opts?: PaxClientOptions);
1111
1112
  get baseUrl(): string;
1112
1113
  get userAgent(): string;
1114
+ get authMode(): string;
1113
1115
  /** GET /v1/health — top-level, not paginated, always safe. */
1114
1116
  health(opts?: RequestOptions): APIPromise<HealthStatus>;
1115
1117
  }
1116
1118
 
1119
+ /**
1120
+ * attach-ref.ts — Wave-2b (2026-09-08)
1121
+ *
1122
+ * Reads a builder referral code from the current URL's `?ref=` (or configured)
1123
+ * query parameter, persists it in cookie / localStorage / memory, and returns
1124
+ * a `defaultHeaders` object with `X-Builder-Ref` set. The returned headers
1125
+ * are meant to be spread into `PaxClient` construction via `defaultHeaders`
1126
+ * OR into a per-request `RequestOptions.headers`.
1127
+ *
1128
+ * Backend behavior: `POST /v1/orders` reads the `X-Builder-Ref` header and,
1129
+ * IF the acting user has no existing acquisition attribution, sets it once
1130
+ * (sticky, never overwrites — same semantics as signup `?ref=`). Response
1131
+ * echoes `attribution.ref_applied` for confirmation.
1132
+ *
1133
+ * @example
1134
+ * import { PaxClient, attachRef } from "@predictasiax/api";
1135
+ *
1136
+ * const { headers, ref } = attachRef({ storage: "localStorage" });
1137
+ * const pax = new PaxClient({ apiKey: "sk_live_...", defaultHeaders: headers });
1138
+ * // From now on every request carries X-Builder-Ref: <ref>.
1139
+ *
1140
+ * @example
1141
+ * // Manual override — server-side or when URL parsing not available:
1142
+ * const { headers } = attachRef({ ref: "BLD_kol_alpha" });
1143
+ */
1144
+ interface AttachRefOptions {
1145
+ /** URL query param name to read the ref from. Default: "ref". */
1146
+ queryParam?: string;
1147
+ /** Explicit ref value (skips URL parsing entirely). */
1148
+ ref?: string;
1149
+ /** Where to persist the ref for cross-request continuity. */
1150
+ storage?: "cookie" | "localStorage" | "memory";
1151
+ /** Cookie / localStorage key. Default: "pax_builder_ref". */
1152
+ storageKey?: string;
1153
+ /** Cookie max-age in seconds. Default 90d. */
1154
+ cookieMaxAgeSec?: number;
1155
+ /** Cookie domain. Default: current host. */
1156
+ cookieDomain?: string;
1157
+ /** Optional pre-existing URL to parse instead of `window.location.href`. */
1158
+ url?: string;
1159
+ }
1160
+ interface AttachRefResult {
1161
+ /** The resolved ref value or null if none found. */
1162
+ ref: string | null;
1163
+ /**
1164
+ * Default headers ready to spread into PaxClient constructor
1165
+ * (`defaultHeaders`) or per-request `RequestOptions.headers`.
1166
+ * Empty object when ref is null.
1167
+ */
1168
+ headers: Record<string, string>;
1169
+ /** Whether the ref was persisted this call. */
1170
+ persisted: boolean;
1171
+ /** Source: "explicit" | "url" | "cookie" | "localStorage" | "memory" | "none". */
1172
+ source: string;
1173
+ }
1174
+ /**
1175
+ * Detect + persist a builder ref, then return headers ready for PaxClient.
1176
+ *
1177
+ * Precedence: explicit `ref` opt → URL `?ref=` → cookie → localStorage →
1178
+ * in-memory (this process) → none.
1179
+ *
1180
+ * When a fresh value is found in URL / explicit, it is persisted according
1181
+ * to `storage` (default `cookie` in the browser, `memory` server-side).
1182
+ */
1183
+ declare function attachRef(opts?: AttachRefOptions): AttachRefResult;
1184
+ /**
1185
+ * Explicit clear — removes the ref from all storages this SDK owns.
1186
+ * Useful on logout or user-initiated attribution reset.
1187
+ */
1188
+ declare function clearRef(opts?: {
1189
+ storageKey?: string;
1190
+ cookieDomain?: string;
1191
+ }): void;
1192
+
1117
1193
  /**
1118
1194
  * PaxWSClient — real-time market data + private events over WebSocket.
1119
1195
  *
@@ -1210,51 +1286,48 @@ declare class PaxWSClient {
1210
1286
  }
1211
1287
 
1212
1288
  /**
1213
- * HMAC signing helpers — Polymarket-compatible 5-header pattern.
1289
+ * HMAC request signing for the PAX API gateway (https://api.predictasiax.com).
1214
1290
  *
1215
- * Signature construction:
1216
- * message = timestamp_ms + method_upper + path_with_query + body
1217
- * signature = base64(HMAC-SHA256(secret, message))
1291
+ * What the gateway verifies:
1218
1292
  *
1219
- * Headers sent:
1220
- * POLY_ACCESS_KEY: <key_id>
1221
- * POLY_TIMESTAMP: <ms epoch>
1222
- * POLY_PASSPHRASE: <passphrase>
1223
- * POLY_SIGNATURE: <base64 sig>
1293
+ * canonical = timestamp + "\n" + nonce + "\n" + METHOD + "\n" + pathWithQuery + "\n" + body
1294
+ * signature = base64(HMAC-SHA256(key = apiKey, msg = canonical))
1224
1295
  *
1225
- * Server rejects with 401 INVALID_SIGNATURE if timestamp is more than
1226
- * ±30 seconds from server clock — sync your machine via NTP.
1296
+ * PAX-ADDRESS: <key id, e.g. api_0123456789ab>
1297
+ * PAX-TIMESTAMP: <unix seconds> accepted window: ±300 s
1298
+ * PAX-NONCE: <random, single use> remembered for 600 s per key
1299
+ * PAX-SIGNATURE: <base64 signature>
1227
1300
  *
1228
- * Runtime support:
1229
- * - Node.js 18+ / Bun / Deno → node:crypto (via createHmac)
1230
- * - Browser / Cloudflare Workers / Vercel Edge → WebCrypto (subtle.sign)
1301
+ * `apiKey` is the full `sk_live_...` string shown once at mint time; the key
1302
+ * itself is never sent. `pathWithQuery` includes `/v1` and the query string.
1303
+ * Sign every attempt afresh (new timestamp + nonce), retries included.
1231
1304
  *
1232
- * `signRequest` is async because WebCrypto's subtle.sign is async.
1305
+ * Runtime: WebCrypto when available (browsers, edge, Node 18+), else node:crypto.
1233
1306
  */
1234
1307
  interface HmacHeaders {
1235
- POLY_ACCESS_KEY: string;
1236
- POLY_TIMESTAMP: string;
1237
- POLY_PASSPHRASE: string;
1238
- POLY_SIGNATURE: string;
1308
+ "PAX-ADDRESS": string;
1309
+ "PAX-TIMESTAMP": string;
1310
+ "PAX-NONCE": string;
1311
+ "PAX-SIGNATURE": string;
1239
1312
  }
1240
1313
  interface SignInput {
1241
1314
  method: string;
1242
- path: string;
1315
+ /** Path including `/v1` and the query string, exactly as sent. */
1316
+ pathWithQuery: string;
1317
+ /** Raw body exactly as sent ("" when there is none). */
1243
1318
  body: string;
1319
+ /** Key id (`api_...`), sent as PAX-ADDRESS. */
1244
1320
  keyId: string;
1245
- secret: string;
1246
- passphrase: string;
1247
- timestampMs?: number;
1248
- }
1249
- /** Return the canonical signing message (exposed for debugging). */
1250
- declare function buildMessage(method: string, path: string, body: string, timestampMs: number): string;
1251
- /**
1252
- * Sign a PAX request. Returns the four POLY_* headers.
1253
- *
1254
- * On Node this uses `node:crypto`; on browser / edge runtimes it falls back
1255
- * to WebCrypto. Both paths are byte-for-byte identical because HMAC-SHA256
1256
- * is deterministic.
1257
- */
1321
+ /** Full `sk_live_...` key, used as the HMAC key. */
1322
+ apiKey: string;
1323
+ /** Unix seconds override (tests only). */
1324
+ timestampSec?: number;
1325
+ /** Nonce override (tests only). Never reuse a nonce. */
1326
+ nonce?: string;
1327
+ }
1328
+ /** Return the exact string the gateway signs (exposed for debugging). */
1329
+ declare function buildCanonical(timestamp: string | number, nonce: string, method: string, pathWithQuery: string, body: string): string;
1330
+ /** Build the four PAX-* headers for one request attempt. */
1258
1331
  declare function signRequest(input: SignInput): Promise<HmacHeaders>;
1259
1332
 
1260
1333
  /**
@@ -1348,4 +1421,4 @@ declare function runWithRetry<T>(fn: () => Promise<T>, opts?: {
1348
1421
  onRetry?: (attempt: number, error: Error) => void;
1349
1422
  }): Promise<T>;
1350
1423
 
1351
- export { APIPromise, type APIResponseInfo, type Account, type AccountBalance, AccountResource, type ApiKey, type ApplicationResult, type ApplicationStatus, type ApplyCreateParams, ApplyResource, type AuditBatch, type AuditEvent, AuditResource, type AuditStatus, type BatchCancelResult, type BatchCancelResultItem, type BatchOrderResultItem, type BatchOrderSummary, type BatchOrdersResult, type Candle, type CandleInterval, type CandlesParams, type Category, type CreateKeyParams, type CreateMarketParams, CursorPage, type CursorPageInit, type CursorPageParams, type Decimal, type Env, type Envelope, type FeeEstimate, type FeeEstimateParams, FeesResource, type GrantClaimResult, type GrantEvent, type GrantEventType, type GrantPhase, type GrantTier, type GrantVesting, GrantsResource, type HealthStatus, type HmacHeaders, type HttpClientOptions, type KeyScope, KeysResource, type ListEnvelope, type ListMarketsParams, type ListOrdersParams, type ListTemplatesParams, type ListTradesParams, type Market, type MarketStatus, type MarketTemplate, type MarketTradesParams, type MarketType, MarketsResource, type MerkleProof, type Order, type OrderStatus, type OrderType, type Orderbook, type OrderbookLevel, type OrderbookParams, OrdersResource, type Outcome, PagePromise, PaxAuthError, PaxCircuitBreakerError, PaxClient, type PaxClientOptions, PaxConflictError, PaxError, type PaxErrorDetails, type PaxErrorPayload, PaxNotFoundError, PaxRateLimitError, PaxReadOnlyModeError, PaxSandboxOnlyError, PaxServerError, PaxValidationError, PaxWSClient, type PaxWSClientOptions, PaxWrongEnvKeyError, type PlaceOrderParams, type Position, type RequestOptions, type ResponseMeta, type SandboxKeyMintParams, type SandboxKeyResult, SandboxKeysResource, SandboxResource, type Side, type SignInput, TemplatesResource, type Tier, type TierLimits, type TimeInForce, type TokenGrant, type Trade, VERSION, type WithResponseResult, type WsEvent, type WsHandler, buildError, buildMessage, computeBackoff, runWithRetry, signRequest };
1424
+ export { APIPromise, type APIResponseInfo, type Account, type AccountBalance, AccountResource, type ApiKey, type ApplicationResult, type ApplicationStatus, type ApplyCreateParams, ApplyResource, type AttachRefOptions, type AttachRefResult, type AuditAnchor, type AuditBatch, type AuditEvent, AuditResource, type AuditStatus, type AuditVerification, type BatchOrderResultItem, type BatchOrdersResult, type Candle, type CandleInterval, type Category, type CreateMarketParams, CursorPage, type CursorPageInit, type CursorPageParams, DEFAULT_BASE_URL, type Decimal, type Env, type Envelope, type FeeEstimate, type FeeEstimateParams, FeesResource, type GrantClaimResult, type GrantEvent, type GrantEventType, type GrantPhase, type GrantTier, type GrantVesting, GrantsResource, type HealthStatus, type HmacHeaders, type HttpClientOptions, type KeyScope, type ListEnvelope, type ListMarketsParams, type ListOrdersParams, type ListTemplatesParams, type Market, type MarketStatus, type MarketTemplate, type MarketType, MarketsResource, type MerkleProof, type Order, type OrderHistoryParams, type OrderList, type OrderRow, type OrderStatus, type OrderType, type Orderbook, type OrderbookLevel, OrdersResource, type Outcome, PagePromise, PaxAuthError, PaxCircuitBreakerError, PaxClient, type PaxClientOptions, PaxConflictError, PaxError, type PaxErrorDetails, type PaxErrorPayload, PaxNotFoundError, PaxRateLimitError, PaxReadOnlyModeError, PaxSandboxOnlyError, PaxServerError, PaxValidationError, PaxWSClient, type PaxWSClientOptions, PaxWrongEnvKeyError, type PlaceOrderParams, type Position, type PriceHistoryRange, type RequestOptions, type ResponseMeta, type SandboxKeyMintParams, type SandboxKeyResult, SandboxKeysResource, SandboxResource, SettleResource, type Side, type SignInput, TemplatesResource, type Tier, type TierLimits, type TimeInForce, type TokenGrant, type Trade, VERSION, type WithResponseResult, type WsEvent, type WsHandler, attachRef, buildCanonical, buildError, clearRef, computeBackoff, expectedProofLength, normalizeBaseUrl, runWithRetry, signRequest };