@lightconexyz/lightcone-sdk 0.8.1-rc.6 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/README.md +51 -10
  2. package/dist/auth/client.d.ts +10 -0
  3. package/dist/auth/client.d.ts.map +1 -1
  4. package/dist/auth/client.js +26 -4
  5. package/dist/auth/client.js.map +1 -1
  6. package/dist/auth/index.d.ts +2 -0
  7. package/dist/auth/index.d.ts.map +1 -1
  8. package/dist/auth/index.js +5 -0
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/client.d.ts +26 -2
  11. package/dist/client.d.ts.map +1 -1
  12. package/dist/client.js +32 -0
  13. package/dist/client.js.map +1 -1
  14. package/dist/context.d.ts +36 -1
  15. package/dist/context.d.ts.map +1 -1
  16. package/dist/context.js +81 -5
  17. package/dist/context.js.map +1 -1
  18. package/dist/domain/market/client.d.ts +16 -0
  19. package/dist/domain/market/client.d.ts.map +1 -1
  20. package/dist/domain/market/client.js +33 -0
  21. package/dist/domain/market/client.js.map +1 -1
  22. package/dist/domain/market/convert.d.ts.map +1 -1
  23. package/dist/domain/market/convert.js +24 -10
  24. package/dist/domain/market/convert.js.map +1 -1
  25. package/dist/domain/market/index.d.ts +18 -4
  26. package/dist/domain/market/index.d.ts.map +1 -1
  27. package/dist/domain/market/index.js.map +1 -1
  28. package/dist/domain/market/tokens.d.ts +1 -0
  29. package/dist/domain/market/tokens.d.ts.map +1 -1
  30. package/dist/domain/market/tokens.js +11 -4
  31. package/dist/domain/market/tokens.js.map +1 -1
  32. package/dist/domain/market/wire.d.ts +17 -0
  33. package/dist/domain/market/wire.d.ts.map +1 -1
  34. package/dist/domain/market/wire.js.map +1 -1
  35. package/dist/domain/order/client.d.ts +8 -7
  36. package/dist/domain/order/client.d.ts.map +1 -1
  37. package/dist/domain/order/client.js +23 -8
  38. package/dist/domain/order/client.js.map +1 -1
  39. package/dist/domain/orderbook/client.d.ts +7 -1
  40. package/dist/domain/orderbook/client.d.ts.map +1 -1
  41. package/dist/domain/orderbook/client.js +54 -1
  42. package/dist/domain/orderbook/client.js.map +1 -1
  43. package/dist/domain/orderbook/index.d.ts +7 -9
  44. package/dist/domain/orderbook/index.d.ts.map +1 -1
  45. package/dist/domain/orderbook/index.js +28 -24
  46. package/dist/domain/orderbook/index.js.map +1 -1
  47. package/dist/domain/orderbook/state.d.ts +21 -16
  48. package/dist/domain/orderbook/state.d.ts.map +1 -1
  49. package/dist/domain/orderbook/state.js +36 -15
  50. package/dist/domain/orderbook/state.js.map +1 -1
  51. package/dist/domain/orderbook/ticker.d.ts +1 -0
  52. package/dist/domain/orderbook/ticker.d.ts.map +1 -1
  53. package/dist/domain/orderbook/ticker.js.map +1 -1
  54. package/dist/domain/orderbook/wire.d.ts +29 -10
  55. package/dist/domain/orderbook/wire.d.ts.map +1 -1
  56. package/dist/domain/orderbook/wire.js +47 -0
  57. package/dist/domain/orderbook/wire.js.map +1 -1
  58. package/dist/domain/position/builders.d.ts +6 -2
  59. package/dist/domain/position/builders.d.ts.map +1 -1
  60. package/dist/domain/position/builders.js +24 -8
  61. package/dist/domain/position/builders.js.map +1 -1
  62. package/dist/domain/position/client.d.ts +10 -12
  63. package/dist/domain/position/client.d.ts.map +1 -1
  64. package/dist/domain/position/client.js +25 -14
  65. package/dist/domain/position/client.js.map +1 -1
  66. package/dist/domain/position/index.d.ts +4 -0
  67. package/dist/domain/position/index.d.ts.map +1 -1
  68. package/dist/domain/position/index.js.map +1 -1
  69. package/dist/env.d.ts.map +1 -1
  70. package/dist/env.js +2 -2
  71. package/dist/env.js.map +1 -1
  72. package/dist/error.d.ts +26 -2
  73. package/dist/error.d.ts.map +1 -1
  74. package/dist/error.js +46 -1
  75. package/dist/error.js.map +1 -1
  76. package/dist/http/client.d.ts +76 -1
  77. package/dist/http/client.d.ts.map +1 -1
  78. package/dist/http/client.js +259 -39
  79. package/dist/http/client.js.map +1 -1
  80. package/dist/http/credentialRestorer.d.ts +49 -0
  81. package/dist/http/credentialRestorer.d.ts.map +1 -0
  82. package/dist/http/credentialRestorer.js +3 -0
  83. package/dist/http/credentialRestorer.js.map +1 -0
  84. package/dist/http/index.d.ts +1 -0
  85. package/dist/http/index.d.ts.map +1 -1
  86. package/dist/http/index.js.map +1 -1
  87. package/dist/index.d.ts +4 -4
  88. package/dist/index.d.ts.map +1 -1
  89. package/dist/index.js +4 -1
  90. package/dist/index.js.map +1 -1
  91. package/dist/prelude.d.ts +5 -3
  92. package/dist/prelude.d.ts.map +1 -1
  93. package/dist/prelude.js +3 -2
  94. package/dist/prelude.js.map +1 -1
  95. package/dist/privy/index.d.ts +4 -4
  96. package/dist/privy/index.d.ts.map +1 -1
  97. package/dist/privy/index.js +11 -16
  98. package/dist/privy/index.js.map +1 -1
  99. package/dist/program/accounts.d.ts +10 -6
  100. package/dist/program/accounts.d.ts.map +1 -1
  101. package/dist/program/accounts.js +33 -9
  102. package/dist/program/accounts.js.map +1 -1
  103. package/dist/program/builder.d.ts +13 -11
  104. package/dist/program/builder.d.ts.map +1 -1
  105. package/dist/program/builder.js +31 -16
  106. package/dist/program/builder.js.map +1 -1
  107. package/dist/program/constants.d.ts +14 -3
  108. package/dist/program/constants.d.ts.map +1 -1
  109. package/dist/program/constants.js +15 -4
  110. package/dist/program/constants.js.map +1 -1
  111. package/dist/program/envelope.d.ts +14 -16
  112. package/dist/program/envelope.d.ts.map +1 -1
  113. package/dist/program/envelope.js +48 -39
  114. package/dist/program/envelope.js.map +1 -1
  115. package/dist/program/error.d.ts +7 -2
  116. package/dist/program/error.d.ts.map +1 -1
  117. package/dist/program/error.js +17 -2
  118. package/dist/program/error.js.map +1 -1
  119. package/dist/program/index.d.ts +4 -4
  120. package/dist/program/index.d.ts.map +1 -1
  121. package/dist/program/index.js +23 -4
  122. package/dist/program/index.js.map +1 -1
  123. package/dist/program/instructions.d.ts +77 -9
  124. package/dist/program/instructions.d.ts.map +1 -1
  125. package/dist/program/instructions.js +241 -19
  126. package/dist/program/instructions.js.map +1 -1
  127. package/dist/program/orders.d.ts +7 -8
  128. package/dist/program/orders.d.ts.map +1 -1
  129. package/dist/program/orders.js +20 -22
  130. package/dist/program/orders.js.map +1 -1
  131. package/dist/program/types.d.ts +69 -7
  132. package/dist/program/types.d.ts.map +1 -1
  133. package/dist/program/types.js +11 -1
  134. package/dist/program/types.js.map +1 -1
  135. package/dist/rpc.d.ts +44 -1
  136. package/dist/rpc.d.ts.map +1 -1
  137. package/dist/rpc.js +160 -4
  138. package/dist/rpc.js.map +1 -1
  139. package/dist/shared/api_response.d.ts +9 -1
  140. package/dist/shared/api_response.d.ts.map +1 -1
  141. package/dist/shared/api_response.js +10 -1
  142. package/dist/shared/api_response.js.map +1 -1
  143. package/dist/shared/index.d.ts +2 -2
  144. package/dist/shared/index.d.ts.map +1 -1
  145. package/dist/shared/index.js +12 -6
  146. package/dist/shared/index.js.map +1 -1
  147. package/dist/shared/json.d.ts +5 -0
  148. package/dist/shared/json.d.ts.map +1 -0
  149. package/dist/shared/json.js +38 -0
  150. package/dist/shared/json.js.map +1 -0
  151. package/dist/shared/rejection.d.ts.map +1 -1
  152. package/dist/shared/rejection.js +8 -0
  153. package/dist/shared/rejection.js.map +1 -1
  154. package/dist/shared/scaling.d.ts +30 -18
  155. package/dist/shared/scaling.d.ts.map +1 -1
  156. package/dist/shared/scaling.js +153 -95
  157. package/dist/shared/scaling.js.map +1 -1
  158. package/dist/shared/types.d.ts +6 -6
  159. package/dist/shared/types.d.ts.map +1 -1
  160. package/dist/shared/types.js.map +1 -1
  161. package/dist/ws/index.d.ts.map +1 -1
  162. package/dist/ws/index.js +15 -2
  163. package/dist/ws/index.js.map +1 -1
  164. package/package.json +5 -2
