odin-connect 2.0.0 → 2.0.2

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/readme.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # OdinConnect
2
2
 
3
- A TypeScript SDK for integrating with the [Odin](https://odin.fun) decentralized token platform on the Internet Computer (ICP). OdinConnect handles user authentication, token trading, liquidity management, and API interactions through a simple, promise-based interface.
3
+ A TypeScript SDK for integrating with the [Odin](https://odin.fun) decentralized token platform on the Internet Computer (ICP). OdinConnect handles user authentication, token trading, liquidity management, and API interactions. Connect and action results land in one small state store you subscribe to (the same code for popups and wallet in-app browser redirects); data calls are plain promises.
4
4
 
5
5
  ## Table of Contents
6
6
 
@@ -11,8 +11,12 @@ A TypeScript SDK for integrating with the [Odin](https://odin.fun) decentralized
11
11
  - [Trading Action Flow](#trading-action-flow)
12
12
  - [API Request Flow](#api-request-flow)
13
13
  - [Getting Started](#getting-started)
14
+ - [React](#react)
14
15
  - [Authentication](#authentication)
15
- - [Session Restoration](#session-restoration)
16
+ - [Verified connect](#verified-connect)
17
+ - [Wallet in-app browsers (redirect mode)](#wallet-in-app-browsers-redirect-mode)
18
+ - [State and sessions](#state-and-sessions)
19
+ - [Migrating to 2.0.0](#migrating-to-200)
16
20
  - [Connected User Operations](#connected-user-operations)
17
21
  - [Fetching User Data](#fetching-user-data)
18
22
  - [Trading](#trading)
@@ -78,7 +82,7 @@ graph TB
78
82
 
79
83
  ### Authentication Flow
80
84
 
81
- When your app calls `connect()`, a popup opens to the Odin frontend where the user signs in. On success, user credentials are passed back to your app via `postMessage`.
85
+ When your app calls `connect()`, a popup opens to the Odin frontend where the user signs in (inside wallet in-app browsers the tab navigates there and back instead, see [redirect mode](#wallet-in-app-browsers-redirect-mode)). On success, Odin posts back the principal, a delegation chain (if requested) and a signed identity proof; the SDK verifies the proof with odin-api before it sets `state.user` (see [Verified connect](#verified-connect)).
82
86
 
83
87
  ```mermaid
84
88
  sequenceDiagram
@@ -87,21 +91,26 @@ sequenceDiagram
87
91
  participant Popup as Odin Frontend (Popup)
88
92
  participant User as User
89
93
 
94
+ participant API as odin-api
95
+
90
96
  App->>SDK: odinConnect.connect(options)
91
- SDK->>Popup: window.open(odin.fun/authorize/connect?...)
97
+ SDK->>Popup: window.open(odin.fun/authorize/connect?v=2&request_id&session_pubkey...)
92
98
  Popup->>User: Show sign-in UI
93
99
  User->>Popup: Authenticates
94
- Popup->>SDK: postMessage({ principal, jwt, delegationChain? })
100
+ Popup->>SDK: postMessage({ principal, delegationChain?, proof })
101
+ SDK->>SDK: Check proof nonce/origin/principal and the delegation chain
102
+ SDK->>API: POST /connect/verify (proof, audience, nonce, issue_jwt, client_signature)
103
+ API->>SDK: { principal, username, jwt? }
95
104
  SDK->>SDK: Create ConnectedUser instance
96
105
  SDK->>SDK: Persist session to localStorage
97
- SDK->>App: Returns ConnectedUser
106
+ SDK->>App: state.user + request "success" (subscribe), promise resolves
98
107
  ```
99
108
 
100
109
  **What gets returned depends on your options:**
101
110
 
102
111
  | Option | What You Get |
103
112
  |--------|-------------|
104
- | `requires_api: true` | A JWT token for authenticated API calls (image uploads, etc.) |
113
+ | `requires_api: true` | A JWT for authenticated API calls (image uploads, etc.), issued by odin-api after verification |
105
114
  | `requires_delegation: true` | A `DelegationIdentity` for direct canister calls |
106
115
  | Neither | Basic connection with user's principal |
107
116
 
@@ -123,11 +132,20 @@ sequenceDiagram
123
132
  User->>Popup: Approves transaction
124
133
  Popup->>Chain: Execute on-chain transaction
125
134
  Chain->>Popup: Transaction result
126
- Popup->>SDK: postMessage("purchased")
127
- SDK->>App: Returns true
135
+ Popup->>SDK: postMessage({ message: "purchased" })
136
+ SDK->>App: request "success" (subscribe), promise resolves true
128
137
  ```
129
138
 
130
- If the user rejects the transaction, the popup sends `"rejected"` and the promise resolves to `false`.
139
+ If the user rejects the transaction, the popup sends `"rejected"`:
140
+ `state.request.status` becomes `"rejected"` and the promise rejects (as in
141
+ 1.6.0).
142
+
143
+ Every authorize URL carries `v=2` and a fresh, random `request_id`. For
144
+ `icrcApprove()`, the result exposes the ledger block index of the approval as
145
+ `state.request.detail.block_index` (decimal string). Odin sends no ICRC-2
146
+ memo: the Odin canister rejects approvals that carry one, so an approval is
147
+ not bound to its `request_id` on chain. The `icrcApprove()` promise still
148
+ resolves `true`.
131
149
 
132
150
  ### API Request Flow
133
151
 
@@ -145,28 +163,81 @@ flowchart LR
145
163
 
146
164
  ## Getting Started
147
165
 
166
+ One pattern for every browser. Results (a connect, a buy, an approval) land
167
+ in the SDK's state, whether they came back through a popup or, in wallet
168
+ in-app browsers, through a full-page redirect and reload. Render from that
169
+ state:
170
+
148
171
  ```typescript
149
172
  import { OdinConnect } from "odin-connect";
150
173
 
151
- // 1. Initialize
152
- const odinConnect = new OdinConnect({
153
- name: "My App",
154
- env: "prod",
155
- });
174
+ // 1. Initialize. The constructor starts restoring the session (and, after a
175
+ // redirect, verifying its result) right away.
176
+ const odin = new OdinConnect({ name: "My App", env: "prod" });
177
+
178
+ // 2. Render from state, now and on every change.
179
+ odin.subscribe(({ user, request }) => render(user, request));
180
+ await odin.ready();
181
+ render(odin.state.user, odin.state.request);
182
+
183
+ // 3. Start things from buttons; the outcome arrives through subscribe().
184
+ connectButton.onclick = () => odin.connect({ requires_api: true });
185
+ buyButton.onclick = () =>
186
+ odin.user?.buy({ token: "2jjj", btcAmount: 10_000_000n });
156
187
 
157
- // 2. Restore existing session or authenticate
158
- let user = odinConnect.restoreSession();
159
- if (!user) {
160
- user = await odinConnect.connect({ requires_api: true });
188
+ function render(user, request) {
189
+ // user: OdinConnectedUser | null
190
+ // request: the latest connect() or action, e.g.
191
+ // { action: "buy", status: "success", input: { token, btcAmount } }
161
192
  }
193
+ ```
162
194
 
163
- // 3. Fetch data
164
- const balances = await user.getBalances({ page: 1, limit: 10 });
195
+ Data calls are plain promises:
165
196
 
166
- // 4. Perform actions
167
- await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
197
+ ```typescript
198
+ const balances = await odin.user?.getBalances({ page: 1, limit: 10 });
168
199
  ```
169
200
 
201
+ ### React
202
+
203
+ ```tsx
204
+ import { useSyncExternalStore } from "react";
205
+ import { OdinConnect } from "odin-connect";
206
+
207
+ const odin = new OdinConnect({ name: "My App", env: "prod" });
208
+
209
+ function App() {
210
+ const { status, user, request } = useSyncExternalStore(
211
+ odin.subscribe,
212
+ odin.getState,
213
+ odin.getServerState // SSR / hydration: always the "initializing" snapshot
214
+ );
215
+ if (status === "initializing") return <Spinner />;
216
+ return (
217
+ <>
218
+ {request && <p>{request.action}: {request.status}</p>}
219
+ {user ? (
220
+ <button onClick={() => user.buy({ token: "2jjj", btcAmount: 1_000n })}>
221
+ Buy
222
+ </button>
223
+ ) : (
224
+ <button onClick={() => odin.connect()}>Connect</button>
225
+ )}
226
+ </>
227
+ );
228
+ }
229
+ ```
230
+
231
+ `subscribe`, `getState` and `getServerState` are bound, so they can be passed
232
+ as is. `getServerState()` always returns the same frozen
233
+ `{ status: "initializing", user: null, request: null }` (also exported as
234
+ `INITIAL_ODIN_STATE` and `OdinConnect.serverState`): that is what a server
235
+ renders, so passing it as the third argument keeps hydration from
236
+ mismatching; React switches to `getState` right after. Do not pass
237
+ `getState` there: in the browser it can already be `"ready"`. Creating
238
+ the instance twice (React StrictMode) is fine: both share one redirect read
239
+ and odin-api is asked once.
240
+
170
241
  ## Authentication
171
242
 
172
243
  ### Initializing a new instance
@@ -174,8 +245,9 @@ await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
174
245
  ```typescript
175
246
  const odinConnect = new OdinConnect({
176
247
  name: "Demo App", // Your app name (shown in auth popup)
177
- env: "prod", // "prod" | "dev" | "local" | "legacy"
248
+ env: "prod", // "prod" | "staging" | "dev" | "local" | "legacy"
178
249
  lang: "en", // Popup UI language: "en" | "zh" (default "en")
250
+ mode: "auto", // "auto" (default) | "popup" | "redirect", see below
179
251
  });
180
252
  ```
181
253
 
@@ -196,7 +268,7 @@ pass it on each construction from your app's own i18n state.
196
268
  ### Connecting a user
197
269
 
198
270
  ```typescript
199
- const user = await odinConnect.connect({
271
+ odinConnect.connect({
200
272
  // window.open() settings for the auth popup
201
273
  open: {
202
274
  target: "_blank",
@@ -209,17 +281,34 @@ const user = await odinConnect.connect({
209
281
  });
210
282
  ```
211
283
 
284
+ `state.request` becomes `{ action: "connect", status: "pending", input:
285
+ { requires_api, requires_delegation, targets } }` at once and then settles:
286
+
287
+ | `status` | Meaning |
288
+ |----------|---------|
289
+ | `"success"` | Verified; `state.user` is the connected user. |
290
+ | `"rejected"` | The user declined in Odin. |
291
+ | `"failed"` | The popup could not open (blocked), or the redirect could not start; `error` says why. |
292
+ | `"unverified"` | Odin's answer failed verification (`error` says why). Not connected, nothing stored. |
293
+
294
+ `connect()` still returns a promise, as in 1.6.0: in popup mode it resolves
295
+ with the user or rejects. In redirect mode the tab navigates away and it
296
+ never settles. Build on `subscribe()` / `state`; the `await` is there so
297
+ existing popup code keeps working. Ignoring the promise never causes an
298
+ unhandled rejection.
299
+
212
300
  ### Getting a Delegation Identity
213
301
 
214
302
  If you need to make direct calls to ICP canisters, request a delegation:
215
303
 
216
304
  ```typescript
217
- const user = await odinConnect.connect({
305
+ odinConnect.connect({
218
306
  requires_delegation: true,
219
307
  targets: ["aaaa-aa"], // Canister IDs the delegation is scoped to
220
308
  });
221
309
 
222
- const identity = user.getIdentity();
310
+ // once state.user is set:
311
+ const identity = odinConnect.user?.getIdentity();
223
312
  // Use identity with @dfinity/agent
224
313
  ```
225
314
 
@@ -228,53 +317,134 @@ const identity = user.getIdentity();
228
317
  >
229
318
  > **Failure mode:** if any target does not list your origin (or does not implement ICRC-28), the authorize popup silently hides the action — no delegation is issued and no error is surfaced to your app. Ensure each target canister declares your origin before requesting `requires_delegation: true`.
230
319
 
320
+ ### Verified connect
321
+
322
+ Since 2.0.0 a connect result is never taken on trust. A forged "connected as
323
+ X" (devtools, a crafted URL fragment) is rejected:
324
+
325
+ 1. Every connect generates a session key in your page (with or without
326
+ `requires_delegation`) and sends **only its public key** to Odin
327
+ (`session_pubkey`). The secret never leaves the SDK.
328
+ 2. Odin signs an identity proof with the user's Odin identity, bound to your
329
+ origin (`aud`), to this request (`request_id` nonce) and to that session
330
+ key (`sk` = the `session_pubkey` string). The SDK rejects a proof whose
331
+ `sk` is missing or is not its own key.
332
+ 3. With `requires_delegation`, the SDK checks the chain locally: not expired,
333
+ issued to its own session key, rooted at the reported principal, and only
334
+ scoped to the `targets` you asked for.
335
+ 4. The SDK posts the proof to odin-api `POST /connect/verify` (on the same
336
+ base URL as the other API calls) with `audience: window.location.origin`,
337
+ `nonce: request_id`, `issue_jwt: requires_api` and `client_signature`:
338
+ the session key's signature over `"odin-connect-verify:v1\n" + payload`.
339
+ odin-api verifies the proof's signature (including Internet Identity
340
+ canister signatures) and that `client_signature` matches the key in `sk`,
341
+ rejects replays and returns `{ principal, username, jwt }`. The principal
342
+ must match.
343
+ 5. Only then is `state.user` set and the session persisted. With
344
+ `requires_api`, the JWT comes from that API response; it never travels in
345
+ a URL or `postMessage`.
346
+
347
+ The `sk` binding is what makes a leaked proof worthless. In redirect mode the
348
+ proof travels in the return URL's fragment, where browser history, extensions,
349
+ analytics capturing `location.href` or third-party scripts can read it before
350
+ the SDK does. Without the binding, whoever read it first could redeem it at
351
+ `/connect/verify` for the user's JWT. With it, redeeming the proof needs a
352
+ signature from the session secret, which stayed in your page (popup: in
353
+ memory; redirect: in that tab's `sessionStorage` until the result is read).
354
+
355
+ If any step fails, `state.request` is `{ action: "connect", status:
356
+ "unverified", error }` in both modes, and a popup `connect()` promise rejects
357
+ with an `OdinConnectVerificationError` ("OdinConnect could not verify the
358
+ connection: ..."). Nothing is stored.
359
+
231
360
  ### Wallet in-app browsers (redirect mode)
232
361
 
233
362
  Some wallet in-app browsers (OKX) open `window.open` targets as a detached
234
363
  page with no `window.opener`, so a popup can never send its result back.
235
- Set `mode` on the instance; it applies to `connect()` **and every action**
236
- (buy, sell, transfer, swap, liquidity, ICRC-2 approve, create token):
364
+ There, the SDK navigates the tab to Odin and back instead ("redirect mode").
365
+ The default `mode: "auto"` does this only inside wallet in-app browsers and
366
+ app webviews and uses popups everywhere else. `mode` applies to `connect()`
367
+ **and every action** (buy, sell, transfer, swap, liquidity, ICRC-2 approve,
368
+ create token).
369
+
370
+ Nothing in your code changes for it: the
371
+ [Getting Started](#getting-started) pattern already covers it. Before
372
+ navigating, the SDK keeps the pending request (its `input`, `returnState` and
373
+ a one-time nonce) in that tab's `sessionStorage`. When Odin sends the tab
374
+ back, the new page's `OdinConnect` reads the result, verifies it (connect),
375
+ and `ready()` resolves with it as `state.request` (and `state.user` for a
376
+ connect). Subscribers are notified as usual.
237
377
 
238
378
  ```typescript
239
- const odinConnect = new OdinConnect({
379
+ const odin = new OdinConnect({
240
380
  name: "My App",
241
381
  env: "prod",
242
- mode: "auto", // "popup" (default) | "redirect" | "auto" (redirect in wallet browsers)
382
+ // mode: "auto" (default) | "popup" (never redirect) | "redirect" (always)
243
383
  });
244
-
245
- // On page load: read the outcome of the redirect this load returned from.
246
- try {
247
- const result = odinConnect.handleRedirectResult();
248
- if (result?.action === "connect" && result.status === "connected") {
249
- user = result.user;
250
- } else if (result?.action === "connect") {
251
- // Rejected. Show that, and do NOT call connect() automatically on this
252
- // load, or a user who taps Reject is sent straight back to Odin.
253
- } else if (result) {
254
- // An action: { action: "buy", status: "success" | "failed" }
255
- }
256
- } catch (error) {
257
- // Stale or foreign result; ignore.
258
- }
259
- user ??= odinConnect.restoreSession();
260
-
261
- // From a button click. In redirect mode these navigate this tab to Odin and
262
- // back, and the promise never settles; the outcome arrives via
263
- // handleRedirectResult() above.
264
- await odinConnect.connect({ requires_delegation: true, targets: ["aaaa-aa"] });
265
- await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
384
+ odin.subscribe(({ user, request }) => render(user, request));
385
+ await odin.ready();
386
+ // Read URL query state (?step=2) only after ready(): on the return from Odin
387
+ // the SDK puts the page's query string back.
388
+ render(odin.state.user, odin.state.request);
389
+
390
+ // A rejected connect comes back as request.status === "rejected". Show that,
391
+ // and do NOT call connect() automatically on that load, or a user who taps
392
+ // Reject is sent straight back to Odin.
266
393
  ```
267
394
 
395
+ - **No setup needed.** Redirect mode works for any app, like popups. For
396
+ delegations, every target canister must still trust your origin
397
+ (ICRC-28, see above). Pass `mode: "popup"` to opt out of redirect mode
398
+ (popups still cannot return a result inside those wallet browsers).
399
+ - **Odin returns to the same page path; the SDK restores the query.** The
400
+ SDK sends `return_url` as your page's origin and path only (no query, no
401
+ fragment), because Odin refuses return URLs with a query string or
402
+ fragment, or on another origin. Your page's full URL waits with the
403
+ one-time nonce in `sessionStorage`, and once the result is read the SDK
404
+ replaces the address (`history.replaceState`, `history.state` kept) with
405
+ the original path and query. Read URL query state after `await ready()`,
406
+ not before. A fragment on the original page is not restored.
407
+ - **Security: no open redirects on your origin.** Odin only returns to your
408
+ origin and never with a query string, which stops `/go?to=...`-style open
409
+ redirects from forwarding the result. Path-style redirects
410
+ (`/redirect/https://evil.example`) are not blocked, so an app that uses
411
+ redirect mode with delegations or API access must not have open-redirect
412
+ pages on its origin.
268
413
  - `mode` can be changed at runtime: `odinConnect.mode = "redirect"`.
269
414
  - The result comes back in the URL fragment of the page that started the
270
- request. `handleRedirectResult()` checks it against a one-time nonce kept
271
- in `sessionStorage` and removes it from the address bar.
272
- - `restoreSession()` finishes a redirected `connect()` on its own, but leaves
273
- action results for `handleRedirectResult()`.
274
- - Page state is lost across the round trip. Pass what the page needs to
275
- resume as `returnState` (see below).
276
- - `requires_api` is not supported in redirect mode (it rejects), so the JWT
277
- never lands in a URL. Use a delegation instead.
415
+ request. It is checked against the one-time nonce (sent as both `state` and
416
+ `request_id`), removed from the address bar and, for connect, verified like
417
+ a popup connect. A stale or foreign result (another tab, a replay, a
418
+ tampered fragment) is removed from the URL and ignored: `request` stays
419
+ `null`.
420
+ - Connect with `requires_api` or `requires_delegation` if users will run
421
+ actions in redirect mode: a connect with neither is not persisted, so
422
+ after the next redirect `state.user` is `null`.
423
+ - A rejected or unverified redirect connect keeps a previously stored
424
+ session: `state.user` is that user, `state.request` tells what happened.
425
+ - Several `OdinConnect` instances for the same `slug` and `env` on one page
426
+ load (React StrictMode) all get the same outcome, and odin-api is asked
427
+ once, as long as they exist while the result is being read and verified
428
+ (in practice: created in the same render). Once it has been delivered, an
429
+ instance created later on that page load (e.g. one per route) does not
430
+ get it again: its `request` is `null` and its `user` is the stored
431
+ session (`null` after a connect with neither `requires_api` nor
432
+ `requires_delegation`, which is not stored). Keep one instance per app (a
433
+ module-level `const odin = new OdinConnect(...)`) if several parts of the
434
+ page need the result. An app with another `slug` or `env` never sees it.
435
+ - `disconnect()` wins over a connect still in flight: a popup or redirect
436
+ connect that finishes verifying after `disconnect()` is neither stored nor
437
+ applied. So does a newer request: when a connect succeeds after another
438
+ `connect()` or action replaced it as `state.request`, its promise still
439
+ resolves with that user (1.6.0), but `state.user`, the stored session and
440
+ the instance's API key are left as they are.
441
+ - A pending request that never got its result (the user left Odin) is
442
+ deleted after 10 minutes, the next time the app loads without a result.
443
+ - In-memory page state is lost across the round trip (the query string is
444
+ restored). `state.request.input` holds what the request was for; pass
445
+ anything else the page needs to resume as `returnState` (see below).
446
+ - `requires_api` works in redirect mode: the JWT comes from odin-api, never
447
+ from the URL.
278
448
  - `"auto"` redirects when `isInAppBrowser()` is true: a known wallet user
279
449
  agent (OKX), an app webview (Android `; wv)`, iOS WebKit without
280
450
  `Safari/`), or a mobile browser with an injected wallet (`XverseProviders`,
@@ -282,74 +452,138 @@ await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
282
452
  toward redirect, which works everywhere. Call `isInAppBrowser()` yourself
283
453
  if you want to choose the mode.
284
454
 
285
- #### Resuming after a redirect (`returnState`)
455
+ #### Resuming a multi-step flow (`returnState`)
286
456
 
287
- In redirect mode the page reloads, so an awaited `connect()` / action never
288
- returns and in-memory state is gone. Pass anything you need to continue as
289
- `returnState`; it is kept with the one-time nonce in `sessionStorage` (never
290
- sent to Odin) and comes back on `handleRedirectResult()`. Any JSON value
291
- works, and bigints are preserved. In popup mode it is ignored and the awaited
292
- call resolves as usual, so the same code works in both modes:
457
+ Every call takes an optional `returnState`, handed back as
458
+ `state.request.returnState` in both modes (never sent to Odin). In redirect
459
+ mode it is kept with the pending request in `sessionStorage`, so it must be
460
+ JSON-serializable; bigints are preserved:
293
461
 
294
462
  ```typescript
295
463
  type Resume = { step: "approve"; token: string; amount: bigint };
296
464
 
297
- // 1. Start the action with what the page needs to resume.
298
- const ok = await user.icrcApprove({
465
+ // 1. From a button: start the action with what the page needs to resume.
466
+ odin.user?.icrcApprove({
299
467
  token,
300
468
  spender,
301
469
  amount,
302
470
  returnState: { step: "approve", token, amount } satisfies Resume,
303
471
  });
304
- if (ok) goToStep("commit"); // popup mode lands here
305
-
306
- // 2. On page load (redirect mode lands here instead).
307
- const result = odinConnect.handleRedirectResult<Resume>();
308
- if (result?.action === "icrc_approve" && result.returnState) {
309
- const { token, amount } = result.returnState;
310
- if (result.status === "success") goToStep("commit", { token, amount });
311
- else showError("Approval was rejected");
312
- }
313
- ```
314
472
 
315
- ## Session Restoration
316
-
317
- OdinConnect automatically persists session data to `localStorage` after a successful `connect()`. This allows you to restore sessions on page load without requiring user action.
473
+ // 2. In the subscriber (popup result, or the redirect result after reload).
474
+ odin.subscribe(({ request }) => {
475
+ if (request?.action !== "icrc_approve") return;
476
+ const resume = request.returnState as Resume | undefined;
477
+ if (request.status === "success" && resume) {
478
+ // request.detail?.block_index: ledger block of the approval
479
+ goToStep("commit", { token: resume.token, amount: resume.amount });
480
+ } else if (request.status !== "pending") {
481
+ showError(request.error ?? "Approval was rejected");
482
+ }
483
+ });
484
+ ```
318
485
 
319
- ### Restoring a session
486
+ ## State and sessions
320
487
 
321
488
  ```typescript
322
- const odinConnect = new OdinConnect({ name: "My App", env: "prod" });
323
-
324
- // Attempt to restore a previous session (synchronous, no popup)
325
- const user = odinConnect.restoreSession();
326
- if (user) {
327
- // Session restored — user is ready
328
- const balances = await user.getBalances({ page: 1, limit: 10 });
329
- } else {
330
- // No valid session — prompt the user to connect
331
- const user = await odinConnect.connect({ requires_api: true });
332
- }
489
+ type OdinState = {
490
+ status: "initializing" | "ready";
491
+ user: OdinConnectedUser | null;
492
+ request: OdinRequestState | null; // the latest request; a new one replaces it
493
+ };
494
+
495
+ type OdinRequestState = {
496
+ id: string; // request_id
497
+ action: "connect" | OdinAction; // "buy" | "sell" | "transfer" | "swap" |
498
+ // "add_liquidity" | "remove_liquidity" | "icrc_approve" | "create_token"
499
+ status: "pending" | "success" | "rejected" | "failed" | "unverified";
500
+ input: /* per action, see below */;
501
+ detail?: OdinActionDetail; // icrc_approve: { block_index }
502
+ returnState?: unknown;
503
+ error?: string; // "failed" / "unverified": why; "rejected": OdinRejectReason
504
+ };
333
505
  ```
334
506
 
335
- ### Checking session validity
507
+ | Member | |
508
+ |--------|-|
509
+ | `ready(): Promise<OdinState>` | Restores the stored session and applies a redirect result. Started by the constructor; idempotent; never rejects. Without a redirect result the state is `"ready"` right after construction. |
510
+ | `state` / `getState()` | The current snapshot. A new frozen object after every change, the same object in between (what `useSyncExternalStore` needs). |
511
+ | `getServerState()` | Always `INITIAL_ODIN_STATE` (`"initializing"`, no user, no request); `useSyncExternalStore`'s `getServerSnapshot`. |
512
+ | `restoreSession()` | Deprecated (1.6.0). Synchronous: the stored session's user (`state.user` once `ready()` finished). Does not apply a redirect result. |
513
+ | `subscribe(listener)` | Calls `listener(state)` after every change, not on subscribe (read `state` after `await ready()`). Returns the unsubscribe function. |
514
+ | `user` | `state.user`. |
515
+ | `disconnect()` | Clears the stored session and the API key; `user` and `request` become `null`. |
516
+ | `isSessionValid()` | A non-expired session exists in storage. |
517
+
518
+ `input` is what the call was given, without `returnState` and the
519
+ principal; amounts stay `bigint`, also across a redirect:
520
+
521
+ | `action` | `input` |
522
+ |----------|---------|
523
+ | `connect` | `{ requires_api, requires_delegation, targets }` |
524
+ | `buy` | `{ token, btcAmount }` |
525
+ | `sell` | `{ token, tokenAmount }` |
526
+ | `transfer` | `{ token, amount, destination }` |
527
+ | `swap` | `{ fromToken, toToken, fromAmount }` |
528
+ | `add_liquidity` | `{ token, btcAmount }` |
529
+ | `remove_liquidity` | `{ token, lpAmount }` |
530
+ | `icrc_approve` | `{ token, spender, amount }` |
531
+ | `create_token` | the token fields, with `image` = the uploaded image URL (never the `File`; set once the upload finished) |
532
+
533
+ An action is `"success"` when Odin confirms it, `"rejected"` when the user
534
+ declines (or closes the popup, see below), and `"failed"` otherwise (popup blocked, Odin reported an error, a
535
+ `createToken` validation or upload error). The `user.<action>()` promises
536
+ work as in 1.6.0: popup mode resolves `true` or rejects; redirect mode never
537
+ settles.
538
+
539
+ #### Rejection reasons
540
+
541
+ When Odin cannot offer the request, its error screen has a "Back to app"
542
+ button. It returns a `"rejected"` result (popup and redirect mode), and
543
+ `request.error` holds a reason code (`OdinRejectReason`). A plain Reject
544
+ leaves `error` unset. Popup promises still reject with the 1.6.0 text
545
+ ("User rejected the connection" / the action's failure text).
546
+
547
+ | `request.error` | Meaning |
548
+ |-----------------|---------|
549
+ | `untrusted_origin` | A delegation target canister does not list your origin in its ICRC-28 trusted origins. Add your origin to every target canister's `icrc28_trusted_origins`. |
550
+ | `invalid_targets` | A `targets` canister id is invalid or not allowed. |
551
+ | `no_targets` | `requires_delegation` without any `targets`. |
552
+ | `invalid_session_key` | The session public key is missing or malformed. |
553
+ | `missing_request_id` | No request id, or no identity, to bind the identity proof. |
554
+ | `unsupported_identity` | The user's wallet cannot sign the identity proof. |
555
+ | `no_action` | Odin has no authorize page for this action. |
556
+ | `popup_closed` | Set by the SDK, popup mode only: the popup was closed without an answer (checked every 500 ms, then a 1.5 s grace period for an answer posted just before the close). |
557
+ | `navigated_back` | Set by the SDK, redirect mode only: the user pressed Back on Odin and the browser restored the app page from its back-forward cache without a result. |
558
+
559
+ A closed popup settles the pending `connect()` or action as `"rejected"` /
560
+ `popup_closed`, so the app never waits forever; the popup promise rejects
561
+ with the same text as a user rejection. Odin posts its answer and then closes
562
+ the popup, so the SDK waits a 1.5 s grace period after it sees the
563
+ popup closed: an answer arriving in that time is handled as usual (a connect
564
+ is still fully verified). An answer after the grace period is ignored.
565
+
566
+ Odin may add codes; treat an unknown one as a plain rejection.
567
+
568
+ ### Session persistence
569
+
570
+ A verified `connect()` with `requires_api` or `requires_delegation` is
571
+ persisted to `localStorage`, and `ready()` restores it on the next load
572
+ (including sessions stored by 1.6.0 and 1.7.0). A connect with neither is
573
+ kept in memory only. A new verified connect replaces the stored session.
336
574
 
337
575
  ```typescript
338
576
  if (odinConnect.isSessionValid()) {
339
577
  // A non-expired session exists in storage
340
578
  }
341
- ```
342
579
 
343
- ### Disconnecting
344
-
345
- ```typescript
346
- // Clears persisted session data and resets the API key
580
+ // Clears persisted session data, the API key, state.user and state.request
347
581
  odinConnect.disconnect();
348
582
  ```
349
583
 
350
584
  ### Custom app slug
351
585
 
352
- Storage keys are scoped by a slug derived from your app name (e.g. `"My App"` becomes `"my-app"`). You can provide a custom slug to control the storage key:
586
+ Storage keys are scoped by a slug derived from your app name: the name in lowercase kebab-case plus a short hash of it, so the key is `odin_connect:<slug>-<hash>:<env>:session` (e.g. `"My App"` becomes `my-app-12b`, key `odin_connect:my-app-12b:prod:session`). Renaming the app therefore starts with no stored session. You can provide a custom slug to control the storage key; it is used as is:
353
587
 
354
588
  ```typescript
355
589
  const odinConnect = new OdinConnect({
@@ -363,10 +597,120 @@ const odinConnect = new OdinConnect({
363
597
  > - Sessions with a delegation chain are automatically invalidated when the delegation expires.
364
598
  > - Calling `disconnect()` in one tab clears the session for all tabs on the same origin.
365
599
  > - In environments where `localStorage` is unavailable (SSR, strict privacy mode), session persistence is silently skipped.
600
+ > - On a server (no `window`) the constructor does not touch the browser and `state` stays `"initializing"`.
601
+
602
+ ## Migrating to 2.0.0
603
+
604
+ > **Using a coding agent?** Point it at
605
+ > [`MIGRATION-2.0.md`](./MIGRATION-2.0.md) (also shipped in the package
606
+ > from 2.0.0 on, at `node_modules/odin-connect/MIGRATION-2.0.md`): step-by-step upgrade
607
+ > instructions written for agents, with search commands, code changes,
608
+ > pitfalls and a verification checklist.
609
+
610
+ 2.0.0 makes connect results verifiable, stops sending secrets through URLs,
611
+ supports wallet in-app browsers by default, and delivers every result
612
+ through one state store. It needs the Odin frontend and odin-api that
613
+ support `v=2` (already deployed before this release).
614
+
615
+ ### From 1.6.0
616
+
617
+ Popup code keeps working unchanged: `restoreSession()` is still synchronous
618
+ and returns the stored session's user, `connect()` still resolves with the
619
+ user or rejects, and actions still resolve `true` or reject. No `await` or
620
+ other edit is needed.
621
+
622
+ ```typescript
623
+ // 1.6.0 code, unchanged in 2.0 (popup mode)
624
+ const odin = new OdinConnect({ name: "My App", env: "prod" });
625
+ let user = odin.restoreSession(); // deprecated, still synchronous
626
+ connectButton.onclick = async () => {
627
+ user = await odin.connect({ requires_api: true });
628
+ };
629
+ ```
630
+
631
+ Then, in order of importance:
632
+
633
+ 1. **Wallet in-app browsers** (the new default `mode: "auto"` redirects
634
+ there): a redirect reloads the page, so an awaited `connect()` or action
635
+ never returns, and `restoreSession()` does not see the result. Render
636
+ from `state` as in [Getting Started](#getting-started):
637
+
638
+ ```typescript
639
+ odin.subscribe(({ user, request }) => render(user, request));
640
+ const { user, request } = await odin.ready(); // applies a redirect result
641
+ render(user, request);
642
+ ```
643
+
644
+ To keep popups everywhere instead (they cannot return a result inside
645
+ those wallet browsers), pass `mode: "popup"`.
646
+ 2. Replace `restoreSession()` with `(await odin.ready()).user` or
647
+ `odin.state.user` when convenient; it is deprecated.
648
+ 3. If your page reads URL query state on load, read it after
649
+ `await odin.ready()`: Odin returns to the page path without the query,
650
+ and the SDK restores it.
651
+ 4. Make sure the app can reach `api.odin.fun` (CSP `connect-src`): every
652
+ connect is verified by odin-api.
653
+
654
+ ### From 1.7.0
655
+
656
+ As above, plus: `handleRedirectResult()` and the `OdinRedirectResult` type
657
+ are gone, and `restoreSession()` no longer finishes a redirect-mode connect
658
+ (1.7.0 did). Read redirect outcomes from `(await odin.ready()).request` /
659
+ `subscribe()` instead (`status: "success"` replaces `"connected"`, and the
660
+ user is `state.user`). If you passed `mode: "redirect"` or `"auto"`,
661
+ nothing else changes; `"popup"` was the 1.7.0 default.
662
+
663
+ ### Breaking changes in 2.0
664
+
665
+ Relative to 1.6.0 and 1.7.0:
666
+
667
+ - **Default `mode` is `"auto"`** (1.7.0 defaulted to `"popup"`; 1.6.0 had
668
+ popups only): redirect mode inside wallet in-app browsers and app
669
+ webviews (`isInAppBrowser()`), popups elsewhere.
670
+ - **Connect results are verified.** Every connect sends `v=2`, a
671
+ `request_id` and `session_pubkey`, and is checked locally and by odin-api
672
+ (`POST /connect/verify`). A result that fails is `"unverified"`: popup
673
+ `connect()` rejects with an `OdinConnectVerificationError`, nothing is
674
+ stored. `requires_api` fails when odin-api issues no JWT. The JWT comes
675
+ only from odin-api, never from the Odin page.
676
+ - **`session_key` is no longer sent**; Odin only receives the public key.
677
+ - **A blocked connect popup rejects** ("Failed to open authorize/connect
678
+ window, please always allow popups and try again") and settles
679
+ `state.request` as `"failed"`. In 1.6.0 / 1.7.0 the promise never settled.
680
+ - **A new verified connect replaces the stored session**, even when it asks
681
+ for neither `requires_api` nor `requires_delegation` (the previous user's
682
+ JWT and delegation are cleared).
683
+ - **Only the latest request updates the state.** A connect that succeeds
684
+ after a newer `connect()` / action replaced it, or after `disconnect()`,
685
+ still resolves its promise but no longer sets the user or the stored
686
+ session.
687
+ - **1.7.0 only:** `handleRedirectResult()` / `OdinRedirectResult` were
688
+ removed (use `ready()` / `state.request`), and `restoreSession()` no
689
+ longer consumes redirect connect results.
690
+ - Redirect mode returns to `origin + pathname` (no query, no fragment) and
691
+ restores the query once the result is read.
692
+ - **A popup closed without an answer settles the request** as `"rejected"`
693
+ with `error: "popup_closed"` (after a 1.5 s grace period); the promise
694
+ rejects with the usual rejection text. In 1.6.0 / 1.7.0 it never settled.
695
+
696
+ ### New in 2.0
697
+
698
+ - State API: `ready()`, `state`, `getState()`, `getServerState()`,
699
+ `subscribe()`, `user`, `INITIAL_ODIN_STATE` (see
700
+ [State and sessions](#state-and-sessions)). Popup and redirect results
701
+ both land in `state.request`.
702
+ - `requires_api` works in redirect mode (1.7.0 rejected it).
703
+ - `returnState` on every call; action results can carry `detail`
704
+ (`icrc_approve`: `block_index`). Popup actions still resolve
705
+ `true`.
706
+ - Rejection reasons: a `"rejected"` request carries `state.request.error`
707
+ (`OdinRejectReason`, e.g. `untrusted_origin`, `no_targets`,
708
+ `popup_closed`) when Odin's "Back to app" or a closed popup ended it (see
709
+ [Rejection reasons](#rejection-reasons)).
366
710
 
367
711
  ## Connected User Operations
368
712
 
369
- After calling `connect()`, you receive a `ConnectedUser` with the following capabilities:
713
+ Once connected, `odinConnect.user` (`state.user`) is a `ConnectedUser` with the following capabilities:
370
714
 
371
715
  ### Fetching User Data
372
716
 
@@ -632,6 +976,7 @@ OdinUtils.createTokenValidators.telegram("https://t.me/...");
632
976
  | Environment | Frontend URL | API Base URL |
633
977
  |-------------|-------------|-------------|
634
978
  | `prod` (default) | `https://odin.fun` | `https://api.odin.fun/v2` |
979
+ | `staging` | `https://staging.odin.fun` | `https://api.odin.fun/v2` |
635
980
  | `dev` | `https://dev.odin.fun` | `https://api.odin.fun/dev` |
636
981
  | `local` | `http://localhost:5173` | `https://api.odin.fun/dev` |
637
982
  | `legacy` | `https://legacy.odin.fun` | `https://api.odin.fun/v1` |
@@ -659,6 +1004,13 @@ import type {
659
1004
  OdinAchievement,
660
1005
  OdinAchievementCategory,
661
1006
  OdinConnectedUser,
1007
+ OdinState,
1008
+ OdinRequestState,
1009
+ OdinRequestStatus,
1010
+ OdinRequestInput,
1011
+ OdinAction,
1012
+ OdinActionDetail,
1013
+ OdinRejectReason,
662
1014
  SessionData,
663
1015
  } from "odin-connect";
664
1016
  ```
@@ -682,7 +1034,7 @@ Bootstrap a new app with [odin-app-template](https://github.com/Toniq-Labs/odin-
682
1034
  ## General Notes
683
1035
 
684
1036
  - All BTC amounts are in **millisatoshis** (1 BTC = 100,000,000,000 millisats)
685
- - All trading actions (buy, sell, transfer, swap, liquidity) open a popup for user authorization and return a `boolean`
1037
+ - All trading actions (buy, sell, transfer, swap, liquidity) open a popup (or redirect) for user authorization; the outcome lands in `state.request`, and the popup-mode promise resolves `true` or rejects
686
1038
  - API data methods return paginated results; pass `{ page, limit }` to control pagination
687
1039
  - The SDK uses `postMessage` for secure cross-origin communication between your app and the Odin frontend popup
688
1040
  - BigInt fields (balances, amounts, market caps) are automatically deserialized from JSON