odin-connect 2.0.0 → 2.0.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.
- package/MIGRATION-2.0.md +327 -0
- package/dist/index.d.ts +393 -63
- package/dist/index.js +3 -2
- package/package.json +4 -2
- package/readme.md +454 -103
package/MIGRATION-2.0.md
ADDED
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
# Upgrading an app to odin-connect 2.0 — instructions for coding agents
|
|
2
|
+
|
|
3
|
+
This file is written for an AI coding agent (Claude Code, Cursor, Codex, …)
|
|
4
|
+
asked to upgrade an application that uses `odin-connect` from **1.6.x or
|
|
5
|
+
1.7.x to 2.0**. It is shipped inside the npm package from 2.0.0 on, so once
|
|
6
|
+
the app depends on 2.x it is at `node_modules/odin-connect/MIGRATION-2.0.md`
|
|
7
|
+
(an app still on 1.x does not have that file yet). Humans can read the
|
|
8
|
+
"Migrating to 2.0.0" section of the readme instead; both say the same thing.
|
|
9
|
+
|
|
10
|
+
Follow the steps in order. Do not skip the verification step.
|
|
11
|
+
|
|
12
|
+
## What changed, in one paragraph
|
|
13
|
+
|
|
14
|
+
2.0 delivers every result (a connect, a buy, an approval) through **one
|
|
15
|
+
state store** instead of only through the promise returned by the call.
|
|
16
|
+
That is what makes wallet in-app browsers (OKX, Xverse, …) work: there the
|
|
17
|
+
SDK uses a full-page **redirect** to Odin and back (the new default
|
|
18
|
+
`mode: "auto"`), the page reloads, and an awaited promise from before the
|
|
19
|
+
reload never returns. The app reads results from `odin.state` /
|
|
20
|
+
`odin.subscribe()` instead, which works the same way in popup mode. Connect
|
|
21
|
+
results are now cryptographically verified (locally and by
|
|
22
|
+
`POST https://api.odin.fun/<env>/connect/verify`), and the SDK no longer
|
|
23
|
+
sends secrets in URLs. 1.6.0-style popup code still compiles and works.
|
|
24
|
+
|
|
25
|
+
## Step 1 — Inventory (read-only)
|
|
26
|
+
|
|
27
|
+
Run these from the app's repo root and keep the output for your report:
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
grep -rn -E \
|
|
31
|
+
--include='*.ts' --include='*.tsx' --include='*.js' --include='*.jsx' \
|
|
32
|
+
--include='*.mjs' --include='*.vue' --include='*.svelte' \
|
|
33
|
+
"odin-connect|OdinConnect|restoreSession|handleRedirectResult|lastRedirectResult|OdinRedirectResult|requires_api|requires_delegation|mode:[[:space:]]*\"(popup|redirect|auto)\"|\.(connect|disconnect|buy|sell|transfer|swap|addLiquidity|removeLiquidity|icrcApprove|createToken)\(" \
|
|
34
|
+
--exclude-dir=node_modules --exclude-dir=dist --exclude-dir=build .
|
|
35
|
+
grep -n '"odin-connect"' package.json
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Record:
|
|
39
|
+
- the installed version (1.6.x or 1.7.x);
|
|
40
|
+
- where `new OdinConnect(` is called (it must end up as **one** instance per
|
|
41
|
+
page load, created at module level or once in a provider — not per render
|
|
42
|
+
or per route);
|
|
43
|
+
- every `restoreSession()`, `connect(…)` and `user.<action>(…)` call, and
|
|
44
|
+
what the code does **after** each `await` (that logic is what moves);
|
|
45
|
+
- 1.7.x only: every `handleRedirectResult()` use and any `mode:` option;
|
|
46
|
+
- whether the app sets a Content-Security-Policy (`connect-src`);
|
|
47
|
+
- whether any page reads URL query parameters on load;
|
|
48
|
+
- the framework (React, Vue, Svelte, vanilla) and whether it server-renders.
|
|
49
|
+
|
|
50
|
+
## Step 2 — Upgrade the dependency
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
npm install odin-connect@^2.0.0 # or pnpm add / yarn add
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
2.0 is a major version: `^1.x` ranges will not pick it up on their own.
|
|
57
|
+
|
|
58
|
+
Testing an unreleased 2.0 build (before it is on npm): run `npm pack` in
|
|
59
|
+
the odin-connect repo and install the tarball **temporarily**
|
|
60
|
+
(`npm install /path/to/odin-connect-<version>.tgz`). Never commit a `file:`
|
|
61
|
+
or tarball dependency; once 2.0 is released, put back `^2.0.0` and
|
|
62
|
+
regenerate the lockfile. A pack built before the release version bump
|
|
63
|
+
reports the old version (e.g. `1.7.0`) in `package.json`, so do not trust
|
|
64
|
+
the version number: confirm you have 2.0 by checking that
|
|
65
|
+
`node_modules/odin-connect/dist/index.d.ts` declares `getServerState`.
|
|
66
|
+
|
|
67
|
+
## Step 3 — Decide the scope
|
|
68
|
+
|
|
69
|
+
- **Recommended (full migration):** do Steps 4–7. The app then works in
|
|
70
|
+
normal browsers *and* in wallet in-app browsers.
|
|
71
|
+
- **Popup-only (minimal):** if the owner explicitly does not want wallet
|
|
72
|
+
in-app browser support, pass `mode: "popup"` to the constructor and stop
|
|
73
|
+
after Step 6. Existing 1.6.0 popup code then behaves as before. Say in your
|
|
74
|
+
report that wallet in-app browsers stay broken in this mode (popups cannot
|
|
75
|
+
return results there).
|
|
76
|
+
|
|
77
|
+
Never leave a 1.6.0-style app on the default `mode: "auto"` without doing
|
|
78
|
+
Step 4: inside wallet browsers it would redirect, come back, and show the
|
|
79
|
+
user as not logged in.
|
|
80
|
+
|
|
81
|
+
## Step 4 — Render from state
|
|
82
|
+
|
|
83
|
+
Typical mapping from an app's own auth state machine:
|
|
84
|
+
|
|
85
|
+
| App state | 2.0 state |
|
|
86
|
+
|---|---|
|
|
87
|
+
| idle / logged out | `status: "ready"`, `user: null`, no pending `request` |
|
|
88
|
+
| connecting | `request.action === "connect"` and `request.status === "pending"` |
|
|
89
|
+
| connected | `user !== null` |
|
|
90
|
+
| error | `request.action === "connect"` and `request.status` is `"rejected"`, `"failed"` or `"unverified"` |
|
|
91
|
+
| (loading) | `status: "initializing"` |
|
|
92
|
+
|
|
93
|
+
Check `user` first: a user who is still connected stays connected when a
|
|
94
|
+
re-connect is rejected (`user` is set **and** `request.status` is
|
|
95
|
+
`"rejected"`); show them as connected, not as an error screen.
|
|
96
|
+
|
|
97
|
+
### 4a. One instance, then `subscribe` + `ready`
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import { OdinConnect } from "odin-connect";
|
|
101
|
+
|
|
102
|
+
export const odin = new OdinConnect({ name: "My App", env: "prod" }); // once per page load
|
|
103
|
+
|
|
104
|
+
odin.subscribe((state) => applyOdinState(state)); // every change, both modes
|
|
105
|
+
const initial = await odin.ready(); // stored session + any returning redirect result
|
|
106
|
+
applyOdinState(initial);
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
`state` is `{ status: "initializing" | "ready", user, request }`:
|
|
110
|
+
- `user` — `OdinConnectedUser | null` (replaces `restoreSession()`'s return
|
|
111
|
+
value and the value `await connect()` returned);
|
|
112
|
+
- `request` — the latest `connect()` or action:
|
|
113
|
+
`{ id, action, status, input, detail?, returnState?, error? }`, with
|
|
114
|
+
`status` one of `"pending" | "success" | "rejected" | "failed" | "unverified"`
|
|
115
|
+
and `input` the call's own arguments (e.g. `{ token, spender, amount }`,
|
|
116
|
+
bigints preserved).
|
|
117
|
+
|
|
118
|
+
### 4b. Move "after await" logic into the state handler
|
|
119
|
+
|
|
120
|
+
Before (1.6.0):
|
|
121
|
+
|
|
122
|
+
```ts
|
|
123
|
+
const ok = await user.icrcApprove({ token, spender, amount });
|
|
124
|
+
if (ok) goToStep("commit", { token, amount });
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
After (2.0, works in popup and redirect mode):
|
|
128
|
+
|
|
129
|
+
```ts
|
|
130
|
+
// button handler: just start it
|
|
131
|
+
const user = odin.user;
|
|
132
|
+
if (!user) return showError("Connect first");
|
|
133
|
+
void user.icrcApprove({ token, spender, amount });
|
|
134
|
+
|
|
135
|
+
// in applyOdinState:
|
|
136
|
+
function applyOdinState({ user, request }) {
|
|
137
|
+
setUser(user);
|
|
138
|
+
if (request?.action === "icrc_approve") {
|
|
139
|
+
if (request.status === "success") goToStep("commit", request.input);
|
|
140
|
+
if (request.status === "rejected") showError("Approval was rejected");
|
|
141
|
+
if (request.status === "failed") showError(request.error ?? "Approval failed");
|
|
142
|
+
}
|
|
143
|
+
if (request?.action === "connect" && request.status === "unverified") {
|
|
144
|
+
showError("Could not verify the sign-in. Please try again.");
|
|
145
|
+
}
|
|
146
|
+
if (request?.action === "connect" && request.status === "rejected") {
|
|
147
|
+
if (request.error === "untrusted_origin") {
|
|
148
|
+
// Odin's ICRC-28 check failed: a target canister does not list this
|
|
149
|
+
// app's origin in icrc28_trusted_origins. Not fixable by retrying.
|
|
150
|
+
showError("This app's origin is not trusted by the target canisters.");
|
|
151
|
+
} else {
|
|
152
|
+
showError("Sign-in was cancelled.");
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
A `"rejected"` request carries `request.error` when the user tapped "Back
|
|
159
|
+
to app" on an Odin error screen (`untrusted_origin`, `invalid_targets`,
|
|
160
|
+
`no_targets`, `invalid_session_key`, `missing_request_id`,
|
|
161
|
+
`unsupported_identity`, `no_action`) or closed the popup without answering
|
|
162
|
+
(`popup_closed`, set by the SDK in popup mode; `navigated_back`, set by the SDK in redirect mode when the user presses Back on Odin) — `OdinRejectReason`; see the
|
|
163
|
+
readme's "Rejection reasons". A plain Reject leaves it unset. Treat unknown
|
|
164
|
+
codes as a plain rejection. For a plain rejection (no `error`), supply your
|
|
165
|
+
own copy (e.g. "Approval was rejected"); the SDK has no message for it.
|
|
166
|
+
|
|
167
|
+
Starting an action without awaiting it is safe: the returned promise is
|
|
168
|
+
already marked handled, so ignoring it never causes an unhandled rejection.
|
|
169
|
+
Do not write `odin.user?.icrcApprove(…)` as a statement: it silently does
|
|
170
|
+
nothing when `user` is null, and lint (`no-floating-promises`) flags it.
|
|
171
|
+
Check for the user, show an error if it is missing, and use `void` as above.
|
|
172
|
+
|
|
173
|
+
Rules:
|
|
174
|
+
- Use `request.input` instead of variables captured before the call; they
|
|
175
|
+
are gone after a redirect. Use `returnState` (any JSON, bigints allowed)
|
|
176
|
+
only for extra app context that is not part of the call's inputs, e.g.
|
|
177
|
+
`user.icrcApprove({ …, returnState: { step: "approve" } })` →
|
|
178
|
+
`request.returnState`. If the follow-up needs values that are not the
|
|
179
|
+
call's own arguments, they must go in `returnState`; nothing else survives
|
|
180
|
+
a redirect.
|
|
181
|
+
- Two flows that start the same action (e.g. a deposit and a withdrawal that
|
|
182
|
+
both `icrcApprove` the same spender) can have identical `input`: tag each
|
|
183
|
+
call's `returnState` (`{ flow: "deposit" }`) and match on
|
|
184
|
+
`request.returnState` as well as `request.action`.
|
|
185
|
+
- Key handlers on `request.action` + `request.status`, and make them
|
|
186
|
+
idempotent. A settled request stays in `state` until the next request, and
|
|
187
|
+
effects re-run (re-render, React StrictMode, remount), so the handler sees
|
|
188
|
+
it again. When the follow-up moves value this is mandatory: claim
|
|
189
|
+
`request.id` **synchronously, before any `await`**, in storage that
|
|
190
|
+
outlives the component (module scope), e.g.
|
|
191
|
+
|
|
192
|
+
```ts
|
|
193
|
+
const handled = new Set<string>(); // module scope, not component state
|
|
194
|
+
function onApproved(request) {
|
|
195
|
+
if (handled.has(request.id)) return;
|
|
196
|
+
handled.add(request.id); // claim before awaiting anything
|
|
197
|
+
void commitDeposit(request.input);
|
|
198
|
+
}
|
|
199
|
+
```
|
|
200
|
+
- After a redirect reload, async resources the app rebuilds from the session
|
|
201
|
+
(e.g. a canister actor created from `user`'s delegation identity) can arrive
|
|
202
|
+
after the `success` state. Wait for them before acting, and do not mark
|
|
203
|
+
the request handled until you actually act (in the example above, return
|
|
204
|
+
before `handled.add` while the actor is not ready, and run the handler
|
|
205
|
+
again when it is).
|
|
206
|
+
- **Never** call `connect()` automatically when `request.status` is
|
|
207
|
+
`"rejected"` or `"unverified"` — in redirect mode that sends the user
|
|
208
|
+
straight back to Odin in a loop. Show a retry button instead.
|
|
209
|
+
- Pages that derive their screen from on-chain/API data (balances,
|
|
210
|
+
allowances, positions) may need no handler at all beyond re-fetching when
|
|
211
|
+
`request.status === "success"`.
|
|
212
|
+
|
|
213
|
+
### 4c. Replace `restoreSession()`
|
|
214
|
+
|
|
215
|
+
`restoreSession()` still works (synchronous, deprecated) but does **not**
|
|
216
|
+
see a result that just came back from a redirect. Replace
|
|
217
|
+
|
|
218
|
+
```ts
|
|
219
|
+
const user = odin.restoreSession();
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
with `odin.state.user` after `await odin.ready()`, or with the `user` from
|
|
223
|
+
the state handler.
|
|
224
|
+
|
|
225
|
+
### 4d. React
|
|
226
|
+
|
|
227
|
+
```tsx
|
|
228
|
+
import { useSyncExternalStore } from "react";
|
|
229
|
+
import { odin } from "./odin"; // the single instance from 4a
|
|
230
|
+
|
|
231
|
+
export function useOdin() {
|
|
232
|
+
return useSyncExternalStore(odin.subscribe, odin.getState, odin.getServerState);
|
|
233
|
+
}
|
|
234
|
+
```
|
|
235
|
+
|
|
236
|
+
Pass `odin.getServerState` (not `getState`) as the third argument so
|
|
237
|
+
server-rendered HTML hydrates without a mismatch. With
|
|
238
|
+
`useSyncExternalStore` you do not call `ready()` or `subscribe()` yourself:
|
|
239
|
+
React subscribes, and the constructor already started `ready()`; while
|
|
240
|
+
`status === "initializing"`, render a loading state. React StrictMode's
|
|
241
|
+
double effects are safe (odin-api is asked once).
|
|
242
|
+
|
|
243
|
+
### 4e. 1.7.x only
|
|
244
|
+
|
|
245
|
+
- Delete `handleRedirectResult()` calls and the `OdinRedirectResult` type;
|
|
246
|
+
read `(await odin.ready()).request` / `subscribe()` instead.
|
|
247
|
+
`status: "connected"` is now `"success"`; the user is `state.user`.
|
|
248
|
+
- `restoreSession()` no longer finishes a redirect connect (1.7.0 did).
|
|
249
|
+
- Remove `mode: "auto"` / `"redirect"` if it only restated the new default.
|
|
250
|
+
|
|
251
|
+
## Step 5 — URL query, CSP, redirects
|
|
252
|
+
|
|
253
|
+
- **Query string:** in redirect mode Odin returns to `origin + pathname`
|
|
254
|
+
(no query) and the SDK restores the original query once the result is
|
|
255
|
+
read. Code that reads `location.search` on load must read it **after**
|
|
256
|
+
`await odin.ready()`. Readers that consume and remove a parameter on the
|
|
257
|
+
first load, before any connect or action can start (e.g. a referral code
|
|
258
|
+
stored and stripped at startup), are unaffected: the query they saw is the
|
|
259
|
+
one before any redirect.
|
|
260
|
+
- **CSP:** if the app sets `connect-src`, add `https://api.odin.fun` (every
|
|
261
|
+
connect is verified there).
|
|
262
|
+
- **Open redirects:** if the app has any page that forwards to a URL taken
|
|
263
|
+
from the query or path (`/go?to=…`, `/redirect/<url>`), flag it in your
|
|
264
|
+
report — apps using redirect mode with `requires_delegation` or
|
|
265
|
+
`requires_api` must not have one. Do not try to "fix" it silently.
|
|
266
|
+
- `requires_api` now works in redirect mode (1.7.0 rejected it); nothing to
|
|
267
|
+
change.
|
|
268
|
+
|
|
269
|
+
## Step 6 — Errors and behavior changes to account for
|
|
270
|
+
|
|
271
|
+
- Popup `connect()` can reject with `OdinConnectVerificationError` (the
|
|
272
|
+
result could not be verified). Existing `catch` blocks should show a retry.
|
|
273
|
+
- A blocked connect popup now **rejects** ("Failed to open authorize/connect
|
|
274
|
+
window, please always allow popups and try again") instead of hanging.
|
|
275
|
+
- A popup the user closes without answering settles the request as
|
|
276
|
+
`"rejected"` with `error: "popup_closed"` (the promise rejects with the
|
|
277
|
+
usual rejection text) once a 1.5 s grace period has passed; an answer
|
|
278
|
+
Odin posted just before closing the popup still wins. Do not keep buttons
|
|
279
|
+
disabled until a reload: re-enable them on any settled status.
|
|
280
|
+
- A new verified connect replaces the stored session (the previous user's
|
|
281
|
+
JWT and delegation are cleared).
|
|
282
|
+
- Only the latest request updates `state`; a connect that finishes after a
|
|
283
|
+
newer request or `disconnect()` resolves its promise but does not set the
|
|
284
|
+
user.
|
|
285
|
+
- Action statuses are only a UI signal: before moving value (e.g. a step
|
|
286
|
+
that spends an ICRC-2 allowance), confirm on-chain (`icrc2_allowance`,
|
|
287
|
+
balances). Never treat `"success"` as proof.
|
|
288
|
+
|
|
289
|
+
## Step 7 — Verify
|
|
290
|
+
|
|
291
|
+
1. The checks the app has (typecheck, lint, format, unit tests, production
|
|
292
|
+
build — whichever exist) pass.
|
|
293
|
+
2. Desktop browser, default mode: connect → user shown; one action → the
|
|
294
|
+
handler runs on `success`; reject in Odin → `rejected` shown, no loop.
|
|
295
|
+
3. Redirect path without a wallet browser: temporarily construct with
|
|
296
|
+
`mode: "redirect"` (or run `odin.mode = "redirect"` in the console),
|
|
297
|
+
repeat step 2 from a page whose URL has a query string; after the reload
|
|
298
|
+
the user/result appear and the query string is back. Use `https://` or
|
|
299
|
+
`http://localhost` (plain-http LAN addresses are rejected by Odin).
|
|
300
|
+
4. If possible, open the app inside the OKX or Xverse in-app browser and
|
|
301
|
+
repeat step 2 with the default mode.
|
|
302
|
+
5. Revert any temporary `mode: "redirect"`.
|
|
303
|
+
|
|
304
|
+
## Report back
|
|
305
|
+
|
|
306
|
+
List: files changed; every former "after await" block and where its logic
|
|
307
|
+
moved; which `request.action` values the app now handles; whether CSP,
|
|
308
|
+
query-on-load or open-redirect findings needed attention; the verification
|
|
309
|
+
results from Step 7 (and what could not be tested, e.g. no wallet device).
|
|
310
|
+
|
|
311
|
+
## Quick reference (2.0 public API)
|
|
312
|
+
|
|
313
|
+
| API | Purpose |
|
|
314
|
+
|---|---|
|
|
315
|
+
| `new OdinConnect({ name, env, mode?, lang?, slug? })` | One instance per page load. `mode` defaults to `"auto"`. |
|
|
316
|
+
| `await odin.ready()` | Initial state: stored session + any returning redirect result. Idempotent. |
|
|
317
|
+
| `odin.state` / `odin.getState()` | Current immutable snapshot `{ status, user, request }`. |
|
|
318
|
+
| `odin.subscribe(listener)` → `unsubscribe` | Called on every state change (popup and redirect). |
|
|
319
|
+
| `odin.getServerState()` / `INITIAL_ODIN_STATE` | Server snapshot for `useSyncExternalStore`. |
|
|
320
|
+
| `odin.user` | Shortcut for `odin.state.user`. |
|
|
321
|
+
| `odin.connect(options)` | Start a connect (`requires_api`, `requires_delegation`, `targets`, `returnState`). |
|
|
322
|
+
| `odin.user.buy/sell/transfer/swap/addLiquidity/removeLiquidity/icrcApprove/createToken(…)` | Start an action; optional `returnState`. |
|
|
323
|
+
| `odin.disconnect()` | Clear the session; `user` and `request` become `null`. |
|
|
324
|
+
| `odin.mode` | Read/override `"popup" \| "redirect" \| "auto"`. |
|
|
325
|
+
| `restoreSession()` | Deprecated, synchronous, stored session only. |
|
|
326
|
+
| `OdinConnectVerificationError` | Popup connect rejection when verification fails. |
|
|
327
|
+
| `isInAppBrowser()` | The detection `"auto"` uses. |
|