package/README.md CHANGED
@@ -69,7 +69,7 @@ async function main() {
69
69
  .amount(1_000_000n)
70
70
  .buildIx();
71
71
 
72
- // 4. Build, sign, and submit a limit order
72
+ // 4. Fetch/cache immutable trading rules, validate exactly, sign, and submit
73
73
  const response = await client.orders().limitOrder()
74
74
  .maker(keypair.publicKey)
75
75
  .bid()
@@ -177,7 +177,23 @@ ws.subscribe({
177
177
  });
178
178
  ```
179
179
 
180
- Book streams are snapshot-only: every `book_update` frame carries the full top-20 levels per side (~50ms conflation) and replaces the previous book wholesale (`OrderbookState` handles this; never gate on `seq` — the initial snapshot after every (re)subscribe is `seq: 0`). Subscriptions accept an optional Hyperliquid-style aggregation (`nSigFigs` 2–5, `mantissa` 1/2/5 only with `nSigFigs: 5`; validate with `validateAggregation`). Each `(orderbook, aggregation)` pair is a distinct subscription, so one connection can hold the full-precision and a grouped view of the same book simultaneously — incoming frames are tagged with snake_case `n_sig_figs`/`mantissa` (absent = full precision); key state by `aggregationFromFrame(frame.n_sig_figs, frame.mantissa)`. See [`examples/ws_book_and_trades.ts`](examples/ws_book_and_trades.ts).
180
+ Book streams are snapshot-only: every accepted `book_update` replaces the full
181
+ top-20 view. `OrderbookState` discards equal/older `seq` values within a
182
+ subscription generation and accepts forward gaps. Call `beginGeneration()` on
183
+ reconnect/resubscribe; `resync: true` requires unsubscribe/resubscribe with the
184
+ same aggregation. Each `(orderbook, aggregation)` pair needs its own state.
185
+ Truncation flags are preserved and mean that side is not exhaustive. See
186
+ [`examples/ws_book_and_trades.ts`](examples/ws_book_and_trades.ts).
187
+ Ticker consumers should use the supplied `mid`; it is engine-authoritative and
188
+ may use one-sided-book or last-trade fallback.
189
+ REST depth is a coherent projection that may briefly lag a mutation. Use its
190
+ `revision` and `captured_at_ms` metadata, and expect revision gaps.
191
+
192
+ Order submission accepts decimal strings and uses exact `bigint` construction.
193
+ `submit()` fetches and caches `/api/orderbooks/{id}/decimals` before invoking a
194
+ signer. Direct `sign()`/`finalize()` calls require the returned `OrderbookRules`.
195
+ Raw amounts, explicit salts, and derived prices are preflighted against the same
196
+ signed-64-bit admission rules; no tick or size normalization is implicit.
181
197
 
182
198
  ```typescript
183
199
  ws.subscribe({ type: "book_update", orderbook_ids: [orderbook.orderbookId], nSigFigs: 5, mantissa: 2 });
@@ -208,6 +224,8 @@ const txHash = await client.positions().merge()
208
224
  .signAndSubmit();
209
225
  ```
210
226
 
227
+ `market.numOutcomes` is the validated protocol outcome count. Market deposit, merge, and unified withdrawal use it instead of the length of display outcome metadata. The pubkey-only `withdrawFromPosition()` builder requires `.numOutcomes(market.numOutcomes)` before building.
228
+
211
229
  ### Step 7: Withdraw
212
230
 
213
231
  ```typescript
@@ -222,6 +240,9 @@ const withdrawIx = client.positions().withdraw()
222
240
 
223
241
  Authentication is only required for user-specific endpoints. Authentication is session-based using ED25519 signed messages. The flow is: request a nonce, sign it with your wallet, and exchange it for a session cookie.
224
242
 
243
+ Use `walletDisplayName(session.user, session.auth_method)` to show a shortened
244
+ label for the wallet the session trades with, regardless of login identity.
245
+
225
246
  ### Cookie handling
226
247
 
227
248
  After login succeeds, the SDK stores the session token internally and attaches it as `Cookie: lightcone-token=…` on every authenticated request. Behaviour depends on the runtime:
@@ -235,14 +256,17 @@ After login succeeds, the SDK stores the session token internally and attaches i
235
256
 
236
257
  When the SDK runs on a server (SSR, an Express / Next.js route handler, etc.) and the *user's* `auth_token` cookie arrives on an incoming HTTP request, the SDK's process-wide token store is the wrong place to route it through — the store is shared across all users of that server process.
237
258
 
259
+ > **Behavior change.** `getWithCookies` responses no longer capture `Set-Cookie` into the shared token slot (they previously did): a forwarded per-user request rotating its token must not leak that token to every later request from a shared server client. These requests also never consult the credential restorer.
260
+
238
261
  For these cases, authed methods that need per-call forwarding ship a `*WithAuth(authToken)` sibling that injects the cookie just for that one call:
239
262
 
240
263
  ```typescript
241
264
  // Inside a server route, after extracting the auth_token cookie
242
265
  // from the incoming request:
243
- const balances = await client
266
+ const snapshot = await client
244
267
  .positions()
245
- .depositTokenBalancesWithAuth(authToken);
268
+ .depositTokenBalancesWithCookies(undefined, authToken);
269
+ console.log(`snapshot slot ${snapshot.context_slot}: ${Object.keys(snapshot.balances).length} balances`);
246
270
 
247
271
  const positions = await client
248
272
  .positions()
@@ -279,6 +303,8 @@ Each environment configures the API URL, WebSocket URL, Solana RPC URL, and on-c
279
303
 
280
304
  The Solana RPC URL can also be overridden via the `SDK_RPC_URL` environment variable, which takes precedence over the environment default. This is useful for pointing all examples at a private RPC to avoid public devnet rate limits.
281
305
 
306
+ Favorite-market add and remove methods are idempotent set operations, so the SDK may safely replay them after supported credential restoration or transient transport failures. Per-call cookie variants used by SSR and route handlers retry transient failures with the supplied cookie but never invoke the process-wide credential restorer.
307
+
282
308
  ## Examples
283
309
 
284
310
  All examples are runnable with `npx tsx examples/<name>.ts`. Examples default to the production environment and read the wallet keypair from `~/.config/solana/id.json`.
@@ -288,13 +314,13 @@ All examples are runnable with `npx tsx examples/<name>.ts`. Examples default to
288
314
  | Example | Description |
289
315
  |---------|-------------|
290
316
  | [`login`](examples/login.ts) | Full auth lifecycle: sign message, login, check session, logout |
291
- | [`with_auth`](examples/with_auth.ts) | Per-call auth-token forwarding for SSR / route-handler consumers — logs in, captures the token via `client.authToken()`, clears the SDK's internal store, and exercises every `*WithAuth` variant |
317
+ | [`with_cookies`](examples/with_cookies.ts) | Per-call cookie forwarding for SSR / route-handler consumers, including paginated favorite-market list/add/remove while restoring the original state |
292
318
 
293
319
  ### Market Discovery & Data
294
320
 
295
321
  | Example | Description |
296
322
  |---------|-------------|
297
- | [`markets`](examples/markets.ts) | Featured markets, paginated listing, fetch by pubkey, search, platform deposit assets via `globalDepositAssets()` |
323
+ | [`markets`](examples/markets.ts) | Featured markets, paginated listing, fetch by pubkey, search, and platform deposit assets via `globalDepositAssets()`; authenticated favorite-market APIs are demonstrated by `with_cookies` |
298
324
  | [`orderbook`](examples/orderbook.ts) | Fetch orderbook depth (bids/asks) and decimal precision metadata |
299
325
  | [`trades`](examples/trades.ts) | Recent trade history with cursor-based pagination (per-orderbook and market-wide) |
300
326
  | [`price_history`](examples/price_history.ts) | Historical candlestick data (OHLCV) at various resolutions |
@@ -305,7 +331,7 @@ All examples are runnable with `npx tsx examples/<name>.ts`. Examples default to
305
331
 
306
332
  | Example | Description |
307
333
  |---------|-------------|
308
- | [`submit_order`](examples/submit_order.ts) | Deposit the quote amount into the global pool, then place a limit order via `client.orders().limitOrder()` with human-readable price/size, auto-scaling, and fill tracking. Companion `cancel_order` cancels it and withdraws to stay net-neutral |
334
+ | [`submit_order`](examples/submit_order.ts) | Deposit collateral, then place an exactly validated limit order using cached trading rules. Companion `cancel_order` cancels it and withdraws to stay net-neutral |
309
335
 
310
336
  ### Cancelling Orders
311
337
 
@@ -430,14 +456,29 @@ The SDK generates a UUID v4 `x-request-id` header on every HTTP request. On reje
430
456
  | `NotFound` | 404 - resource not found |
431
457
  | `BadRequest` | 400 - invalid request |
432
458
  | `Timeout` | Request timed out |
433
- | `MaxRetriesExceeded` | All retry attempts exhausted |
459
+ | `MaxRetriesExceeded` | Never produced by the SDK itself: the HTTP retry loop propagates the final underlying error on exhaustion (structured details intact — see the retry-exhaustion tests). Kept public for consumer-built retry loops |
434
460
 
435
461
  ## Retry Strategy
436
462
 
437
- - **GET requests**: `RetryPolicy.Idempotent` - retries on transport failures and 502/503/504, backs off on 429 with exponential backoff + jitter.
438
- - **POST requests** (order submit, cancel, auth): `RetryPolicy.None` - no automatic retry. Non-idempotent actions are never retried to prevent duplicate side effects.
463
+ - **Replay-safe requests**: GETs and idempotent set operations such as favorite-market updates use `RetryPolicy.Idempotent`, which retries transport failures and 502/503/504 and backs off on 429 with exponential backoff + jitter.
464
+ - **Non-idempotent requests** (order submit, cancel, auth): `RetryPolicy.None` - no automatic retry, which prevents duplicate side effects.
439
465
  - Customizable per-call with `RetryPolicy.custom(config)`.
440
466
 
467
+ ### Credential restoration (401 recovery)
468
+
469
+ Sessions built on short-lived tokens expire mid-run: the backend starts answering 401 even though the app could mint a fresh token (e.g. a browser refreshing its Privy session). Rather than every caller hand-rolling "detect 401 → refresh → retry", the transport accepts a host-supplied hook:
470
+
471
+ ```typescript
472
+ client.setCredentialRestorer(async () => {
473
+ // e.g. ask the auth provider's SDK to refresh the session
474
+ return await refreshSession();
475
+ });
476
+ ```
477
+
478
+ When a request to the API origin fails with HTTP 401 and a restorer is registered, the transport consults it **at most once per logical request**, with concurrent 401s sharing one restoration (bounded by a 30-second timeout). A successful restoration replays the request once **only if it declared itself retry-safe** (an idempotent/custom retry policy); `RetryPolicy.None` requests — mutations like orders and cancels — are never auto-replayed: the restoration still heals the session for the caller's next attempt, but the original 401 propagates. Restoration is skipped for credential-management endpoints (login, logout) and for cookie-override/custom-session requests, redirects are never followed on the API transport, and without a registered restorer 401s propagate unchanged. A timed-out restoration has its `AbortSignal` fired — promises cannot be cancelled, so restorers whose work is non-idempotent (refresh-token rotation) must honor the signal or serialize internally.
479
+
480
+ The SDK stays credential-agnostic: what "restore" means belongs to the host. For classifying auth failures in your own code, use `isUnauthorized(error)` from the error module — it covers both bare 401s and 401s carrying a structured rejection envelope (`ApiRejectedDetails.httpStatus`).
481
+
441
482
  ## Trigger Orders
442
483
 
443
484
  Trigger orders (stop-limit, take-profit-limit) are under development and not yet available. Internal types exist in the source for internal use only.
@@ -15,6 +15,16 @@ export declare class Auth {
15
15
  getNonce(): Promise<string>;
16
16
  loginWithMessage(message: string, signatureBs58: string, pubkeyBytes: Uint8Array, useEmbeddedWallet?: boolean): Promise<SessionResponse>;
17
17
  checkSession(): Promise<SessionResponse>;
18
+ /**
19
+ * Logout — clears the server-side cookie, internal token, and credentials.
20
+ *
21
+ * Local state is cleared even when the server call fails — the caller asked
22
+ * to be signed out locally regardless — but the failure is then rethrown:
23
+ * callers gating security decisions on teardown (e.g. whether an app may
24
+ * restart an authenticated transport) must be able to see that the
25
+ * server-side cookie may still be valid. A 401 counts as success: it means
26
+ * "already logged out".
27
+ */
18
28
  logout(): Promise<void>;
19
29
  disconnectX(): Promise<void>;
20
30
  connectXUrl(): string;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/auth/client.ts"],"names":[],"mappings":"AACA,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,SA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AAU,aAAa;IACrB,IAAI,EAAE,aAAa,CAAC;IACpB,SAAS,EAAE,SAAS,CAAC;CACtB;AAED,qBAAa,IAAI;IACH,OAAO,CAAC,QAAQ,CAAC,MAAM;gBAAN,MAAM,EAAE,aAAa;IAE5C,QAAQ,IAAI,OAAO,CAAC,MAAM,CAAC;IAM3B,gBAAgB,CACpB,OAAO,EAAE,MAAM,EACf,aAAa,EAAE,MAAM,EACrB,WAAW,EAAE,UAAU,EACvB,iBAAiB,CAAC,EAAE,OAAO,GAC1B,OAAO,CAAC,eAAe,CAAC;IAuBrB,YAAY,IAAI,OAAO,CAAC,eAAe,CAAC;IAgB9C;;;;;;;;;OASG;IACG,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAyBvB,WAAW,IAAI,OAAO,CAAC,IAAI,CAAC;IAKlC,WAAW,IAAI,MAAM;IAIrB,WAAW,IAAI,eAAe,GAAG,SAAS;IAI1C,eAAe,IAAI,OAAO;CAO3B"}
@@ -23,7 +23,11 @@ class Auth {
23
23
  pubkey_bytes: Array.from(pubkeyBytes),
24
24
  use_embedded_wallet: useEmbeddedWallet,
25
25
  };
26
- const session = await this.client.http.post(url, body, http_1.RetryPolicy.None);
26
+ // Credential-management endpoint: opts out of the transport's 401
27
+ // restore-and-replay. The backend consumes the login nonce before
28
+ // verifying the signature, so a replayed login deterministically fails —
29
+ // and restoring credentials in order to log in is circular.
30
+ const session = await this.client.http.postWithoutCredentialRestore(url, body, http_1.RetryPolicy.None);
27
31
  this.client.authState.setCredentials(credentialsFromSession(session));
28
32
  return session;
29
33
  }
@@ -40,17 +44,35 @@ class Auth {
40
44
  this.client.authState.setCredentials(credentialsFromSession(session));
41
45
  return session;
42
46
  }
47
+ /**
48
+ * Logout — clears the server-side cookie, internal token, and credentials.
49
+ *
50
+ * Local state is cleared even when the server call fails — the caller asked
51
+ * to be signed out locally regardless — but the failure is then rethrown:
52
+ * callers gating security decisions on teardown (e.g. whether an app may
53
+ * restart an authenticated transport) must be able to see that the
54
+ * server-side cookie may still be valid. A 401 counts as success: it means
55
+ * "already logged out".
56
+ */
43
57
  async logout() {
44
58
  const url = `${this.client.http.baseUrl()}/api/auth/logout`;
59
+ let logoutError = null;
45
60
  try {
46
- await this.client.http.post(url, {}, http_1.RetryPolicy.None);
61
+ // Credential-management endpoint: opts out of the transport's 401
62
+ // restore-and-replay — a 401 here means "already logged out".
63
+ await this.client.http.postWithoutCredentialRestore(url, {}, http_1.RetryPolicy.None);
47
64
  }
48
- catch {
49
- // Backend cookie clear can fail in local/dev setups; still clear local state.
65
+ catch (error) {
66
+ if (!(0, error_1.isUnauthorized)(error)) {
67
+ logoutError = error;
68
+ }
50
69
  }
51
70
  await this.client.http.clearAuthToken();
52
71
  this.client.authState.setCredentials(undefined);
53
72
  await this.client.authState.clearCaches();
73
+ if (logoutError !== null) {
74
+ throw logoutError;
75
+ }
54
76
  }
55
77
  async disconnectX() {
56
78
  const url = `${this.client.http.baseUrl()}/api/auth/disconnect_x`;
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/auth/client.ts"],"names":[],"mappings":";;;AAAA,oCAAoC;AACpC,kCAA0D;AAC1D,sCAAwC;AACxC,mCAAwC;AAcxC,MAAa,IAAI;IACc;IAA7B,YAA6B,MAAqB;QAArB,WAAM,GAAN,MAAM,CAAe;IAAG,CAAC;IAEtD,KAAK,CAAC,QAAQ;QACZ,MAAM,GAAG,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,iBAAiB,CAAC;QAC3D,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAgB,GAAG,EAAE,kBAAW,CAAC,IAAI,CAAC,CAAC;QAClF,OAAO,QAAQ,CAAC,KAAK,CAAC;IACxB,CAAC;IAED,KAAK,CAAC,gBAAgB,CACpB,OAAe,EACf,aAAqB,EACrB,WAAuB,EACvB,iBAA2B;QAE3B,MAAM,GAAG,GA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AE,OAAO,CAAC,WAAW,CAAC,CAAC;QAC7E,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,UAAU,CAAC;KAC5C,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,SAAiB;IACpC,IAAI,SAAS,GAAG,iBAAiB,EAAE,CAAC;QAClC,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7B,CAAC;IACD,OAAO,IAAI,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import { SdkError } from \"../error\";\nimport { RetryPolicy, type LightconeHttp } from \"../http\";\nimport { asPubkeyStr } from \"../shared\";\nimport { tradingWallet } from \"./index\";\nimport type { AuthCredentials, LoginRequest, NonceResponse, SessionResponse } from \"./index\";\n\ninterface AuthState {\n getCredentials(): AuthCredentials | undefined;\n setCredentials(credentials: AuthCredentials | undefined): void;\n clearCaches(): Promise<void>;\n}\n\ninterface ClientContext {\n http: LightconeHttp;\n authState: AuthState;\n}\n\nexport class Auth {\n constructor(private readonly client: ClientContext) {}\n\n async getNonce(): Promise<string> {\n const url = `${this.client.http.baseUrl()}/api/auth/nonce`;\n const response = await this.client.http.get<NonceResponse>(url, RetryPolicy.None);\n return response.nonce;\n }\n\n async loginWithMessage(\n message: string,\n signatureBs58: string,\n pubkeyBytes: Uint8Array,\n useEmbeddedWallet?: boolean\n ): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/login_or_register_with_message`;\n const body: LoginRequest = {\n message,\n signature_bs58: signatureBs58,\n pubkey_bytes: Array.from(pubkeyBytes),\n use_embedded_wallet: useEmbeddedWallet,\n };\n\n const session = await this.client.http.post<SessionResponse, LoginRequest>(\n url,\n body,\n RetryPolicy.None\n );\n\n this.client.authState.setCredentials(credentialsFromSession(session));\n\n return session;\n }\n\n async checkSession(): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/me`;\n\n let session: SessionResponse;\n try {\n session = await this.client.http.get<SessionResponse>(url, RetryPolicy.Idempotent);\n } catch (error) {\n this.client.authState.setCredentials(undefined);\n throw SdkError.from(error);\n }\n\n this.client.authState.setCredentials(credentialsFromSession(session));\n\n return session;\n }\n\n async logout(): Promise<void> {\n const url = `${this.client.http.baseUrl()}/api/auth/logout`;\n try {\n await this.client.http.post<{ success: boolean }, Record<string, never>>(url, {}, RetryPolicy.None);\n } catch {\n // Backend cookie clear can fail in local/dev setups; still clear local state.\n }\n\n await this.client.http.clearAuthToken();\n this.client.authState.setCredentials(undefined);\n await this.client.authState.clearCaches();\n }\n\n async disconnectX(): Promise<void> {\n const url = `${this.client.http.baseUrl()}/api/auth/disconnect_x`;\n await this.client.http.post<{ success: boolean }, Record<string, never>>(url, {}, RetryPolicy.None);\n }\n\n connectXUrl(): string {\n return `${this.client.http.baseUrl()}/api/auth/oauth/link/x`;\n }\n\n credentials(): AuthCredentials | undefined {\n return this.client.authState.getCredentials();\n }\n\n isAuthenticated(): boolean {\n const credentials = this.credentials();\n if (!credentials) {\n return false;\n }\n return Date.now() < credentials.expires_at.getTime();\n }\n}\n\n/**\n * Derive session credentials from the envelope. The trading wallet comes from\n * the identity + auth method.\n */\nfunction credentialsFromSession(session: SessionResponse): AuthCredentials {\n return {\n user_id: session.user.user_id,\n wallet_address: asPubkeyStr(tradingWallet(session.user, session.auth_method)),\n expires_at: parseExpiry(session.expires_at),\n };\n}\n\nfunction parseExpiry(timestamp: number): Date {\n if (timestamp > 1_000_000_000_000) {\n return new Date(timestamp);\n }\n return new Date(timestamp * 1000);\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/auth/client.ts"],"names":[],"mappings":";;;AAAA,oCAAoD;AACpD,kCAA0D;AAC1D,sCAAwC;AACxC,mCAAwC;AAcxC,MAAa,IAAI;IACc;IAA7B,YAA6B,MAAqB;QAArB,WAAM,GAAN,MAAM,CAAe;IAAG,CAAC;IAEtD,KAAK,CAAC,QAAQ;QACZ,MAAM,GAAG,GAAG,GAAG,I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kBAAW,CAAC,IAAI,CAAC,CAAC;IACtG,CAAC;IAED,WAAW;QACT,OAAO,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,wBAAwB,CAAC;IAC/D,CAAC;IAED,WAAW;QACT,OAAO,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC,cAAc,EAAE,CAAC;IAChD,CAAC;IAED,eAAe;QACb,MAAM,WAAW,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACvC,IAAI,CAAC,WAAW,EAAE,CAAC;YACjB,OAAO,KAAK,CAAC;QACf,CAAC;QACD,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,WAAW,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;IACvD,CAAC;CACF;AA5GD,oBA4GC;AAED;;;GAGG;AACH,SAAS,sBAAsB,CAAC,OAAwB;IACtD,OAAO;QACL,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,OAAO;QAC7B,cAAc,EAAE,IAAA,oBAAW,EAAC,IAAA,qBAAa,EAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,WAAW,CAAC,CAAC;QAC7E,UAAU,EAAE,WAAW,CAAC,OAAO,CAAC,UAAU,CAAC;KAC5C,CAAC;AACJ,CAAC;AAED,SAAS,WAAW,CAAC,SAAiB;IACpC,IAAI,SAAS,GAAG,iBAAiB,EAAE,CAAC;QAClC,OAAO,IAAI,IAAI,CAAC,SAAS,CAAC,CAAC;IAC7B,CAAC;IACD,OAAO,IAAI,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC,CAAC;AACpC,CAAC","sourcesContent":["import { SdkError, isUnauthorized } from \"../error\";\nimport { RetryPolicy, type LightconeHttp } from \"../http\";\nimport { asPubkeyStr } from \"../shared\";\nimport { tradingWallet } from \"./index\";\nimport type { AuthCredentials, LoginRequest, NonceResponse, SessionResponse } from \"./index\";\n\ninterface AuthState {\n getCredentials(): AuthCredentials | undefined;\n setCredentials(credentials: AuthCredentials | undefined): void;\n clearCaches(): Promise<void>;\n}\n\ninterface ClientContext {\n http: LightconeHttp;\n authState: AuthState;\n}\n\nexport class Auth {\n constructor(private readonly client: ClientContext) {}\n\n async getNonce(): Promise<string> {\n const url = `${this.client.http.baseUrl()}/api/auth/nonce`;\n const response = await this.client.http.get<NonceResponse>(url, RetryPolicy.None);\n return response.nonce;\n }\n\n async loginWithMessage(\n message: string,\n signatureBs58: string,\n pubkeyBytes: Uint8Array,\n useEmbeddedWallet?: boolean\n ): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/login_or_register_with_message`;\n const body: LoginRequest = {\n message,\n signature_bs58: signatureBs58,\n pubkey_bytes: Array.from(pubkeyBytes),\n use_embedded_wallet: useEmbeddedWallet,\n };\n\n // Credential-management endpoint: opts out of the transport's 401\n // restore-and-replay. The backend consumes the login nonce before\n // verifying the signature, so a replayed login deterministically fails —\n // and restoring credentials in order to log in is circular.\n const session = await this.client.http.postWithoutCredentialRestore<\n SessionResponse,\n LoginRequest\n >(url, body, RetryPolicy.None);\n\n this.client.authState.setCredentials(credentialsFromSession(session));\n\n return session;\n }\n\n async checkSession(): Promise<SessionResponse> {\n const url = `${this.client.http.baseUrl()}/api/auth/me`;\n\n let session: SessionResponse;\n try {\n session = await this.client.http.get<SessionResponse>(url, RetryPolicy.Idempotent);\n } catch (error) {\n this.client.authState.setCredentials(undefined);\n throw SdkError.from(error);\n }\n\n this.client.authState.setCredentials(credentialsFromSession(session));\n\n return session;\n }\n\n /**\n * Logout — clears the server-side cookie, internal token, and credentials.\n *\n * Local state is cleared even when the server call fails — the caller asked\n * to be signed out locally regardless — but the failure is then rethrown:\n * callers gating security decisions on teardown (e.g. whether an app may\n * restart an authenticated transport) must be able to see that the\n * server-side cookie may still be valid. A 401 counts as success: it means\n * \"already logged out\".\n */\n async logout(): Promise<void> {\n const url = `${this.client.http.baseUrl()}/api/auth/logout`;\n let logoutError: unknown = null;\n try {\n // Credential-management endpoint: opts out of the transport's 401\n // restore-and-replay — a 401 here means \"already logged out\".\n await this.client.http.postWithoutCredentialRestore<\n { success: boolean },\n Record<string, never>\n >(url, {}, RetryPolicy.None);\n } catch (error) {\n if (!isUnauthorized(error)) {\n logoutError = error;\n }\n }\n\n await this.client.http.clearAuthToken();\n this.client.authState.setCredentials(undefined);\n await this.client.authState.clearCaches();\n\n if (logoutError !== null) {\n throw logoutError;\n }\n }\n\n async disconnectX(): Promise<void> {\n const url = `${this.client.http.baseUrl()}/api/auth/disconnect_x`;\n await this.client.http.post<{ success: boolean }, Record<string, never>>(url, {}, RetryPolicy.None);\n }\n\n connectXUrl(): string {\n return `${this.client.http.baseUrl()}/api/auth/oauth/link/x`;\n }\n\n credentials(): AuthCredentials | undefined {\n return this.client.authState.getCredentials();\n }\n\n isAuthenticated(): boolean {\n const credentials = this.credentials();\n if (!credentials) {\n return false;\n }\n return Date.now() < credentials.expires_at.getTime();\n }\n}\n\n/**\n * Derive session credentials from the envelope. The trading wallet comes from\n * the identity + auth method.\n */\nfunction credentialsFromSession(session: SessionResponse): AuthCredentials {\n return {\n user_id: session.user.user_id,\n wallet_address: asPubkeyStr(tradingWallet(session.user, session.auth_method)),\n expires_at: parseExpiry(session.expires_at),\n };\n}\n\nfunction parseExpiry(timestamp: number): Date {\n if (timestamp > 1_000_000_000_000) {\n return new Date(timestamp);\n }\n return new Date(timestamp * 1000);\n}\n"]}
@@ -104,6 +104,8 @@ export declare function userXAccount(user: User): XAccountData | undefined;
104
104
  * wallet that signed in.
