@agg-build/sdk 4.3.0 → 4.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.
package/dist/index.d.mts CHANGED
@@ -1226,11 +1226,11 @@ interface TSchema extends TKind, SchemaOptions {
1226
1226
  * Always carry a human-readable `message` alongside; the code is additive and
1227
1227
  * may be absent on rejections that pre-date this addition.
1228
1228
  */
1229
- declare const QuoteErrorCodeTB: TUnion<[TLiteral<"quote_not_found">, TLiteral<"quote_expired">, TLiteral<"quote_already_executed">, TLiteral<"quote_cancelled">, TLiteral<"quote_user_mismatch">, TLiteral<"quote_app_blocked">, TLiteral<"quote_unfillable">, TLiteral<"quote_min_order_size">, TLiteral<"quote_stale_status">, TLiteral<"quote_stale_price">, TLiteral<"quote_insufficient_balance">, TLiteral<"quote_market_inactive">, TLiteral<"venue_not_executable">, TLiteral<"outcome_ambiguous">]>;
1229
+ declare const QuoteErrorCodeTB: TUnion<[TLiteral<"quote_not_found">, TLiteral<"quote_expired">, TLiteral<"quote_already_executed">, TLiteral<"quote_cancelled">, TLiteral<"quote_user_mismatch">, TLiteral<"quote_app_blocked">, TLiteral<"quote_unfillable">, TLiteral<"quote_min_order_size">, TLiteral<"quote_stale_status">, TLiteral<"quote_stale_price">, TLiteral<"quote_insufficient_balance">, TLiteral<"quote_market_inactive">, TLiteral<"quote_self_custody_unsupported_venue">, TLiteral<"quote_self_custody_app_fee">, TLiteral<"quote_self_custody_redeem_unsupported">, TLiteral<"venue_not_executable">, TLiteral<"outcome_ambiguous">]>;
1230
1230
  type QuoteErrorCode = Static<typeof QuoteErrorCodeTB>;
1231
1231
  declare const QuoteErrorTB: TObject<{
1232
1232
  message: TString;
1233
- code: TOptional<TUnion<[TLiteral<"quote_not_found">, TLiteral<"quote_expired">, TLiteral<"quote_already_executed">, TLiteral<"quote_cancelled">, TLiteral<"quote_user_mismatch">, TLiteral<"quote_app_blocked">, TLiteral<"quote_unfillable">, TLiteral<"quote_min_order_size">, TLiteral<"quote_stale_status">, TLiteral<"quote_stale_price">, TLiteral<"quote_insufficient_balance">, TLiteral<"quote_market_inactive">, TLiteral<"venue_not_executable">, TLiteral<"outcome_ambiguous">]>>;
1233
+ code: TOptional<TUnion<[TLiteral<"quote_not_found">, TLiteral<"quote_expired">, TLiteral<"quote_already_executed">, TLiteral<"quote_cancelled">, TLiteral<"quote_user_mismatch">, TLiteral<"quote_app_blocked">, TLiteral<"quote_unfillable">, TLiteral<"quote_min_order_size">, TLiteral<"quote_stale_status">, TLiteral<"quote_stale_price">, TLiteral<"quote_insufficient_balance">, TLiteral<"quote_market_inactive">, TLiteral<"quote_self_custody_unsupported_venue">, TLiteral<"quote_self_custody_app_fee">, TLiteral<"quote_self_custody_redeem_unsupported">, TLiteral<"venue_not_executable">, TLiteral<"outcome_ambiguous">]>>;
1234
1234
  }>;
1235
1235
  type QuoteError = Static<typeof QuoteErrorTB>;
1236
1236
 
@@ -2090,9 +2090,13 @@ type AggAuthStartResult = {
2090
2090
  /**
2091
2091
  * Body for `POST /users/me/link-account/start` — authenticated account linking.
2092
2092
  *
2093
- * `redirectUrl` is required for every provider: the callback / magic-link verify
2094
- * hands the partner a `link_confirm_token` by redirecting to `redirectUrl`, and
2095
- * the partner app completes the flow by calling `/confirm` from that page.
2093
+ * `redirectUrl` is required for OAuth/email providers: the callback / magic-link
2094
+ * verify hands the partner a `link_confirm_token` by redirecting to `redirectUrl`,
2095
+ * and the partner app completes the flow by calling `/confirm` from that page.
2096
+ *
2097
+ * Wallet providers (`siwe`/`siws`) instead return a `wallet_challenge` with a
2098
+ * `message` the user signs VERBATIM; the signature is then confirmed with
2099
+ * `{ kind: "wallet_signature", message, signature }`.
2096
2100
  */
2097
2101
  type AggLinkAccountBody = {
2098
2102
  provider: "google" | "twitter" | "apple";
@@ -2101,6 +2105,9 @@ type AggLinkAccountBody = {
2101
2105
  provider: "email";
2102
2106
  email: string;
2103
2107
  redirectUrl: string;
2108
+ } | {
2109
+ provider: "siwe" | "siws";
2110
+ address: string;
2104
2111
  };
2105
2112
  type AggLinkAccountResult = {
2106
2113
  type: "redirect";
@@ -2108,6 +2115,20 @@ type AggLinkAccountResult = {
2108
2115
  } | {
2109
2116
  type: "magic_link";
2110
2117
  success: true;
2118
+ } | {
2119
+ type: "wallet_challenge";
2120
+ message: string;
2121
+ };
2122
+ /**
2123
+ * Wallet branch of `POST /users/me/link-account/confirm`. Requires `kind` so it
2124
+ * can never be confused with the `token` branch. `message` MUST be the exact
2125
+ * `message` returned by `/start`'s `wallet_challenge` — the server compares it
2126
+ * byte-for-byte, so do not reconstruct or edit it client-side.
2127
+ */
2128
+ type AggLinkAccountWalletConfirmBody = {
2129
+ kind: "wallet_signature";
2130
+ message: string;
2131
+ signature: string;
2111
2132
  };
2112
2133
  /**
2113
2134
  * Success result of /users/me/link-account/confirm.
@@ -2143,6 +2164,82 @@ interface PersistedAuthSnapshot {
2143
2164
  }
2144
2165
  /** Auth lifecycle status for UI state machines. */
2145
2166
  type AuthStatus = "unknown" | "authenticated" | "unauthenticated";
2167
+ type SignatureRequestType = "eip712" | "personal_sign"
2168
+ /** EVM transaction — bridge legs and approvals. secp256k1. */
2169
+ | "transaction"
2170
+ /** Solana transaction — bridge legs on SVM. ed25519, NOT secp256k1. */
2171
+ | "solana_transaction" | "hl_l1_action"
2172
+ /**
2173
+ * EIP-7702 authorization over `{ contractAddress, chainId, nonce }`.
2174
+ *
2175
+ * A signature over a RAW digest — `keccak(0x05 ‖ rlp([chainId, delegate,
2176
+ * nonce]))` — not EIP-191 and not EIP-712. Many wallets do not expose this,
2177
+ * and that is expected: reject it and the server falls back to asking the
2178
+ * user to broadcast a plain approve instead.
2179
+ */
2180
+ | "eip7702_authorization";
2181
+ /** One payload the client must sign before a fill can proceed. */
2182
+ interface SignatureRequest {
2183
+ /** Echo this back with the signature. */
2184
+ stepId: string;
2185
+ /** Payload shape. Discriminates how to sign — not which venue. */
2186
+ type: SignatureRequestType;
2187
+ venue: string;
2188
+ /** The address that must produce this signature. Sign with this key, not another. */
2189
+ signerAddress: string;
2190
+ /** Absent for non-EVM payloads (e.g. Hyperliquid L1 actions). */
2191
+ chainId?: number;
2192
+ /** Sign verbatim. */
2193
+ payload: unknown;
2194
+ expiresAt: string;
2195
+ }
2196
+ /**
2197
+ * Supplied by the partner. Receives a payload, returns a signature. The SDK
2198
+ * never sees the key.
2199
+ *
2200
+ * Return a 0x-prefixed hex string for anything the wallet SIGNS:
2201
+ *
2202
+ * - `eip712` — `signTypedData` over `payload`.
2203
+ * - `personal_sign` — `personal_sign` over `payload`.
2204
+ * - `hl_l1_action` — Hyperliquid L1 action, EIP-712 in phantom-agent form.
2205
+ * - `eip7702_authorization` — an EIP-7702 authorization over
2206
+ * `{ contractAddress, chainId, nonce }`. This is a signature over a RAW
2207
+ * digest, not EIP-191 and not EIP-712, and many wallets do not expose it.
2208
+ * **Throwing here does not help**: there is no reject verb, so a thrown
2209
+ * signer is indistinguishable from a slow user — the request simply expires
2210
+ * and the fill dies. If your wallet cannot produce this signature, declare
2211
+ * `approveMode: "user_broadcast"` on the fill instead and the approve is
2212
+ * requested as a `transaction` the user sends themselves. Handling this
2213
+ * request is what makes funding gasless.
2214
+ *
2215
+ * Return `{ txHash }` for anything the wallet BROADCASTS:
2216
+ *
2217
+ * - `transaction` — send it, then return the hash **immediately, without
2218
+ * awaiting the receipt**. The server watches for the mined receipt itself
2219
+ * and will not resume until it matches the request byte-for-byte.
2220
+ */
2221
+ type SignerFn = (req: SignatureRequest) => Promise<string | {
2222
+ txHash: string;
2223
+ }>;
2224
+ /**
2225
+ * How long `fillSelfCustody` will keep waiting before giving up.
2226
+ *
2227
+ * Covers a first-time user: sign the wallet-setup batch, wait for it on-chain,
2228
+ * then sign the order. Generous because the wait is a relayer transaction
2229
+ * confirming, not a human deciding.
2230
+ */
2231
+ declare const SELF_CUSTODY_FILL_TIMEOUT_MS: number;
2232
+ /** Gap between re-reads while an on-chain step is in flight. */
2233
+ declare const SELF_CUSTODY_POLL_INTERVAL_MS = 2000;
2234
+ /**
2235
+ * States a run never leaves. Everything else means "still working".
2236
+ *
2237
+ * Typed against `ExecutionOverallState` so a typo'd or renamed literal (e.g.
2238
+ * `cancelled` drifting to `canceled`) is a compile error instead of a state
2239
+ * that silently stops being treated as terminal. Mirrors
2240
+ * `ExecutionOverallStateTB` in the contract; keep the two in step.
2241
+ */
2242
+ declare const TERMINAL_EXECUTION_STATES: ReadonlySet<ExecutionOverallState>;
2146
2243
  type SportsGameStatus = "scheduled" | "live" | "paused" | "finished" | "cancelled" | "postponed" | "unknown";
2147
2244
  interface SportsLiveParticipant {
2148
2245
  position: "first" | "second";
@@ -2192,6 +2289,17 @@ interface AggClientOptions {
2192
2289
  * When authDelivery is "cookie-refresh", refresh tokens survive via HttpOnly cookies
2193
2290
  * and the SDK attempts a silent refresh on cold start. Defaults to true. */
2194
2291
  persistSession?: boolean;
2292
+ /**
2293
+ * Supplies signatures for self-custodial fills. Required whenever
2294
+ * `fillSelfCustody()` is called with `signingAddress` — the SDK never
2295
+ * holds a key itself, so without this option a fill that needs a
2296
+ * client-side signature cannot proceed. The signature requests never
2297
+ * come back on `POST /execution/fill` itself: `fillSelfCustody()` polls
2298
+ * `GET /execution/status` for them (`pendingSignatures`), signs each one
2299
+ * with this function, and posts the result to
2300
+ * `POST /execution/fill/:quoteId/signatures`.
2301
+ */
2302
+ signer?: SignerFn;
2195
2303
  }
2196
2304
  interface SiweMessageParams {
2197
2305
  domain: string;
@@ -2770,6 +2878,25 @@ interface ExecuteManagedParams {
2770
2878
  sellShares?: number;
2771
2879
  allowedVenues?: Venue[];
2772
2880
  };
2881
+ /**
2882
+ * Self-custody: the wallet that will sign this fill. Must be a wallet
2883
+ * already linked to this account. Omit for managed custody (the default).
2884
+ */
2885
+ signingAddress?: string;
2886
+ /**
2887
+ * Self-custody only: which approve shape a cross-chain fill uses when the
2888
+ * bridge needs an ERC20 approve. Omit (the default) for "sponsored" — we pay
2889
+ * the gas, but the wallet must sign a one-time EIP-7702 authorization over a
2890
+ * RAW DIGEST, which many wallets cannot produce. Send "user_broadcast" when
2891
+ * yours cannot: the user sends the approve and pays their own gas. Only your
2892
+ * client can know which applies — it is a property of the wallet software,
2893
+ * not of the address or the chain.
2894
+ *
2895
+ * Worth surfacing in your UI: "user_broadcast" never establishes the
2896
+ * delegation, so it charges gas on EVERY bridge. "sponsored" costs one
2897
+ * signature once per chain, then is free.
2898
+ */
2899
+ approveMode?: "sponsored" | "user_broadcast";
2773
2900
  }
2774
2901
  interface ExecuteManagedResponse {
2775
2902
  quoteId: string;
@@ -2777,6 +2904,17 @@ interface ExecuteManagedResponse {
2777
2904
  status: "pending";
2778
2905
  redeemId?: string;
2779
2906
  message?: string;
2907
+ /**
2908
+ * What this fill is waiting to be signed, if anything. On the immediate
2909
+ * `POST /execution/fill` response this is always absent or empty — even
2910
+ * for a self-custody fill, the DAG parks asynchronously, after this
2911
+ * response has already been sent. Real entries only ever come back from
2912
+ * polling `GET /execution/status` or from the next
2913
+ * `POST /execution/fill/:quoteId/signatures` response (this same shape,
2914
+ * reused). Drive the whole round trip through `fillSelfCustody()` rather
2915
+ * than reading this field on the fill response by hand.
2916
+ */
2917
+ pendingSignatures?: SignatureRequest[];
2780
2918
  }
2781
2919
  type LimitOrderTimeInForce = "GTC" | "GTD" | "FOK" | "FAK" | "IOC" | "ALO";
2782
2920
  interface PlaceLimitOrderParams {
@@ -3141,6 +3279,14 @@ interface ExecutionStatusResponse {
3141
3279
  dagProgress: ExecutionDagProgress | null;
3142
3280
  steps: ExecutionStatusStep[];
3143
3281
  orders: ExecutionStatusOrder[];
3282
+ /**
3283
+ * What this run is waiting to be signed, mirroring the fill response's
3284
+ * field of the same name. This is the polling route `fillSelfCustody` reads
3285
+ * while an on-chain step is in flight — a caller polling this route for
3286
+ * progress learns about newly-parked steps here too, not just from the
3287
+ * signatures endpoint.
3288
+ */
3289
+ pendingSignatures?: SignatureRequest[];
3144
3290
  }
3145
3291
  type ExecutionPositionsQuery = GetPositionsQuery & {
3146
3292
  mode?: ExecutionMode;
@@ -4017,6 +4163,8 @@ declare class AggClient {
4017
4163
  private authOptions?;
4018
4164
  /** In-flight refresh promise — serializes concurrent 401 retries so only one refresh runs. */
4019
4165
  private pendingRefresh;
4166
+ /** Partner-supplied signature callback for self-custodial fills. The SDK never sees a key. */
4167
+ private readonly signer?;
4020
4168
  constructor(options: AggClientOptions);
4021
4169
  private resolvePaperTradingAppId;
4022
4170
  private paperTradingAccountsPath;
@@ -4084,21 +4232,29 @@ declare class AggClient {
4084
4232
  * the bearer automatically. Response shape:
4085
4233
  * - OAuth providers → `{ type: "redirect", url }`; redirect the browser to `url`.
4086
4234
  * - Email → `{ type: "magic_link", success: true }`; check the destination inbox.
4235
+ * - Wallet providers (siwe/siws) → `{ type: "wallet_challenge", message }`; have the
4236
+ * user sign `message` VERBATIM, then submit it to `linkAccountConfirm()` as
4237
+ * `{ kind: "wallet_signature", message, signature }`.
4087
4238
  *
4088
- * After the provider callback runs, the browser lands back on the app's `redirectUrl`
4239
+ * After the OAuth/email callback runs, the browser lands back on the app's `redirectUrl`
4089
4240
  * with a `link_confirm_token` query param. Feed that token to `linkAccountConfirm()`
4090
4241
  * to persist the Account row.
4091
- *
4092
- * Wallet linking (siwe/siws) is not supported yet — it requires a different message
4093
- * binding protocol than sign-in to be safe against signature phishing.
4094
4242
  */
4095
4243
  linkAccount(body: AggLinkAccountBody): Promise<AggLinkAccountResult>;
4096
4244
  /**
4097
- * Exchange a `link_confirm_token` for a linked `Account` row. The server matches
4098
- * the current bearer's `principalId` to the token's `principalId` before writing —
4099
- * this is the final ownership check.
4245
+ * Finalize an account link.
4246
+ *
4247
+ * - Pass a `link_confirm_token` string (OAuth/email) to exchange it for a linked
4248
+ * `Account` row.
4249
+ * - Pass `{ kind: "wallet_signature", message, signature }` (wallet providers) to
4250
+ * verify the signature over the `wallet_challenge` `message` returned by
4251
+ * `linkAccount()`.
4252
+ *
4253
+ * The server matches the current bearer's `principalId` to the challenge/token's
4254
+ * `principalId` before writing — this is the final ownership check. A wallet already
4255
+ * linked to a DIFFERENT principal rejects with HTTP 409.
4100
4256
  */
4101
- linkAccountConfirm(token: string): Promise<AggLinkAccountConfirmResult>;
4257
+ linkAccountConfirm(input: string | AggLinkAccountWalletConfirmBody): Promise<AggLinkAccountConfirmResult>;
4102
4258
  /** Exchange a one-time auth code (from OAuth/magic-link callback) for tokens. */
4103
4259
  exchangeAuthCode(code: string): Promise<UserAuthResult>;
4104
4260
  /** Refresh the access token using the stored refresh token. */
@@ -4142,7 +4298,13 @@ declare class AggClient {
4142
4298
  * rollup (total cost, share-weighted avg price, to-win).
4143
4299
  */
4144
4300
  getExecutionOrders(params?: ExecutionOrdersQuery): Promise<PaginatedResponse<ExecutionOrderItem>>;
4145
- /** Get quote-scoped execution progress, DAG step state, and order leg terminal status. */
4301
+ /**
4302
+ * Get quote-scoped execution progress, DAG step state, and order leg
4303
+ * terminal status. Also carries `pendingSignatures` — this is the route
4304
+ * `fillSelfCustody` polls while an on-chain step is in flight, so a caller
4305
+ * already polling this for progress learns about newly-parked steps here
4306
+ * too, not just from the signatures endpoint.
4307
+ */
4146
4308
  getExecutionStatus(params: ExecutionStatusQuery): Promise<ExecutionStatusResponse>;
4147
4309
  /** Unified user activity feed (trades, deposits, withdrawals, bridges, wallet ops). */
4148
4310
  getUserActivity(params?: UserActivityQuery): Promise<PaginatedResponse<UserActivityItem>>;
@@ -4376,6 +4538,27 @@ declare class AggClient {
4376
4538
  }): AggWebSocket;
4377
4539
  /** Execute a previously quoted managed trade. Returns pending order IDs. */
4378
4540
  executeManaged(params: ExecuteManagedParams): Promise<ExecuteManagedResponse>;
4541
+ /** Submit signatures for a parked fill. Returns whatever is still outstanding. */
4542
+ submitFillSignatures(quoteId: string, signatures: Array<{
4543
+ stepId: string;
4544
+ signature?: string;
4545
+ txHash?: string;
4546
+ }>): Promise<ExecuteManagedResponse & {
4547
+ accepted?: number;
4548
+ }>;
4549
+ /**
4550
+ * Execute a quote in self-custodial mode.
4551
+ *
4552
+ * Identical to `executeManaged` when the server can sign for the user. When
4553
+ * it cannot, the DAG parks on a signature request instead — but that park
4554
+ * always happens asynchronously, in the trade-executor process, so it can
4555
+ * never show up on this `POST /execution/fill` response itself. This
4556
+ * drives the round trip from there: poll `getExecutionStatus` while an
4557
+ * on-chain step is in flight, sign whatever it hands back with the
4558
+ * configured `signer`, post the signatures back, and repeat until the
4559
+ * server reports nothing outstanding and the run reaches a terminal state.
4560
+ */
4561
+ fillSelfCustody(params: ExecuteManagedParams): Promise<ExecuteManagedResponse>;
4379
4562
  /** Place a managed limit order. Returns the venue-backed order state. */
4380
4563
  placeLimitOrder(params: PlaceLimitOrderParams): Promise<PlaceLimitOrderResponse>;
4381
4564
  /**
@@ -4552,4 +4735,4 @@ declare function aggregateMidpoint(midpoints: (number | null | undefined)[]): nu
4552
4735
 
4553
4736
  declare function createAggClient(options: AggClientOptions): AggClient;
4554
4737
 
4555
- export { ACTIVE_VENUES, type Account, AccountProvider, AccountType, AggApiError, type AggApiErrorInit, type AggApiFieldError, type AggAuthDeliveryMode, type AggAuthProviderType, type AggAuthStartBody, type AggAuthStartResult, type AggAuthVerifyBody, AggClient, type AggClientAuthOptions, type AggClientSessionInput, type AggLinkAccountBody, type AggLinkAccountConfirmResult, type AggLinkAccountResult, type AggSessionUser, AggWebSocket, type AggWebSocketCallbacks, type AggWebSocketOptions, type AggregatedOrderbookLevel, type AggregatedOrderbookResponse, type App, type AppClientConfigResponse, type AttributedOrderbook, type AttributedOrderbookLevel, type AuthCodeResponse, type AuthStatus, type AuthTokenResponse, type AuthUser, type BalanceRefillAttempt, type BalanceRefillAttemptStatus, type BalanceRefillPolicy, type BalanceRefillPolicyStatus, type BatchMidpointsResponse, type BatchOrderbooksResponse, type BookQuality, type BuildVenueUrlOpts, CONFIRMED_MATCH_STATUSES, type CancelManagedExecutionResponse, type Candle, CandleBuilder, type CandleInterval, type Category, Chain, type ChartBarsResponse, type ChartCandle, type ChartResolution, type ChartVenueCandles, type ComputeSplitsRequest, type ComputeSplitsResponse, type ComputeSplitsSelection, type CorrelatedMarketCascadeItem, type CorrelatedMarketCascadeResponse, type CorrelatedMarketQueryResult, type CorrelatedMarketSide, type CorrelatedMarketSignal, type CorrelatedMarketSignalBatch, type CorrelatedMarketSignalDirection, type CorrelatedMarketsStatus, type CreateApp, type CreateBalanceRefillPolicyParams, type CreatePaperTradingAccountParams, type CryptoReferencePriceError, type CryptoReferencePriceExternalMarketInput, type CryptoReferencePriceMarketInput, type CryptoReferencePriceResult, type CryptoReferencePriceSource, type CryptoReferencePriceTarget, type CryptoReferencePricesResponse, DEFAULT_BALANCE_REFILL_DAILY_CAP_RAW, DEFAULT_BALANCE_REFILL_MAX_FEE_RAW, type DepositAddressesPendingResponse, type DepositAddressesReadyResponse, type DepositAddressesResponse, type DepositAddressesSupportedChain, type DepositAddressesToken, type DepositStep, type DiagnosticCallback, type DiagnosticEvent, type ExecuteManagedParams, type ExecuteManagedRequest, type ExecuteManagedResponse, type ExecuteTradeRequest, type ExecuteTradeResponse, type ExecutionDagProgress, type ExecutionDisplayGroupStatus, type ExecutionDisplayStepKind, type ExecutionMode, type ExecutionOrderItem, type ExecutionOrdersQuery, type ExecutionOverallState, type ExecutionPositionGroup, type ExecutionPositionsQuery, type ExecutionStatusOrder, type ExecutionStatusQuery, type ExecutionStatusResponse, type ExecutionStatusStep, type GetBalanceQuery, type GetBalanceResponse, type GetCryptoReferencePricesOptions, type GetHoldingsQuery, type GetHoldingsResponse, type GetOrdersParams, type GetOrdersQuery, type GetPositionsParams, type GetPositionsQuery, type HelloResponse, IMAGE_SIZES, INACTIVE_VENUES, ImageSize, LIMIT_PRICE_RAW_SCALE, type LimitOrderTimeInForce, type LimitPriceSide, type LimitPriceTickAdjustment, type ListRecurringCryptoMarketsOptions, type ManagedBalancesParams, type MarkSource, type MarketPriceHistory, MarketStatus, MatchStatus, MatchType, type MatchedMidpoint, type MatchedMidpointOutcome, type MatchedOrderbookMarket, type MatchedVenueMarketOutcomeRef, type MidpointItem, type MidpointRow, type NewsFeedArticleFeedItem, type NewsFeedArticleFeedResponse, type NewsFeedArticleWithSummary, type NewsFeedLinkedMarket, type NewsFeedListResponse, type NewsFeedMarketFeedArticle, type NewsFeedMarketFeedItem, type NewsFeedMarketFeedResponse, type NewsFeedMarketNewsParams, type NewsFeedMarketNewsResponse, type NewsFeedMarketNewsResult, type NewsFeedPageOptions, type NewsFeedStatusResponse, type NonceResponse, type OrderListItem, type OrderListQuery, OrderStatus, OrderType, type Orderbook, type OrderbookBatchItemError, type OrderbookBatchItemErrorCode, type OrderbookBatchItemStatus, type OrderbookHistoryPoint, type OrderbookHistoryResponse, type OrderbookLevel, type OrderbookQuoteFill, type OrderbookQuoteParams, type OrderbookQuoteResponse, type OrderbookServiceUnavailableError, type OrderbookState, type OrderbooksOnlyError, type OutcomeMidpoint, type OutcomeMidpointRow, type OutcomeOrderbookResponse, type PaginatedResponse, type PaperTradingAccount, type PaperTradingAccountsPage, type PaperTradingAppOptions, type PaperTradingBalanceAdjustment, type PaperTradingBalanceResponse, type PaperTradingLiquidityStatus, type PaperTradingListParams, type PaperTradingMarkSource, type PaperTradingOrder, type PaperTradingOrdersPage, type PaperTradingPortfolio, type PaperTradingPosition, type PaperTradingPositionsPage, type PersistedAuthSnapshot, type PlaceLimitOrderParams, type PlaceLimitOrderResponse, type PlacePaperTradingOrderParams, type PositionGroup, type PositionRedeemStatus, type PricePoint, type PriceSource, type PricesHistoryResponse, type QuoteError, type QuoteErrorCode, RECURRENCE_CADENCES, type RampQuote, type RampQuoteRequest, type RampSessionRequest, type RampWidgetSession, type RecurrenceCadence, type RecurrenceFilter, type RecurringCryptoComparisonPoint, type RecurringCryptoComparisonPriceSource, type RecurringCryptoDuration, type RecurringCryptoDurationInput, type RecurringCryptoMarketMetrics, type RecurringCryptoMarketsResponse, type RecurringCryptoOrderbookDepthLevel, type RecurringCryptoOrderbookDepthSide, type RecurringCryptoOutcome, type RecurringCryptoOutcomeOrderbookDepth, type RecurringCryptoPriceComparison, type RecurringCryptoReferencePrice, type RecurringCryptoResolution, type RecurringCryptoSourceConfidence, type RecurringCryptoVenueMarket, type RecurringCryptoWindowComparisons, type RecurringCryptoWindowMarket, type RedeemLegResult, type RedeemLegStatus, type RedeemRequest, type RedeemResponse, type RequestedOrderbookMarket, type ResetPaperTradingAccountParams, type ResolveCorrelatedMarketsParams, type ResolveCorrelatedMarketsResponse, type ResolvedCorrelatedMarketsResponse, type RpcTokenResponse, type SafeParseFailure, type SafeParseResult, type SafeParseSuccess, type ServerWallet, type SetPaperTradingBalanceParams, type SettlementDiff, type SettlementDifference, type SettlementSource, type SetupDepositAddressStep, type SetupVenueKeyStep, type SimpleOrderbookLevel, type SmartRouteAllocation, type SmartRouteBridgeStep, type SmartRouteFeeBreakdown, type SmartRouteFill, type SmartRouteParams, type SmartRouteResponse, type SmartRouteSettlementLeg, type SmartRouteSettlementPlan, type SmartRouteSetupCostLine, type SmartRouteSide, type SmartRouteStatus, type SmartRouteVenueFill, type SplitsByAmountResult, type SportsGameStatus, type SportsLiveParticipant, type SportsLiveResponse, type SportsLiveState, type SyncBalancesResponse, TimeInForce, type TradeExecutorOrder, type TradeExecutorOrderListResponse, TradeSide$1 as TradeSide, type TradeSplit, type TradeStep, TurnstileChallengeError, type UnifiedBalanceResponse, type UpdateBalanceRefillPolicyParams, type UpdateUserBody, type UpsertVenueKey, type UserActivityBridge, type UserActivityDeposit, type UserActivityItem, type UserActivityQuery, type UserActivityRedeem, type UserActivityRedeemLeg, type UserActivityTrade, type UserActivityType, type UserActivityUserOp, type UserActivityWithdrawal, type UserHolding, type UserProfile, VENUES, VENUE_CHAIN_IDS, type ValidateBalanceOnClientStep, type ValidateManagedParams, type ValidateManagedRequest, type ValidateManagedResponse, type ValidateTradeRequest, type ValidateTradeResponse, Venue, type VenueEvent, type VenueEventListItem, type VenueEventWithMarkets, type VenueGeoPolicyEntry, type VenueGeoPolicyResponse, type VenueKeyStatus, type VenueKeySummary, type VenueMarket, type VenueMarketClusterNode, type VenueMarketListItem, type VenueMarketOutcome, type VenueMarketRef, type VenueOrderbookEntry, type VenueOrderbookLevel, type VenuePositionBalance, type VenuePriceInfo, type VenueSoloQuote, type VerifyBody, type VerifyResponse, type WalletChainBalance, type WalletTokenBalance, type WithdrawManagedParams, type WithdrawManagedRequest, type WithdrawManagedResponse, type WithdrawManagedSourceItem, type WithdrawPreviewParams, type WithdrawPreviewResponse, type WithdrawTokenSymbol, type WithdrawalExpected, type WithdrawalLeg, type WithdrawalLegStatus, type WithdrawalLegType, type WithdrawalLifecycleStatus, type WithdrawalQuoteParams, type WithdrawalQuoteResponse, type WithdrawalSource, type WithdrawalSourceItem, type WithdrawalSourceStatus, type WithdrawalSourceTokenSymbol, type WsArbFeedBatch, type WsArbFeedEntry, type WsArbMarketUpdate, type WsAttributedLevel, type WsAuthenticated, type WsBalanceUpdate, type WsCandleInterval, type WsClientMessage, type WsConnected, type WsError, type WsHeartbeat, type WsMarkSource, type WsMarketResolved, type WsOrderEvent, type WsOrderEventType, type WsOrderSubmitted, type WsOrderbookDelta, type WsOrderbookSnapshot, type WsRedeemEvent, type WsServerMessage, type WsSubscribed, type WsTrade, type WsUnsubscribed, type WsVenueBook, type WsVenueInfo, type WsVenueLevel, type WsWithdrawalLegStatus, type WsWithdrawalLifecycleEvent, type WsWithdrawalLifecycleLeg, type WsWithdrawalLifecycleStatus, adjustLimitPriceRawToTick, aggregateMidpoint, applyOrderbookDelta, buildVenueUrl, computeBestSplitsByAmount, computeChecksum, createAggClient, enumGuard, formatMarketQuestion, formatOutcomeLabel, formatOutcomeTitle, getBalanceRefillMaximumRaw, getEffectiveDisabledVenues, getWalletAddressFromUserProfile, hasShape, isAggApiError, isBalanceRefillWithinDailyCap, isEmail, isEnum, isFiniteNonNeg, isNonEmptyString, isVenueActive, isVenueDataVisible, isVenueInactive, mergeCandles, mergeClosedCandles, normalizeVenueMarketCluster, optimizedImageUrl, parse, parseEmail, parseEmailStrict, safeParse, snapshotToOrderbook, sortVenues };
4738
+ export { ACTIVE_VENUES, type Account, AccountProvider, AccountType, AggApiError, type AggApiErrorInit, type AggApiFieldError, type AggAuthDeliveryMode, type AggAuthProviderType, type AggAuthStartBody, type AggAuthStartResult, type AggAuthVerifyBody, AggClient, type AggClientAuthOptions, type AggClientOptions, type AggClientSessionInput, type AggLinkAccountBody, type AggLinkAccountConfirmResult, type AggLinkAccountResult, type AggLinkAccountWalletConfirmBody, type AggSessionUser, AggWebSocket, type AggWebSocketCallbacks, type AggWebSocketOptions, type AggregatedOrderbookLevel, type AggregatedOrderbookResponse, type App, type AppClientConfigResponse, type AttributedOrderbook, type AttributedOrderbookLevel, type AuthCodeResponse, type AuthStatus, type AuthTokenResponse, type AuthUser, type BalanceRefillAttempt, type BalanceRefillAttemptStatus, type BalanceRefillPolicy, type BalanceRefillPolicyStatus, type BatchMidpointsResponse, type BatchOrderbooksResponse, type BookQuality, type BuildVenueUrlOpts, CONFIRMED_MATCH_STATUSES, type CancelManagedExecutionResponse, type Candle, CandleBuilder, type CandleInterval, type Category, Chain, type ChartBarsResponse, type ChartCandle, type ChartResolution, type ChartVenueCandles, type ComputeSplitsRequest, type ComputeSplitsResponse, type ComputeSplitsSelection, type CorrelatedMarketCascadeItem, type CorrelatedMarketCascadeResponse, type CorrelatedMarketQueryResult, type CorrelatedMarketSide, type CorrelatedMarketSignal, type CorrelatedMarketSignalBatch, type CorrelatedMarketSignalDirection, type CorrelatedMarketsStatus, type CreateApp, type CreateBalanceRefillPolicyParams, type CreatePaperTradingAccountParams, type CryptoReferencePriceError, type CryptoReferencePriceExternalMarketInput, type CryptoReferencePriceMarketInput, type CryptoReferencePriceResult, type CryptoReferencePriceSource, type CryptoReferencePriceTarget, type CryptoReferencePricesResponse, DEFAULT_BALANCE_REFILL_DAILY_CAP_RAW, DEFAULT_BALANCE_REFILL_MAX_FEE_RAW, type DepositAddressesPendingResponse, type DepositAddressesReadyResponse, type DepositAddressesResponse, type DepositAddressesSupportedChain, type DepositAddressesToken, type DepositStep, type DiagnosticCallback, type DiagnosticEvent, type ExecuteManagedParams, type ExecuteManagedRequest, type ExecuteManagedResponse, type ExecuteTradeRequest, type ExecuteTradeResponse, type ExecutionDagProgress, type ExecutionDisplayGroupStatus, type ExecutionDisplayStepKind, type ExecutionMode, type ExecutionOrderItem, type ExecutionOrdersQuery, type ExecutionOverallState, type ExecutionPositionGroup, type ExecutionPositionsQuery, type ExecutionStatusOrder, type ExecutionStatusQuery, type ExecutionStatusResponse, type ExecutionStatusStep, type GetBalanceQuery, type GetBalanceResponse, type GetCryptoReferencePricesOptions, type GetHoldingsQuery, type GetHoldingsResponse, type GetOrdersParams, type GetOrdersQuery, type GetPositionsParams, type GetPositionsQuery, type HelloResponse, IMAGE_SIZES, INACTIVE_VENUES, ImageSize, LIMIT_PRICE_RAW_SCALE, type LimitOrderTimeInForce, type LimitPriceSide, type LimitPriceTickAdjustment, type ListRecurringCryptoMarketsOptions, type ManagedBalancesParams, type MarkSource, type MarketPriceHistory, MarketStatus, MatchStatus, MatchType, type MatchedMidpoint, type MatchedMidpointOutcome, type MatchedOrderbookMarket, type MatchedVenueMarketOutcomeRef, type MidpointItem, type MidpointRow, type NewsFeedArticleFeedItem, type NewsFeedArticleFeedResponse, type NewsFeedArticleWithSummary, type NewsFeedLinkedMarket, type NewsFeedListResponse, type NewsFeedMarketFeedArticle, type NewsFeedMarketFeedItem, type NewsFeedMarketFeedResponse, type NewsFeedMarketNewsParams, type NewsFeedMarketNewsResponse, type NewsFeedMarketNewsResult, type NewsFeedPageOptions, type NewsFeedStatusResponse, type NonceResponse, type OrderListItem, type OrderListQuery, OrderStatus, OrderType, type Orderbook, type OrderbookBatchItemError, type OrderbookBatchItemErrorCode, type OrderbookBatchItemStatus, type OrderbookHistoryPoint, type OrderbookHistoryResponse, type OrderbookLevel, type OrderbookQuoteFill, type OrderbookQuoteParams, type OrderbookQuoteResponse, type OrderbookServiceUnavailableError, type OrderbookState, type OrderbooksOnlyError, type OutcomeMidpoint, type OutcomeMidpointRow, type OutcomeOrderbookResponse, type PaginatedResponse, type PaperTradingAccount, type PaperTradingAccountsPage, type PaperTradingAppOptions, type PaperTradingBalanceAdjustment, type PaperTradingBalanceResponse, type PaperTradingLiquidityStatus, type PaperTradingListParams, type PaperTradingMarkSource, type PaperTradingOrder, type PaperTradingOrdersPage, type PaperTradingPortfolio, type PaperTradingPosition, type PaperTradingPositionsPage, type PersistedAuthSnapshot, type PlaceLimitOrderParams, type PlaceLimitOrderResponse, type PlacePaperTradingOrderParams, type PositionGroup, type PositionRedeemStatus, type PricePoint, type PriceSource, type PricesHistoryResponse, type QuoteError, type QuoteErrorCode, RECURRENCE_CADENCES, type RampQuote, type RampQuoteRequest, type RampSessionRequest, type RampWidgetSession, type RecurrenceCadence, type RecurrenceFilter, type RecurringCryptoComparisonPoint, type RecurringCryptoComparisonPriceSource, type RecurringCryptoDuration, type RecurringCryptoDurationInput, type RecurringCryptoMarketMetrics, type RecurringCryptoMarketsResponse, type RecurringCryptoOrderbookDepthLevel, type RecurringCryptoOrderbookDepthSide, type RecurringCryptoOutcome, type RecurringCryptoOutcomeOrderbookDepth, type RecurringCryptoPriceComparison, type RecurringCryptoReferencePrice, type RecurringCryptoResolution, type RecurringCryptoSourceConfidence, type RecurringCryptoVenueMarket, type RecurringCryptoWindowComparisons, type RecurringCryptoWindowMarket, type RedeemLegResult, type RedeemLegStatus, type RedeemRequest, type RedeemResponse, type RequestedOrderbookMarket, type ResetPaperTradingAccountParams, type ResolveCorrelatedMarketsParams, type ResolveCorrelatedMarketsResponse, type ResolvedCorrelatedMarketsResponse, type RpcTokenResponse, SELF_CUSTODY_FILL_TIMEOUT_MS, SELF_CUSTODY_POLL_INTERVAL_MS, type SafeParseFailure, type SafeParseResult, type SafeParseSuccess, type ServerWallet, type SetPaperTradingBalanceParams, type SettlementDiff, type SettlementDifference, type SettlementSource, type SetupDepositAddressStep, type SetupVenueKeyStep, type SignatureRequest, type SignatureRequestType, type SignerFn, type SimpleOrderbookLevel, type SmartRouteAllocation, type SmartRouteBridgeStep, type SmartRouteFeeBreakdown, type SmartRouteFill, type SmartRouteParams, type SmartRouteResponse, type SmartRouteSettlementLeg, type SmartRouteSettlementPlan, type SmartRouteSetupCostLine, type SmartRouteSide, type SmartRouteStatus, type SmartRouteVenueFill, type SplitsByAmountResult, type SportsGameStatus, type SportsLiveParticipant, type SportsLiveResponse, type SportsLiveState, type SyncBalancesResponse, TERMINAL_EXECUTION_STATES, TimeInForce, type TradeExecutorOrder, type TradeExecutorOrderListResponse, TradeSide$1 as TradeSide, type TradeSplit, type TradeStep, TurnstileChallengeError, type UnifiedBalanceResponse, type UpdateBalanceRefillPolicyParams, type UpdateUserBody, type UpsertVenueKey, type UserActivityBridge, type UserActivityDeposit, type UserActivityItem, type UserActivityQuery, type UserActivityRedeem, type UserActivityRedeemLeg, type UserActivityTrade, type UserActivityType, type UserActivityUserOp, type UserActivityWithdrawal, type UserHolding, type UserProfile, VENUES, VENUE_CHAIN_IDS, type ValidateBalanceOnClientStep, type ValidateManagedParams, type ValidateManagedRequest, type ValidateManagedResponse, type ValidateTradeRequest, type ValidateTradeResponse, Venue, type VenueEvent, type VenueEventListItem, type VenueEventWithMarkets, type VenueGeoPolicyEntry, type VenueGeoPolicyResponse, type VenueKeyStatus, type VenueKeySummary, type VenueMarket, type VenueMarketClusterNode, type VenueMarketListItem, type VenueMarketOutcome, type VenueMarketRef, type VenueOrderbookEntry, type VenueOrderbookLevel, type VenuePositionBalance, type VenuePriceInfo, type VenueSoloQuote, type VerifyBody, type VerifyResponse, type WalletChainBalance, type WalletTokenBalance, type WithdrawManagedParams, type WithdrawManagedRequest, type WithdrawManagedResponse, type WithdrawManagedSourceItem, type WithdrawPreviewParams, type WithdrawPreviewResponse, type WithdrawTokenSymbol, type WithdrawalExpected, type WithdrawalLeg, type WithdrawalLegStatus, type WithdrawalLegType, type WithdrawalLifecycleStatus, type WithdrawalQuoteParams, type WithdrawalQuoteResponse, type WithdrawalSource, type WithdrawalSourceItem, type WithdrawalSourceStatus, type WithdrawalSourceTokenSymbol, type WsArbFeedBatch, type WsArbFeedEntry, type WsArbMarketUpdate, type WsAttributedLevel, type WsAuthenticated, type WsBalanceUpdate, type WsCandleInterval, type WsClientMessage, type WsConnected, type WsError, type WsHeartbeat, type WsMarkSource, type WsMarketResolved, type WsOrderEvent, type WsOrderEventType, type WsOrderSubmitted, type WsOrderbookDelta, type WsOrderbookSnapshot, type WsRedeemEvent, type WsServerMessage, type WsSubscribed, type WsTrade, type WsUnsubscribed, type WsVenueBook, type WsVenueInfo, type WsVenueLevel, type WsWithdrawalLegStatus, type WsWithdrawalLifecycleEvent, type WsWithdrawalLifecycleLeg, type WsWithdrawalLifecycleStatus, adjustLimitPriceRawToTick, aggregateMidpoint, applyOrderbookDelta, buildVenueUrl, computeBestSplitsByAmount, computeChecksum, createAggClient, enumGuard, formatMarketQuestion, formatOutcomeLabel, formatOutcomeTitle, getBalanceRefillMaximumRaw, getEffectiveDisabledVenues, getWalletAddressFromUserProfile, hasShape, isAggApiError, isBalanceRefillWithinDailyCap, isEmail, isEnum, isFiniteNonNeg, isNonEmptyString, isVenueActive, isVenueDataVisible, isVenueInactive, mergeCandles, mergeClosedCandles, normalizeVenueMarketCluster, optimizedImageUrl, parse, parseEmail, parseEmailStrict, safeParse, snapshotToOrderbook, sortVenues };
package/dist/index.d.ts CHANGED
@@ -1226,11 +1226,11 @@ interface TSchema extends TKind, SchemaOptions {
1226
1226
  * Always carry a human-readable `message` alongside; the code is additive and
1227
1227
  * may be absent on rejections that pre-date this addition.
1228
1228
  */
1229
- declare const QuoteErrorCodeTB: TUnion<[TLiteral<"quote_not_found">, TLiteral<"quote_expired">, TLiteral<"quote_already_executed">, TLiteral<"quote_cancelled">, TLiteral<"quote_user_mismatch">, TLiteral<"quote_app_blocked">, TLiteral<"quote_unfillable">, TLiteral<"quote_min_order_size">, TLiteral<"quote_stale_status">, TLiteral<"quote_stale_price">, TLiteral<"quote_insufficient_balance">, TLiteral<"quote_market_inactive">, TLiteral<"venue_not_executable">, TLiteral<"outcome_ambiguous">]>;
1229
+ declare const QuoteErrorCodeTB: TUnion<[TLiteral<"quote_not_found">, TLiteral<"quote_expired">, TLiteral<"quote_already_executed">, TLiteral<"quote_cancelled">, TLiteral<"quote_user_mismatch">, TLiteral<"quote_app_blocked">, TLiteral<"quote_unfillable">, TLiteral<"quote_min_order_size">, TLiteral<"quote_stale_status">, TLiteral<"quote_stale_price">, TLiteral<"quote_insufficient_balance">, TLiteral<"quote_market_inactive">, TLiteral<"quote_self_custody_unsupported_venue">, TLiteral<"quote_self_custody_app_fee">, TLiteral<"quote_self_custody_redeem_unsupported">, TLiteral<"venue_not_executable">, TLiteral<"outcome_ambiguous">]>;
1230
1230
  type QuoteErrorCode = Static<typeof QuoteErrorCodeTB>;
1231
1231
  declare const QuoteErrorTB: TObject<{
1232
1232
  message: TString;
1233
- code: TOptional<TUnion<[TLiteral<"quote_not_found">, TLiteral<"quote_expired">, TLiteral<"quote_already_executed">, TLiteral<"quote_cancelled">, TLiteral<"quote_user_mismatch">, TLiteral<"quote_app_blocked">, TLiteral<"quote_unfillable">, TLiteral<"quote_min_order_size">, TLiteral<"quote_stale_status">, TLiteral<"quote_stale_price">, TLiteral<"quote_insufficient_balance">, TLiteral<"quote_market_inactive">, TLiteral<"venue_not_executable">, TLiteral<"outcome_ambiguous">]>>;
1233
+ code: TOptional<TUnion<[TLiteral<"quote_not_found">, TLiteral<"quote_expired">, TLiteral<"quote_already_executed">, TLiteral<"quote_cancelled">, TLiteral<"quote_user_mismatch">, TLiteral<"quote_app_blocked">, TLiteral<"quote_unfillable">, TLiteral<"quote_min_order_size">, TLiteral<"quote_stale_status">, TLiteral<"quote_stale_price">, TLiteral<"quote_insufficient_balance">, TLiteral<"quote_market_inactive">, TLiteral<"quote_self_custody_unsupported_venue">, TLiteral<"quote_self_custody_app_fee">, TLiteral<"quote_self_custody_redeem_unsupported">, TLiteral<"venue_not_executable">, TLiteral<"outcome_ambiguous">]>>;
1234
1234
  }>;
1235
1235
  type QuoteError = Static<typeof QuoteErrorTB>;
1236
1236
 
@@ -2090,9 +2090,13 @@ type AggAuthStartResult = {
2090
2090
  /**
2091
2091
  * Body for `POST /users/me/link-account/start` — authenticated account linking.
2092
2092
  *
2093
- * `redirectUrl` is required for every provider: the callback / magic-link verify
2094
- * hands the partner a `link_confirm_token` by redirecting to `redirectUrl`, and
2095
- * the partner app completes the flow by calling `/confirm` from that page.
2093
+ * `redirectUrl` is required for OAuth/email providers: the callback / magic-link
2094
+ * verify hands the partner a `link_confirm_token` by redirecting to `redirectUrl`,
2095
+ * and the partner app completes the flow by calling `/confirm` from that page.
2096
+ *
2097
+ * Wallet providers (`siwe`/`siws`) instead return a `wallet_challenge` with a
2098
+ * `message` the user signs VERBATIM; the signature is then confirmed with
2099
+ * `{ kind: "wallet_signature", message, signature }`.
2096
2100
  */
2097
2101
  type AggLinkAccountBody = {
2098
2102
  provider: "google" | "twitter" | "apple";
@@ -2101,6 +2105,9 @@ type AggLinkAccountBody = {
2101
2105
  provider: "email";
2102
2106
  email: string;
2103
2107
  redirectUrl: string;
2108
+ } | {
2109
+ provider: "siwe" | "siws";
2110
+ address: string;
2104
2111
  };
2105
2112
  type AggLinkAccountResult = {
2106
2113
  type: "redirect";
@@ -2108,6 +2115,20 @@ type AggLinkAccountResult = {
2108
2115
  } | {
2109
2116
  type: "magic_link";
2110
2117
  success: true;
2118
+ } | {
2119
+ type: "wallet_challenge";
2120
+ message: string;
2121
+ };
2122
+ /**
2123
+ * Wallet branch of `POST /users/me/link-account/confirm`. Requires `kind` so it
2124
+ * can never be confused with the `token` branch. `message` MUST be the exact
2125
+ * `message` returned by `/start`'s `wallet_challenge` — the server compares it
2126
+ * byte-for-byte, so do not reconstruct or edit it client-side.
2127
+ */
2128
+ type AggLinkAccountWalletConfirmBody = {
2129
+ kind: "wallet_signature";
2130
+ message: string;
2131
+ signature: string;
2111
2132
  };
2112
2133
  /**
2113
2134
  * Success result of /users/me/link-account/confirm.
@@ -2143,6 +2164,82 @@ interface PersistedAuthSnapshot {
2143
2164
  }
2144
2165
  /** Auth lifecycle status for UI state machines. */
2145
2166
  type AuthStatus = "unknown" | "authenticated" | "unauthenticated";
2167
+ type SignatureRequestType = "eip712" | "personal_sign"
2168
+ /** EVM transaction — bridge legs and approvals. secp256k1. */
2169
+ | "transaction"
2170
+ /** Solana transaction — bridge legs on SVM. ed25519, NOT secp256k1. */
2171
+ | "solana_transaction" | "hl_l1_action"
2172
+ /**
2173
+ * EIP-7702 authorization over `{ contractAddress, chainId, nonce }`.
2174
+ *
2175
+ * A signature over a RAW digest — `keccak(0x05 ‖ rlp([chainId, delegate,
2176
+ * nonce]))` — not EIP-191 and not EIP-712. Many wallets do not expose this,
2177
+ * and that is expected: reject it and the server falls back to asking the
2178
+ * user to broadcast a plain approve instead.
2179
+ */
2180
+ | "eip7702_authorization";
2181
+ /** One payload the client must sign before a fill can proceed. */
2182
+ interface SignatureRequest {
2183
+ /** Echo this back with the signature. */
2184
+ stepId: string;
2185
+ /** Payload shape. Discriminates how to sign — not which venue. */
2186
+ type: SignatureRequestType;
2187
+ venue: string;
2188
+ /** The address that must produce this signature. Sign with this key, not another. */
2189
+ signerAddress: string;
2190
+ /** Absent for non-EVM payloads (e.g. Hyperliquid L1 actions). */
2191
+ chainId?: number;
2192
+ /** Sign verbatim. */
2193
+ payload: unknown;
2194
+ expiresAt: string;
2195
+ }
2196
+ /**
2197
+ * Supplied by the partner. Receives a payload, returns a signature. The SDK
2198
+ * never sees the key.
2199
+ *
2200
+ * Return a 0x-prefixed hex string for anything the wallet SIGNS:
2201
+ *
2202
+ * - `eip712` — `signTypedData` over `payload`.
2203
+ * - `personal_sign` — `personal_sign` over `payload`.
2204
+ * - `hl_l1_action` — Hyperliquid L1 action, EIP-712 in phantom-agent form.
2205
+ * - `eip7702_authorization` — an EIP-7702 authorization over
2206
+ * `{ contractAddress, chainId, nonce }`. This is a signature over a RAW
2207
+ * digest, not EIP-191 and not EIP-712, and many wallets do not expose it.
2208
+ * **Throwing here does not help**: there is no reject verb, so a thrown
2209
+ * signer is indistinguishable from a slow user — the request simply expires
2210
+ * and the fill dies. If your wallet cannot produce this signature, declare
2211
+ * `approveMode: "user_broadcast"` on the fill instead and the approve is
2212
+ * requested as a `transaction` the user sends themselves. Handling this
2213
+ * request is what makes funding gasless.
2214
+ *
2215
+ * Return `{ txHash }` for anything the wallet BROADCASTS:
2216
+ *
2217
+ * - `transaction` — send it, then return the hash **immediately, without
2218
+ * awaiting the receipt**. The server watches for the mined receipt itself
2219
+ * and will not resume until it matches the request byte-for-byte.
2220
+ */
2221
+ type SignerFn = (req: SignatureRequest) => Promise<string | {
2222
+ txHash: string;
2223
+ }>;
2224
+ /**
2225
+ * How long `fillSelfCustody` will keep waiting before giving up.
2226
+ *
2227
+ * Covers a first-time user: sign the wallet-setup batch, wait for it on-chain,
2228
+ * then sign the order. Generous because the wait is a relayer transaction
2229
+ * confirming, not a human deciding.
2230
+ */
2231
+ declare const SELF_CUSTODY_FILL_TIMEOUT_MS: number;
2232
+ /** Gap between re-reads while an on-chain step is in flight. */
2233
+ declare const SELF_CUSTODY_POLL_INTERVAL_MS = 2000;
2234
+ /**
2235
+ * States a run never leaves. Everything else means "still working".
2236
+ *
2237
+ * Typed against `ExecutionOverallState` so a typo'd or renamed literal (e.g.
2238
+ * `cancelled` drifting to `canceled`) is a compile error instead of a state
2239
+ * that silently stops being treated as terminal. Mirrors
2240
+ * `ExecutionOverallStateTB` in the contract; keep the two in step.
2241
+ */
2242
+ declare const TERMINAL_EXECUTION_STATES: ReadonlySet<ExecutionOverallState>;
2146
2243
  type SportsGameStatus = "scheduled" | "live" | "paused" | "finished" | "cancelled" | "postponed" | "unknown";
2147
2244
  interface SportsLiveParticipant {
2148
2245
  position: "first" | "second";
@@ -2192,6 +2289,17 @@ interface AggClientOptions {
2192
2289
  * When authDelivery is "cookie-refresh", refresh tokens survive via HttpOnly cookies
2193
2290
  * and the SDK attempts a silent refresh on cold start. Defaults to true. */
2194
2291
  persistSession?: boolean;
2292
+ /**
2293
+ * Supplies signatures for self-custodial fills. Required whenever
2294
+ * `fillSelfCustody()` is called with `signingAddress` — the SDK never
2295
+ * holds a key itself, so without this option a fill that needs a
2296
+ * client-side signature cannot proceed. The signature requests never
2297
+ * come back on `POST /execution/fill` itself: `fillSelfCustody()` polls
2298
+ * `GET /execution/status` for them (`pendingSignatures`), signs each one
2299
+ * with this function, and posts the result to
2300
+ * `POST /execution/fill/:quoteId/signatures`.
2301
+ */
2302
+ signer?: SignerFn;
2195
2303
  }
2196
2304
  interface SiweMessageParams {
2197
2305
  domain: string;
@@ -2770,6 +2878,25 @@ interface ExecuteManagedParams {
2770
2878
  sellShares?: number;
2771
2879
  allowedVenues?: Venue[];
2772
2880
  };
2881
+ /**
2882
+ * Self-custody: the wallet that will sign this fill. Must be a wallet
2883
+ * already linked to this account. Omit for managed custody (the default).
2884
+ */
2885
+ signingAddress?: string;
2886
+ /**
2887
+ * Self-custody only: which approve shape a cross-chain fill uses when the
2888
+ * bridge needs an ERC20 approve. Omit (the default) for "sponsored" — we pay
2889
+ * the gas, but the wallet must sign a one-time EIP-7702 authorization over a
2890
+ * RAW DIGEST, which many wallets cannot produce. Send "user_broadcast" when
2891
+ * yours cannot: the user sends the approve and pays their own gas. Only your
2892
+ * client can know which applies — it is a property of the wallet software,
2893
+ * not of the address or the chain.
2894
+ *
2895
+ * Worth surfacing in your UI: "user_broadcast" never establishes the
2896
+ * delegation, so it charges gas on EVERY bridge. "sponsored" costs one
2897
+ * signature once per chain, then is free.
2898
+ */
2899
+ approveMode?: "sponsored" | "user_broadcast";
2773
2900
  }
2774
2901
  interface ExecuteManagedResponse {
2775
2902
  quoteId: string;
@@ -2777,6 +2904,17 @@ interface ExecuteManagedResponse {
2777
2904
  status: "pending";
2778
2905
  redeemId?: string;
2779
2906
  message?: string;
2907
+ /**
2908
+ * What this fill is waiting to be signed, if anything. On the immediate
2909
+ * `POST /execution/fill` response this is always absent or empty — even
2910
+ * for a self-custody fill, the DAG parks asynchronously, after this
2911
+ * response has already been sent. Real entries only ever come back from
2912
+ * polling `GET /execution/status` or from the next
2913
+ * `POST /execution/fill/:quoteId/signatures` response (this same shape,
2914
+ * reused). Drive the whole round trip through `fillSelfCustody()` rather
2915
+ * than reading this field on the fill response by hand.
2916
+ */
2917
+ pendingSignatures?: SignatureRequest[];
2780
2918
  }
2781
2919
  type LimitOrderTimeInForce = "GTC" | "GTD" | "FOK" | "FAK" | "IOC" | "ALO";
2782
2920
  interface PlaceLimitOrderParams {
@@ -3141,6 +3279,14 @@ interface ExecutionStatusResponse {
3141
3279
  dagProgress: ExecutionDagProgress | null;
3142
3280
  steps: ExecutionStatusStep[];
3143
3281
  orders: ExecutionStatusOrder[];
3282
+ /**
3283
+ * What this run is waiting to be signed, mirroring the fill response's
3284
+ * field of the same name. This is the polling route `fillSelfCustody` reads
3285
+ * while an on-chain step is in flight — a caller polling this route for
3286
+ * progress learns about newly-parked steps here too, not just from the
3287
+ * signatures endpoint.
3288
+ */
3289
+ pendingSignatures?: SignatureRequest[];
3144
3290
  }
3145
3291
  type ExecutionPositionsQuery = GetPositionsQuery & {
3146
3292
  mode?: ExecutionMode;
@@ -4017,6 +4163,8 @@ declare class AggClient {
4017
4163
  private authOptions?;
4018
4164
  /** In-flight refresh promise — serializes concurrent 401 retries so only one refresh runs. */
4019
4165
  private pendingRefresh;
4166
+ /** Partner-supplied signature callback for self-custodial fills. The SDK never sees a key. */
4167
+ private readonly signer?;
4020
4168
  constructor(options: AggClientOptions);
4021
4169
  private resolvePaperTradingAppId;
4022
4170
  private paperTradingAccountsPath;
@@ -4084,21 +4232,29 @@ declare class AggClient {
4084
4232
  * the bearer automatically. Response shape:
4085
4233
  * - OAuth providers → `{ type: "redirect", url }`; redirect the browser to `url`.
4086
4234
  * - Email → `{ type: "magic_link", success: true }`; check the destination inbox.
4235
+ * - Wallet providers (siwe/siws) → `{ type: "wallet_challenge", message }`; have the
4236
+ * user sign `message` VERBATIM, then submit it to `linkAccountConfirm()` as
4237
+ * `{ kind: "wallet_signature", message, signature }`.
4087
4238
  *
4088
- * After the provider callback runs, the browser lands back on the app's `redirectUrl`
4239
+ * After the OAuth/email callback runs, the browser lands back on the app's `redirectUrl`
4089
4240
  * with a `link_confirm_token` query param. Feed that token to `linkAccountConfirm()`
4090
4241
  * to persist the Account row.
4091
- *
4092
- * Wallet linking (siwe/siws) is not supported yet — it requires a different message
4093
- * binding protocol than sign-in to be safe against signature phishing.
4094
4242
  */
4095
4243
  linkAccount(body: AggLinkAccountBody): Promise<AggLinkAccountResult>;
4096
4244
  /**
4097
- * Exchange a `link_confirm_token` for a linked `Account` row. The server matches
4098
- * the current bearer's `principalId` to the token's `principalId` before writing —
4099
- * this is the final ownership check.
4245
+ * Finalize an account link.
4246
+ *
4247
+ * - Pass a `link_confirm_token` string (OAuth/email) to exchange it for a linked
4248
+ * `Account` row.
4249
+ * - Pass `{ kind: "wallet_signature", message, signature }` (wallet providers) to
4250
+ * verify the signature over the `wallet_challenge` `message` returned by
4251
+ * `linkAccount()`.
4252
+ *
4253
+ * The server matches the current bearer's `principalId` to the challenge/token's
4254
+ * `principalId` before writing — this is the final ownership check. A wallet already
4255
+ * linked to a DIFFERENT principal rejects with HTTP 409.
4100
4256
  */
4101
- linkAccountConfirm(token: string): Promise<AggLinkAccountConfirmResult>;
4257
+ linkAccountConfirm(input: string | AggLinkAccountWalletConfirmBody): Promise<AggLinkAccountConfirmResult>;
4102
4258
  /** Exchange a one-time auth code (from OAuth/magic-link callback) for tokens. */
4103
4259
  exchangeAuthCode(code: string): Promise<UserAuthResult>;
4104
4260
  /** Refresh the access token using the stored refresh token. */
@@ -4142,7 +4298,13 @@ declare class AggClient {
4142
4298
  * rollup (total cost, share-weighted avg price, to-win).
4143
4299
  */
4144
4300
  getExecutionOrders(params?: ExecutionOrdersQuery): Promise<PaginatedResponse<ExecutionOrderItem>>;
4145
- /** Get quote-scoped execution progress, DAG step state, and order leg terminal status. */
4301
+ /**
4302
+ * Get quote-scoped execution progress, DAG step state, and order leg
4303
+ * terminal status. Also carries `pendingSignatures` — this is the route
4304
+ * `fillSelfCustody` polls while an on-chain step is in flight, so a caller
4305
+ * already polling this for progress learns about newly-parked steps here
4306
+ * too, not just from the signatures endpoint.
4307
+ */
4146
4308
  getExecutionStatus(params: ExecutionStatusQuery): Promise<ExecutionStatusResponse>;
4147
4309
  /** Unified user activity feed (trades, deposits, withdrawals, bridges, wallet ops). */
4148
4310
  getUserActivity(params?: UserActivityQuery): Promise<PaginatedResponse<UserActivityItem>>;
@@ -4376,6 +4538,27 @@ declare class AggClient {
4376
4538
  }): AggWebSocket;
4377
4539
  /** Execute a previously quoted managed trade. Returns pending order IDs. */
4378
4540
  executeManaged(params: ExecuteManagedParams): Promise<ExecuteManagedResponse>;
4541
+ /** Submit signatures for a parked fill. Returns whatever is still outstanding. */
4542
+ submitFillSignatures(quoteId: string, signatures: Array<{
4543
+ stepId: string;
4544
+ signature?: string;
4545
+ txHash?: string;
4546
+ }>): Promise<ExecuteManagedResponse & {
4547
+ accepted?: number;
4548
+ }>;
4549
+ /**
4550
+ * Execute a quote in self-custodial mode.
4551
+ *
4552
+ * Identical to `executeManaged` when the server can sign for the user. When
4553
+ * it cannot, the DAG parks on a signature request instead — but that park
4554
+ * always happens asynchronously, in the trade-executor process, so it can
4555
+ * never show up on this `POST /execution/fill` response itself. This
4556
+ * drives the round trip from there: poll `getExecutionStatus` while an
4557
+ * on-chain step is in flight, sign whatever it hands back with the
4558
+ * configured `signer`, post the signatures back, and repeat until the
4559
+ * server reports nothing outstanding and the run reaches a terminal state.
4560
+ */
4561
+ fillSelfCustody(params: ExecuteManagedParams): Promise<ExecuteManagedResponse>;
4379
4562
  /** Place a managed limit order. Returns the venue-backed order state. */
4380
4563
  placeLimitOrder(params: PlaceLimitOrderParams): Promise<PlaceLimitOrderResponse>;
4381
4564
  /**
@@ -4552,4 +4735,4 @@ declare function aggregateMidpoint(midpoints: (number | null | undefined)[]): nu
4552
4735
 
4553
4736
  declare function createAggClient(options: AggClientOptions): AggClient;
4554
4737
 
4555
- export { ACTIVE_VENUES, type Account, AccountProvider, AccountType, AggApiError, type AggApiErrorInit, type AggApiFieldError, type AggAuthDeliveryMode, type AggAuthProviderType, type AggAuthStartBody, type AggAuthStartResult, type AggAuthVerifyBody, AggClient, type AggClientAuthOptions, type AggClientSessionInput, type AggLinkAccountBody, type AggLinkAccountConfirmResult, type AggLinkAccountResult, type AggSessionUser, AggWebSocket, type AggWebSocketCallbacks, type AggWebSocketOptions, type AggregatedOrderbookLevel, type AggregatedOrderbookResponse, type App, type AppClientConfigResponse, type AttributedOrderbook, type AttributedOrderbookLevel, type AuthCodeResponse, type AuthStatus, type AuthTokenResponse, type AuthUser, type BalanceRefillAttempt, type BalanceRefillAttemptStatus, type BalanceRefillPolicy, type BalanceRefillPolicyStatus, type BatchMidpointsResponse, type BatchOrderbooksResponse, type BookQuality, type BuildVenueUrlOpts, CONFIRMED_MATCH_STATUSES, type CancelManagedExecutionResponse, type Candle, CandleBuilder, type CandleInterval, type Category, Chain, type ChartBarsResponse, type ChartCandle, type ChartResolution, type ChartVenueCandles, type ComputeSplitsRequest, type ComputeSplitsResponse, type ComputeSplitsSelection, type CorrelatedMarketCascadeItem, type CorrelatedMarketCascadeResponse, type CorrelatedMarketQueryResult, type CorrelatedMarketSide, type CorrelatedMarketSignal, type CorrelatedMarketSignalBatch, type CorrelatedMarketSignalDirection, type CorrelatedMarketsStatus, type CreateApp, type CreateBalanceRefillPolicyParams, type CreatePaperTradingAccountParams, type CryptoReferencePriceError, type CryptoReferencePriceExternalMarketInput, type CryptoReferencePriceMarketInput, type CryptoReferencePriceResult, type CryptoReferencePriceSource, type CryptoReferencePriceTarget, type CryptoReferencePricesResponse, DEFAULT_BALANCE_REFILL_DAILY_CAP_RAW, DEFAULT_BALANCE_REFILL_MAX_FEE_RAW, type DepositAddressesPendingResponse, type DepositAddressesReadyResponse, type DepositAddressesResponse, type DepositAddressesSupportedChain, type DepositAddressesToken, type DepositStep, type DiagnosticCallback, type DiagnosticEvent, type ExecuteManagedParams, type ExecuteManagedRequest, type ExecuteManagedResponse, type ExecuteTradeRequest, type ExecuteTradeResponse, type ExecutionDagProgress, type ExecutionDisplayGroupStatus, type ExecutionDisplayStepKind, type ExecutionMode, type ExecutionOrderItem, type ExecutionOrdersQuery, type ExecutionOverallState, type ExecutionPositionGroup, type ExecutionPositionsQuery, type ExecutionStatusOrder, type ExecutionStatusQuery, type ExecutionStatusResponse, type ExecutionStatusStep, type GetBalanceQuery, type GetBalanceResponse, type GetCryptoReferencePricesOptions, type GetHoldingsQuery, type GetHoldingsResponse, type GetOrdersParams, type GetOrdersQuery, type GetPositionsParams, type GetPositionsQuery, type HelloResponse, IMAGE_SIZES, INACTIVE_VENUES, ImageSize, LIMIT_PRICE_RAW_SCALE, type LimitOrderTimeInForce, type LimitPriceSide, type LimitPriceTickAdjustment, type ListRecurringCryptoMarketsOptions, type ManagedBalancesParams, type MarkSource, type MarketPriceHistory, MarketStatus, MatchStatus, MatchType, type MatchedMidpoint, type MatchedMidpointOutcome, type MatchedOrderbookMarket, type MatchedVenueMarketOutcomeRef, type MidpointItem, type MidpointRow, type NewsFeedArticleFeedItem, type NewsFeedArticleFeedResponse, type NewsFeedArticleWithSummary, type NewsFeedLinkedMarket, type NewsFeedListResponse, type NewsFeedMarketFeedArticle, type NewsFeedMarketFeedItem, type NewsFeedMarketFeedResponse, type NewsFeedMarketNewsParams, type NewsFeedMarketNewsResponse, type NewsFeedMarketNewsResult, type NewsFeedPageOptions, type NewsFeedStatusResponse, type NonceResponse, type OrderListItem, type OrderListQuery, OrderStatus, OrderType, type Orderbook, type OrderbookBatchItemError, type OrderbookBatchItemErrorCode, type OrderbookBatchItemStatus, type OrderbookHistoryPoint, type OrderbookHistoryResponse, type OrderbookLevel, type OrderbookQuoteFill, type OrderbookQuoteParams, type OrderbookQuoteResponse, type OrderbookServiceUnavailableError, type OrderbookState, type OrderbooksOnlyError, type OutcomeMidpoint, type OutcomeMidpointRow, type OutcomeOrderbookResponse, type PaginatedResponse, type PaperTradingAccount, type PaperTradingAccountsPage, type PaperTradingAppOptions, type PaperTradingBalanceAdjustment, type PaperTradingBalanceResponse, type PaperTradingLiquidityStatus, type PaperTradingListParams, type PaperTradingMarkSource, type PaperTradingOrder, type PaperTradingOrdersPage, type PaperTradingPortfolio, type PaperTradingPosition, type PaperTradingPositionsPage, type PersistedAuthSnapshot, type PlaceLimitOrderParams, type PlaceLimitOrderResponse, type PlacePaperTradingOrderParams, type PositionGroup, type PositionRedeemStatus, type PricePoint, type PriceSource, type PricesHistoryResponse, type QuoteError, type QuoteErrorCode, RECURRENCE_CADENCES, type RampQuote, type RampQuoteRequest, type RampSessionRequest, type RampWidgetSession, type RecurrenceCadence, type RecurrenceFilter, type RecurringCryptoComparisonPoint, type RecurringCryptoComparisonPriceSource, type RecurringCryptoDuration, type RecurringCryptoDurationInput, type RecurringCryptoMarketMetrics, type RecurringCryptoMarketsResponse, type RecurringCryptoOrderbookDepthLevel, type RecurringCryptoOrderbookDepthSide, type RecurringCryptoOutcome, type RecurringCryptoOutcomeOrderbookDepth, type RecurringCryptoPriceComparison, type RecurringCryptoReferencePrice, type RecurringCryptoResolution, type RecurringCryptoSourceConfidence, type RecurringCryptoVenueMarket, type RecurringCryptoWindowComparisons, type RecurringCryptoWindowMarket, type RedeemLegResult, type RedeemLegStatus, type RedeemRequest, type RedeemResponse, type RequestedOrderbookMarket, type ResetPaperTradingAccountParams, type ResolveCorrelatedMarketsParams, type ResolveCorrelatedMarketsResponse, type ResolvedCorrelatedMarketsResponse, type RpcTokenResponse, type SafeParseFailure, type SafeParseResult, type SafeParseSuccess, type ServerWallet, type SetPaperTradingBalanceParams, type SettlementDiff, type SettlementDifference, type SettlementSource, type SetupDepositAddressStep, type SetupVenueKeyStep, type SimpleOrderbookLevel, type SmartRouteAllocation, type SmartRouteBridgeStep, type SmartRouteFeeBreakdown, type SmartRouteFill, type SmartRouteParams, type SmartRouteResponse, type SmartRouteSettlementLeg, type SmartRouteSettlementPlan, type SmartRouteSetupCostLine, type SmartRouteSide, type SmartRouteStatus, type SmartRouteVenueFill, type SplitsByAmountResult, type SportsGameStatus, type SportsLiveParticipant, type SportsLiveResponse, type SportsLiveState, type SyncBalancesResponse, TimeInForce, type TradeExecutorOrder, type TradeExecutorOrderListResponse, TradeSide$1 as TradeSide, type TradeSplit, type TradeStep, TurnstileChallengeError, type UnifiedBalanceResponse, type UpdateBalanceRefillPolicyParams, type UpdateUserBody, type UpsertVenueKey, type UserActivityBridge, type UserActivityDeposit, type UserActivityItem, type UserActivityQuery, type UserActivityRedeem, type UserActivityRedeemLeg, type UserActivityTrade, type UserActivityType, type UserActivityUserOp, type UserActivityWithdrawal, type UserHolding, type UserProfile, VENUES, VENUE_CHAIN_IDS, type ValidateBalanceOnClientStep, type ValidateManagedParams, type ValidateManagedRequest, type ValidateManagedResponse, type ValidateTradeRequest, type ValidateTradeResponse, Venue, type VenueEvent, type VenueEventListItem, type VenueEventWithMarkets, type VenueGeoPolicyEntry, type VenueGeoPolicyResponse, type VenueKeyStatus, type VenueKeySummary, type VenueMarket, type VenueMarketClusterNode, type VenueMarketListItem, type VenueMarketOutcome, type VenueMarketRef, type VenueOrderbookEntry, type VenueOrderbookLevel, type VenuePositionBalance, type VenuePriceInfo, type VenueSoloQuote, type VerifyBody, type VerifyResponse, type WalletChainBalance, type WalletTokenBalance, type WithdrawManagedParams, type WithdrawManagedRequest, type WithdrawManagedResponse, type WithdrawManagedSourceItem, type WithdrawPreviewParams, type WithdrawPreviewResponse, type WithdrawTokenSymbol, type WithdrawalExpected, type WithdrawalLeg, type WithdrawalLegStatus, type WithdrawalLegType, type WithdrawalLifecycleStatus, type WithdrawalQuoteParams, type WithdrawalQuoteResponse, type WithdrawalSource, type WithdrawalSourceItem, type WithdrawalSourceStatus, type WithdrawalSourceTokenSymbol, type WsArbFeedBatch, type WsArbFeedEntry, type WsArbMarketUpdate, type WsAttributedLevel, type WsAuthenticated, type WsBalanceUpdate, type WsCandleInterval, type WsClientMessage, type WsConnected, type WsError, type WsHeartbeat, type WsMarkSource, type WsMarketResolved, type WsOrderEvent, type WsOrderEventType, type WsOrderSubmitted, type WsOrderbookDelta, type WsOrderbookSnapshot, type WsRedeemEvent, type WsServerMessage, type WsSubscribed, type WsTrade, type WsUnsubscribed, type WsVenueBook, type WsVenueInfo, type WsVenueLevel, type WsWithdrawalLegStatus, type WsWithdrawalLifecycleEvent, type WsWithdrawalLifecycleLeg, type WsWithdrawalLifecycleStatus, adjustLimitPriceRawToTick, aggregateMidpoint, applyOrderbookDelta, buildVenueUrl, computeBestSplitsByAmount, computeChecksum, createAggClient, enumGuard, formatMarketQuestion, formatOutcomeLabel, formatOutcomeTitle, getBalanceRefillMaximumRaw, getEffectiveDisabledVenues, getWalletAddressFromUserProfile, hasShape, isAggApiError, isBalanceRefillWithinDailyCap, isEmail, isEnum, isFiniteNonNeg, isNonEmptyString, isVenueActive, isVenueDataVisible, isVenueInactive, mergeCandles, mergeClosedCandles, normalizeVenueMarketCluster, optimizedImageUrl, parse, parseEmail, parseEmailStrict, safeParse, snapshotToOrderbook, sortVenues };
4738
+ export { ACTIVE_VENUES, type Account, AccountProvider, AccountType, AggApiError, type AggApiErrorInit, type AggApiFieldError, type AggAuthDeliveryMode, type AggAuthProviderType, type AggAuthStartBody, type AggAuthStartResult, type AggAuthVerifyBody, AggClient, type AggClientAuthOptions, type AggClientOptions, type AggClientSessionInput, type AggLinkAccountBody, type AggLinkAccountConfirmResult, type AggLinkAccountResult, type AggLinkAccountWalletConfirmBody, type AggSessionUser, AggWebSocket, type AggWebSocketCallbacks, type AggWebSocketOptions, type AggregatedOrderbookLevel, type AggregatedOrderbookResponse, type App, type AppClientConfigResponse, type AttributedOrderbook, type AttributedOrderbookLevel, type AuthCodeResponse, type AuthStatus, type AuthTokenResponse, type AuthUser, type BalanceRefillAttempt, type BalanceRefillAttemptStatus, type BalanceRefillPolicy, type BalanceRefillPolicyStatus, type BatchMidpointsResponse, type BatchOrderbooksResponse, type BookQuality, type BuildVenueUrlOpts, CONFIRMED_MATCH_STATUSES, type CancelManagedExecutionResponse, type Candle, CandleBuilder, type CandleInterval, type Category, Chain, type ChartBarsResponse, type ChartCandle, type ChartResolution, type ChartVenueCandles, type ComputeSplitsRequest, type ComputeSplitsResponse, type ComputeSplitsSelection, type CorrelatedMarketCascadeItem, type CorrelatedMarketCascadeResponse, type CorrelatedMarketQueryResult, type CorrelatedMarketSide, type CorrelatedMarketSignal, type CorrelatedMarketSignalBatch, type CorrelatedMarketSignalDirection, type CorrelatedMarketsStatus, type CreateApp, type CreateBalanceRefillPolicyParams, type CreatePaperTradingAccountParams, type CryptoReferencePriceError, type CryptoReferencePriceExternalMarketInput, type CryptoReferencePriceMarketInput, type CryptoReferencePriceResult, type CryptoReferencePriceSource, type CryptoReferencePriceTarget, type CryptoReferencePricesResponse, DEFAULT_BALANCE_REFILL_DAILY_CAP_RAW, DEFAULT_BALANCE_REFILL_MAX_FEE_RAW, type DepositAddressesPendingResponse, type DepositAddressesReadyResponse, type DepositAddressesResponse, type DepositAddressesSupportedChain, type DepositAddressesToken, type DepositStep, type DiagnosticCallback, type DiagnosticEvent, type ExecuteManagedParams, type ExecuteManagedRequest, type ExecuteManagedResponse, type ExecuteTradeRequest, type ExecuteTradeResponse, type ExecutionDagProgress, type ExecutionDisplayGroupStatus, type ExecutionDisplayStepKind, type ExecutionMode, type ExecutionOrderItem, type ExecutionOrdersQuery, type ExecutionOverallState, type ExecutionPositionGroup, type ExecutionPositionsQuery, type ExecutionStatusOrder, type ExecutionStatusQuery, type ExecutionStatusResponse, type ExecutionStatusStep, type GetBalanceQuery, type GetBalanceResponse, type GetCryptoReferencePricesOptions, type GetHoldingsQuery, type GetHoldingsResponse, type GetOrdersParams, type GetOrdersQuery, type GetPositionsParams, type GetPositionsQuery, type HelloResponse, IMAGE_SIZES, INACTIVE_VENUES, ImageSize, LIMIT_PRICE_RAW_SCALE, type LimitOrderTimeInForce, type LimitPriceSide, type LimitPriceTickAdjustment, type ListRecurringCryptoMarketsOptions, type ManagedBalancesParams, type MarkSource, type MarketPriceHistory, MarketStatus, MatchStatus, MatchType, type MatchedMidpoint, type MatchedMidpointOutcome, type MatchedOrderbookMarket, type MatchedVenueMarketOutcomeRef, type MidpointItem, type MidpointRow, type NewsFeedArticleFeedItem, type NewsFeedArticleFeedResponse, type NewsFeedArticleWithSummary, type NewsFeedLinkedMarket, type NewsFeedListResponse, type NewsFeedMarketFeedArticle, type NewsFeedMarketFeedItem, type NewsFeedMarketFeedResponse, type NewsFeedMarketNewsParams, type NewsFeedMarketNewsResponse, type NewsFeedMarketNewsResult, type NewsFeedPageOptions, type NewsFeedStatusResponse, type NonceResponse, type OrderListItem, type OrderListQuery, OrderStatus, OrderType, type Orderbook, type OrderbookBatchItemError, type OrderbookBatchItemErrorCode, type OrderbookBatchItemStatus, type OrderbookHistoryPoint, type OrderbookHistoryResponse, type OrderbookLevel, type OrderbookQuoteFill, type OrderbookQuoteParams, type OrderbookQuoteResponse, type OrderbookServiceUnavailableError, type OrderbookState, type OrderbooksOnlyError, type OutcomeMidpoint, type OutcomeMidpointRow, type OutcomeOrderbookResponse, type PaginatedResponse, type PaperTradingAccount, type PaperTradingAccountsPage, type PaperTradingAppOptions, type PaperTradingBalanceAdjustment, type PaperTradingBalanceResponse, type PaperTradingLiquidityStatus, type PaperTradingListParams, type PaperTradingMarkSource, type PaperTradingOrder, type PaperTradingOrdersPage, type PaperTradingPortfolio, type PaperTradingPosition, type PaperTradingPositionsPage, type PersistedAuthSnapshot, type PlaceLimitOrderParams, type PlaceLimitOrderResponse, type PlacePaperTradingOrderParams, type PositionGroup, type PositionRedeemStatus, type PricePoint, type PriceSource, type PricesHistoryResponse, type QuoteError, type QuoteErrorCode, RECURRENCE_CADENCES, type RampQuote, type RampQuoteRequest, type RampSessionRequest, type RampWidgetSession, type RecurrenceCadence, type RecurrenceFilter, type RecurringCryptoComparisonPoint, type RecurringCryptoComparisonPriceSource, type RecurringCryptoDuration, type RecurringCryptoDurationInput, type RecurringCryptoMarketMetrics, type RecurringCryptoMarketsResponse, type RecurringCryptoOrderbookDepthLevel, type RecurringCryptoOrderbookDepthSide, type RecurringCryptoOutcome, type RecurringCryptoOutcomeOrderbookDepth, type RecurringCryptoPriceComparison, type RecurringCryptoReferencePrice, type RecurringCryptoResolution, type RecurringCryptoSourceConfidence, type RecurringCryptoVenueMarket, type RecurringCryptoWindowComparisons, type RecurringCryptoWindowMarket, type RedeemLegResult, type RedeemLegStatus, type RedeemRequest, type RedeemResponse, type RequestedOrderbookMarket, type ResetPaperTradingAccountParams, type ResolveCorrelatedMarketsParams, type ResolveCorrelatedMarketsResponse, type ResolvedCorrelatedMarketsResponse, type RpcTokenResponse, SELF_CUSTODY_FILL_TIMEOUT_MS, SELF_CUSTODY_POLL_INTERVAL_MS, type SafeParseFailure, type SafeParseResult, type SafeParseSuccess, type ServerWallet, type SetPaperTradingBalanceParams, type SettlementDiff, type SettlementDifference, type SettlementSource, type SetupDepositAddressStep, type SetupVenueKeyStep, type SignatureRequest, type SignatureRequestType, type SignerFn, type SimpleOrderbookLevel, type SmartRouteAllocation, type SmartRouteBridgeStep, type SmartRouteFeeBreakdown, type SmartRouteFill, type SmartRouteParams, type SmartRouteResponse, type SmartRouteSettlementLeg, type SmartRouteSettlementPlan, type SmartRouteSetupCostLine, type SmartRouteSide, type SmartRouteStatus, type SmartRouteVenueFill, type SplitsByAmountResult, type SportsGameStatus, type SportsLiveParticipant, type SportsLiveResponse, type SportsLiveState, type SyncBalancesResponse, TERMINAL_EXECUTION_STATES, TimeInForce, type TradeExecutorOrder, type TradeExecutorOrderListResponse, TradeSide$1 as TradeSide, type TradeSplit, type TradeStep, TurnstileChallengeError, type UnifiedBalanceResponse, type UpdateBalanceRefillPolicyParams, type UpdateUserBody, type UpsertVenueKey, type UserActivityBridge, type UserActivityDeposit, type UserActivityItem, type UserActivityQuery, type UserActivityRedeem, type UserActivityRedeemLeg, type UserActivityTrade, type UserActivityType, type UserActivityUserOp, type UserActivityWithdrawal, type UserHolding, type UserProfile, VENUES, VENUE_CHAIN_IDS, type ValidateBalanceOnClientStep, type ValidateManagedParams, type ValidateManagedRequest, type ValidateManagedResponse, type ValidateTradeRequest, type ValidateTradeResponse, Venue, type VenueEvent, type VenueEventListItem, type VenueEventWithMarkets, type VenueGeoPolicyEntry, type VenueGeoPolicyResponse, type VenueKeyStatus, type VenueKeySummary, type VenueMarket, type VenueMarketClusterNode, type VenueMarketListItem, type VenueMarketOutcome, type VenueMarketRef, type VenueOrderbookEntry, type VenueOrderbookLevel, type VenuePositionBalance, type VenuePriceInfo, type VenueSoloQuote, type VerifyBody, type VerifyResponse, type WalletChainBalance, type WalletTokenBalance, type WithdrawManagedParams, type WithdrawManagedRequest, type WithdrawManagedResponse, type WithdrawManagedSourceItem, type WithdrawPreviewParams, type WithdrawPreviewResponse, type WithdrawTokenSymbol, type WithdrawalExpected, type WithdrawalLeg, type WithdrawalLegStatus, type WithdrawalLegType, type WithdrawalLifecycleStatus, type WithdrawalQuoteParams, type WithdrawalQuoteResponse, type WithdrawalSource, type WithdrawalSourceItem, type WithdrawalSourceStatus, type WithdrawalSourceTokenSymbol, type WsArbFeedBatch, type WsArbFeedEntry, type WsArbMarketUpdate, type WsAttributedLevel, type WsAuthenticated, type WsBalanceUpdate, type WsCandleInterval, type WsClientMessage, type WsConnected, type WsError, type WsHeartbeat, type WsMarkSource, type WsMarketResolved, type WsOrderEvent, type WsOrderEventType, type WsOrderSubmitted, type WsOrderbookDelta, type WsOrderbookSnapshot, type WsRedeemEvent, type WsServerMessage, type WsSubscribed, type WsTrade, type WsUnsubscribed, type WsVenueBook, type WsVenueInfo, type WsVenueLevel, type WsWithdrawalLegStatus, type WsWithdrawalLifecycleEvent, type WsWithdrawalLifecycleLeg, type WsWithdrawalLifecycleStatus, adjustLimitPriceRawToTick, aggregateMidpoint, applyOrderbookDelta, buildVenueUrl, computeBestSplitsByAmount, computeChecksum, createAggClient, enumGuard, formatMarketQuestion, formatOutcomeLabel, formatOutcomeTitle, getBalanceRefillMaximumRaw, getEffectiveDisabledVenues, getWalletAddressFromUserProfile, hasShape, isAggApiError, isBalanceRefillWithinDailyCap, isEmail, isEnum, isFiniteNonNeg, isNonEmptyString, isVenueActive, isVenueDataVisible, isVenueInactive, mergeCandles, mergeClosedCandles, normalizeVenueMarketCluster, optimizedImageUrl, parse, parseEmail, parseEmailStrict, safeParse, snapshotToOrderbook, sortVenues };
package/dist/index.js CHANGED
@@ -90,6 +90,9 @@ __export(index_exports, {
90
90
  OrderStatus: () => OrderStatus,
91
91
  OrderType: () => OrderType,
92
92
  RECURRENCE_CADENCES: () => RECURRENCE_CADENCES,
93
+ SELF_CUSTODY_FILL_TIMEOUT_MS: () => SELF_CUSTODY_FILL_TIMEOUT_MS,
94
+ SELF_CUSTODY_POLL_INTERVAL_MS: () => SELF_CUSTODY_POLL_INTERVAL_MS,
95
+ TERMINAL_EXECUTION_STATES: () => TERMINAL_EXECUTION_STATES,
93
96
  TimeInForce: () => TimeInForce,
94
97
  TradeSide: () => TradeSide,
95
98
  TurnstileChallengeError: () => TurnstileChallengeError,
@@ -818,6 +821,21 @@ function isAggApiError(value) {
818
821
  return value instanceof AggApiError;
819
822
  }
820
823
 
824
+ // src/types.ts
825
+ var SELF_CUSTODY_FILL_TIMEOUT_MS = 5 * 6e4;
826
+ var SELF_CUSTODY_POLL_INTERVAL_MS = 2e3;
827
+ var TERMINAL_EXECUTION_STATES = /* @__PURE__ */ new Set(["filled", "partially_filled", "failed", "cancelled", "expired"]);
828
+ var RECURRENCE_CADENCES = [
829
+ "PT5M",
830
+ "PT10M",
831
+ "PT15M",
832
+ "PT1H",
833
+ "P1D",
834
+ "P1W",
835
+ "P1M",
836
+ "P1Y"
837
+ ];
838
+
821
839
  // src/orderbook-utils.ts
822
840
  var PRICE_KEY_SCALE = 1e9;
823
841
  function crc32(str) {
@@ -1838,6 +1856,7 @@ var AggClient = class {
1838
1856
  this.appId = options.appId;
1839
1857
  this.adminKey = options.adminKey;
1840
1858
  this.apiKey = options.apiKey;
1859
+ this.signer = options.signer;
1841
1860
  this.baseUrl = options.baseUrl.replace(/\/$/, "");
1842
1861
  this.wsUrl = options.wsUrl;
1843
1862
  this.authOptions = options.auth;
@@ -2258,13 +2277,13 @@ Issued At: ${issuedAt}`;
2258
2277
  * the bearer automatically. Response shape:
2259
2278
  * - OAuth providers → `{ type: "redirect", url }`; redirect the browser to `url`.
2260
2279
  * - Email → `{ type: "magic_link", success: true }`; check the destination inbox.
2280
+ * - Wallet providers (siwe/siws) → `{ type: "wallet_challenge", message }`; have the
2281
+ * user sign `message` VERBATIM, then submit it to `linkAccountConfirm()` as
2282
+ * `{ kind: "wallet_signature", message, signature }`.
2261
2283
  *
2262
- * After the provider callback runs, the browser lands back on the app's `redirectUrl`
2284
+ * After the OAuth/email callback runs, the browser lands back on the app's `redirectUrl`
2263
2285
  * with a `link_confirm_token` query param. Feed that token to `linkAccountConfirm()`
2264
2286
  * to persist the Account row.
2265
- *
2266
- * Wallet linking (siwe/siws) is not supported yet — it requires a different message
2267
- * binding protocol than sign-in to be safe against signature phishing.
2268
2287
  */
2269
2288
  linkAccount(body) {
2270
2289
  return __async(this, null, function* () {
@@ -2279,18 +2298,27 @@ Issued At: ${issuedAt}`;
2279
2298
  });
2280
2299
  }
2281
2300
  /**
2282
- * Exchange a `link_confirm_token` for a linked `Account` row. The server matches
2283
- * the current bearer's `principalId` to the token's `principalId` before writing —
2284
- * this is the final ownership check.
2301
+ * Finalize an account link.
2302
+ *
2303
+ * - Pass a `link_confirm_token` string (OAuth/email) to exchange it for a linked
2304
+ * `Account` row.
2305
+ * - Pass `{ kind: "wallet_signature", message, signature }` (wallet providers) to
2306
+ * verify the signature over the `wallet_challenge` `message` returned by
2307
+ * `linkAccount()`.
2308
+ *
2309
+ * The server matches the current bearer's `principalId` to the challenge/token's
2310
+ * `principalId` before writing — this is the final ownership check. A wallet already
2311
+ * linked to a DIFFERENT principal rejects with HTTP 409.
2285
2312
  */
2286
- linkAccountConfirm(token) {
2313
+ linkAccountConfirm(input) {
2287
2314
  return __async(this, null, function* () {
2288
2315
  if (!this.accessToken) {
2289
2316
  yield this.refreshWithDedup();
2290
2317
  }
2318
+ const body = typeof input === "string" ? { token: input } : input;
2291
2319
  return this.request(
2292
2320
  "/users/me/link-account/confirm",
2293
- this.buildAuthRequestInit({ method: "POST", body: JSON.stringify({ token }) })
2321
+ this.buildAuthRequestInit({ method: "POST", body: JSON.stringify(body) })
2294
2322
  );
2295
2323
  });
2296
2324
  }
@@ -2472,7 +2500,13 @@ Issued At: ${issuedAt}`;
2472
2500
  });
2473
2501
  });
2474
2502
  }
2475
- /** Get quote-scoped execution progress, DAG step state, and order leg terminal status. */
2503
+ /**
2504
+ * Get quote-scoped execution progress, DAG step state, and order leg
2505
+ * terminal status. Also carries `pendingSignatures` — this is the route
2506
+ * `fillSelfCustody` polls while an on-chain step is in flight, so a caller
2507
+ * already polling this for progress learns about newly-parked steps here
2508
+ * too, not just from the signatures endpoint.
2509
+ */
2476
2510
  getExecutionStatus(params) {
2477
2511
  return __async(this, null, function* () {
2478
2512
  const query = { quoteId: params.quoteId };
@@ -3142,6 +3176,87 @@ Issued At: ${issuedAt}`;
3142
3176
  });
3143
3177
  });
3144
3178
  }
3179
+ /** Submit signatures for a parked fill. Returns whatever is still outstanding. */
3180
+ submitFillSignatures(quoteId, signatures) {
3181
+ return __async(this, null, function* () {
3182
+ return this.request(`/execution/fill/${encodeURIComponent(quoteId)}/signatures`, {
3183
+ method: "POST",
3184
+ body: JSON.stringify({ signatures })
3185
+ });
3186
+ });
3187
+ }
3188
+ /**
3189
+ * Execute a quote in self-custodial mode.
3190
+ *
3191
+ * Identical to `executeManaged` when the server can sign for the user. When
3192
+ * it cannot, the DAG parks on a signature request instead — but that park
3193
+ * always happens asynchronously, in the trade-executor process, so it can
3194
+ * never show up on this `POST /execution/fill` response itself. This
3195
+ * drives the round trip from there: poll `getExecutionStatus` while an
3196
+ * on-chain step is in flight, sign whatever it hands back with the
3197
+ * configured `signer`, post the signatures back, and repeat until the
3198
+ * server reports nothing outstanding and the run reaches a terminal state.
3199
+ */
3200
+ fillSelfCustody(params) {
3201
+ return __async(this, null, function* () {
3202
+ var _a, _b, _c;
3203
+ if (this.signer && !params.signingAddress) {
3204
+ throw new Error(
3205
+ "fillSelfCustody requires `signingAddress` \u2014 the wallet that will sign this fill."
3206
+ );
3207
+ }
3208
+ if (params.signingAddress && !this.signer) {
3209
+ throw new Error(
3210
+ "This fill requires client-side signatures, but no `signer` was passed to createAggClient(). Provide one to trade in self-custodial mode."
3211
+ );
3212
+ }
3213
+ const first = yield this.executeManaged(params);
3214
+ if (!this.signer && !params.signingAddress) return first;
3215
+ const signer = this.signer;
3216
+ const quoteId = first.quoteId;
3217
+ let pending = (_a = first.pendingSignatures) != null ? _a : [];
3218
+ let lastKey = "";
3219
+ const deadline = Date.now() + SELF_CUSTODY_FILL_TIMEOUT_MS;
3220
+ for (; ; ) {
3221
+ if (Date.now() > deadline) {
3222
+ throw new Error(`Fill for quote ${quoteId} did not finish within the timeout.`);
3223
+ }
3224
+ if (pending.length === 0) {
3225
+ yield new Promise((r) => setTimeout(r, SELF_CUSTODY_POLL_INTERVAL_MS));
3226
+ const polled = yield this.getExecutionStatus({ quoteId });
3227
+ if (TERMINAL_EXECUTION_STATES.has(polled.overallState)) {
3228
+ if (polled.overallState !== "filled" && polled.overallState !== "partially_filled") {
3229
+ throw new Error(`Fill for quote ${quoteId} ended as ${polled.overallState}.`);
3230
+ }
3231
+ return __spreadProps(__spreadValues({}, first), { pendingSignatures: [] });
3232
+ }
3233
+ pending = (_b = polled.pendingSignatures) != null ? _b : [];
3234
+ continue;
3235
+ }
3236
+ const key = pending.map((p) => p.stepId).sort().join(",");
3237
+ if (key === lastKey) {
3238
+ throw new Error(
3239
+ `Fill for quote ${quoteId} did not advance \u2014 still awaiting steps [${key}] after signing them.`
3240
+ );
3241
+ }
3242
+ lastKey = key;
3243
+ const signatures = [];
3244
+ for (const req of pending) {
3245
+ if (Date.now() > new Date(req.expiresAt).getTime()) {
3246
+ throw new Error(
3247
+ `Signature request ${req.stepId} for quote ${quoteId} expired at ${req.expiresAt}; the fill must be re-quoted.`
3248
+ );
3249
+ }
3250
+ const signed = yield signer(req);
3251
+ signatures.push(
3252
+ typeof signed === "string" ? { stepId: req.stepId, signature: signed } : { stepId: req.stepId, txHash: signed.txHash }
3253
+ );
3254
+ }
3255
+ const next = yield this.submitFillSignatures(quoteId, signatures);
3256
+ pending = (_c = next.pendingSignatures) != null ? _c : [];
3257
+ }
3258
+ });
3259
+ }
3145
3260
  /** Place a managed limit order. Returns the venue-backed order state. */
3146
3261
  placeLimitOrder(params) {
3147
3262
  return __async(this, null, function* () {
@@ -3330,18 +3445,6 @@ Issued At: ${issuedAt}`;
3330
3445
  // src/best-split.ts
3331
3446
  var computeBestSplitsByAmount2 = computeBestSplitsByAmount;
3332
3447
 
3333
- // src/types.ts
3334
- var RECURRENCE_CADENCES = [
3335
- "PT5M",
3336
- "PT10M",
3337
- "PT15M",
3338
- "PT1H",
3339
- "P1D",
3340
- "P1W",
3341
- "P1M",
3342
- "P1Y"
3343
- ];
3344
-
3345
3448
  // src/candle-builder.ts
3346
3449
  var INTERVAL_SECS = {
3347
3450
  "1m": 60,
@@ -3553,6 +3656,9 @@ function createAggClient(options) {
3553
3656
  OrderStatus,
3554
3657
  OrderType,
3555
3658
  RECURRENCE_CADENCES,
3659
+ SELF_CUSTODY_FILL_TIMEOUT_MS,
3660
+ SELF_CUSTODY_POLL_INTERVAL_MS,
3661
+ TERMINAL_EXECUTION_STATES,
3556
3662
  TimeInForce,
3557
3663
  TradeSide,
3558
3664
  TurnstileChallengeError,
package/dist/index.mjs CHANGED
@@ -690,6 +690,21 @@ function isAggApiError(value) {
690
690
  return value instanceof AggApiError;
691
691
  }
692
692
 
693
+ // src/types.ts
694
+ var SELF_CUSTODY_FILL_TIMEOUT_MS = 5 * 6e4;
695
+ var SELF_CUSTODY_POLL_INTERVAL_MS = 2e3;
696
+ var TERMINAL_EXECUTION_STATES = /* @__PURE__ */ new Set(["filled", "partially_filled", "failed", "cancelled", "expired"]);
697
+ var RECURRENCE_CADENCES = [
698
+ "PT5M",
699
+ "PT10M",
700
+ "PT15M",
701
+ "PT1H",
702
+ "P1D",
703
+ "P1W",
704
+ "P1M",
705
+ "P1Y"
706
+ ];
707
+
693
708
  // src/orderbook-utils.ts
694
709
  var PRICE_KEY_SCALE = 1e9;
695
710
  function crc32(str) {
@@ -1710,6 +1725,7 @@ var AggClient = class {
1710
1725
  this.appId = options.appId;
1711
1726
  this.adminKey = options.adminKey;
1712
1727
  this.apiKey = options.apiKey;
1728
+ this.signer = options.signer;
1713
1729
  this.baseUrl = options.baseUrl.replace(/\/$/, "");
1714
1730
  this.wsUrl = options.wsUrl;
1715
1731
  this.authOptions = options.auth;
@@ -2130,13 +2146,13 @@ Issued At: ${issuedAt}`;
2130
2146
  * the bearer automatically. Response shape:
2131
2147
  * - OAuth providers → `{ type: "redirect", url }`; redirect the browser to `url`.
2132
2148
  * - Email → `{ type: "magic_link", success: true }`; check the destination inbox.
2149
+ * - Wallet providers (siwe/siws) → `{ type: "wallet_challenge", message }`; have the
2150
+ * user sign `message` VERBATIM, then submit it to `linkAccountConfirm()` as
2151
+ * `{ kind: "wallet_signature", message, signature }`.
2133
2152
  *
2134
- * After the provider callback runs, the browser lands back on the app's `redirectUrl`
2153
+ * After the OAuth/email callback runs, the browser lands back on the app's `redirectUrl`
2135
2154
  * with a `link_confirm_token` query param. Feed that token to `linkAccountConfirm()`
2136
2155
  * to persist the Account row.
2137
- *
2138
- * Wallet linking (siwe/siws) is not supported yet — it requires a different message
2139
- * binding protocol than sign-in to be safe against signature phishing.
2140
2156
  */
2141
2157
  linkAccount(body) {
2142
2158
  return __async(this, null, function* () {
@@ -2151,18 +2167,27 @@ Issued At: ${issuedAt}`;
2151
2167
  });
2152
2168
  }
2153
2169
  /**
2154
- * Exchange a `link_confirm_token` for a linked `Account` row. The server matches
2155
- * the current bearer's `principalId` to the token's `principalId` before writing —
2156
- * this is the final ownership check.
2170
+ * Finalize an account link.
2171
+ *
2172
+ * - Pass a `link_confirm_token` string (OAuth/email) to exchange it for a linked
2173
+ * `Account` row.
2174
+ * - Pass `{ kind: "wallet_signature", message, signature }` (wallet providers) to
2175
+ * verify the signature over the `wallet_challenge` `message` returned by
2176
+ * `linkAccount()`.
2177
+ *
2178
+ * The server matches the current bearer's `principalId` to the challenge/token's
2179
+ * `principalId` before writing — this is the final ownership check. A wallet already
2180
+ * linked to a DIFFERENT principal rejects with HTTP 409.
2157
2181
  */
2158
- linkAccountConfirm(token) {
2182
+ linkAccountConfirm(input) {
2159
2183
  return __async(this, null, function* () {
2160
2184
  if (!this.accessToken) {
2161
2185
  yield this.refreshWithDedup();
2162
2186
  }
2187
+ const body = typeof input === "string" ? { token: input } : input;
2163
2188
  return this.request(
2164
2189
  "/users/me/link-account/confirm",
2165
- this.buildAuthRequestInit({ method: "POST", body: JSON.stringify({ token }) })
2190
+ this.buildAuthRequestInit({ method: "POST", body: JSON.stringify(body) })
2166
2191
  );
2167
2192
  });
2168
2193
  }
@@ -2344,7 +2369,13 @@ Issued At: ${issuedAt}`;
2344
2369
  });
2345
2370
  });
2346
2371
  }
2347
- /** Get quote-scoped execution progress, DAG step state, and order leg terminal status. */
2372
+ /**
2373
+ * Get quote-scoped execution progress, DAG step state, and order leg
2374
+ * terminal status. Also carries `pendingSignatures` — this is the route
2375
+ * `fillSelfCustody` polls while an on-chain step is in flight, so a caller
2376
+ * already polling this for progress learns about newly-parked steps here
2377
+ * too, not just from the signatures endpoint.
2378
+ */
2348
2379
  getExecutionStatus(params) {
2349
2380
  return __async(this, null, function* () {
2350
2381
  const query = { quoteId: params.quoteId };
@@ -3014,6 +3045,87 @@ Issued At: ${issuedAt}`;
3014
3045
  });
3015
3046
  });
3016
3047
  }
3048
+ /** Submit signatures for a parked fill. Returns whatever is still outstanding. */
3049
+ submitFillSignatures(quoteId, signatures) {
3050
+ return __async(this, null, function* () {
3051
+ return this.request(`/execution/fill/${encodeURIComponent(quoteId)}/signatures`, {
3052
+ method: "POST",
3053
+ body: JSON.stringify({ signatures })
3054
+ });
3055
+ });
3056
+ }
3057
+ /**
3058
+ * Execute a quote in self-custodial mode.
3059
+ *
3060
+ * Identical to `executeManaged` when the server can sign for the user. When
3061
+ * it cannot, the DAG parks on a signature request instead — but that park
3062
+ * always happens asynchronously, in the trade-executor process, so it can
3063
+ * never show up on this `POST /execution/fill` response itself. This
3064
+ * drives the round trip from there: poll `getExecutionStatus` while an
3065
+ * on-chain step is in flight, sign whatever it hands back with the
3066
+ * configured `signer`, post the signatures back, and repeat until the
3067
+ * server reports nothing outstanding and the run reaches a terminal state.
3068
+ */
3069
+ fillSelfCustody(params) {
3070
+ return __async(this, null, function* () {
3071
+ var _a, _b, _c;
3072
+ if (this.signer && !params.signingAddress) {
3073
+ throw new Error(
3074
+ "fillSelfCustody requires `signingAddress` \u2014 the wallet that will sign this fill."
3075
+ );
3076
+ }
3077
+ if (params.signingAddress && !this.signer) {
3078
+ throw new Error(
3079
+ "This fill requires client-side signatures, but no `signer` was passed to createAggClient(). Provide one to trade in self-custodial mode."
3080
+ );
3081
+ }
3082
+ const first = yield this.executeManaged(params);
3083
+ if (!this.signer && !params.signingAddress) return first;
3084
+ const signer = this.signer;
3085
+ const quoteId = first.quoteId;
3086
+ let pending = (_a = first.pendingSignatures) != null ? _a : [];
3087
+ let lastKey = "";
3088
+ const deadline = Date.now() + SELF_CUSTODY_FILL_TIMEOUT_MS;
3089
+ for (; ; ) {
3090
+ if (Date.now() > deadline) {
3091
+ throw new Error(`Fill for quote ${quoteId} did not finish within the timeout.`);
3092
+ }
3093
+ if (pending.length === 0) {
3094
+ yield new Promise((r) => setTimeout(r, SELF_CUSTODY_POLL_INTERVAL_MS));
3095
+ const polled = yield this.getExecutionStatus({ quoteId });
3096
+ if (TERMINAL_EXECUTION_STATES.has(polled.overallState)) {
3097
+ if (polled.overallState !== "filled" && polled.overallState !== "partially_filled") {
3098
+ throw new Error(`Fill for quote ${quoteId} ended as ${polled.overallState}.`);
3099
+ }
3100
+ return __spreadProps(__spreadValues({}, first), { pendingSignatures: [] });
3101
+ }
3102
+ pending = (_b = polled.pendingSignatures) != null ? _b : [];
3103
+ continue;
3104
+ }
3105
+ const key = pending.map((p) => p.stepId).sort().join(",");
3106
+ if (key === lastKey) {
3107
+ throw new Error(
3108
+ `Fill for quote ${quoteId} did not advance \u2014 still awaiting steps [${key}] after signing them.`
3109
+ );
3110
+ }
3111
+ lastKey = key;
3112
+ const signatures = [];
3113
+ for (const req of pending) {
3114
+ if (Date.now() > new Date(req.expiresAt).getTime()) {
3115
+ throw new Error(
3116
+ `Signature request ${req.stepId} for quote ${quoteId} expired at ${req.expiresAt}; the fill must be re-quoted.`
3117
+ );
3118
+ }
3119
+ const signed = yield signer(req);
3120
+ signatures.push(
3121
+ typeof signed === "string" ? { stepId: req.stepId, signature: signed } : { stepId: req.stepId, txHash: signed.txHash }
3122
+ );
3123
+ }
3124
+ const next = yield this.submitFillSignatures(quoteId, signatures);
3125
+ pending = (_c = next.pendingSignatures) != null ? _c : [];
3126
+ }
3127
+ });
3128
+ }
3017
3129
  /** Place a managed limit order. Returns the venue-backed order state. */
3018
3130
  placeLimitOrder(params) {
3019
3131
  return __async(this, null, function* () {
@@ -3202,18 +3314,6 @@ Issued At: ${issuedAt}`;
3202
3314
  // src/best-split.ts
3203
3315
  var computeBestSplitsByAmount2 = computeBestSplitsByAmount;
3204
3316
 
3205
- // src/types.ts
3206
- var RECURRENCE_CADENCES = [
3207
- "PT5M",
3208
- "PT10M",
3209
- "PT15M",
3210
- "PT1H",
3211
- "P1D",
3212
- "P1W",
3213
- "P1M",
3214
- "P1Y"
3215
- ];
3216
-
3217
3317
  // src/candle-builder.ts
3218
3318
  var INTERVAL_SECS = {
3219
3319
  "1m": 60,
@@ -3424,6 +3524,9 @@ export {
3424
3524
  OrderStatus,
3425
3525
  OrderType,
3426
3526
  RECURRENCE_CADENCES,
3527
+ SELF_CUSTODY_FILL_TIMEOUT_MS,
3528
+ SELF_CUSTODY_POLL_INTERVAL_MS,
3529
+ TERMINAL_EXECUTION_STATES,
3427
3530
  TimeInForce,
3428
3531
  TradeSide,
3429
3532
  TurnstileChallengeError,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agg-build/sdk",
3
- "version": "4.3.0",
3
+ "version": "4.6.0",
4
4
  "description": "Vanilla TypeScript client for the AGG prediction market aggregator (auth, markets, orderbooks, charts, trading, managed execution, WebSockets). Works in browsers, Node.js, and React Native.",
5
5
  "sideEffects": false,
6
6
  "license": "MIT",