105
105
  */
106
106
  export declare function tradingWallet(user: User, authMethod: AuthMethod): string;
107
+ /** Short display label for the wallet a session operates as. */
108
+ export declare function walletDisplayName(user: User, authMethod: AuthMethod): string;
107
109
  /**
108
110
  * Best display name for the user. Google: `name`, falling back to the email;
109
111
  * X: `display_name`, falling back to the username; wallet identities show the
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,E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MAAM,CAS9C;AAED,mEAAmE;AACnE,wBAAgB,SAAS,CAAC,IAAI,EAAE,IAAI,GAAG,MAAM,GAAG,SAAS,CAQxD;AAED,MAAM,WAAW,eAAe;IAC9B,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,SAAS,CAAC;IAC1B,UAAU,EAAE,IAAI,CAAC;CAClB;AAED,wBAAgB,eAAe,CAAC,WAAW,CAAC,EAAE,eAAe,GAAG,OAAO,CAKtE;AAED,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,CAE/D;AAED,MAAM,WAAW,YAAY;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,cAAc,EAAE,MAAM,CAAC;IACvB,YAAY,EAAE,MAAM,EAAE,CAAC;IACvB,mBAAmB,CAAC,EAAE,OAAO,CAAC;CAC/B;AAED,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;CACf"}
@@ -19,6 +19,7 @@ exports.identityText = identityText;
19
19
  exports.userPrivy = userPrivy;
20
20
  exports.userXAccount = userXAccount;
21
21
  exports.tradingWallet = tradingWallet;
22
+ exports.walletDisplayName = walletDisplayName;
22
23
  exports.displayName = displayName;
23
24
  exports.avatarUrl = avatarUrl;
24
25
  exports.isAuthenticated = isAuthenticated;
@@ -89,6 +90,10 @@ function tradingWallet(user, authMethod) {
89
90
  : user.identity.address;
90
91
  }
91
92
  }
93
+ /** Short display label for the wallet a session operates as. */
94
+ function walletDisplayName(user, authMethod) {
95
+ return (0, str_1.shorten)(tradingWallet(user, authMethod), 8);
96
+ }
92
97
  /**
93
98
  * Best display name for the user. Google: `name`, falling back to the email;
94
99
  * X: `display_name`, falling back to the username; wallet identities show the
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA6FA,oCAaC;AAGD,8BAQC;AAGD,oCAEC;AAWD,sCAUC;AAOD,kCASC;AAGD,8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,CAAC;IACrB,CAAC;AACH,CAAC;AAQD,SAAgB,eAAe,CAAC,WAA6B;IAC3D,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,WAAW,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;AACvD,CAAC;AAED,SAAgB,qBAAqB,CAAC,KAAa;IACjD,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,gCAAgC,KAAK,EAAE,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["import type { PubkeyStr } from \"../shared\";\nimport { shorten } from \"../shared/fmt/str\";\n\nexport * from \"./client\";\nexport * from \"./native\";\n\n/**\n * How a session authenticated, as reported by the backend (derived from which\n * token verified the request).\n */\nexport enum AuthMethod {\n Privy = \"privy\",\n Lightcone = \"lightcone\",\n}\n\nexport enum ChainType {\n Solana = \"solana\",\n Ethereum = \"ethereum\",\n}\n\n/** A Privy-managed embedded wallet. */\nexport interface PrivyEmbeddedWallet {\n privy_id: string;\n chain: ChainType;\n address: string;\n}\n\n/** Privy account data attached to an identity. */\nexport interface UserPrivyData {\n /** The Privy DID (`did:privy:...`). */\n id: string;\n /**\n * Always present: Privy registration provisions the embedded wallet in the\n * same transaction that creates the user.\n */\n wallet: PrivyEmbeddedWallet;\n}\n\n/**\n * X account data — the same shape whether X is the login identity or a\n * connected account on a Google/wallet identity.\n */\nexport interface XAccountData {\n /** X numeric user id (Privy `subject`); absent on legacy rows. */\n user_id?: string;\n username: string;\n display_name?: string;\n avatar_url?: string;\n}\n\n/** Google account data for a Google login identity. */\nexport interface GoogleAccountData {\n email: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n avatar_url?: string;\n}\n\n/**\n * The login identity — how the user authenticates. `type` narrows the variant.\n *\n * Privy data lives on the variant because its presence is determined by the\n * identity type: Google/X login only exists via Privy OAuth (guaranteed DID +\n * embedded wallet), while wallet users opt into Privy (SIWS) or stay\n * self-custody.\n */\nexport type UserIdentity =\n | { type: \"google\"; account: GoogleAccountData; privy: UserPrivyData }\n | { type: \"x\"; account: XAccountData; privy: UserPrivyData }\n | { type: \"wallet\"; address: string; chain: ChainType; privy?: UserPrivyData };\n\n/** Full user profile — the `user` object of {@link SessionResponse}. */\nexport interface User {\n user_id: string;\n identity: UserIdentity;\n /** X account connected by a non-X-identity user; absent when identity is X. */\n connected_x?: XAccountData;\n}\n\n/**\n * Session envelope returned by `loginWithMessage`, `register-privy`, and\n * `GET /api/auth/me`. There is no `wallet_address` field — derive the\n * session's trading wallet with {@link tradingWallet}.\n */\nexport interface SessionResponse {\n user: User;\n expires_at: number;\n auth_method: AuthMethod;\n is_beta: boolean;\n}\n\n/** Human-readable login-method label (\"Google\" / \"X\" / \"Solana\"). */\nexport function identityText(identity: UserIdentity): \"Google\" | \"X\" | \"Solana\" {\n switch (identity.type) {\n case \"google\":\n return \"Google\";\n case \"x\":\n return \"X\";\n case \"wallet\":\n return \"Solana\";\n default: {\n const exhaustive: never = identity;\n throw new Error(`Unknown identity: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n\n/** Privy account data, regardless of identity type. */\nexport function userPrivy(user: User): UserPrivyData | undefined {\n switch (user.identity.type) {\n case \"google\":\n case \"x\":\n return user.identity.privy;\n case \"wallet\":\n return user.identity.privy;\n }\n}\n\n/** The X account, whether it is the login identity or a connected account. */\nexport function userXAccount(user: User): XAccountData | undefined {\n return user.identity.type === \"x\" ? user.identity.account : user.connected_x;\n}\n\n/**\n * The wallet a session operates as.\n *\n * Google/X identities only exist via Privy registration, which always\n * provisions an embedded wallet — that wallet is the answer regardless of\n * auth method. Wallet identities depend on the session: a Privy (SIWS)\n * session trades via the embedded wallet, a Lightcone session trades via the\n * wallet that signed in.\n */\nexport function tradingWallet(user: User, authMethod: AuthMethod): string {\n switch (user.identity.type) {\n case \"google\":\n case \"x\":\n return user.identity.privy.wallet.address;\n case \"wallet\":\n return authMethod === AuthMethod.Privy\n ? (user.identity.privy?.wallet.address ?? user.identity.address)\n : user.identity.address;\n }\n}\n\n/**\n * Best display name for the user. Google: `name`, falling back to the email;\n * X: `display_name`, falling back to the username; wallet identities show the\n * shortened address (`FRGk...WcPR`).\n */\nexport function displayName(user: User): string {\n switch (user.identity.type) {\n case \"google\":\n return user.identity.account.name ?? user.identity.account.email;\n case \"x\":\n return user.identity.account.display_name ?? user.identity.account.username;\n case \"wallet\":\n return shorten(user.identity.address, 8);\n }\n}\n\n/** Avatar URL from the login identity's OAuth provider, if any. */\nexport function avatarUrl(user: User): string | undefined {\n switch (user.identity.type) {\n case \"google\":\n case \"x\":\n return user.identity.account.avatar_url;\n case \"wallet\":\n return undefined;\n }\n}\n\nexport interface AuthCredentials {\n user_id: string;\n wallet_address: PubkeyStr;\n expires_at: Date;\n}\n\nexport function isAuthenticated(credentials?: AuthCredentials): boolean {\n if (!credentials) {\n return false;\n }\n return Date.now() < credentials.expires_at.getTime();\n}\n\nexport function generateSigninMessage(nonce: string): Uint8Array {\n return new TextEncoder().encode(`Sign in to Lightcone\\nNonce: ${nonce}`);\n}\n\nexport interface LoginRequest {\n message: string;\n signature_bs58: string;\n pubkey_bytes: number[];\n use_embedded_wallet?: boolean;\n}\n\nexport interface NonceResponse {\n nonce: string;\n}\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AA6FA,oCAaC;AAGD,8BAQC;AAGD,oCAEC;AAWD,sCAUC;AAGD,8CAEC;AAOD,kCASC;AAGD,8BAQC;AAQD,0CAKC;AAED,sDAEC;AA/LD,2CAA4C;AAE5C,2CAAyB;AACzB,2CAAyB;AAEzB;;;GAGG;AACH,IAAY,UAGX;AAHD,WAAY,UAAU;IACpB,6BAAe,CAAA;IACf,qCAAuB,CAAA;AACzB,CAAC,EAHW,UAAU,0BAAV,UAAU,QAGrB;AAED,IAAY,SAGX;AAHD,WAAY,SAAS;IACnB,8BAAiB,CAAA;I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,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC,GAAG,EAAE,GAAG,WAAW,CAAC,UAAU,CAAC,OAAO,EAAE,CAAC;AACvD,CAAC;AAED,SAAgB,qBAAqB,CAAC,KAAa;IACjD,OAAO,IAAI,WAAW,EAAE,CAAC,MAAM,CAAC,gCAAgC,KAAK,EAAE,CAAC,CAAC;AAC3E,CAAC","sourcesContent":["import type { PubkeyStr } from \"../shared\";\nimport { shorten } from \"../shared/fmt/str\";\n\nexport * from \"./client\";\nexport * from \"./native\";\n\n/**\n * How a session authenticated, as reported by the backend (derived from which\n * token verified the request).\n */\nexport enum AuthMethod {\n Privy = \"privy\",\n Lightcone = \"lightcone\",\n}\n\nexport enum ChainType {\n Solana = \"solana\",\n Ethereum = \"ethereum\",\n}\n\n/** A Privy-managed embedded wallet. */\nexport interface PrivyEmbeddedWallet {\n privy_id: string;\n chain: ChainType;\n address: string;\n}\n\n/** Privy account data attached to an identity. */\nexport interface UserPrivyData {\n /** The Privy DID (`did:privy:...`). */\n id: string;\n /**\n * Always present: Privy registration provisions the embedded wallet in the\n * same transaction that creates the user.\n */\n wallet: PrivyEmbeddedWallet;\n}\n\n/**\n * X account data — the same shape whether X is the login identity or a\n * connected account on a Google/wallet identity.\n */\nexport interface XAccountData {\n /** X numeric user id (Privy `subject`); absent on legacy rows. */\n user_id?: string;\n username: string;\n display_name?: string;\n avatar_url?: string;\n}\n\n/** Google account data for a Google login identity. */\nexport interface GoogleAccountData {\n email: string;\n name?: string;\n given_name?: string;\n family_name?: string;\n avatar_url?: string;\n}\n\n/**\n * The login identity — how the user authenticates. `type` narrows the variant.\n *\n * Privy data lives on the variant because its presence is determined by the\n * identity type: Google/X login only exists via Privy OAuth (guaranteed DID +\n * embedded wallet), while wallet users opt into Privy (SIWS) or stay\n * self-custody.\n */\nexport type UserIdentity =\n | { type: \"google\"; account: GoogleAccountData; privy: UserPrivyData }\n | { type: \"x\"; account: XAccountData; privy: UserPrivyData }\n | { type: \"wallet\"; address: string; chain: ChainType; privy?: UserPrivyData };\n\n/** Full user profile — the `user` object of {@link SessionResponse}. */\nexport interface User {\n user_id: string;\n identity: UserIdentity;\n /** X account connected by a non-X-identity user; absent when identity is X. */\n connected_x?: XAccountData;\n}\n\n/**\n * Session envelope returned by `loginWithMessage`, `register-privy`, and\n * `GET /api/auth/me`. There is no `wallet_address` field — derive the\n * session's trading wallet with {@link tradingWallet}.\n */\nexport interface SessionResponse {\n user: User;\n expires_at: number;\n auth_method: AuthMethod;\n is_beta: boolean;\n}\n\n/** Human-readable login-method label (\"Google\" / \"X\" / \"Solana\"). */\nexport function identityText(identity: UserIdentity): \"Google\" | \"X\" | \"Solana\" {\n switch (identity.type) {\n case \"google\":\n return \"Google\";\n case \"x\":\n return \"X\";\n case \"wallet\":\n return \"Solana\";\n default: {\n const exhaustive: never = identity;\n throw new Error(`Unknown identity: ${JSON.stringify(exhaustive)}`);\n }\n }\n}\n\n/** Privy account data, regardless of identity type. */\nexport function userPrivy(user: User): UserPrivyData | undefined {\n switch (user.identity.type) {\n case \"google\":\n case \"x\":\n return user.identity.privy;\n case \"wallet\":\n return user.identity.privy;\n }\n}\n\n/** The X account, whether it is the login identity or a connected account. */\nexport function userXAccount(user: User): XAccountData | undefined {\n return user.identity.type === \"x\" ? user.identity.account : user.connected_x;\n}\n\n/**\n * The wallet a session operates as.\n *\n * Google/X identities only exist via Privy registration, which always\n * provisions an embedded wallet — that wallet is the answer regardless of\n * auth method. Wallet identities depend on the session: a Privy (SIWS)\n * session trades via the embedded wallet, a Lightcone session trades via the\n * wallet that signed in.\n */\nexport function tradingWallet(user: User, authMethod: AuthMethod): string {\n switch (user.identity.type) {\n case \"google\":\n case \"x\":\n return user.identity.privy.wallet.address;\n case \"wallet\":\n return authMethod === AuthMethod.Privy\n ? (user.identity.privy?.wallet.address ?? user.identity.address)\n : user.identity.address;\n }\n}\n\n/** Short display label for the wallet a session operates as. */\nexport function walletDisplayName(user: User, authMethod: AuthMethod): string {\n return shorten(tradingWallet(user, authMethod), 8);\n}\n\n/**\n * Best display name for the user. Google: `name`, falling back to the email;\n * X: `display_name`, falling back to the username; wallet identities show the\n * shortened address (`FRGk...WcPR`).\n */\nexport function displayName(user: User): string {\n switch (user.identity.type) {\n case \"google\":\n return user.identity.account.name ?? user.identity.account.email;\n case \"x\":\n return user.identity.account.display_name ?? user.identity.account.username;\n case \"wallet\":\n return shorten(user.identity.address, 8);\n }\n}\n\n/** Avatar URL from the login identity's OAuth provider, if any. */\nexport function avatarUrl(user: User): string | undefined {\n switch (user.identity.type) {\n case \"google\":\n case \"x\":\n return user.identity.account.avatar_url;\n case \"wallet\":\n return undefined;\n }\n}\n\nexport interface AuthCredentials {\n user_id: string;\n wallet_address: PubkeyStr;\n expires_at: Date;\n}\n\nexport function isAuthenticated(credentials?: AuthCredentials): boolean {\n if (!credentials) {\n return false;\n }\n return Date.now() < credentials.expires_at.getTime();\n}\n\nexport function generateSigninMessage(nonce: string): Uint8Array {\n return new TextEncoder().encode(`Sign in to Lightcone\\nNonce: ${nonce}`);\n}\n\nexport interface LoginRequest {\n message: string;\n signature_bs58: string;\n pubkey_bytes: number[];\n use_embedded_wallet?: boolean;\n}\n\nexport interface NonceResponse {\n nonce: string;\n}\n"]}
package/dist/client.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { Connection, Keypair, PublicKey, Transaction } from "@solana/web3.js";
2
2
  import { Auth, type AuthCredentials } from "./auth";
3
3
  import type { ClientContext } from "./context";
4
+ import type { ConfirmedTransaction } from "./context";
4
5
  import type { FaucetResponse } from "./domain/faucet";
5
6
  import { Markets } from "./domain/market";
6
7
  import { Metrics } from "./domain/metrics";
@@ -11,12 +12,12 @@ import { Positions } from "./domain/position";
11
12
  import { PriceHistoryClient } from "./domain/price_history";
12
13
  import { Referrals } from "./domain/referral";
13
14
  import { Trades } from "./domain/trade";
14
- import { LightconeHttp } from "./http";
15
+ import { LightconeHttp, type CredentialRestorer } from "./http";
15
16
  import { LightconeEnv } from "./env";
16
17
  import { Privy } from "./privy";
17
18
  import { Rpc } from "./rpc";
18
19
  import { RpcFailoverState } from "./rpcFailover";
19
- import { DepositSource, type PubkeyStr } from "./shared";
20
+ import { DepositSource, type OrderbookRules, type PubkeyStr } from "./shared";
20
21
  import { type ExternalSigner, type SigningStrategy } from "./shared/signing";
21
22
  import { WsClient, type WsConfig } from "./ws";
22
23
  declare class AuthState {
@@ -37,6 +38,7 @@ export declare class LightconeClient implements ClientContext {
37
38
  private orderNonceValue;
38
39
  private readonly wsConfigValue;
39
40
  private readonly authStateStore;
41
+ readonly orderbookRulesCache: Map<string, Promise<OrderbookRules>>;
40
42
  /** @deprecated Use primaryConnection — kept for ClientContext compat. */
41
43
  get connection(): Connection | undefined;
42
44
  constructor(params: {
@@ -51,6 +53,7 @@ export declare class LightconeClient implements ClientContext {
51
53
  orderNonce?: number;
52
54
  authCredentials?: AuthCredentials;
53
55
  authState?: AuthState;
56
+ orderbookRulesCache?: Map<string, Promise<OrderbookRules>>;
54
57
  });
55
58
  get depositSource(): DepositSource;
56
59
  setDepositSource(source: DepositSource): void;
@@ -73,7 +76,28 @@ export declare class LightconeClient implements ClientContext {
73
76
  * `*WithCookies` variant.
74
77
  */
75
78
  clearAuthToken(): Promise<void>;
79
+ /**
80
+ * Register the credential restorer consulted when a request fails with
81
+ * HTTP 401: it attempts to restore credentials (e.g. refresh the app's
82
+ * auth session so the auth cookie is valid again); on success the
83
+ * transport replays the request once IF it declared itself retry-safe
84
+ * (RetryPolicy.None mutations are never auto-replayed). See {@link CredentialRestorer}.
85
+ * Without a restorer, 401s propagate to callers unchanged.
86
+ *
87
+ * Common use: set once at app startup, alongside the signing strategy.
88
+ */
89
+ setCredentialRestorer(restorer: CredentialRestorer): void;
90
+ /** Remove the credential restorer (e.g. in tests); 401s propagate again. */
91
+ clearCredentialRestorer(): void;
76
92
  signAndSubmitTx(tx: Transaction): Promise<string>;
93
+ /**
94
+ * Sign and submit a transaction, then wait until it reaches `confirmed`
95
+ * commitment on-chain. Prefer this over {@link signAndSubmitTx} when a
96
+ * follow-up transaction depends on this one's state.
97
+ */
98
+ signAndSubmitTxConfirmed(tx: Transaction): Promise<string>;
99
+ /** Sign, submit, confirm, and return the transaction's processing slot. */
100
+ signAndSubmitTxConfirmedWithSlot(tx: Transaction): Promise<ConfirmedTransaction>;
77
101
  static builder(): LightconeClientBuilder;
78
102
  markets(): Markets;
79
103
  orderbooks(): Orderbooks;
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,IAAI,EAAE,KAAK,eAAe,EAAE,MAAM,QAAQ,CAAC;AACpD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAE/C,OAAO,KAAK,EAAiB,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACrE,OAAO,EAAE,OAAO,EAAE,MAAM,iBAAiB,CAAC;AAC1C,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,kBAAkB,EAAE,MAAM,wBAAwB,CAAC;AAC5D,OAAO,EAAE,SAAS,EAAE,MAAM,mBAAmB,CAAC;AAC9C,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,aAAa,EAAe,MAAM,QAAQ,CAAC;AACpD,OAAO,EAAE,YAAY,EAAoD,MAAM,OAAO,CAAC;AACvF,OAAO,EAAE,KAAK,EAAE,MAAM,S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Aa,CAAC,QAAQ,EAAE,MAAM,GAAG,sBAAsB;IAKvD,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,sBAAsB;IAK3C,0DAA0D;IAC1D,YAAY,CAAC,GAAG,EAAE,MAAM,GAAG,sBAAsB;IAKjD,KAAK,IAAI,eAAe;CAuBzB"}
package/dist/client.js CHANGED
@@ -46,6 +46,7 @@ class LightconeClient {
46
46
  orderNonceValue;
47
47
  wsConfigValue;
48
48
  authStateStore;
49
+ orderbookRulesCache;
49
50
  /** @deprecated Use primaryConnection — kept for ClientContext compat. */
50
51
  get connection() {
51
52
  return this.primaryConnection;
@@ -64,6 +65,7 @@ class LightconeClient {
64
65
  this.authStateStore =
65
66
  params.authState ??
66
67
  new AuthState(params.authCredentials);
68
+ this.orderbookRulesCache = params.orderbookRulesCache ?? new Map();
67
69
  }
68
70
  // ── Deposit source ──────────────────────────────────────────────────
69
71
  get depositSource() {
@@ -110,10 +112,39 @@ class LightconeClient {
110
112
  async clearAuthToken() {
111
113
  await this.http.clearAuthToken();
112
114
  }
115
+ /**
116
+ * Register the credential restorer consulted when a request fails with
117
+ * HTTP 401: it attempts to restore credentials (e.g. refresh the app's
118
+ * auth session so the auth cookie is valid again); on success the
119
+ * transport replays the request once IF it declared itself retry-safe
120
+ * (RetryPolicy.None mutations are never auto-replayed). See {@link CredentialRestorer}.
121
+ * Without a restorer, 401s propagate to callers unchanged.
122
+ *
123
+ * Common use: set once at app startup, alongside the signing strategy.
124
+ */
125
+ setCredentialRestorer(restorer) {
126
+ this.http.setCredentialRestorer(restorer);
127
+ }
128
+ /** Remove the credential restorer (e.g. in tests); 401s propagate again. */
129
+ clearCredentialRestorer() {
130
+ this.http.clearCredentialRestorer();
131
+ }
113
132
  // ── Transaction signing + submission ────────────────────────────────
114
133
  async signAndSubmitTx(tx) {
115
134
  return (0, context_1.signAndSubmitTx)(this, tx);
116
135
  }
136
+ /**
137
+ * Sign and submit a transaction, then wait until it reaches `confirmed`
138
+ * commitment on-chain. Prefer this over {@link signAndSubmitTx} when a
139
+ * follow-up transaction depends on this one's state.
140
+ */
141
+ async signAndSubmitTxConfirmed(tx) {
142
+ return (0, context_1.signAndSubmitTxConfirmed)(this, tx);
143
+ }
144
+ /** Sign, submit, confirm, and return the transaction's processing slot. */
145
+ async signAndSubmitTxConfirmedWithSlot(tx) {
146
+ return (0, context_1.signAndSubmitTxConfirmedWithSlot)(this, tx);
147
+ }
117
148
  static builder() {
118
149
  return new LightconeClientBuilder();
119
150
  }
@@ -195,6 +226,7 @@ class LightconeClient {
195
226
  signingStrategy: this.signingStrategyValue,
196
227
  orderNonce: this.orderNonceValue,
197
228
  authState: this.authStateStore,
229
+ orderbookRulesCache: this.orderbookRulesCache,
198
230
  });
199
231
  }
200
232
  }
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,6CAA8E;AAC9E,iCAAoD;AAEpD,uCAAiE;AAEjE,4CAA0C;AAC1C,8CAA2C;AAC3C,wDAAsD;AACtD,0CAAwC;AACxC,kDAAgD;AAChD,gDAA8C;AAC9C,0DAA4D;AAC5D,gDAA8C;AAC9C,0CAAwC;AACxC,iCAAoD;AACpD,+BAAuF;AACvF,mCAAgC;AAChC,+BAA4B;AAC5B,+CAAiD;AACjD,qCAAyD;AAEzD,6BAA+C;AAE/C,MAAM,SAAS;IACL,gBAAgB,CAA8B;IAEtD,YAAY,OAAyB;QACnC,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IAClC,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,gBAAgB,CAAC;IAC/B,CAAC;IAED,cAAc,CAAC,WAAwC;QACrD,IAAI,CAAC,gBAAgB,GAAG,WAAW,CAAC;IACtC,CAAC;IAED,KAAK,CAAC,WAAW;QACf,6EAA6E;IAC/E,CAAC;CACF;AAED,MAAa,eAAe;IACjB,IAAI,CAAgB;IACpB,SAAS,CAAY;IACrB,iBAAiB,CAAc;IAC/B,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ChB,IAAI,CAAC,kBAAkB,GAAG,GAAG,CAAC;QAC9B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,0DAA0D;IAC1D,YAAY,CAAC,GAAW;QACtB,IAAI,CAAC,iBAAiB,GAAG,GAAG,CAAC;QAC7B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK;QACH,OAAO,IAAI,eAAe,CAAC;YACzB,IAAI,EAAE,IAAI,oBAAa,CAAC,IAAI,CAAC,YAAY,CAAC;YAC1C,QAAQ,EAAE;gBACR,GAAG,EAAE,IAAI,CAAC,UAAU;gBACpB,SAAS,EAAE,IAAI;gBACf,oBAAoB,EAAE,EAAE;gBACxB,oBAAoB,EAAE,KAAK;gBAC3B,cAAc,EAAE,MAAM;gBACtB,aAAa,EAAE,MAAM;aACtB;YACD,SAAS,EAAE,IAAI,CAAC,cAAc;YAC9B,aAAa,EAAE,IAAI,CAAC,kBAAkB;YACtC,eAAe,EAAE,IAAI,CAAC,oBAAoB;YAC1C,iBAAiB,EAAE,IAAI,CAAC,kBAAkB;gBACxC,CAAC,CAAC,IAAI,oBAAU,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC;gBACtE,CAAC,CAAC,SAAS;YACb,gBAAgB,EAAE,IAAI,CAAC,iBAAiB;gBACtC,CAAC,CAAC,IAAI,oBAAU,CAAC,IAAI,CAAC,iBAAiB,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC;gBACrE,CAAC,CAAC,SAAS;YACb,eAAe,EAAE,IAAI,CAAC,eAAe;SACtC,CAAC,CAAC;IACL,CAAC;CACF;AA/GD,wDA+GC","sourcesContent":["import { Connection, Keypair, PublicKey, Transaction } from \"@solana/web3.js\";\nimport { Auth, type AuthCredentials } from \"./auth\";\nimport type { ClientContext } from \"./context\";\nimport { signAndSubmitTx as signAndSubmitTxFn } from \"./context\";\nimport type { FaucetRequest, FaucetResponse } from \"./domain/faucet\";\nimport { Markets } from \"./domain/market\";\nimport { Metrics } from \"./domain/metrics\";\nimport { Notifications } from \"./domain/notification\";\nimport { Orders } from \"./domain/order\";\nimport { Orderbooks } from \"./domain/orderbook\";\nimport { Positions } from \"./domain/position\";\nimport { PriceHistoryClient } from \"./domain/price_history\";\nimport { Referrals } from \"./domain/referral\";\nimport { Trades } from \"./domain/trade\";\nimport { LightconeHttp, RetryPolicy } from \"./http\";\nimport { LightconeEnv, apiUrl, wsUrl, rpcUrl, programId as envProgramId } from \"./env\";\nimport { Privy } from \"./privy\";\nimport { Rpc } from \"./rpc\";\nimport { RpcFailoverState } from \"./rpcFailover\";\nimport { DepositSource, type PubkeyStr } from \"./shared\";\nimport { type ExternalSigner, type SigningStrategy } from \"./shared/signing\";\nimport { WsClient, type WsConfig } from \"./ws\";\n\nclass AuthState {\n private credentialsValue: AuthCredentials | undefined;\n\n constructor(initial?: AuthCredentials) {\n this.credentialsValue = initial;\n }\n\n getCredentials(): AuthCredentials | undefined {\n return this.credentialsValue;\n }\n\n setCredentials(credentials: AuthCredentials | undefined): void {\n this.credentialsValue = credentials;\n }\n\n async clearCaches(): Promise<void> {\n // No caches to clear — decimals are derived locally from orderbook metadata.\n }\n}\n\nexport class LightconeClient implements ClientContext {\n readonly http: LightconeHttp;\n readonly programId: PublicKey;\n readonly primaryConnection?: Connection;\n readonly backupConnection?: Connection;\n readonly rpcFailoverState: RpcFailoverState;\n private depositSourceValue: DepositSource;\n private signingStrategyValue?: SigningStrategy;\n private orderNonceValue: number | undefined;\n private readonly wsConfigValue: WsConfig;\n private readonly authStateStore: AuthState;\n\n /** @deprecated Use primaryConnection — kept for ClientContext compat. */\n get connection(): Connection | undefined {\n return this.primaryConnection;\n }\n\n constructor(params: {\n http: LightconeHttp;\n wsConfig: WsConfig;\n programId?: PublicKey;\n primaryConnection?: Connection;\n backupConnection?: Connection;\n rpcFailoverState?: RpcFailoverState;\n depositSource?: DepositSource;\n signingStrategy?: SigningStrategy;\n orderNonce?: number;\n authCredentials?: AuthCredentials;\n authState?: AuthState;\n }) {\n this.http = params.http;\n this.programId = params.programId ?? envProgramId(LightconeEnv.Prod);\n this.primaryConnection = params.primaryConnection;\n this.backupConnection = params.backupConnection;\n this.rpcFailoverState =\n params.rpcFailoverState ?? new RpcFailoverState();\n this.depositSourceValue = params.depositSource ?? DepositSource.Global;\n this.signingStrategyValue = params.signingStrategy;\n this.orderNonceValue = params.orderNonce;\n this.wsConfigValue = params.wsConfig;\n this.authStateStore =\n params.authState ??\n new AuthState(params.authCredentials);\n }\n\n // ── Deposit source ──────────────────────────────────────────────────\n\n get depositSource(): DepositSource {\n return this.depositSourceValue;\n }\n\n setDepositSource(source: DepositSource): void {\n this.depositSourceValue = source;\n }\n\n // ── Signing strategy ────────────────────────────────────────────────\n\n get signingStrategy(): SigningStrategy | undefined {\n return this.signingStrategyValue;\n }\n\n setSigningStrategy(strategy: SigningStrategy): void {\n this.signingStrategyValue = strategy;\n }\n\n clearSigningStrategy(): void {\n this.signingStrategyValue = undefined;\n }\n\n // ── Nonce cache ──────────────────────────────────────────────────────\n\n orderNonce(): number | undefined {\n return this.orderNonceValue;\n }\n\n setOrderNonce(nonce: number): void {\n this.orderNonceValue = nonce;\n }\n\n clearOrderNonce(): void {\n this.orderNonceValue = undefined;\n }\n\n // ── Auth token (cookie) ─────────────────────────────────────────────\n\n /**\n * Get the current `lightcone-token` cookie value, if any. Populated by the SDK\n * after a successful login, then attached on every authed request. Useful\n * for forwarding the token through the `*WithCookies` methods, or\n * persisting the session across processes.\n */\n async authToken(): Promise<string | undefined> {\n return this.http.authTokenRef()();\n }\n\n /**\n * Clear the cached `lightcone-token`. Subsequent authed calls will go out\n * without a `Cookie` header (and 401) unless they use a\n * `*WithCookies` variant.\n */\n async clearAuthToken(): Promise<void> {\n await this.http.clearAuthToken();\n }\n\n // ── Transaction signing + submission ────────────────────────────────\n\n async signAndSubmitTx(tx: Transaction): Promise<string> {\n return signAndSubmitTxFn(this, tx);\n }\n\n static builder(): LightconeClientBuilder {\n return new LightconeClientBuilder();\n }\n\n // ── Sub-client accessors ─────────────────────────────────────────────\n\n markets(): Markets {\n return new Markets(this);\n }\n\n orderbooks(): Orderbooks {\n return new Orderbooks(this);\n }\n\n orders(): Orders {\n return new Orders(this);\n }\n\n positions(): Positions {\n return new Positions(this);\n }\n\n trades(): Trades {\n return new Trades(this);\n }\n\n priceHistory(): PriceHistoryClient {\n return new PriceHistoryClient(this);\n }\n\n notifications(): Notifications {\n return new Notifications(this);\n }\n\n /**\n * Metrics sub-client — platform / market / orderbook / category / deposit-token\n * volume metrics, market leaderboard, and time-series history.\n */\n metrics(): Metrics {\n return new Metrics(this);\n }\n\n /**\n * Request testnet SOL and whitelisted deposit tokens for a wallet.\n *\n * Only active on environments whose backend has the faucet enabled (typically\n * local and staging).\n *\n * `POST /api/claim`\n */\n async claim(walletAddress: PubkeyStr): Promise<FaucetResponse> {\n const url = `${this.http.baseUrl()}/api/claim`;\n return this.http.post<FaucetResponse, FaucetRequest>(\n url,\n { wallet_address: walletAddress },\n RetryPolicy.None\n );\n }\n\n auth(): Auth {\n return new Auth({\n http: this.http,\n authState: this.authStateStore,\n });\n }\n\n privy(): Privy {\n return new Privy(this);\n }\n\n referrals(): Referrals {\n return new Referrals(this);\n }\n\n rpc(): Rpc {\n return new Rpc(this);\n }\n\n wsConfig(): WsConfig {\n return this.wsConfigValue;\n }\n\n ws(): WsClient {\n return new WsClient(this.wsConfigValue, this.http.authTokenRef());\n }\n\n clone(): LightconeClient {\n return new LightconeClient({\n http: this.http,\n wsConfig: { ...this.wsConfigValue },\n programId: this.programId,\n primaryConnection: this.primaryConnection\n ? new Connection(this.primaryConnection.rpcEndpoint, { commitment: \"confirmed\" })\n : undefined,\n backupConnection: this.backupConnection\n ? new Connection(this.backupConnection.rpcEndpoint, { commitment: \"confirmed\" })\n : undefined,\n rpcFailoverState: this.rpcFailoverState,\n depositSource: this.depositSourceValue,\n signingStrategy: this.signingStrategyValue,\n orderNonce: this.orderNonceValue,\n authState: this.authStateStore,\n });\n }\n}\n\nexport class LightconeClientBuilder {\n private baseUrlValue: string = apiUrl(LightconeEnv.Prod);\n private wsUrlValue: string = wsUrl(LightconeEnv.Prod);\n private authCredentials?: AuthCredentials;\n private programIdValue: PublicKey = envProgramId(LightconeEnv.Prod);\n private depositSourceValue: DepositSource = DepositSource.Global;\n private signingStrategyValue?: SigningStrategy;\n private primaryRpcUrlValue?: string = rpcUrl(LightconeEnv.Prod);\n private backupRpcUrlValue?: string;\n\n /**\n * Set the deployment environment. Configures the API URL, WebSocket URL,\n * RPC URL, and program ID for the given environment.\n *\n * Individual URL overrides (e.g. `.baseUrl()`) take precedence when\n * called **after** `.env()`.\n */\n env(environment: LightconeEnv): LightconeClientBuilder {\n this.baseUrlValue = apiUrl(environment);\n this.wsUrlValue = wsUrl(environment);\n this.programIdValue = envProgramId(environment);\n this.primaryRpcUrlValue = rpcUrl(environment);\n return this;\n }\n\n baseUrl(url: string): LightconeClientBuilder {\n return this.withBaseUrl(url);\n }\n\n withBaseUrl(url: string): LightconeClientBuilder {\n this.baseUrlValue = url;\n return this;\n }\n\n wsUrl(url: string): LightconeClientBuilder {\n return this.withWsUrl(url);\n }\n\n withWsUrl(url: string): LightconeClientBuilder {\n this.wsUrlValue = url;\n return this;\n }\n\n auth(credentials: AuthCredentials): LightconeClientBuilder {\n return this.withAuth(credentials);\n }\n\n withAuth(credentials: AuthCredentials): LightconeClientBuilder {\n this.authCredentials = credentials;\n return this;\n }\n\n programId(id: PublicKey): LightconeClientBuilder {\n this.programIdValue = id;\n return this;\n }\n\n depositSource(source: DepositSource): LightconeClientBuilder {\n this.depositSourceValue = source;\n return this;\n }\n\n nativeSigner(keypair: Keypair): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"native\", keypair };\n return this;\n }\n\n externalSigner(signer: ExternalSigner): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"walletAdapter\", signer };\n return this;\n }\n\n privyWalletId(walletId: string): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"privy\", walletId };\n return this;\n }\n\n rpcUrl(url: string): LightconeClientBuilder {\n this.primaryRpcUrlValue = url;\n return this;\n }\n\n /** Set a backup Solana RPC URL for automatic failover. */\n backupRpcUrl(url: string): LightconeClientBuilder {\n this.backupRpcUrlValue = url;\n return this;\n }\n\n build(): LightconeClient {\n return new LightconeClient({\n http: new LightconeHttp(this.baseUrlValue),\n wsConfig: {\n url: this.wsUrlValue,\n reconnect: true,\n maxReconnectAttempts: 10,\n baseReconnectDelayMs: 1_000,\n pingIntervalMs: 30_000,\n pongTimeoutMs: 10_000,\n },\n programId: this.programIdValue,\n depositSource: this.depositSourceValue,\n signingStrategy: this.signingStrategyValue,\n primaryConnection: this.primaryRpcUrlValue\n ? new Connection(this.primaryRpcUrlValue, { commitment: \"confirmed\" })\n : undefined,\n backupConnection: this.backupRpcUrlValue\n ? new Connection(this.backupRpcUrlValue, { commitment: \"confirmed\" })\n : undefined,\n authCredentials: this.authCredentials,\n });\n }\n}\n"]}
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;;AAAA,6CAA8E;AAC9E,iCAAoD;AAEpD,uCAImB;AAGnB,4CAA0C;AAC1C,8CAA2C;AAC3C,wDAAsD;AACtD,0CAAwC;AACxC,kDAAgD;AAChD,gDAA8C;AAC9C,0DAA4D;AAC5D,gDAA8C;AAC9C,0CAAwC;AACxC,iCAA6E;AAC7E,+BAAuF;AACvF,mCAAgC;AAChC,+BAA4B;AAC5B,+CAAiD;AACjD,qCAA8E;AAE9E,6BAA+C;AAE/C,MAAM,SAAS;IACL,gBAAgB,CAA8B;IAEtD,YAAY,OAAyB;QACnC,IAAI,CAAC,gBAAgB,GAAG,OAAO,CAAC;IAClC,CAAC;IAED,cAAc;QACZ,OAAO,IAAI,CAAC,gBAAgB,CAAC;IAC/B,CAAC;IAED,cAAc,CAAC,WAAwC;QACrD,IAAI,CAAC,gBAAgB,GAAG,WAAW,CAAC;IACtC,CAAC;IAED,KAA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ACtB;YACD,SAAS,EAAE,IAAI,CAAC,cAAc;YAC9B,aAAa,EAAE,IAAI,CAAC,kBAAkB;YACtC,eAAe,EAAE,IAAI,CAAC,oBAAoB;YAC1C,iBAAiB,EAAE,IAAI,CAAC,kBAAkB;gBACxC,CAAC,CAAC,IAAI,oBAAU,CAAC,IAAI,CAAC,kBAAkB,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC;gBACtE,CAAC,CAAC,SAAS;YACb,gBAAgB,EAAE,IAAI,CAAC,iBAAiB;gBACtC,CAAC,CAAC,IAAI,oBAAU,CAAC,IAAI,CAAC,iBAAiB,EAAE,EAAE,UAAU,EAAE,WAAW,EAAE,CAAC;gBACrE,CAAC,CAAC,SAAS;YACb,eAAe,EAAE,IAAI,CAAC,eAAe;SACtC,CAAC,CAAC;IACL,CAAC;CACF;AA/GD,wDA+GC","sourcesContent":["import { Connection, Keypair, PublicKey, Transaction } from \"@solana/web3.js\";\nimport { Auth, type AuthCredentials } from \"./auth\";\nimport type { ClientContext } from \"./context\";\nimport {\n signAndSubmitTx as signAndSubmitTxFn,\n signAndSubmitTxConfirmed as signAndSubmitTxConfirmedFn,\n signAndSubmitTxConfirmedWithSlot as signAndSubmitTxConfirmedWithSlotFn,\n} from \"./context\";\nimport type { ConfirmedTransaction } from \"./context\";\nimport type { FaucetRequest, FaucetResponse } from \"./domain/faucet\";\nimport { Markets } from \"./domain/market\";\nimport { Metrics } from \"./domain/metrics\";\nimport { Notifications } from \"./domain/notification\";\nimport { Orders } from \"./domain/order\";\nimport { Orderbooks } from \"./domain/orderbook\";\nimport { Positions } from \"./domain/position\";\nimport { PriceHistoryClient } from \"./domain/price_history\";\nimport { Referrals } from \"./domain/referral\";\nimport { Trades } from \"./domain/trade\";\nimport { LightconeHttp, RetryPolicy, type CredentialRestorer } from \"./http\";\nimport { LightconeEnv, apiUrl, wsUrl, rpcUrl, programId as envProgramId } from \"./env\";\nimport { Privy } from \"./privy\";\nimport { Rpc } from \"./rpc\";\nimport { RpcFailoverState } from \"./rpcFailover\";\nimport { DepositSource, type OrderbookRules, type PubkeyStr } from \"./shared\";\nimport { type ExternalSigner, type SigningStrategy } from \"./shared/signing\";\nimport { WsClient, type WsConfig } from \"./ws\";\n\nclass AuthState {\n private credentialsValue: AuthCredentials | undefined;\n\n constructor(initial?: AuthCredentials) {\n this.credentialsValue = initial;\n }\n\n getCredentials(): AuthCredentials | undefined {\n return this.credentialsValue;\n }\n\n setCredentials(credentials: AuthCredentials | undefined): void {\n this.credentialsValue = credentials;\n }\n\n async clearCaches(): Promise<void> {\n // No caches to clear — decimals are derived locally from orderbook metadata.\n }\n}\n\nexport class LightconeClient implements ClientContext {\n readonly http: LightconeHttp;\n readonly programId: PublicKey;\n readonly primaryConnection?: Connection;\n readonly backupConnection?: Connection;\n readonly rpcFailoverState: RpcFailoverState;\n private depositSourceValue: DepositSource;\n private signingStrategyValue?: SigningStrategy;\n private orderNonceValue: number | undefined;\n private readonly wsConfigValue: WsConfig;\n private readonly authStateStore: AuthState;\n readonly orderbookRulesCache: Map<string, Promise<OrderbookRules>>;\n\n /** @deprecated Use primaryConnection — kept for ClientContext compat. */\n get connection(): Connection | undefined {\n return this.primaryConnection;\n }\n\n constructor(params: {\n http: LightconeHttp;\n wsConfig: WsConfig;\n programId?: PublicKey;\n primaryConnection?: Connection;\n backupConnection?: Connection;\n rpcFailoverState?: RpcFailoverState;\n depositSource?: DepositSource;\n signingStrategy?: SigningStrategy;\n orderNonce?: number;\n authCredentials?: AuthCredentials;\n authState?: AuthState;\n orderbookRulesCache?: Map<string, Promise<OrderbookRules>>;\n }) {\n this.http = params.http;\n this.programId = params.programId ?? envProgramId(LightconeEnv.Prod);\n this.primaryConnection = params.primaryConnection;\n this.backupConnection = params.backupConnection;\n this.rpcFailoverState =\n params.rpcFailoverState ?? new RpcFailoverState();\n this.depositSourceValue = params.depositSource ?? DepositSource.Global;\n this.signingStrategyValue = params.signingStrategy;\n this.orderNonceValue = params.orderNonce;\n this.wsConfigValue = params.wsConfig;\n this.authStateStore =\n params.authState ??\n new AuthState(params.authCredentials);\n this.orderbookRulesCache = params.orderbookRulesCache ?? new Map();\n }\n\n // ── Deposit source ──────────────────────────────────────────────────\n\n get depositSource(): DepositSource {\n return this.depositSourceValue;\n }\n\n setDepositSource(source: DepositSource): void {\n this.depositSourceValue = source;\n }\n\n // ── Signing strategy ────────────────────────────────────────────────\n\n get signingStrategy(): SigningStrategy | undefined {\n return this.signingStrategyValue;\n }\n\n setSigningStrategy(strategy: SigningStrategy): void {\n this.signingStrategyValue = strategy;\n }\n\n clearSigningStrategy(): void {\n this.signingStrategyValue = undefined;\n }\n\n // ── Nonce cache ──────────────────────────────────────────────────────\n\n orderNonce(): number | undefined {\n return this.orderNonceValue;\n }\n\n setOrderNonce(nonce: number): void {\n this.orderNonceValue = nonce;\n }\n\n clearOrderNonce(): void {\n this.orderNonceValue = undefined;\n }\n\n // ── Auth token (cookie) ─────────────────────────────────────────────\n\n /**\n * Get the current `lightcone-token` cookie value, if any. Populated by the SDK\n * after a successful login, then attached on every authed request. Useful\n * for forwarding the token through the `*WithCookies` methods, or\n * persisting the session across processes.\n */\n async authToken(): Promise<string | undefined> {\n return this.http.authTokenRef()();\n }\n\n /**\n * Clear the cached `lightcone-token`. Subsequent authed calls will go out\n * without a `Cookie` header (and 401) unless they use a\n * `*WithCookies` variant.\n */\n async clearAuthToken(): Promise<void> {\n await this.http.clearAuthToken();\n }\n\n /**\n * Register the credential restorer consulted when a request fails with\n * HTTP 401: it attempts to restore credentials (e.g. refresh the app's\n * auth session so the auth cookie is valid again); on success the\n * transport replays the request once IF it declared itself retry-safe\n * (RetryPolicy.None mutations are never auto-replayed). See {@link CredentialRestorer}.\n * Without a restorer, 401s propagate to callers unchanged.\n *\n * Common use: set once at app startup, alongside the signing strategy.\n */\n setCredentialRestorer(restorer: CredentialRestorer): void {\n this.http.setCredentialRestorer(restorer);\n }\n\n /** Remove the credential restorer (e.g. in tests); 401s propagate again. */\n clearCredentialRestorer(): void {\n this.http.clearCredentialRestorer();\n }\n\n // ── Transaction signing + submission ────────────────────────────────\n\n async signAndSubmitTx(tx: Transaction): Promise<string> {\n return signAndSubmitTxFn(this, tx);\n }\n\n /**\n * Sign and submit a transaction, then wait until it reaches `confirmed`\n * commitment on-chain. Prefer this over {@link signAndSubmitTx} when a\n * follow-up transaction depends on this one's state.\n */\n async signAndSubmitTxConfirmed(tx: Transaction): Promise<string> {\n return signAndSubmitTxConfirmedFn(this, tx);\n }\n\n /** Sign, submit, confirm, and return the transaction's processing slot. */\n async signAndSubmitTxConfirmedWithSlot(\n tx: Transaction\n ): Promise<ConfirmedTransaction> {\n return signAndSubmitTxConfirmedWithSlotFn(this, tx);\n }\n\n static builder(): LightconeClientBuilder {\n return new LightconeClientBuilder();\n }\n\n // ── Sub-client accessors ─────────────────────────────────────────────\n\n markets(): Markets {\n return new Markets(this);\n }\n\n orderbooks(): Orderbooks {\n return new Orderbooks(this);\n }\n\n orders(): Orders {\n return new Orders(this);\n }\n\n positions(): Positions {\n return new Positions(this);\n }\n\n trades(): Trades {\n return new Trades(this);\n }\n\n priceHistory(): PriceHistoryClient {\n return new PriceHistoryClient(this);\n }\n\n notifications(): Notifications {\n return new Notifications(this);\n }\n\n /**\n * Metrics sub-client — platform / market / orderbook / category / deposit-token\n * volume metrics, market leaderboard, and time-series history.\n */\n metrics(): Metrics {\n return new Metrics(this);\n }\n\n /**\n * Request testnet SOL and whitelisted deposit tokens for a wallet.\n *\n * Only active on environments whose backend has the faucet enabled (typically\n * local and staging).\n *\n * `POST /api/claim`\n */\n async claim(walletAddress: PubkeyStr): Promise<FaucetResponse> {\n const url = `${this.http.baseUrl()}/api/claim`;\n return this.http.post<FaucetResponse, FaucetRequest>(\n url,\n { wallet_address: walletAddress },\n RetryPolicy.None\n );\n }\n\n auth(): Auth {\n return new Auth({\n http: this.http,\n authState: this.authStateStore,\n });\n }\n\n privy(): Privy {\n return new Privy(this);\n }\n\n referrals(): Referrals {\n return new Referrals(this);\n }\n\n rpc(): Rpc {\n return new Rpc(this);\n }\n\n wsConfig(): WsConfig {\n return this.wsConfigValue;\n }\n\n ws(): WsClient {\n return new WsClient(this.wsConfigValue, this.http.authTokenRef());\n }\n\n clone(): LightconeClient {\n return new LightconeClient({\n http: this.http,\n wsConfig: { ...this.wsConfigValue },\n programId: this.programId,\n primaryConnection: this.primaryConnection\n ? new Connection(this.primaryConnection.rpcEndpoint, { commitment: \"confirmed\" })\n : undefined,\n backupConnection: this.backupConnection\n ? new Connection(this.backupConnection.rpcEndpoint, { commitment: \"confirmed\" })\n : undefined,\n rpcFailoverState: this.rpcFailoverState,\n depositSource: this.depositSourceValue,\n signingStrategy: this.signingStrategyValue,\n orderNonce: this.orderNonceValue,\n authState: this.authStateStore,\n orderbookRulesCache: this.orderbookRulesCache,\n });\n }\n}\n\nexport class LightconeClientBuilder {\n private baseUrlValue: string = apiUrl(LightconeEnv.Prod);\n private wsUrlValue: string = wsUrl(LightconeEnv.Prod);\n private authCredentials?: AuthCredentials;\n private programIdValue: PublicKey = envProgramId(LightconeEnv.Prod);\n private depositSourceValue: DepositSource = DepositSource.Global;\n private signingStrategyValue?: SigningStrategy;\n private primaryRpcUrlValue?: string = rpcUrl(LightconeEnv.Prod);\n private backupRpcUrlValue?: string;\n\n /**\n * Set the deployment environment. Configures the API URL, WebSocket URL,\n * RPC URL, and program ID for the given environment.\n *\n * Individual URL overrides (e.g. `.baseUrl()`) take precedence when\n * called **after** `.env()`.\n */\n env(environment: LightconeEnv): LightconeClientBuilder {\n this.baseUrlValue = apiUrl(environment);\n this.wsUrlValue = wsUrl(environment);\n this.programIdValue = envProgramId(environment);\n this.primaryRpcUrlValue = rpcUrl(environment);\n return this;\n }\n\n baseUrl(url: string): LightconeClientBuilder {\n return this.withBaseUrl(url);\n }\n\n withBaseUrl(url: string): LightconeClientBuilder {\n this.baseUrlValue = url;\n return this;\n }\n\n wsUrl(url: string): LightconeClientBuilder {\n return this.withWsUrl(url);\n }\n\n withWsUrl(url: string): LightconeClientBuilder {\n this.wsUrlValue = url;\n return this;\n }\n\n auth(credentials: AuthCredentials): LightconeClientBuilder {\n return this.withAuth(credentials);\n }\n\n withAuth(credentials: AuthCredentials): LightconeClientBuilder {\n this.authCredentials = credentials;\n return this;\n }\n\n programId(id: PublicKey): LightconeClientBuilder {\n this.programIdValue = id;\n return this;\n }\n\n depositSource(source: DepositSource): LightconeClientBuilder {\n this.depositSourceValue = source;\n return this;\n }\n\n nativeSigner(keypair: Keypair): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"native\", keypair };\n return this;\n }\n\n externalSigner(signer: ExternalSigner): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"walletAdapter\", signer };\n return this;\n }\n\n privyWalletId(walletId: string): LightconeClientBuilder {\n this.signingStrategyValue = { type: \"privy\", walletId };\n return this;\n }\n\n rpcUrl(url: string): LightconeClientBuilder {\n this.primaryRpcUrlValue = url;\n return this;\n }\n\n /** Set a backup Solana RPC URL for automatic failover. */\n backupRpcUrl(url: string): LightconeClientBuilder {\n this.backupRpcUrlValue = url;\n return this;\n }\n\n build(): LightconeClient {\n return new LightconeClient({\n http: new LightconeHttp(this.baseUrlValue),\n wsConfig: {\n url: this.wsUrlValue,\n reconnect: true,\n maxReconnectAttempts: 10,\n baseReconnectDelayMs: 1_000,\n pingIntervalMs: 30_000,\n pongTimeoutMs: 10_000,\n },\n programId: this.programIdValue,\n depositSource: this.depositSourceValue,\n signingStrategy: this.signingStrategyValue,\n primaryConnection: this.primaryRpcUrlValue\n ? new Connection(this.primaryRpcUrlValue, { commitment: \"confirmed\" })\n : undefined,\n backupConnection: this.backupRpcUrlValue\n ? new Connection(this.backupRpcUrlValue, { commitment: \"confirmed\" })\n : undefined,\n authCredentials: this.authCredentials,\n });\n }\n}\n"]}