odin-connect 2.0.1 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MIGRATION-2.0.md +51 -6
- package/dist/index.d.ts +318 -21
- package/dist/index.js +3 -3
- package/package.json +3 -3
- package/readme.md +171 -2
package/MIGRATION-2.0.md
CHANGED
|
@@ -9,6 +9,9 @@ the app depends on 2.x it is at `node_modules/odin-connect/MIGRATION-2.0.md`
|
|
|
9
9
|
|
|
10
10
|
Follow the steps in order. Do not skip the verification step.
|
|
11
11
|
|
|
12
|
+
**App already on 2.0.x?** Skip to
|
|
13
|
+
[Upgrading from 2.0 to 2.1](#upgrading-from-20-to-21) at the end.
|
|
14
|
+
|
|
12
15
|
## What changed, in one paragraph
|
|
13
16
|
|
|
14
17
|
2.0 delivers every result (a connect, a buy, an approval) through **one
|
|
@@ -50,10 +53,12 @@ Record:
|
|
|
50
53
|
## Step 2 — Upgrade the dependency
|
|
51
54
|
|
|
52
55
|
```bash
|
|
53
|
-
npm install odin-connect@^2.
|
|
56
|
+
npm install odin-connect@^2.1.0 # or pnpm add / yarn add
|
|
54
57
|
```
|
|
55
58
|
|
|
56
59
|
2.0 is a major version: `^1.x` ranges will not pick it up on their own.
|
|
60
|
+
Install 2.1 or later: 2.0.x stops being able to connect after the v1 proof
|
|
61
|
+
deadline (`"legacy"` env: a later date; see [Upgrading from 2.0 to 2.1](#upgrading-from-20-to-21)).
|
|
57
62
|
|
|
58
63
|
Testing an unreleased 2.0 build (before it is on npm): run `npm pack` in
|
|
59
64
|
the odin-connect repo and install the tarball **temporarily**
|
|
@@ -85,6 +90,7 @@ Typical mapping from an app's own auth state machine:
|
|
|
85
90
|
| App state | 2.0 state |
|
|
86
91
|
|---|---|
|
|
87
92
|
| idle / logged out | `status: "ready"`, `user: null`, no pending `request` |
|
|
93
|
+
| signed out by odin.fun | `user: null` and `logoutReason` set (`"revoked"` / `"expired"`) |
|
|
88
94
|
| connecting | `request.action === "connect"` and `request.status === "pending"` |
|
|
89
95
|
| connected | `user !== null` |
|
|
90
96
|
| error | `request.action === "connect"` and `request.status` is `"rejected"`, `"failed"` or `"unverified"` |
|
|
@@ -106,14 +112,17 @@ const initial = await odin.ready(); // stored session + any retur
|
|
|
106
112
|
applyOdinState(initial);
|
|
107
113
|
```
|
|
108
114
|
|
|
109
|
-
`state` is `{ status: "initializing" | "ready", user, request }`:
|
|
115
|
+
`state` is `{ status: "initializing" | "ready", user, request, logoutReason? }`:
|
|
110
116
|
- `user` — `OdinConnectedUser | null` (replaces `restoreSession()`'s return
|
|
111
117
|
value and the value `await connect()` returned);
|
|
112
118
|
- `request` — the latest `connect()` or action:
|
|
113
119
|
`{ id, action, status, input, detail?, returnState?, error? }`, with
|
|
114
120
|
`status` one of `"pending" | "success" | "rejected" | "failed" | "unverified"`
|
|
115
121
|
and `input` the call's own arguments (e.g. `{ token, spender, amount }`,
|
|
116
|
-
bigints preserved)
|
|
122
|
+
bigints preserved);
|
|
123
|
+
- `logoutReason` — set only when the SDK logged the user out on its own
|
|
124
|
+
(`"revoked"`: logged out on odin.fun; `"expired"`: the API key expired).
|
|
125
|
+
See Step 6.
|
|
117
126
|
|
|
118
127
|
### 4b. Move "after await" logic into the state handler
|
|
119
128
|
|
|
@@ -158,7 +167,7 @@ function applyOdinState({ user, request }) {
|
|
|
158
167
|
A `"rejected"` request carries `request.error` when the user tapped "Back
|
|
159
168
|
to app" on an Odin error screen (`untrusted_origin`, `invalid_targets`,
|
|
160
169
|
`no_targets`, `invalid_session_key`, `missing_request_id`,
|
|
161
|
-
`unsupported_identity`, `no_action`) or closed the popup without answering
|
|
170
|
+
`unsupported_identity`, `no_action`, `session_revoked`) or closed the popup without answering
|
|
162
171
|
(`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
172
|
readme's "Rejection reasons". A plain Reject leaves it unset. Treat unknown
|
|
164
173
|
codes as a plain rejection. For a plain rejection (no `error`), supply your
|
|
@@ -282,6 +291,14 @@ double effects are safe (odin-api is asked once).
|
|
|
282
291
|
- Only the latest request updates `state`; a connect that finishes after a
|
|
283
292
|
newer request or `disconnect()` resolves its promise but does not set the
|
|
284
293
|
user.
|
|
294
|
+
- **The SDK can log the user out on its own** (2.1): when odin-api refuses
|
|
295
|
+
the API key (the user logged out on odin.fun, or the key expired) or Odin
|
|
296
|
+
rejects an action with `session_revoked`. `state.user` becomes `null` and
|
|
297
|
+
`state.logoutReason` is set; `state.request` is kept. Render the logged-out
|
|
298
|
+
screen from `state` (any app-side copy of the user or API key must follow
|
|
299
|
+
`state.user`), optionally with a message such as "You were signed out on
|
|
300
|
+
odin.fun" when `logoutReason === "revoked"`. **Never** call `connect()`
|
|
301
|
+
automatically on a logout; show a sign-in button.
|
|
285
302
|
- Action statuses are only a UI signal: before moving value (e.g. a step
|
|
286
303
|
that spends an ICRC-2 allowance), confirm on-chain (`icrc2_allowance`,
|
|
287
304
|
balances). Never treat `"success"` as proof.
|
|
@@ -312,9 +329,9 @@ results from Step 7 (and what could not be tested, e.g. no wallet device).
|
|
|
312
329
|
|
|
313
330
|
| API | Purpose |
|
|
314
331
|
|---|---|
|
|
315
|
-
| `new OdinConnect({ name, env, mode?, lang?, slug? })` | One instance per page load. `mode` defaults to `"auto"
|
|
332
|
+
| `new OdinConnect({ name, env, mode?, lang?, slug?, sessionCheckIntervalMs? })` | One instance per page load. `mode` defaults to `"auto"`; the session check runs at most every 5 minutes by default. |
|
|
316
333
|
| `await odin.ready()` | Initial state: stored session + any returning redirect result. Idempotent. |
|
|
317
|
-
| `odin.state` / `odin.getState()` | Current immutable snapshot `{ status, user, request }`. |
|
|
334
|
+
| `odin.state` / `odin.getState()` | Current immutable snapshot `{ status, user, request, logoutReason? }`. |
|
|
318
335
|
| `odin.subscribe(listener)` → `unsubscribe` | Called on every state change (popup and redirect). |
|
|
319
336
|
| `odin.getServerState()` / `INITIAL_ODIN_STATE` | Server snapshot for `useSyncExternalStore`. |
|
|
320
337
|
| `odin.user` | Shortcut for `odin.state.user`. |
|
|
@@ -323,5 +340,33 @@ results from Step 7 (and what could not be tested, e.g. no wallet device).
|
|
|
323
340
|
| `odin.disconnect()` | Clear the session; `user` and `request` become `null`. |
|
|
324
341
|
| `odin.mode` | Read/override `"popup" \| "redirect" \| "auto"`. |
|
|
325
342
|
| `restoreSession()` | Deprecated, synchronous, stored session only. |
|
|
343
|
+
| `OdinLogoutReason` | `"revoked"` \| `"expired"`: why the SDK logged the user out (`state.logoutReason`). |
|
|
326
344
|
| `OdinConnectVerificationError` | Popup connect rejection when verification fails. |
|
|
327
345
|
| `isInAppBrowser()` | The detection `"auto"` uses. |
|
|
346
|
+
|
|
347
|
+
## Upgrading from 2.0 to 2.1
|
|
348
|
+
|
|
349
|
+
2.1 ends the app's session when the user logs out on odin.fun. No code
|
|
350
|
+
change is required; do these checks:
|
|
351
|
+
|
|
352
|
+
1. `npm install odin-connect@^2.1.0` and regenerate the lockfile. Upgrade
|
|
353
|
+
before the v1 proof deadline: 2.1 asks Odin for a v2 identity proof (with
|
|
354
|
+
the user's odin.fun session id), and odin-api stops accepting v1 proofs
|
|
355
|
+
30 days after the 2.1.0 release (the date is announced with it). After
|
|
356
|
+
that, connect fails with 2.0.x on `env` `"prod"`, `"staging"`, `"dev"`
|
|
357
|
+
and `"local"`. `"legacy"` (odin-api `/v1`) keeps accepting v1 proofs until a
|
|
358
|
+
separate date, announced later; upgrade legacy apps anyway.
|
|
359
|
+
2. Search for places that keep their own copy of the user or the API key
|
|
360
|
+
(`grep -rn -E "\.user\b|apiKey|getState\(\)" --exclude-dir=node_modules .`).
|
|
361
|
+
They must follow `state.user`: it can now become `null` without a
|
|
362
|
+
`disconnect()` call (see Step 6).
|
|
363
|
+
3. Optional: show a message when `state.logoutReason === "revoked"` (the user
|
|
364
|
+
logged out on odin.fun). Do not call `connect()` automatically.
|
|
365
|
+
4. Optional: `sessionCheckIntervalMs` in the constructor changes how often
|
|
366
|
+
the SDK checks the session (default 5 minutes, `0` = on every load and
|
|
367
|
+
focus). Leave the default unless the owner asks.
|
|
368
|
+
5. Verify: connect with `requires_api`, log out on odin.fun in another tab,
|
|
369
|
+
then come back to the app tab after 5 minutes (or reload it); the app
|
|
370
|
+
shows the user as logged out (on `env: "legacy"` only once legacy.odin.fun
|
|
371
|
+
and odin-api `/v1` support it; until then skip this check). Starting an action after the odin.fun
|
|
372
|
+
logout also logs the user out, with `request.error === "session_revoked"`.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { AxiosRequestConfig } from 'axios';
|
|
1
2
|
import { DelegationIdentity } from '@dfinity/identity';
|
|
2
3
|
|
|
3
4
|
interface BaseToken {
|
|
@@ -138,6 +139,219 @@ interface Transaction {
|
|
|
138
139
|
amount: bigint;
|
|
139
140
|
}
|
|
140
141
|
|
|
142
|
+
declare const ORIGINS: {
|
|
143
|
+
local: string;
|
|
144
|
+
prod: string;
|
|
145
|
+
dev: string;
|
|
146
|
+
legacy: string;
|
|
147
|
+
staging: string;
|
|
148
|
+
};
|
|
149
|
+
type Environment = keyof typeof ORIGINS;
|
|
150
|
+
|
|
151
|
+
/** A member's standing in a community. `owner` is the community's creator. */
|
|
152
|
+
type CommunityRole = "owner" | "admin" | "moderator" | "member";
|
|
153
|
+
/** Roles an owner/admin may assign. `owner` is never assignable. */
|
|
154
|
+
type AssignableCommunityRole = Exclude<CommunityRole, "owner">;
|
|
155
|
+
interface CommunityProfile {
|
|
156
|
+
user: string;
|
|
157
|
+
/** Storage filename, not a URL. Use `getBannerImageUrl()` to display it. */
|
|
158
|
+
banner_image: string | null;
|
|
159
|
+
is_public: boolean;
|
|
160
|
+
created_at: Date;
|
|
161
|
+
}
|
|
162
|
+
interface CommunityStats {
|
|
163
|
+
volume_7d: bigint;
|
|
164
|
+
volume_30d: bigint;
|
|
165
|
+
volume_6m: bigint;
|
|
166
|
+
volume_total: bigint;
|
|
167
|
+
power_users_7d: number;
|
|
168
|
+
power_users_30d: number;
|
|
169
|
+
power_users_6m: number;
|
|
170
|
+
power_users_total: number;
|
|
171
|
+
users_7d: number;
|
|
172
|
+
users_30d: number;
|
|
173
|
+
users_6m: number;
|
|
174
|
+
users_total: number;
|
|
175
|
+
/** Only present for the community's owner/admins and platform admins. */
|
|
176
|
+
fees_total?: bigint;
|
|
177
|
+
fees_7d?: bigint;
|
|
178
|
+
fees_30d?: bigint;
|
|
179
|
+
fee_payouts?: number;
|
|
180
|
+
}
|
|
181
|
+
interface Community {
|
|
182
|
+
principal: string;
|
|
183
|
+
username: string;
|
|
184
|
+
image?: string;
|
|
185
|
+
bio?: string;
|
|
186
|
+
twitter?: string;
|
|
187
|
+
telegram?: string;
|
|
188
|
+
discord?: string;
|
|
189
|
+
website?: string;
|
|
190
|
+
ref_code?: string | null;
|
|
191
|
+
member_count: number;
|
|
192
|
+
created_at: Date;
|
|
193
|
+
profile: CommunityProfile;
|
|
194
|
+
stats?: CommunityStats | null;
|
|
195
|
+
}
|
|
196
|
+
/** A list row: the community plus the caller's role (null when anonymous or not a member). */
|
|
197
|
+
interface CommunityListItem extends Community {
|
|
198
|
+
membership: CommunityRole | null;
|
|
199
|
+
}
|
|
200
|
+
type ChatAccessDenialReason = "membership" | "threshold" | "banned";
|
|
201
|
+
interface ChatChannelAccess {
|
|
202
|
+
can_view: boolean;
|
|
203
|
+
can_post: boolean;
|
|
204
|
+
/** Null when `can_view` is true. Never `banned` (a ban is a mute). */
|
|
205
|
+
can_view_reason: ChatAccessDenialReason | null;
|
|
206
|
+
/** Null when `can_post` is true. */
|
|
207
|
+
can_post_reason: ChatAccessDenialReason | null;
|
|
208
|
+
}
|
|
209
|
+
interface ChatAccess {
|
|
210
|
+
public: ChatChannelAccess;
|
|
211
|
+
private: ChatChannelAccess;
|
|
212
|
+
}
|
|
213
|
+
/** The detail response: list row plus the caller's chat verdicts. */
|
|
214
|
+
interface CommunityDetail extends CommunityListItem {
|
|
215
|
+
chat_access: ChatAccess;
|
|
216
|
+
/** Minimum recommended-token value (msats) to post in the public chat. Null when the API sends none. */
|
|
217
|
+
public_chat_threshold: bigint | null;
|
|
218
|
+
/** Minimum recommended-token value (msats) to view/post in the private chat. Null when the API sends none. */
|
|
219
|
+
private_chat_threshold: bigint | null;
|
|
220
|
+
}
|
|
221
|
+
type CommunityMemberUser = Pick<User, "principal" | "username" | "image"> & {
|
|
222
|
+
bio: string | null;
|
|
223
|
+
};
|
|
224
|
+
interface CommunityMemberBan {
|
|
225
|
+
id: bigint;
|
|
226
|
+
context_type: "community";
|
|
227
|
+
context_id: string;
|
|
228
|
+
user: string;
|
|
229
|
+
/** Null when no reason was given, or when the viewer may not see it. */
|
|
230
|
+
reason: string | null;
|
|
231
|
+
/** Null when the viewer may not see it. */
|
|
232
|
+
banned_by: string | null;
|
|
233
|
+
banned_at: Date;
|
|
234
|
+
expires_at: Date | null;
|
|
235
|
+
is_active: boolean;
|
|
236
|
+
}
|
|
237
|
+
interface CommunityMember {
|
|
238
|
+
community: string;
|
|
239
|
+
user: string;
|
|
240
|
+
role: CommunityRole;
|
|
241
|
+
joined_at: Date;
|
|
242
|
+
rel_user: CommunityMemberUser | null;
|
|
243
|
+
/** Only set by `getMembers()`; omitted by join/add/update responses. */
|
|
244
|
+
comment_ban?: CommunityMemberBan | null;
|
|
245
|
+
}
|
|
246
|
+
interface CommunityRecommendedTokenSummary {
|
|
247
|
+
id: string;
|
|
248
|
+
name: string;
|
|
249
|
+
ticker: string;
|
|
250
|
+
vanity_ticker: string;
|
|
251
|
+
image?: string | null;
|
|
252
|
+
price: number;
|
|
253
|
+
/** 24h price change as a percentage (5.5 = +5.5%). */
|
|
254
|
+
priceChange24h: number;
|
|
255
|
+
marketCap: number;
|
|
256
|
+
}
|
|
257
|
+
/** Note: this payload is camelCase on the API, unlike the rest of the module. */
|
|
258
|
+
interface CommunityRecommendedToken {
|
|
259
|
+
communityId: string;
|
|
260
|
+
tokenId: string;
|
|
261
|
+
token: CommunityRecommendedTokenSummary;
|
|
262
|
+
description?: string | null;
|
|
263
|
+
addedBy: {
|
|
264
|
+
id: string;
|
|
265
|
+
name: string;
|
|
266
|
+
};
|
|
267
|
+
addedAt: Date;
|
|
268
|
+
}
|
|
269
|
+
type CommunitySortableFields = "member_count" | "volume_7d" | "volume_30d" | "volume_6m" | "volume_total" | "power_users_7d" | "power_users_30d" | "power_users_6m" | "power_users_total" | "users_7d" | "users_30d" | "users_6m" | "users_total"
|
|
270
|
+
/** `fees_*` sorts are honoured only for platform admins; otherwise dropped. */
|
|
271
|
+
| "fees_total" | "fees_7d" | "fees_30d";
|
|
272
|
+
type CommunityFilterFields = {
|
|
273
|
+
/** Matches username, bio or principal. Max 128 chars. */
|
|
274
|
+
search: string;
|
|
275
|
+
/** Only communities where the connected user holds one of these roles. Requires an API key. */
|
|
276
|
+
role_in: ReadonlyArray<CommunityRole>;
|
|
277
|
+
};
|
|
278
|
+
|
|
279
|
+
declare class HttpClient {
|
|
280
|
+
/**
|
|
281
|
+
* Called with the token when a request sent with a Bearer token gets a
|
|
282
|
+
* `401`: the token is no longer accepted (expired, or its odin.fun session
|
|
283
|
+
* logged out). One place for every API-key request, so no method has to
|
|
284
|
+
* handle it. The request still rejects as before.
|
|
285
|
+
*/
|
|
286
|
+
onUnauthorized: ((token: string) => void) | null;
|
|
287
|
+
get<ResponseType>(url: string, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
288
|
+
fetch<ResponseType>(url: string, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
289
|
+
post<ResponseType, DataType = string>(url: string, data?: DataType, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
290
|
+
put<DataType, ResponseType>(url: string, data?: DataType, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
291
|
+
patch<ResponseType, DataType = string>(url: string, data?: DataType, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
292
|
+
delete<ResponseType>(url: string, options?: AxiosRequestConfig): Promise<ResponseType>;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Adapter for odin-api's Communities module (`GET /communities`,
|
|
297
|
+
* `/community/:principal/...`). Mounted at `OdinApiClient.communities`.
|
|
298
|
+
*
|
|
299
|
+
* Reads are public but send the API key as a Bearer token when one is set, so
|
|
300
|
+
* caller-relative fields (`membership`, `chat_access`, `stats.fees_*`) and the
|
|
301
|
+
* `role_in` filter work for a connected user. Mutations require the key, which
|
|
302
|
+
* `connect({ requires_api: true })` provides.
|
|
303
|
+
*
|
|
304
|
+
* Token amounts (`stats.volume_*`, `stats.fees_*`, chat thresholds) are
|
|
305
|
+
* re-cast to `bigint`; the API serialises them as JSON numbers / strings.
|
|
306
|
+
*
|
|
307
|
+
* Every method rejects with an `Error` carrying the API's message (e.g. a
|
|
308
|
+
* 403 on a private community), never a raw `AxiosError`.
|
|
309
|
+
*/
|
|
310
|
+
declare class OdinCommunitiesClient {
|
|
311
|
+
private _http;
|
|
312
|
+
private _baseUrl;
|
|
313
|
+
private _apiKey;
|
|
314
|
+
constructor(http: HttpClient, baseUrl: string, apiKey: () => string | null);
|
|
315
|
+
/**
|
|
316
|
+
* Public communities. `filters.role_in` requires an API key (rejects with
|
|
317
|
+
* "API key is not set" before any request); an empty `role_in` means no
|
|
318
|
+
* role filter.
|
|
319
|
+
*/
|
|
320
|
+
getCommunities(pagination: Pagination, sort?: Sort<CommunitySortableFields>, filters?: Partial<CommunityFilterFields>): Promise<PaginatedResponse<CommunityListItem>>;
|
|
321
|
+
/** One community with the caller's membership and chat access. 403 when private and not a member. */
|
|
322
|
+
getCommunity(principal: string): Promise<CommunityDetail>;
|
|
323
|
+
/** Members, newest first. Private communities: members only. */
|
|
324
|
+
getMembers(principal: string, pagination: Pagination, role?: CommunityRole): Promise<PaginatedResponse<CommunityMember>>;
|
|
325
|
+
/** Tokens recommended by the community, newest first. */
|
|
326
|
+
getRecommendedTokens(principal: string, pagination: Pagination): Promise<PaginatedResponse<CommunityRecommendedToken>>;
|
|
327
|
+
/** URL of the community's banner image (served by odin-api). */
|
|
328
|
+
getBannerImageUrl(principal: string): string;
|
|
329
|
+
/** Join a public community as the connected user. */
|
|
330
|
+
join(principal: string): Promise<CommunityMember>;
|
|
331
|
+
/** Leave a community. The owner cannot leave. */
|
|
332
|
+
leave(principal: string): Promise<void>;
|
|
333
|
+
/** Add a user with a role below the caller's own (owner/admin only). */
|
|
334
|
+
addMember(principal: string, userId: string, role: AssignableCommunityRole): Promise<CommunityMember>;
|
|
335
|
+
/** Change a member's role (owner/admin only; cannot target yourself). */
|
|
336
|
+
updateMemberRole(principal: string, userId: string, role: AssignableCommunityRole): Promise<CommunityMember>;
|
|
337
|
+
/** Remove a member (admin or higher). `reason` max 500 chars. */
|
|
338
|
+
kickMember(principal: string, userId: string, reason?: string): Promise<void>;
|
|
339
|
+
/** Recommend a token (owner/moderator). `description` max 512 chars. */
|
|
340
|
+
addRecommendedToken(principal: string, token: string, description?: string): Promise<CommunityRecommendedToken>;
|
|
341
|
+
/** Remove a recommended token (owner/moderator). */
|
|
342
|
+
removeRecommendedToken(principal: string, tokenId: string): Promise<void>;
|
|
343
|
+
/**
|
|
344
|
+
* Axios options carrying the Bearer header when an API key is set. With
|
|
345
|
+
* `required`, a missing key throws before any request is made.
|
|
346
|
+
*/
|
|
347
|
+
private authOptions;
|
|
348
|
+
/**
|
|
349
|
+
* Every call, read or mutation, goes through here so failures surface the
|
|
350
|
+
* API's message (`toApiError`) rather than a raw `AxiosError`.
|
|
351
|
+
*/
|
|
352
|
+
private request;
|
|
353
|
+
}
|
|
354
|
+
|
|
141
355
|
type Pagination = {
|
|
142
356
|
page: number;
|
|
143
357
|
limit: number;
|
|
@@ -179,8 +393,10 @@ declare class OdinApiClient {
|
|
|
179
393
|
private _apiKey;
|
|
180
394
|
private _httpClient;
|
|
181
395
|
readonly BASE_URL: string;
|
|
182
|
-
readonly ENV:
|
|
183
|
-
|
|
396
|
+
readonly ENV: Environment;
|
|
397
|
+
/** Communities API adapter. Shares this client's HTTP client and API key. */
|
|
398
|
+
readonly communities: OdinCommunitiesClient;
|
|
399
|
+
constructor(env?: Environment);
|
|
184
400
|
getUser(id: string): Promise<User>;
|
|
185
401
|
getUserAvatarUrl(principal: string): string;
|
|
186
402
|
getBalances(principal: string, pagination: Pagination): Promise<readonly Balance[]>;
|
|
@@ -225,6 +441,17 @@ declare class OdinApiClient {
|
|
|
225
441
|
* any non-2xx response.
|
|
226
442
|
*/
|
|
227
443
|
verifyConnect(body: VerifyConnectRequest): Promise<VerifyConnectResponse>;
|
|
444
|
+
/**
|
|
445
|
+
* Ask odin-api whether the API key is still a live session for `audience`
|
|
446
|
+
* (`GET /connect/session`). Resolves `true` when it is and `false` on a
|
|
447
|
+
* `401` (expired, wrong audience, or its odin.fun session logged out).
|
|
448
|
+
* Resolves `null` on a `404` from the `legacy` env: odin-api `/v1` has no
|
|
449
|
+
* session check yet. Rejects on anything else (offline, `5xx`, a `404`
|
|
450
|
+
* from any other env): that is not a logout.
|
|
451
|
+
*/
|
|
452
|
+
checkConnectSession(audience: string): Promise<boolean | null>;
|
|
453
|
+
/** Called when a request sent with the API key gets a `401` (see HttpClient). */
|
|
454
|
+
set onUnauthorized(handler: ((token: string) => void) | null);
|
|
228
455
|
set apiKey(key: string | null);
|
|
229
456
|
get apiKey(): string | null;
|
|
230
457
|
}
|
|
@@ -471,19 +698,41 @@ type OdinRequestState = {
|
|
|
471
698
|
* - `missing_request_id`: no request id, or no identity, to bind the proof.
|
|
472
699
|
* - `unsupported_identity`: the user's wallet cannot sign the identity proof.
|
|
473
700
|
* - `no_action`: Odin has no authorize page for this action.
|
|
701
|
+
* - `session_revoked`: the user is logged out on odin.fun, so the action
|
|
702
|
+
* cannot run. The SDK then logs the user out too (`state.user` becomes
|
|
703
|
+
* null, `state.logoutReason` `"revoked"`); the request stays rejected.
|
|
474
704
|
*
|
|
475
705
|
* Set by the SDK itself:
|
|
476
706
|
* - `popup_closed` (popup mode): the popup was closed without an answer.
|
|
477
707
|
* - `navigated_back` (redirect mode): the user pressed Back on Odin and the
|
|
478
708
|
* browser restored this page from its back-forward cache, with no result.
|
|
479
709
|
*/
|
|
480
|
-
type OdinRejectReason = "untrusted_origin" | "invalid_targets" | "no_targets" | "invalid_session_key" | "missing_request_id" | "unsupported_identity" | "no_action" | "popup_closed" | "navigated_back";
|
|
710
|
+
type OdinRejectReason = "untrusted_origin" | "invalid_targets" | "no_targets" | "invalid_session_key" | "missing_request_id" | "unsupported_identity" | "no_action" | "session_revoked" | "popup_closed" | "navigated_back";
|
|
711
|
+
/**
|
|
712
|
+
* Why the SDK logged the user out (`state.logoutReason`): odin-api refused the
|
|
713
|
+
* API key with a `401`, or Odin rejected an action with `session_revoked`.
|
|
714
|
+
* - `"revoked"`: the user is logged out on odin.fun (an action rejected with
|
|
715
|
+
* `session_revoked`, or a key refused before its expiry). Show e.g. "You
|
|
716
|
+
* were signed out on odin.fun".
|
|
717
|
+
* - `"expired"`: the key had reached its expiry time (or was within 5
|
|
718
|
+
* minutes of it, allowing for the device's clock).
|
|
719
|
+
*/
|
|
720
|
+
type OdinLogoutReason = "revoked" | "expired";
|
|
481
721
|
type OdinState = {
|
|
482
722
|
/** `"initializing"` until `ready()` has restored the session. */
|
|
483
723
|
status: "initializing" | "ready";
|
|
484
724
|
user: ConnectedUser | null;
|
|
485
725
|
/** The latest request; a new request replaces it. */
|
|
486
726
|
request: OdinRequestState | null;
|
|
727
|
+
/**
|
|
728
|
+
* Set when the SDK logged the user out because odin-api refused the API
|
|
729
|
+
* key or Odin rejected an action with `session_revoked` (see
|
|
730
|
+
* `OdinLogoutReason`). Absent otherwise: after the app's own
|
|
731
|
+
* `disconnect()`, and when a reload finds an expired stored session.
|
|
732
|
+
* Cleared when a user is connected again. Not persisted: gone after a
|
|
733
|
+
* reload.
|
|
734
|
+
*/
|
|
735
|
+
logoutReason?: OdinLogoutReason;
|
|
487
736
|
};
|
|
488
737
|
type OdinStateListener = (state: OdinState) => void;
|
|
489
738
|
type StateEvent =
|
|
@@ -512,6 +761,11 @@ type StateEvent =
|
|
|
512
761
|
user?: ConnectedUser;
|
|
513
762
|
} | {
|
|
514
763
|
type: "disconnect";
|
|
764
|
+
}
|
|
765
|
+
/** The SDK logged the user out (odin-api refused the API key). */
|
|
766
|
+
| {
|
|
767
|
+
type: "logout";
|
|
768
|
+
reason: OdinLogoutReason;
|
|
515
769
|
};
|
|
516
770
|
/**
|
|
517
771
|
* The state before `ready()` restored anything, and always on a server. A
|
|
@@ -687,14 +941,6 @@ declare class ConnectedUser {
|
|
|
687
941
|
swap(params: Omit<SwapOptions, "principal">): Promise<boolean>;
|
|
688
942
|
}
|
|
689
943
|
|
|
690
|
-
declare const ORIGINS: {
|
|
691
|
-
local: string;
|
|
692
|
-
prod: string;
|
|
693
|
-
dev: string;
|
|
694
|
-
legacy: string;
|
|
695
|
-
};
|
|
696
|
-
type Environment = keyof typeof ORIGINS;
|
|
697
|
-
|
|
698
944
|
type OdinLang = "en" | "zh";
|
|
699
945
|
|
|
700
946
|
interface AppInitOptions {
|
|
@@ -709,6 +955,16 @@ interface AppInitOptions {
|
|
|
709
955
|
* `"redirect"`. See `ConnectMode`.
|
|
710
956
|
*/
|
|
711
957
|
mode?: ConnectMode;
|
|
958
|
+
/**
|
|
959
|
+
* How often, at most, to ask odin-api whether the stored session is still
|
|
960
|
+
* alive, in ms (default `SESSION_CHECK_INTERVAL_MS`, 5 minutes). Checked on
|
|
961
|
+
* page load and when the tab becomes visible or regains focus; all tabs of
|
|
962
|
+
* the app share the timer. `0` checks every time. A logout on odin.fun is
|
|
963
|
+
* noticed at the first load or focus after this time (a tab that just stays
|
|
964
|
+
* focused is not checked again), or at once by any API call that gets a
|
|
965
|
+
* `401`. Only sessions with an API key (`requires_api`) are checked.
|
|
966
|
+
*/
|
|
967
|
+
sessionCheckIntervalMs?: number;
|
|
712
968
|
}
|
|
713
969
|
interface BaseConnectOptions extends RedirectCallOptions {
|
|
714
970
|
open?: WindowClientSettings;
|
|
@@ -787,6 +1043,54 @@ declare class Connect {
|
|
|
787
1043
|
/** Synchronous up to the redirect read, so the URL is read right away. */
|
|
788
1044
|
private initialize;
|
|
789
1045
|
private finishReady;
|
|
1046
|
+
private get sessionCheckIntervalMs();
|
|
1047
|
+
/**
|
|
1048
|
+
* Tab focus or visibility (via the page's one listener, `watchActivity`):
|
|
1049
|
+
* check the session if it's due. A field, so `watchActivity` can hold it
|
|
1050
|
+
* weakly: it lives exactly as long as this instance.
|
|
1051
|
+
*/
|
|
1052
|
+
private handleActivity;
|
|
1053
|
+
/**
|
|
1054
|
+
* Ask odin-api whether the stored session is still alive, at most once per
|
|
1055
|
+
* `sessionCheckIntervalMs` across all tabs (the time of the last answered
|
|
1056
|
+
* check is in localStorage). A `401` logs the user out; being offline or a
|
|
1057
|
+
* `5xx` keeps the session and leaves the timer alone, so the next load or
|
|
1058
|
+
* focus tries again. On `legacy` a `404` (odin-api `/v1` has no session
|
|
1059
|
+
* check yet) keeps the session but sets the time, so it is asked again
|
|
1060
|
+
* only after the interval; it confirms nothing. Never rejects.
|
|
1061
|
+
*/
|
|
1062
|
+
private checkSession;
|
|
1063
|
+
/**
|
|
1064
|
+
* odin-api no longer accepts `token`: log the user out, with
|
|
1065
|
+
* `state.logoutReason` `"expired"` when the token's `exp` has passed (or is
|
|
1066
|
+
* within `EXPIRY_SKEW_MS`, for a client clock that runs slow) and
|
|
1067
|
+
* `"revoked"` otherwise. Ignored when
|
|
1068
|
+
* `token` is not this instance's API key any more (a request from before a
|
|
1069
|
+
* re-connect or disconnect).
|
|
1070
|
+
*
|
|
1071
|
+
* Unlike `disconnect()`, `state.request` is kept, so a request in flight
|
|
1072
|
+
* (e.g. a `createToken` whose upload got the `401`) still settles and the
|
|
1073
|
+
* app sees how it ended. The stored session is cleared only when it still
|
|
1074
|
+
* holds `token`: another tab may have stored a newer session since.
|
|
1075
|
+
*/
|
|
1076
|
+
private endSession;
|
|
1077
|
+
/**
|
|
1078
|
+
* Odin answered an action with `session_revoked`: the user is logged out
|
|
1079
|
+
* on odin.fun. Log out here too (`"revoked"`), whatever the check timer
|
|
1080
|
+
* says. Same path for popup results and redirect results applied by
|
|
1081
|
+
* `ready()`, since both land in the store. The logout is decided here, on
|
|
1082
|
+
* the dispatch that delivered the rejection, and applied after it, so
|
|
1083
|
+
* every listener first sees the rejected request. A listener that starts a
|
|
1084
|
+
* new request meanwhile (a retry, `connect()`) does not cancel it; only a
|
|
1085
|
+
* change of session (disconnect, re-connect, a `401`) does.
|
|
1086
|
+
*/
|
|
1087
|
+
private handleSessionRevoked;
|
|
1088
|
+
/**
|
|
1089
|
+
* Log out with `"revoked"` without a refused API key: odin.fun told us.
|
|
1090
|
+
* The stored session is cleared only when it is still this instance's
|
|
1091
|
+
* (same principal and API key); another tab may have stored a newer one.
|
|
1092
|
+
*/
|
|
1093
|
+
private revokeSession;
|
|
790
1094
|
/**
|
|
791
1095
|
* Start a connect. `state.request` becomes a pending `"connect"` request
|
|
792
1096
|
* right away and settles as `"success"` (and `state.user` is set),
|
|
@@ -826,7 +1130,6 @@ declare class Connect {
|
|
|
826
1130
|
* client, so its JWT never becomes this instance's API key.
|
|
827
1131
|
*/
|
|
828
1132
|
private detachedUser;
|
|
829
|
-
private get apiEnv();
|
|
830
1133
|
private get disconnectGeneration();
|
|
831
1134
|
/** Every local and odin-api check; no side effects. */
|
|
832
1135
|
private verifyConnection;
|
|
@@ -837,7 +1140,7 @@ declare class Connect {
|
|
|
837
1140
|
private persistConnection;
|
|
838
1141
|
get api(): OdinApiClient;
|
|
839
1142
|
get odin(): OdinCanisterClient;
|
|
840
|
-
get currentEnv(): "legacy" | "
|
|
1143
|
+
get currentEnv(): "legacy" | "local" | "prod" | "dev" | "staging";
|
|
841
1144
|
/**
|
|
842
1145
|
* @deprecated Since 2.0.0: use `(await odin.ready()).user`, or `state` /
|
|
843
1146
|
* `subscribe()`. Kept with its 1.6.0 behavior: synchronous, returns the
|
|
@@ -885,13 +1188,7 @@ interface InAppBrowserEnv {
|
|
|
885
1188
|
}
|
|
886
1189
|
declare function isInAppBrowser(env?: InAppBrowserEnv): boolean;
|
|
887
1190
|
|
|
888
|
-
|
|
889
|
-
dev: string;
|
|
890
|
-
prod: string;
|
|
891
|
-
local: string;
|
|
892
|
-
legacy: string;
|
|
893
|
-
};
|
|
894
|
-
type OdinEnv = keyof typeof IMAGE_CDN_ENV;
|
|
1191
|
+
type OdinEnv = Environment;
|
|
895
1192
|
|
|
896
1193
|
declare function isDelegationValid(chainJson: string): boolean;
|
|
897
1194
|
|
|
@@ -925,4 +1222,4 @@ interface SessionData {
|
|
|
925
1222
|
jwt: string | null;
|
|
926
1223
|
}
|
|
927
1224
|
|
|
928
|
-
export { INITIAL_ODIN_STATE, type Achievement as OdinAchievement, type AchievementCategory as OdinAchievementCategory, type OdinAction, type OdinActionDetail, type Activity as OdinActivity, type Balance as OdinBalance, type BaseToken as OdinBaseToken, Connect as OdinConnect, type ConnectMode as OdinConnectMode, ConnectVerificationError as OdinConnectVerificationError, ConnectedUser as OdinConnectedUser, type OdinLang, type RedirectCallOptions as OdinRedirectCallOptions, type OdinRejectReason, type OdinRequestInput, type OdinRequestState, type OdinRequestStatus, type OdinState, type OdinStateListener, type Token as OdinToken, type TokenWithBalance as OdinTokenWithBalance, type Transaction as OdinTransaction, type User as OdinUser, index as OdinUtils, type SessionData, isInAppBrowser };
|
|
1225
|
+
export { INITIAL_ODIN_STATE, type Achievement as OdinAchievement, type AchievementCategory as OdinAchievementCategory, type OdinAction, type OdinActionDetail, type Activity as OdinActivity, type AssignableCommunityRole as OdinAssignableCommunityRole, type Balance as OdinBalance, type BaseToken as OdinBaseToken, type ChatAccess as OdinChatAccess, type ChatAccessDenialReason as OdinChatAccessDenialReason, type ChatChannelAccess as OdinChatChannelAccess, OdinCommunitiesClient, type Community as OdinCommunity, type CommunityDetail as OdinCommunityDetail, type CommunityFilterFields as OdinCommunityFilterFields, type CommunityListItem as OdinCommunityListItem, type CommunityMember as OdinCommunityMember, type CommunityMemberBan as OdinCommunityMemberBan, type CommunityMemberUser as OdinCommunityMemberUser, type CommunityProfile as OdinCommunityProfile, type CommunityRecommendedToken as OdinCommunityRecommendedToken, type CommunityRecommendedTokenSummary as OdinCommunityRecommendedTokenSummary, type CommunityRole as OdinCommunityRole, type CommunitySortableFields as OdinCommunitySortableFields, type CommunityStats as OdinCommunityStats, Connect as OdinConnect, type ConnectMode as OdinConnectMode, ConnectVerificationError as OdinConnectVerificationError, ConnectedUser as OdinConnectedUser, type OdinLang, type OdinLogoutReason, type RedirectCallOptions as OdinRedirectCallOptions, type OdinRejectReason, type OdinRequestInput, type OdinRequestState, type OdinRequestStatus, type OdinState, type OdinStateListener, type Token as OdinToken, type TokenWithBalance as OdinTokenWithBalance, type Transaction as OdinTransaction, type User as OdinUser, index as OdinUtils, type SessionData, isInAppBrowser };
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import me from'axios';import ye from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';import {Principal}from'@dfinity/principal';var he=Object.defineProperty;var fe=(n,e)=>{for(var t in e)he(n,t,{get:e[t],enumerable:true});};var _e=n=>{try{return ye.parse(n)}catch(e){return console.error("Error parsing response:",e),n}},P=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let i={transformResponse:[_e],...t};return (await me(e,i)).data}async post(e,t,i){return this.fetch(e,{method:"POST",data:t,...i})}async put(e,t,i){return this.fetch(e,{method:"PUT",data:t,...i})}async delete(e,t){return this.fetch(e,{method:"DELETE",...t})}};var re={};fe(re,{DEFAULT_LANG:()=>y,buildTokenImageUrl:()=>Oe,convertToOdinAmount:()=>Ce,createTokenValidators:()=>b,isDelegationValid:()=>_,normalizeOdinLang:()=>v});var ie={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1"},q={dev:"https://images.odin.fun/dev",prod:"https://images.odin.fun/v2",local:"https://images.odin.fun/dev",legacy:"https://images.odin.fun"};function _(n){try{let e=DelegationChain.fromJSON(JSON.parse(n)),t=BigInt(Date.now())*1000000n;return e.delegations.every(i=>i.delegation.expiration==null||i.delegation.expiration>t)}catch{return false}}var y="en";function v(n){return n==="en"||n==="zh"?n:(n!==void 0&&console.warn(`[odin-connect] Unsupported lang "${n}", falling back to "${y}"`),y)}function Oe(n,e="prod"){return `${q[e]}/token/${n}`}function Ce(n,e={decimals:3,divisibility:8}){let t=e.decimals+e.divisibility;if(n=typeof n=="string"?n.trim():String(n),isNaN(+n))return 0n;let[i,r=""]=n.split(".");return r=r.slice(0,t),r=r.padEnd(t,"0"),i=i.replace(/^0+(?=\d)/,""),i===""&&(i="0"),BigInt(i+r)}var b={name:be,image:Se,ticker:Ae,vanity_ticker:ve,description:Re,twitter:ke,website:Ee,telegram:Te};function be(n){if(typeof n!="string")return "Name must be a string.";if(!n||n.trim()==="")return "Name is required.";if(n.length<3||n.length>30)return "Name must be between 3 and 30 characters."}function Re(n){if(n){if(typeof n!="string")return "Description must be a string.";if(n&&n.length>100)return "Description must not exceed 100 characters."}}function Ae(n){if(typeof n!="string")return "Ticker must be a string.";if(!n||n.trim()==="")return "Ticker is required.";if(n.length<3||n.length>10)return "Ticker must be between 3 and 10 characters.";if(!/^[A-Z0-9]+$/.test(n))return "Ticker must be alphanumeric characters in uppercase only.";if(!/(?=(.*[A-Z].*[A-Z]))/.test(n))return "Ticker must have at least 2 alpha characters."}function ve(n){if(!(n==null||n==="")){if(typeof n!="string")return "Vanity ticker must be a string.";if(n.trim()!==n)return "Vanity ticker must not have leading or trailing whitespace.";if([...n].length>10)return "Vanity ticker must be below 10 characters."}}function Se(n){if(!(n instanceof File))return "Image must be a file.";let e=["image/png","image/jpeg","image/webp","image/svg","image/gif","image/avif"],t=200*1024;if(!n)return "Image file is required.";if(!e.includes(n.type))return `Invalid file type. Allowed types are: ${e.join(", ")}`;if(n.size>t)return `File size exceeds the maximum limit of ${t/1024}KB.`}function ke(n){if(n){if(typeof n!="string")return "Twitter handle must be a string.";if(n&&!/^https?:\/\/(www\.)?(twitter\.com|x\.com)\/[A-Za-z0-9_]{1,15}\/?$/.test(n))return "Twitter must be a valid twitter URL."}}function Ee(n){if(n){if(typeof n!="string")return "Website must be a string.";if(n&&!/^(https?:\/\/)?([\w-]+(\.[\w-]+)+)(\/[\w-./?%&=]*)?$/.test(n))return "Website must be a valid URL."}}function Te(n){if(n){if(typeof n!="string")return "Telegram must be a string.";if(n&&!/^(https?:\/\/)?(t\.me|telegram\.me|telegram\.org)\/[A-Za-z0-9_]{5,32}\/?$/.test(n))return "Telegram must be a valid telegram URL."}}var S=class{_apiKey=null;_httpClient;BASE_URL;ENV;constructor(e="prod"){this._httpClient=new P,this.BASE_URL=ie[e],this.ENV=e;}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${q[this.ENV]}/user/${e}`}async getBalances(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{...t}})).data}async getBalance(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{token_in:t}})).data.find(r=>r.id===t)??null}getTokens(e,t={field:"marketcap",direction:"desc"},i={}){return this._httpClient.get(`${this.BASE_URL}/tokens`,{params:{...e,sort:`${t.field}:${t.direction}`,...i}})}getToken(e){return this._httpClient.get(`${this.BASE_URL}/token/${e}`)}async uploadImage(e){if(!this._apiKey)throw new Error("API key is not set");try{let t=b.image?.(e);if(t)throw new Error(t);let i=new FormData;return i.append("file",e),(await this._httpClient.post(`${this.BASE_URL}/upload`,i,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})).data.upload}catch(t){if(t instanceof Error)if(t.name==="AxiosError"){let i=t;throw new Error(i.response?.data?.message||i.message)}else throw new Error(t.message);else throw new Error("Image upload failed")}}updateTokenImage(e,t){if(!this._apiKey)throw new Error("API key is not set");try{return this._httpClient.post(`${this.BASE_URL}/token/${e}/image`,{image:t},{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})}catch(i){if(i instanceof Error&&i.name==="AxiosError"){let r=i;throw new Error(r.response?.data?.message||r.message)}else throw new Error("Image update failed")}}getUserActivity(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/activity`,{params:{...t}})}async getUserTokens(e,t){let i=await this._httpClient.get(`${this.BASE_URL}/user/${e}/tokens`,{params:{...t}});return {...i,data:i.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserLiquidity(e,t){let i=await this._httpClient.get(`${this.BASE_URL}/user/${e}/liquidity`,{params:{...t}});return {...i,data:i.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserAchievements(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/achievements`,{params:{...t}})).data}getUserTransactions(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/transactions`,{params:{...t}})}getUserCreatedTokens(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/created`,{params:{...t}})}getUserStats(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}/stats`)}async verifyConnect(e){try{return await this._httpClient.post(`${this.BASE_URL}/connect/verify`,e)}catch(t){if(t instanceof Error&&t.name==="AxiosError"){let i=t,r=i.response?.data?.message;throw new Error(typeof r=="string"&&r?r:i.message)}throw t instanceof Error?t:new Error("Connect verification failed")}}set apiKey(e){this._apiKey=e;}get apiKey(){return this._apiKey}};var R=class{_identity;_api;_principal;_odin;constructor(e,t,i,r){this._principal=e,this._identity=t,this._api=i,this._odin=r;}get principal(){return this._principal}set principal(e){this._principal=e;}getIdentity(){return this._identity}getUser(){return this._api.getUser(this.principal)}buildAvatarImageUrl(){return this._api.getUserAvatarUrl(this.principal)}getBalances(e){return this._api.getBalances(this.principal,e)}getBalance(e){return this._api.getBalance(this.principal,e)}getTokens(e){return this._api.getUserTokens(this.principal,e)}getCreatedTokens(e){return this._api.getUserCreatedTokens(this.principal,e)}getActivity(e){return this._api.getUserActivity(this.principal,e)}getLiquidity(e){return this._api.getUserLiquidity(this.principal,e)}getAchievements(e){return this._api.getUserAchievements(this.principal,e)}getTransactions(e){return this._api.getUserTransactions(this.principal,e)}getStats(){return this._api.getUserStats(this.principal)}sell(e){return this._odin.sell({...e,principal:this.principal})}buy(e){return this._odin.buy({...e,principal:this.principal})}addLiquidity(e){return this._odin.addLiquidity({...e,principal:this.principal})}removeLiquidity(e){return this._odin.removeLiquidity({...e,principal:this.principal})}transfer(e){return this._odin.transfer({...e,principal:this.principal})}createToken(e){return this._odin.createToken({...e,principal:this.principal})}icrcApprove(e){return this._odin.icrcApprove({...e,principal:this.principal})}swap(e){return this._odin.swap({...e,principal:this.principal})}};var z={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun"};var U=class{_settings;constructor(e){this._settings={target:e?.target||"_blank",settings:e?.settings||""};}get settings(){return this._settings}set settings(e){this._settings={...this._settings,...e};}open(e){return window.open(e,this._settings?.target||"_blank",this._settings?.settings)}navigate(e){window.location.assign(e.href);}};var xe=[/\bOKApp\b/i],Ie=["XverseProviders","btc_providers","unisat","okxwallet","phantom","LeatherProvider","magicEden","wizz","oyl","ethereum","solana"];function Pe(n,e){return /Android|iPhone|iPad|iPod|Mobile/i.test(n)?true:/Macintosh/.test(n)&&e>1}function qe(n,e){return /Android/i.test(n)&&/;\s*wv\)/.test(n)?true:(/iPhone|iPad|iPod/i.test(n)||/Macintosh/.test(n)&&e>1)&&/AppleWebKit/i.test(n)&&!/Safari\//.test(n)}function Ue(n){return Ie.some(e=>n[e]!=null)}function W(n={}){let e=n.userAgent??(typeof navigator>"u"?"":navigator.userAgent),t=n.maxTouchPoints??(typeof navigator>"u"?0:navigator.maxTouchPoints||0),i=n.globals??(typeof window>"u"?{}:window);return xe.some(r=>r.test(e))||qe(e,t)?true:Pe(e,t)&&Ue(i)}var Le="odin_connect",De=600*1e3,G="$odin_bigint";function Be(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?{[G]:t.toString()}:t)}function Ne(n){return JSON.parse(n,(e,t)=>t!==null&&typeof t=="object"&&Object.keys(t).length===1&&typeof t[G]=="string"?BigInt(t[G]):t)}var L=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:pending_redirect`;}save(e){let t=Be(e);try{return sessionStorage.setItem(this._key,t),sessionStorage.getItem(this._key)===t}catch{return false}}peek(){try{let e=sessionStorage.getItem(this._key);if(!e)return null;let t=Ne(e);return typeof t?.state!="string"||typeof t?.path!="string"?null:t}catch{return null}}take(){let e=this.peek();try{sessionStorage.removeItem(this._key);}catch{}return e}dropIfOlderThan(e){let t=this.peek();if(!t)return;(typeof t.createdAt=="number"?Date.now()-t.createdAt:1/0)>e&&this.take();}};function J(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(){return J(crypto.getRandomValues(new Uint8Array(24)))}function $e(){return window.location.origin+window.location.pathname}function Ve(){let n=new URL(window.location.href);return n.hash="",n.href}function D(){let n=window.location.hash.replace(/^#/,"");return n?new URLSearchParams(n).get(Le):null}function se(n){let e=new URL(window.location.href);if(e.hash="",typeof n=="string")try{let t=new URL(n);t.origin===e.origin&&t.pathname===e.pathname&&(e.search=t.search);}catch{}window.history.replaceState(window.history.state,"",e.href);}function Ke(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=Uint8Array.from(atob(e),r=>r.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(t));return typeof i?.path!="string"||typeof i?.state!="string"?null:i}catch{return null}}var B=class{constructor(e,t){this._window=e;this._pending=t;}_window;_pending;mode="auto";get useRedirect(){return this.mode==="redirect"||this.mode==="auto"&&W()}start(e,t,i,r){let s;try{s=this._pending.save({...t,state:i,createdAt:Date.now(),returnHref:Ve()});}catch{return Promise.reject(new Error("returnState must be JSON-serializable (bigints are allowed)"))}if(!s)return Promise.reject(new Error("Redirect mode needs sessionStorage, which is unavailable"));if(e.searchParams.append("return_url",$e()),e.searchParams.append("state",i),r&&typeof window<"u"){let o=a=>{a.persisted&&(window.removeEventListener("pageshow",o),!D()&&(this._pending.peek()?.state===i&&this._pending.take(),r()));};window.addEventListener("pageshow",o);}return this._window.navigate(e),new Promise(()=>{})}consume(){let e=D();if(e===null)return this._pending.dropIfOlderThan(De),null;let t=Ke(e),i=this._pending.take();if(!t||!i||i.state!==t.state||i.path!==t.path)throw se(),new Error("Unexpected OdinConnect redirect result");return se(i.returnHref),{result:t,pending:i}}};var k={buy:{path:"authorize/buy",success:"purchased",failure:"Purchase failed or was cancelled"},sell:{path:"authorize/sell",success:"sold",failure:"Sell failed or was cancelled"},transfer:{path:"authorize/transfer",success:"transferred",failure:"Transfer failed or was cancelled"},swap:{path:"authorize/swap",success:"swapped",failure:"Swap failed or was cancelled"},add_liquidity:{path:"authorize/add_liquidity",success:"addedLiquidity",failure:"Add liquidity failed or was cancelled"},remove_liquidity:{path:"authorize/remove_liquidity",success:"removedLiquidity",failure:"Remove liquidity failed or was cancelled"},icrc_approve:{path:"authorize/icrc_approve",success:"approved",failure:"ICRC approve failed or was cancelled"},create_token:{path:"authorize/create_token",success:"tokenCreated",failure:"Token creation failed or was cancelled"}};function oe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}var M="popup_closed",H="navigated_back",je=/^[a-z0-9_]{1,64}$/;function $(n){let e=oe(n)?.reason;return typeof e=="string"&&je.test(e)?e:void 0}function Z(n,e,t){if(e===k[n].success){let i=oe(t);return {status:"success",...i?{detail:i}:{}}}if(e==="rejected"){let i=$(t);return {status:"rejected",...i?{error:i}:{}}}return {status:"failed",error:k[n].failure}}function A(n){return n.catch(()=>{}),n}var ze=500,We=1500;function X(n,e,t,i){let r=false,s=null,o=null,a=()=>{if(!t)return true;let{request:c}=t.state;return c?.id===e&&c.status==="pending"},p=()=>{r||(r=true,clearInterval(d),o!==null&&clearTimeout(o),s?.());},d=setInterval(()=>{!n.closed||o!==null||(clearInterval(d),o=setTimeout(()=>{let c=a();p(),c&&i();},We));},ze);return s=t?.subscribe(()=>{a()||p();})??null,p}var N=class{_window;_appInfo;_api;_redirect;_store;origin;constructor(e,t,i,r,s=null,o=null){this._window=e,this._redirect=s,this._api=t,this._appInfo=i,this.origin=r,this._store=o;}get appInfo(){return this._appInfo}createUrl(e,t=w()){let i=new URL(`${this.origin}/${e}`);return i.searchParams.append("v","2"),i.searchParams.append("request_id",t),this._appInfo?.name&&i.searchParams.append("app_name",this._appInfo.name),i.searchParams.append("referrer",window.location.origin),i.searchParams.append("lang",this._appInfo?.lang||y),i}startRequest(e,t,i,r){this._store?.dispatch({type:"request",request:{id:e,action:t,status:"pending",input:i,...r!==void 0?{returnState:r}:{}}});}fail(e,t){let i=t instanceof Error?t:new Error(String(t));return this._store?.dispatch({type:"settle",id:e,status:"failed",error:i.message}),i}baseAction({action:e,input:t,params:i,returnState:r,requestId:s=w()}){let{path:o,failure:a}=k[e];this.startRequest(s,e,t,r);let p=this.createUrl(o,s);for(let d in i)i[d]&&p.searchParams.append(d,i[d]);return this._redirect?.useRedirect?A(this._redirect.start(p,{path:"/"+o,input:t,returnState:r},s,()=>this._store?.dispatch({type:"settle",id:s,status:"rejected",error:H})).catch(d=>{throw this.fail(s,d)})):A(new Promise((d,c)=>{let m=()=>{},u=h=>{if(h.origin===this.origin&&h.data?.path==="/"+o){window.removeEventListener("message",u),m();let O=Z(e,h.data.message,h.data.detail);this._store?.dispatch({type:"settle",id:s,...O}),O.status==="success"?d(true):c(new Error(a));}},g=this._window.open(p);if(!g||g.closed||typeof g.closed>"u"){c(this.fail(s,`Failed to open ${o} window, please always allow popups and try again`));return}window.addEventListener("message",u),m=X(g,s,this._store,()=>{window.removeEventListener("message",u),this._store?.dispatch({type:"settle",id:s,status:"rejected",error:M}),c(new Error(a));});}))}sell({token:e,tokenAmount:t,principal:i,returnState:r}){return this.baseAction({action:"sell",input:{token:e,tokenAmount:t},params:{principal:i,token:e,amount:t.toString()},returnState:r})}buy({principal:e,token:t,btcAmount:i,returnState:r}){return this.baseAction({action:"buy",input:{token:t,btcAmount:i},params:{principal:e,token:t,amount:i.toString()},returnState:r})}transfer({principal:e,token:t,amount:i,destination:r,returnState:s}){return this.baseAction({action:"transfer",input:{token:t,amount:i,destination:r},params:{principal:e,token:t,amount:i.toString(),destination:r},returnState:s})}addLiquidity({principal:e,btcAmount:t,token:i,returnState:r}){return this.baseAction({action:"add_liquidity",input:{token:i,btcAmount:t},params:{principal:e,amount:t.toString(),token:i},returnState:r})}removeLiquidity({principal:e,lpAmount:t,token:i,returnState:r}){return this.baseAction({action:"remove_liquidity",input:{token:i,lpAmount:t},params:{principal:e,amount:t.toString(),token:i},returnState:r})}swap({principal:e,fromToken:t,toToken:i,fromAmount:r,returnState:s}){return this.baseAction({action:"swap",input:{fromToken:t,toToken:i,fromAmount:r},params:{principal:e,from:t,to:i,amount:r.toString()},returnState:s})}icrcApprove({principal:e,token:t,spender:i,amount:r,returnState:s}){return this.baseAction({action:"icrc_approve",input:{token:t,spender:i,amount:r},params:{principal:e,token:t,spender:i,amount:r.toString()},returnState:s})}createToken({image:e,returnState:t,principal:i,...r}){let s=w(),o={...r};return this.startRequest(s,"create_token",o,t),A((async()=>{let a;try{for(let p in b)if(p in r){let c=b[p]?.(r[p]||null);if(c)throw new Error(c)}if(r.discount&&!/^[A-Za-z0-9]{10}$/.test(r.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");a=await this._api.uploadImage(e);}catch(p){throw this.fail(s,p)}return this.baseAction({action:"create_token",input:{...o,image:a},params:{...r,principal:i,image:a,buy:r.buy?.toString()},returnState:t,requestId:s})})())}};var V=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:session`;}save(e){try{localStorage.setItem(this._key,JSON.stringify(e));}catch{}}load(){try{let e=localStorage.getItem(this._key);if(!e)return null;let t=JSON.parse(e);return this.isValidSessionData(t)?t:null}catch{return null}}isValidSessionData(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.principal=="string"&&typeof t.sessionKey=="string"&&(t.delegationChain===null||typeof t.delegationChain=="string")&&(t.jwt===null||typeof t.jwt=="string")}clear(){try{localStorage.removeItem(this._key);}catch{}}};var f=class extends Error{constructor(e){super(`OdinConnect could not verify the connection: ${e}`),this.name="ConnectVerificationError";}};function l(n){throw new f(n)}function Ge(n,e){if(n.byteLength!==e.byteLength)return false;for(let t=0;t<n.byteLength;t++)if(n[t]!==e[t])return false;return true}function Je(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Fe(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Me=`odin-connect-verify:v1
|
|
2
|
-
`;async function pe(n,e){let t=await n.sign(new TextEncoder().encode(Me+e));return Fe(new Uint8Array(t))}function He(n){try{if(n.delegation)return new Uint8Array(DelegationChain.fromJSON(JSON.parse(n.delegation)).publicKey);if(n.publicKey)return Je(n.publicKey)}catch{}l("the identity proof has no readable signer");}function de(n,e){(!n||typeof n.payload!="string"||typeof n.signature!="string")&&l("the result carries no identity proof");let t;try{t=JSON.parse(n.payload);}catch{l("the identity proof payload is malformed");}(t?.typ!=="odin-connect-identity"||t.v!==1)&&l("the identity proof has an unknown type"),t.nonce!==e.nonce&&l("the identity proof belongs to another request"),t.aud!==e.audience&&l("the identity proof was issued to another origin"),t.principal!==e.principal&&l("the identity proof is for another principal"),typeof t.sk!="string"&&l("the identity proof is not bound to a session key"),t.sk!==e.sessionPubkey&&l("the identity proof was issued to another session key"),e.requires_api&&t.api!==true&&l("API access was not granted");let i=He(n);Principal.selfAuthenticating(i).toText()!==e.principal&&l("the identity proof signer does not match the principal");}function le(n,e){n||l("the delegation chain is missing");let t;try{t=DelegationChain.fromJSON(n);}catch{l("the delegation chain is malformed");}t.delegations.length===0&&l("the delegation chain is empty"),_(JSON.stringify(t.toJSON()))||l("the delegation chain has expired");let i=t.delegations[t.delegations.length-1].delegation;Ge(new Uint8Array(i.pubkey),e.sessionPublicKey)||l("the delegation chain was issued to another session key");let r=new Uint8Array(t.publicKey);Principal.selfAuthenticating(r).toText()!==e.principal&&l("the delegation chain belongs to another principal");let s=new Set(e.targets);for(let{delegation:o}of t.delegations)o.targets?.some(a=>!s.has(a.toText()))&&l("the delegation chain targets canisters that were not requested");return t}function Ze(n){return Object.isFrozen(n)?n:(Object.freeze(n.input),n.detail&&Object.freeze(n.detail),Object.freeze(n))}function K(n){return Object.freeze({...n,request:n.request?Ze(n.request):null})}function Xe(n,e){switch(e.type){case "ready":return K({status:"ready",user:n.user??e.user,request:n.request??e.request});case "request":return K({...n,request:{...e.request}});case "settle":{let t=n.request;if(!t||t.id!==e.id)return n;let i={...t,status:e.status,...e.detail?{detail:e.detail}:{},...e.error!==void 0?{error:e.error}:{}};return K({...n,user:e.user??n.user,request:i})}case "disconnect":return n.user===null&&n.request===null?n:K({...n,user:null,request:null})}}var E=Object.freeze({status:"initializing",user:null,request:null}),j=class{_state=E;_listeners=new Set;get state(){return this._state}dispatch(e){let t=Xe(this._state,e);if(t!==this._state){this._state=t;for(let i of [...this._listeners])if(this._listeners.has(i))try{i(t);}catch(r){queueMicrotask(()=>{throw r});}}}subscribe(e){let t=i=>e(i);return this._listeners.add(t),()=>{this._listeners.delete(t);}}};var T=new Map,Qe=1e4,Q=new Map;function et(n){let e=0;for(let t=0;t<n.length;t++)e=e*31+n.charCodeAt(t)|0;return (e>>>0).toString(36).slice(0,3).padStart(3,"0")}function ge(n){return J(new Uint8Array(n.getPublicKey().toDer()))}function tt(n){return `${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${et(n)}`}var ee=class{static serverState=E;_appInfo=null;_api;_window;_odin;_storage;_redirect;_store=new j;_ready=null;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||tt(this._appInfo.name),this._appInfo.lang=v(this._appInfo.lang),this._api=new S(this.apiEnv),this._window=new U,this._redirect=new B(this._window,new L(this._appInfo.slug,this._appInfo.env||"prod")),this._redirect.mode=this._appInfo.mode||"auto",this._odin=new N(this._window,this._api,this._appInfo,z[this._appInfo.env||"prod"],this._redirect,this._store),this._storage=new V(this._appInfo.slug,this._appInfo.env||"prod"),typeof window<"u"&&this.ready();}createUrl(e,t=w()){let i=new URL(`${this.origin}/${e}`);return i.searchParams.append("v","2"),i.searchParams.append("request_id",t),this._appInfo?.name&&i.searchParams.append("app_name",this._appInfo.name),i.searchParams.append("referrer",window.location.origin),i.searchParams.append("lang",this.lang),i}get origin(){return z[this._appInfo?.env||"prod"]}get lang(){return this._appInfo?.lang||y}set lang(e){this._appInfo&&(this._appInfo.lang=v(e));}get mode(){return this._redirect.mode}set mode(e){this._redirect.mode=e,this._appInfo&&(this._appInfo.mode=e);}get appInfo(){return this._appInfo}get slug(){return this._appInfo?.slug||""}ready(){return typeof window>"u"?Promise.resolve(this.state):(this._ready||(this._ready=this.initialize()),this._ready.then(()=>this.state))}get state(){return this._store.state}getState=()=>this._store.state;getServerState=()=>E;subscribe=e=>this._store.subscribe(e);get user(){return this._store.state.user}initialize(){let e=this.disconnectGeneration,t=null;try{t=this.redirectOutcome(),t||this._redirect.consume();}catch{}return this.finishReady(t,e)}async finishReady(e,t){let i=null,r=null;if(e)try{let s=await e;t===this.disconnectGeneration&&(i=s.request,s.connected&&(r=this.bindConnection(s.connected)));}catch{}this._store.dispatch({type:"ready",user:r??this.loadStoredSession(),request:i});}connect({open:e,requires_api:t,requires_delegation:i,targets:r,returnState:s}={requires_delegation:false,requires_api:false}){let o=Ed25519KeyIdentity.generate(),a=w(),p={requires_api:t,requires_delegation:i,targets:r},d={requires_api:!!t,requires_delegation:!!i,targets:r?[...r]:[]};this._store.dispatch({type:"request",request:{id:a,action:"connect",status:"pending",input:d,...s!==void 0?{returnState:s}:{}}});let c=this.createConnectUrl(o,a,p);return this._redirect.useRedirect?A(this._redirect.start(c,{path:"/authorize/connect",sessionKey:JSON.stringify(o.toJSON()),requires_delegation:d.requires_delegation,requires_api:d.requires_api,targets:r,returnState:s},a,()=>this._store.dispatch({type:"settle",id:a,status:"rejected",error:H})).catch(m=>{throw this.settleError(a,"failed",m)})):(e&&(this._window.settings=e),A(new Promise((m,u)=>{let g=null,h=()=>{},O=async C=>{if(C.origin===this.origin&&C.source===g&&C.data?.path==="/authorize/connect"){if(window.removeEventListener("message",O),h(),C.data.message==="rejected"){let I=$(C.data.detail);this._store.dispatch({type:"settle",id:a,status:"rejected",...I?{error:I}:{}}),u(new Error("User rejected the connection"));return}let te={requestId:a,...p},x;try{x=await this.verifyConnection(C.data.message,o,te);}catch(I){u(this.settleError(a,"unverified",I));return}if(this._store.state.request?.id!==a){m(this.detachedUser(x));return}this.persistConnection(x,o,te);let ne=this.bindConnection(x);this._store.dispatch({type:"settle",id:a,status:"success",user:ne}),m(ne);}};if(g=this._window.open(c),!g||g.closed||typeof g.closed>"u"){u(this.settleError(a,"failed",new Error("Failed to open authorize/connect window, please always allow popups and try again")));return}window.addEventListener("message",O),h=X(g,a,this._store,()=>{window.removeEventListener("message",O),this._store.dispatch({type:"settle",id:a,status:"rejected",error:M}),u(new Error("User rejected the connection"));});})))}settleError(e,t,i){let r=i instanceof Error?i:t==="unverified"?new f(String(i)):new Error(String(i));return this._store.dispatch({type:"settle",id:e,status:t,error:r.message}),r}createConnectUrl(e,t,{requires_api:i,requires_delegation:r,targets:s}){let o=this.createUrl("authorize/connect",t);return o.searchParams.append("requires_api",i?"1":"0"),o.searchParams.append("session_pubkey",ge(e)),r&&(o.searchParams.append("requires_delegation","1"),o.searchParams.append("targets",s?.join(",")||"")),o}redirectOutcome(){let e=this.redirectCacheKey,t=D(),i=T.get(e);if(t!==null&&i?.fragment!==t){let r={fragment:t,promise:this.readRedirectResult(),settled:false};T.set(e,r);let s=()=>{r.settled=true,setTimeout(()=>{T.get(e)===r&&T.delete(e);},Qe);};return r.promise.then(s,o=>{console.warn("OdinConnect: ignored a stale or foreign redirect result",o),s();}),r.promise}return i&&!i.settled?i.promise:null}bindConnection({principal:e,identity:t,jwt:i}){return this._api.apiKey=i,new R(e,t,this._api,this._odin)}get redirectCacheKey(){return `${this.slug}:${this.currentEnv}`}async readRedirectResult(){let e=this.disconnectGeneration,t=this._redirect.consume();if(!t)throw new Error("Unexpected OdinConnect redirect result");let{result:i,pending:r}=t,s=r.returnState!==void 0?{returnState:r.returnState}:{},o=r.path.replace(/^\/authorize\//,"");if(o==="connect"){let a={id:r.state,action:"connect",input:{requires_api:!!r.requires_api,requires_delegation:!!r.requires_delegation,targets:r.targets??[]},...s};if(i.message==="rejected"){let c=$(i.detail);return {request:{...a,status:"rejected",...c?{error:c}:{}}}}if(!r.sessionKey)return {request:{...a,status:"unverified",error:new f("the pending request has no session key").message}};let p=Ed25519KeyIdentity.fromJSON(r.sessionKey),d={requestId:r.state,requires_api:r.requires_api,requires_delegation:r.requires_delegation,targets:r.targets};try{let c=await this.verifyConnection(i.message,p,d);return e!==this.disconnectGeneration?{request:{...a,status:"success"}}:(this.persistConnection(c,p,d),{request:{...a,status:"success"},connected:c})}catch(c){return {request:{...a,status:"unverified",error:c instanceof Error?c.message:String(c)}}}}if(!(o in k))throw new Error("Unexpected OdinConnect redirect result");return {request:{id:r.state,action:o,input:r.input??{},...s,...Z(o,i.message,i.detail)}}}detachedUser({principal:e,identity:t,jwt:i}){let r=new S(this.apiEnv);return r.apiKey=i,new R(e,t,r,this._odin)}get apiEnv(){let e=this._appInfo?.env;return e==="prod"?"prod":e==="legacy"?"legacy":"dev"}get disconnectGeneration(){return Q.get(this.redirectCacheKey)??0}async verifyConnection(e,t,{requestId:i,requires_api:r,requires_delegation:s,targets:o}){if(!e||typeof e.principal!="string")throw new f("the result has no principal");let{principal:a,proof:p}=e,d=window.location.origin;de(p,{principal:a,nonce:i,audience:d,requires_api:!!r,sessionPubkey:ge(t)});let c=null;s&&(c=le(e.delegationChain,{principal:a,sessionPublicKey:new Uint8Array(t.getPublicKey().toDer()),targets:o??[]}));let m=await pe(t,p.payload),u;try{u=await this._api.verifyConnect({payload:p.payload,signature:p.signature,delegation:p.delegation??null,publicKey:p.publicKey??null,audience:d,nonce:i,issue_jwt:!!r,client_signature:m});}catch(h){throw new f(`odin-api refused the proof (${h instanceof Error?h.message:String(h)})`)}if(u?.principal!==a)throw new f("odin-api verified a different principal");let g=null;if(r){if(typeof u.jwt!="string"||!u.jwt)throw new f("odin-api issued no API key");g=u.jwt;}return {principal:a,chain:c,identity:c?DelegationIdentity.fromDelegation(t,c):null,jwt:g}}persistConnection({principal:e,chain:t,jwt:i},r,{requires_api:s,requires_delegation:o}){this._storage.clear(),this._api.apiKey=null,(s||o)&&this._storage.save({principal:e,sessionKey:JSON.stringify(r.toJSON()),delegationChain:t?JSON.stringify(t.toJSON()):null,jwt:i});}get api(){return this._api}get odin(){return this._odin}get currentEnv(){return this._appInfo?.env||"prod"}restoreSession(){return this.state.status==="ready"?this.state.user:this.loadStoredSession()}loadStoredSession(){try{let e=this._storage.load();if(!e)return null;if(e.delegationChain&&!_(e.delegationChain))return this._storage.clear(),null;e.jwt&&(this._api.apiKey=e.jwt);let t=null;if(e.delegationChain&&e.sessionKey){let i=Ed25519KeyIdentity.fromJSON(e.sessionKey),r=DelegationChain.fromJSON(JSON.parse(e.delegationChain));t=DelegationIdentity.fromDelegation(i,r);}return new R(e.principal,t,this._api,this._odin)}catch{return this._storage.clear(),null}}disconnect(){let e=this.redirectCacheKey;Q.set(e,(Q.get(e)??0)+1),this._storage.clear(),this._api.apiKey=null,T.delete(e),this._store.dispatch({type:"disconnect"});}isSessionValid(){let e=this._storage.load();return e?e.delegationChain?_(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
|
|
3
|
-
export{
|
|
1
|
+
import Ae from'axios';import Te from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';import {Principal}from'@dfinity/principal';var Se=Object.defineProperty;var ke=(n,e)=>{for(var t in e)Se(n,t,{get:e[t],enumerable:true});};var Ee=n=>{if(typeof n!="string"||n==="")return n;try{return Te.parse(n)}catch(e){return console.error("Error parsing response:",e),n}};function J(n){if(n instanceof Error&&n.name==="AxiosError")return n.response?.status}function Pe(n){let e=n?.headers,t=e?.Authorization??e?.authorization;return typeof t!="string"||!t.startsWith("Bearer ")?null:t.slice(7)}var U=class{onUnauthorized=null;async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let i={transformResponse:[Ee],...t};try{return (await Ae(e,i)).data}catch(r){let s=Pe(t);if(s&&J(r)===401)try{this.onUnauthorized?.(s);}catch{}throw r}}async post(e,t,i){return this.fetch(e,{method:"POST",data:t,...i})}async put(e,t,i){return this.fetch(e,{method:"PUT",data:t,...i})}async patch(e,t,i){return this.fetch(e,{method:"PATCH",data:t,...i})}async delete(e,t){return this.fetch(e,{method:"DELETE",...t})}};var de={};ke(de,{DEFAULT_LANG:()=>y,buildTokenImageUrl:()=>xe,convertToOdinAmount:()=>qe,createTokenValidators:()=>R,isDelegationValid:()=>_,normalizeOdinLang:()=>k});var ue={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1",staging:"https://api.odin.fun/v2"},L={dev:"https://images.odin.fun/dev",prod:"https://images.odin.fun/v2",local:"https://images.odin.fun/dev",legacy:"https://images.odin.fun",staging:"https://images.odin.fun/v2"};function _(n){try{let e=DelegationChain.fromJSON(JSON.parse(n)),t=BigInt(Date.now())*1000000n;return e.delegations.every(i=>i.delegation.expiration==null||i.delegation.expiration>t)}catch{return false}}var y="en";function k(n){return n==="en"||n==="zh"?n:(n!==void 0&&console.warn(`[odin-connect] Unsupported lang "${n}", falling back to "${y}"`),y)}function xe(n,e="prod"){return `${L[e]}/token/${n}`}function qe(n,e={decimals:3,divisibility:8}){let t=e.decimals+e.divisibility;if(n=typeof n=="string"?n.trim():String(n),isNaN(+n))return 0n;let[i,r=""]=n.split(".");return r=r.slice(0,t),r=r.padEnd(t,"0"),i=i.replace(/^0+(?=\d)/,""),i===""&&(i="0"),BigInt(i+r)}var R={name:Ue,image:Ne,ticker:De,vanity_ticker:$e,description:Le,twitter:Be,website:Ke,telegram:Ve};function Ue(n){if(typeof n!="string")return "Name must be a string.";if(!n||n.trim()==="")return "Name is required.";if(n.length<3||n.length>30)return "Name must be between 3 and 30 characters."}function Le(n){if(n){if(typeof n!="string")return "Description must be a string.";if(n&&n.length>100)return "Description must not exceed 100 characters."}}function De(n){if(typeof n!="string")return "Ticker must be a string.";if(!n||n.trim()==="")return "Ticker is required.";if(n.length<3||n.length>10)return "Ticker must be between 3 and 10 characters.";if(!/^[A-Z0-9]+$/.test(n))return "Ticker must be alphanumeric characters in uppercase only.";if(!/(?=(.*[A-Z].*[A-Z]))/.test(n))return "Ticker must have at least 2 alpha characters."}function $e(n){if(!(n==null||n==="")){if(typeof n!="string")return "Vanity ticker must be a string.";if(n.trim()!==n)return "Vanity ticker must not have leading or trailing whitespace.";if([...n].length>10)return "Vanity ticker must be below 10 characters."}}function Ne(n){if(!(n instanceof File))return "Image must be a file.";let e=["image/png","image/jpeg","image/webp","image/svg","image/gif","image/avif"],t=200*1024;if(!n)return "Image file is required.";if(!e.includes(n.type))return `Invalid file type. Allowed types are: ${e.join(", ")}`;if(n.size>t)return `File size exceeds the maximum limit of ${t/1024}KB.`}function Be(n){if(n){if(typeof n!="string")return "Twitter handle must be a string.";if(n&&!/^https?:\/\/(www\.)?(twitter\.com|x\.com)\/[A-Za-z0-9_]{1,15}\/?$/.test(n))return "Twitter must be a valid twitter URL."}}function Ke(n){if(n){if(typeof n!="string")return "Website must be a string.";if(n&&!/^(https?:\/\/)?([\w-]+(\.[\w-]+)+)(\/[\w-./?%&=]*)?$/.test(n))return "Website must be a valid URL."}}function Ve(n){if(n){if(typeof n!="string")return "Telegram must be a string.";if(n&&!/^(https?:\/\/)?(t\.me|telegram\.me|telegram\.org)\/[A-Za-z0-9_]{5,32}\/?$/.test(n))return "Telegram must be a valid telegram URL."}}function w(n,e){if(n instanceof Error&&n.name==="AxiosError"){let t=n,i=t.response?.data?.message,r=Array.isArray(i)?i.filter(s=>typeof s=="string").join("; "):typeof i=="string"?i:"";return new Error(r||t.message)}return n instanceof Error?n:new Error(e)}var $=class{_http;_baseUrl;_apiKey;constructor(e,t,i){this._http=e,this._baseUrl=t,this._apiKey=i;}async getCommunities(e,t,i={}){let r={...e};t&&(r.sort=`${t.field}:${t.direction}`),i.search!==void 0&&(r.search=i.search),i.role_in?.length&&(this.authOptions(true),r.role_in=i.role_in.join(","));let s=await this.request(()=>this._http.get(`${this._baseUrl}/communities`,{params:r,...this.authOptions(false)}),"Failed to load communities");return {...s,data:s.data.map(le)}}async getCommunity(e){let t=await this.request(()=>this._http.get(`${this._baseUrl}/community/${e}`,this.authOptions(false)),"Failed to load community");return Me(t)}async getMembers(e,t,i){let r={...t};i!==void 0&&(r.role=i);let s=await this.request(()=>this._http.get(`${this._baseUrl}/community/${e}/members`,{params:r,...this.authOptions(false)}),"Failed to load community members");return {...s,data:s.data.map(D)}}getRecommendedTokens(e,t){return this.request(()=>this._http.get(`${this._baseUrl}/community/${e}/tokens`,{params:{...t},...this.authOptions(false)}),"Failed to load recommended tokens")}getBannerImageUrl(e){return `${this._baseUrl}/community/${e}/image`}join(e){return this.request(async()=>D(await this._http.post(`${this._baseUrl}/community/${e}/join`,void 0,this.authOptions(true))),"Failed to join community")}leave(e){return this.request(async()=>{await this._http.delete(`${this._baseUrl}/community/${e}/leave`,this.authOptions(true));},"Failed to leave community")}addMember(e,t,i){return this.request(async()=>D(await this._http.post(`${this._baseUrl}/community/${e}/members/${t}`,{role:i},this.authOptions(true))),"Failed to add community member")}updateMemberRole(e,t,i){return this.request(async()=>D(await this._http.patch(`${this._baseUrl}/community/${e}/members/${t}`,{role:i},this.authOptions(true))),"Failed to update community member role")}kickMember(e,t,i){return this.request(async()=>{await this._http.post(`${this._baseUrl}/community/${e}/members/${t}/kick`,i===void 0?{}:{reason:i},this.authOptions(true));},"Failed to kick community member")}addRecommendedToken(e,t,i){return this.request(()=>this._http.post(`${this._baseUrl}/community/${e}/tokens`,i===void 0?{token:t}:{token:t,description:i},this.authOptions(true)),"Failed to add recommended token")}removeRecommendedToken(e,t){return this.request(async()=>{await this._http.delete(`${this._baseUrl}/community/${e}/tokens/${t}`,this.authOptions(true));},"Failed to remove recommended token")}authOptions(e){let t=this._apiKey();if(!t){if(e)throw new Error("API key is not set");return {}}return {headers:{Authorization:`Bearer ${t}`}}}async request(e,t){try{return await e()}catch(i){throw w(i,t)}}},je=["volume_7d","volume_30d","volume_6m","volume_total","fees_total","fees_7d","fees_30d"];function le(n){if(!n.stats)return n;let e={...n.stats};for(let t of je){let i=e[t];i!=null&&(e[t]=BigInt(i));}return {...n,stats:e}}function Me(n){return {...le(n),public_chat_threshold:pe(n.public_chat_threshold),private_chat_threshold:pe(n.private_chat_threshold)}}function pe(n){if(n==null||n==="")return null;if(typeof n=="bigint")return n;try{return BigInt(n)}catch{return null}}function D(n){return n.comment_ban?{...n,comment_ban:{...n.comment_ban,id:BigInt(n.comment_ban.id)}}:n}var A=class{_apiKey=null;_httpClient;BASE_URL;ENV;communities;constructor(e="prod"){this._httpClient=new U,this.BASE_URL=ue[e],this.ENV=e,this.communities=new $(this._httpClient,this.BASE_URL,()=>this._apiKey);}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${L[this.ENV]}/user/${e}`}async getBalances(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{...t}})).data}async getBalance(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{token_in:t}})).data.find(r=>r.id===t)??null}getTokens(e,t={field:"marketcap",direction:"desc"},i={}){return this._httpClient.get(`${this.BASE_URL}/tokens`,{params:{...e,sort:`${t.field}:${t.direction}`,...i}})}getToken(e){return this._httpClient.get(`${this.BASE_URL}/token/${e}`)}async uploadImage(e){if(!this._apiKey)throw new Error("API key is not set");try{let t=R.image?.(e);if(t)throw new Error(t);let i=new FormData;return i.append("file",e),(await this._httpClient.post(`${this.BASE_URL}/upload`,i,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})).data.upload}catch(t){throw w(t,"Image upload failed")}}async updateTokenImage(e,t){if(!this._apiKey)throw new Error("API key is not set");try{return await this._httpClient.post(`${this.BASE_URL}/token/${e}/image`,{image:t},{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})}catch(i){throw w(i,"Image update failed")}}getUserActivity(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/activity`,{params:{...t}})}async getUserTokens(e,t){let i=await this._httpClient.get(`${this.BASE_URL}/user/${e}/tokens`,{params:{...t}});return {...i,data:i.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserLiquidity(e,t){let i=await this._httpClient.get(`${this.BASE_URL}/user/${e}/liquidity`,{params:{...t}});return {...i,data:i.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserAchievements(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/achievements`,{params:{...t}})).data}getUserTransactions(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/transactions`,{params:{...t}})}getUserCreatedTokens(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/created`,{params:{...t}})}getUserStats(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}/stats`)}async verifyConnect(e){try{return await this._httpClient.post(`${this.BASE_URL}/connect/verify`,e)}catch(t){throw w(t,"Connect verification failed")}}async checkConnectSession(e){let t=this._apiKey;if(!t)throw new Error("API key is not set");try{return await this._httpClient.get(`${this.BASE_URL}/connect/session`,{params:{audience:e},headers:{Authorization:`Bearer ${t}`}}),!0}catch(i){let r=J(i);if(r===401)return false;if(r===404&&this.ENV==="legacy")return null;throw w(i,"Session check failed")}}set onUnauthorized(e){this._httpClient.onUnauthorized=e;}set apiKey(e){this._apiKey=e;}get apiKey(){return this._apiKey}};var v=class{_identity;_api;_principal;_odin;constructor(e,t,i,r){this._principal=e,this._identity=t,this._api=i,this._odin=r;}get principal(){return this._principal}set principal(e){this._principal=e;}getIdentity(){return this._identity}getUser(){return this._api.getUser(this.principal)}buildAvatarImageUrl(){return this._api.getUserAvatarUrl(this.principal)}getBalances(e){return this._api.getBalances(this.principal,e)}getBalance(e){return this._api.getBalance(this.principal,e)}getTokens(e){return this._api.getUserTokens(this.principal,e)}getCreatedTokens(e){return this._api.getUserCreatedTokens(this.principal,e)}getActivity(e){return this._api.getUserActivity(this.principal,e)}getLiquidity(e){return this._api.getUserLiquidity(this.principal,e)}getAchievements(e){return this._api.getUserAchievements(this.principal,e)}getTransactions(e){return this._api.getUserTransactions(this.principal,e)}getStats(){return this._api.getUserStats(this.principal)}sell(e){return this._odin.sell({...e,principal:this.principal})}buy(e){return this._odin.buy({...e,principal:this.principal})}addLiquidity(e){return this._odin.addLiquidity({...e,principal:this.principal})}removeLiquidity(e){return this._odin.removeLiquidity({...e,principal:this.principal})}transfer(e){return this._odin.transfer({...e,principal:this.principal})}createToken(e){return this._odin.createToken({...e,principal:this.principal})}icrcApprove(e){return this._odin.icrcApprove({...e,principal:this.principal})}swap(e){return this._odin.swap({...e,principal:this.principal})}};var G={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun",staging:"https://staging.odin.fun"};var N=class{_settings;constructor(e){this._settings={target:e?.target||"_blank",settings:e?.settings||""};}get settings(){return this._settings}set settings(e){this._settings={...this._settings,...e};}open(e){return window.open(e,this._settings?.target||"_blank",this._settings?.settings)}navigate(e){window.location.assign(e.href);}};var Fe=[/\bOKApp\b/i],ze=["XverseProviders","btc_providers","unisat","okxwallet","phantom","LeatherProvider","magicEden","wizz","oyl","ethereum","solana"];function We(n,e){return /Android|iPhone|iPad|iPod|Mobile/i.test(n)?true:/Macintosh/.test(n)&&e>1}function Je(n,e){return /Android/i.test(n)&&/;\s*wv\)/.test(n)?true:(/iPhone|iPad|iPod/i.test(n)||/Macintosh/.test(n)&&e>1)&&/AppleWebKit/i.test(n)&&!/Safari\//.test(n)}function Ge(n){return ze.some(e=>n[e]!=null)}function H(n={}){let e=n.userAgent??(typeof navigator>"u"?"":navigator.userAgent),t=n.maxTouchPoints??(typeof navigator>"u"?0:navigator.maxTouchPoints||0),i=n.globals??(typeof window>"u"?{}:window);return Fe.some(r=>r.test(e))||Je(e,t)?true:We(e,t)&&Ge(i)}var He="odin_connect",Ze=600*1e3,Z="$odin_bigint";function Xe(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?{[Z]:t.toString()}:t)}function Ye(n){return JSON.parse(n,(e,t)=>t!==null&&typeof t=="object"&&Object.keys(t).length===1&&typeof t[Z]=="string"?BigInt(t[Z]):t)}var B=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:pending_redirect`;}save(e){let t=Xe(e);try{return sessionStorage.setItem(this._key,t),sessionStorage.getItem(this._key)===t}catch{return false}}peek(){try{let e=sessionStorage.getItem(this._key);if(!e)return null;let t=Ye(e);return typeof t?.state!="string"||typeof t?.path!="string"?null:t}catch{return null}}take(){let e=this.peek();try{sessionStorage.removeItem(this._key);}catch{}return e}dropIfOlderThan(e){let t=this.peek();if(!t)return;(typeof t.createdAt=="number"?Date.now()-t.createdAt:1/0)>e&&this.take();}};function X(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(){return X(crypto.getRandomValues(new Uint8Array(24)))}function Qe(){return window.location.origin+window.location.pathname}function et(){let n=new URL(window.location.href);return n.hash="",n.href}function K(){let n=window.location.hash.replace(/^#/,"");return n?new URLSearchParams(n).get(He):null}function ge(n){let e=new URL(window.location.href);if(e.hash="",typeof n=="string")try{let t=new URL(n);t.origin===e.origin&&t.pathname===e.pathname&&(e.search=t.search);}catch{}window.history.replaceState(window.history.state,"",e.href);}function tt(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=Uint8Array.from(atob(e),r=>r.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(t));return typeof i?.path!="string"||typeof i?.state!="string"?null:i}catch{return null}}var V=class{constructor(e,t){this._window=e;this._pending=t;}_window;_pending;mode="auto";get useRedirect(){return this.mode==="redirect"||this.mode==="auto"&&H()}start(e,t,i,r){let s;try{s=this._pending.save({...t,state:i,createdAt:Date.now(),returnHref:et()});}catch{return Promise.reject(new Error("returnState must be JSON-serializable (bigints are allowed)"))}if(!s)return Promise.reject(new Error("Redirect mode needs sessionStorage, which is unavailable"));if(e.searchParams.append("return_url",Qe()),e.searchParams.append("state",i),r&&typeof window<"u"){let o=a=>{a.persisted&&(window.removeEventListener("pageshow",o),!K()&&(this._pending.peek()?.state===i&&this._pending.take(),r()));};window.addEventListener("pageshow",o);}return this._window.navigate(e),new Promise(()=>{})}consume(){let e=K();if(e===null)return this._pending.dropIfOlderThan(Ze),null;let t=tt(e),i=this._pending.take();if(!t||!i||i.state!==t.state||i.path!==t.path)throw ge(),new Error("Unexpected OdinConnect redirect result");return ge(i.returnHref),{result:t,pending:i}}};var T={buy:{path:"authorize/buy",success:"purchased",failure:"Purchase failed or was cancelled"},sell:{path:"authorize/sell",success:"sold",failure:"Sell failed or was cancelled"},transfer:{path:"authorize/transfer",success:"transferred",failure:"Transfer failed or was cancelled"},swap:{path:"authorize/swap",success:"swapped",failure:"Swap failed or was cancelled"},add_liquidity:{path:"authorize/add_liquidity",success:"addedLiquidity",failure:"Add liquidity failed or was cancelled"},remove_liquidity:{path:"authorize/remove_liquidity",success:"removedLiquidity",failure:"Remove liquidity failed or was cancelled"},icrc_approve:{path:"authorize/icrc_approve",success:"approved",failure:"ICRC approve failed or was cancelled"},create_token:{path:"authorize/create_token",success:"tokenCreated",failure:"Token creation failed or was cancelled"}};function he(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}var Q="popup_closed",ee="navigated_back",me="session_revoked",nt=/^[a-z0-9_]{1,64}$/;function M(n){let e=he(n)?.reason;return typeof e=="string"&&nt.test(e)?e:void 0}function te(n,e,t){if(e===T[n].success){let i=he(t);return {status:"success",...i?{detail:i}:{}}}if(e==="rejected"){let i=M(t);return {status:"rejected",...i?{error:i}:{}}}return {status:"failed",error:T[n].failure}}function S(n){return n.catch(()=>{}),n}var it=500,rt=1500;function ne(n,e,t,i){let r=false,s=null,o=null,a=()=>{if(!t)return true;let{request:c}=t.state;return c?.id===e&&c.status==="pending"},u=()=>{r||(r=true,clearInterval(d),o!==null&&clearTimeout(o),s?.());},d=setInterval(()=>{!n.closed||o!==null||(clearInterval(d),o=setTimeout(()=>{let c=a();u(),c&&i();},rt));},it);return s=t?.subscribe(()=>{a()||u();})??null,u}var j=class{_window;_appInfo;_api;_redirect;_store;origin;constructor(e,t,i,r,s=null,o=null){this._window=e,this._redirect=s,this._api=t,this._appInfo=i,this.origin=r,this._store=o;}get appInfo(){return this._appInfo}createUrl(e,t=C()){let i=new URL(`${this.origin}/${e}`);return i.searchParams.append("v","2"),i.searchParams.append("request_id",t),this._appInfo?.name&&i.searchParams.append("app_name",this._appInfo.name),i.searchParams.append("referrer",window.location.origin),i.searchParams.append("lang",this._appInfo?.lang||y),i}startRequest(e,t,i,r){this._store?.dispatch({type:"request",request:{id:e,action:t,status:"pending",input:i,...r!==void 0?{returnState:r}:{}}});}fail(e,t){let i=t instanceof Error?t:new Error(String(t));return this._store?.dispatch({type:"settle",id:e,status:"failed",error:i.message}),i}baseAction({action:e,input:t,params:i,returnState:r,requestId:s=C()}){let{path:o,failure:a}=T[e];this.startRequest(s,e,t,r);let u=this.createUrl(o,s);for(let d in i)i[d]&&u.searchParams.append(d,i[d]);return this._redirect?.useRedirect?S(this._redirect.start(u,{path:"/"+o,input:t,returnState:r},s,()=>this._store?.dispatch({type:"settle",id:s,status:"rejected",error:ee})).catch(d=>{throw this.fail(s,d)})):S(new Promise((d,c)=>{let f=()=>{},l=h=>{if(h.origin===this.origin&&h.data?.path==="/"+o){window.removeEventListener("message",l),f();let O=te(e,h.data.message,h.data.detail);this._store?.dispatch({type:"settle",id:s,...O}),O.status==="success"?d(true):c(new Error(a));}},g=this._window.open(u);if(!g||g.closed||typeof g.closed>"u"){c(this.fail(s,`Failed to open ${o} window, please always allow popups and try again`));return}window.addEventListener("message",l),f=ne(g,s,this._store,()=>{window.removeEventListener("message",l),this._store?.dispatch({type:"settle",id:s,status:"rejected",error:Q}),c(new Error(a));});}))}sell({token:e,tokenAmount:t,principal:i,returnState:r}){return this.baseAction({action:"sell",input:{token:e,tokenAmount:t},params:{principal:i,token:e,amount:t.toString()},returnState:r})}buy({principal:e,token:t,btcAmount:i,returnState:r}){return this.baseAction({action:"buy",input:{token:t,btcAmount:i},params:{principal:e,token:t,amount:i.toString()},returnState:r})}transfer({principal:e,token:t,amount:i,destination:r,returnState:s}){return this.baseAction({action:"transfer",input:{token:t,amount:i,destination:r},params:{principal:e,token:t,amount:i.toString(),destination:r},returnState:s})}addLiquidity({principal:e,btcAmount:t,token:i,returnState:r}){return this.baseAction({action:"add_liquidity",input:{token:i,btcAmount:t},params:{principal:e,amount:t.toString(),token:i},returnState:r})}removeLiquidity({principal:e,lpAmount:t,token:i,returnState:r}){return this.baseAction({action:"remove_liquidity",input:{token:i,lpAmount:t},params:{principal:e,amount:t.toString(),token:i},returnState:r})}swap({principal:e,fromToken:t,toToken:i,fromAmount:r,returnState:s}){return this.baseAction({action:"swap",input:{fromToken:t,toToken:i,fromAmount:r},params:{principal:e,from:t,to:i,amount:r.toString()},returnState:s})}icrcApprove({principal:e,token:t,spender:i,amount:r,returnState:s}){return this.baseAction({action:"icrc_approve",input:{token:t,spender:i,amount:r},params:{principal:e,token:t,spender:i,amount:r.toString()},returnState:s})}createToken({image:e,returnState:t,principal:i,...r}){let s=C(),o={...r};return this.startRequest(s,"create_token",o,t),S((async()=>{let a;try{for(let u in R)if(u in r){let c=R[u]?.(r[u]||null);if(c)throw new Error(c)}if(r.discount&&!/^[A-Za-z0-9]{10}$/.test(r.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");a=await this._api.uploadImage(e);}catch(u){throw this.fail(s,u)}return this.baseAction({action:"create_token",input:{...o,image:a},params:{...r,principal:i,image:a,buy:r.buy?.toString()},returnState:t,requestId:s})})())}};var F=class{_key;_checkedKey;constructor(e,t){this._key=`odin_connect:${e}:${t}:session`,this._checkedKey=`odin_connect:${e}:${t}:session_checked_at`;}lastCheckedAt(){try{let e=Number(localStorage.getItem(this._checkedKey));return Number.isFinite(e)&&e>0?e:0}catch{return 0}}markChecked(e=Date.now()){try{localStorage.setItem(this._checkedKey,String(e));}catch{}}save(e){try{localStorage.setItem(this._key,JSON.stringify(e));}catch{}}load(){try{let e=localStorage.getItem(this._key);if(!e)return null;let t=JSON.parse(e);return this.isValidSessionData(t)?t:null}catch{return null}}isValidSessionData(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.principal=="string"&&typeof t.sessionKey=="string"&&(t.delegationChain===null||typeof t.delegationChain=="string")&&(t.jwt===null||typeof t.jwt=="string")}clear(){try{localStorage.removeItem(this._key),localStorage.removeItem(this._checkedKey);}catch{}}};var m=class extends Error{constructor(e){super(`OdinConnect could not verify the connection: ${e}`),this.name="ConnectVerificationError";}};function p(n){throw new m(n)}function st(n,e){if(n.byteLength!==e.byteLength)return false;for(let t=0;t<n.byteLength;t++)if(n[t]!==e[t])return false;return true}function ot(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function at(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var ct=`odin-connect-verify:v1
|
|
2
|
+
`;async function _e(n,e){let t=await n.sign(new TextEncoder().encode(ct+e));return at(new Uint8Array(t))}function ut(n){try{if(n.delegation)return new Uint8Array(DelegationChain.fromJSON(JSON.parse(n.delegation)).publicKey);if(n.publicKey)return ot(n.publicKey)}catch{}p("the identity proof has no readable signer");}function we(n,e){(!n||typeof n.payload!="string"||typeof n.signature!="string")&&p("the result carries no identity proof");let t;try{t=JSON.parse(n.payload);}catch{p("the identity proof payload is malformed");}(t?.typ!=="odin-connect-identity"||t.v!==1&&t.v!==2)&&p("the identity proof has an unknown type"),t.v===2&&(typeof t.sid!="string"||!t.sid)&&p("the identity proof has no session id"),t.nonce!==e.nonce&&p("the identity proof belongs to another request"),t.aud!==e.audience&&p("the identity proof was issued to another origin"),t.principal!==e.principal&&p("the identity proof is for another principal"),typeof t.sk!="string"&&p("the identity proof is not bound to a session key"),t.sk!==e.sessionPubkey&&p("the identity proof was issued to another session key"),e.requires_api&&t.api!==true&&p("API access was not granted");let i=ut(n);Principal.selfAuthenticating(i).toText()!==e.principal&&p("the identity proof signer does not match the principal");}function Ce(n,e){n||p("the delegation chain is missing");let t;try{t=DelegationChain.fromJSON(n);}catch{p("the delegation chain is malformed");}t.delegations.length===0&&p("the delegation chain is empty"),_(JSON.stringify(t.toJSON()))||p("the delegation chain has expired");let i=t.delegations[t.delegations.length-1].delegation;st(new Uint8Array(i.pubkey),e.sessionPublicKey)||p("the delegation chain was issued to another session key");let r=new Uint8Array(t.publicKey);Principal.selfAuthenticating(r).toText()!==e.principal&&p("the delegation chain belongs to another principal");let s=new Set(e.targets);for(let{delegation:o}of t.delegations)o.targets?.some(a=>!s.has(a.toText()))&&p("the delegation chain targets canisters that were not requested");return t}function dt(n){return Object.isFrozen(n)?n:(Object.freeze(n.input),n.detail&&Object.freeze(n.detail),Object.freeze(n))}function E(n){let{logoutReason:e,...t}=n;return Object.freeze({...t,request:n.request?dt(n.request):null,...e&&!n.user?{logoutReason:e}:{}})}function pt(n,e){switch(e.type){case "ready":return E({status:"ready",user:n.user??e.user,request:n.request??e.request,logoutReason:n.logoutReason});case "request":return E({...n,request:{...e.request}});case "settle":{let t=n.request;if(!t||t.id!==e.id)return n;let i={...t,status:e.status,...e.detail?{detail:e.detail}:{},...e.error!==void 0?{error:e.error}:{}};return E({...n,user:e.user??n.user,request:i})}case "logout":return n.user===null&&n.logoutReason===e.reason?n:E({...n,user:null,logoutReason:e.reason});case "disconnect":return n.user===null&&n.request===null&&n.logoutReason===void 0?n:E({...n,user:null,request:null,logoutReason:void 0})}}var P=Object.freeze({status:"initializing",user:null,request:null}),z=class{_state=P;_listeners=new Set;get state(){return this._state}dispatch(e){let t=pt(this._state,e);if(t!==this._state){this._state=t;for(let i of [...this._listeners])if(this._listeners.has(i))try{i(t);}catch(r){queueMicrotask(()=>{throw r});}}}subscribe(e){let t=i=>e(i);return this._listeners.add(t),()=>{this._listeners.delete(t);}}};var I=new Map,mt=1e4,re=new Map,W=new Map,se=new Set,be=false;function Re(){if(document.visibilityState!=="hidden")for(let n of se){let e=n.deref();e?e():se.delete(n);}}function ft(n){se.add(new WeakRef(n)),!be&&(be=true,window.addEventListener("focus",Re),document.addEventListener("visibilitychange",Re));}function yt(n){let e=0;for(let t=0;t<n.length;t++)e=e*31+n.charCodeAt(t)|0;return (e>>>0).toString(36).slice(0,3).padStart(3,"0")}function ve(n){return X(new Uint8Array(n.getPublicKey().toDer()))}var _t=300*1e3;function wt(n){try{let e=n.split(".")[1],t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),i=JSON.parse(t).exp;return typeof i=="number"&&i*1e3<=Date.now()+_t}catch{return false}}function Ct(n){return `${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${yt(n)}`}var oe=class{static serverState=P;_appInfo=null;_api;_window;_odin;_storage;_redirect;_store=new z;_ready=null;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||Ct(this._appInfo.name),this._appInfo.lang=k(this._appInfo.lang),this._api=new A(this.currentEnv),this._window=new N,this._redirect=new V(this._window,new B(this._appInfo.slug,this._appInfo.env||"prod")),this._redirect.mode=this._appInfo.mode||"auto",this._odin=new j(this._window,this._api,this._appInfo,G[this._appInfo.env||"prod"],this._redirect,this._store),this._storage=new F(this._appInfo.slug,this._appInfo.env||"prod"),this._api.onUnauthorized=t=>this.endSession(t),this._store.subscribe(this.handleSessionRevoked),typeof window<"u"&&(this.ready(),ft(this.handleActivity));}createUrl(e,t=C()){let i=new URL(`${this.origin}/${e}`);return i.searchParams.append("v","2"),i.searchParams.append("request_id",t),this._appInfo?.name&&i.searchParams.append("app_name",this._appInfo.name),i.searchParams.append("referrer",window.location.origin),i.searchParams.append("lang",this.lang),i}get origin(){return G[this._appInfo?.env||"prod"]}get lang(){return this._appInfo?.lang||y}set lang(e){this._appInfo&&(this._appInfo.lang=k(e));}get mode(){return this._redirect.mode}set mode(e){this._redirect.mode=e,this._appInfo&&(this._appInfo.mode=e);}get appInfo(){return this._appInfo}get slug(){return this._appInfo?.slug||""}ready(){return typeof window>"u"?Promise.resolve(this.state):(this._ready||(this._ready=this.initialize()),this._ready.then(()=>this.state))}get state(){return this._store.state}getState=()=>this._store.state;getServerState=()=>P;subscribe=e=>this._store.subscribe(e);get user(){return this._store.state.user}initialize(){let e=this.disconnectGeneration,t=null;try{t=this.redirectOutcome(),t||this._redirect.consume();}catch{}return this.finishReady(t,e)}async finishReady(e,t){let i=null,r=null;if(e)try{let s=await e;t===this.disconnectGeneration&&(i=s.request,s.connected&&(r=this.bindConnection(s.connected)));}catch{}this._store.dispatch({type:"ready",user:r??this.loadStoredSession(),request:i}),this.checkSession();}get sessionCheckIntervalMs(){let e=this._appInfo?.sessionCheckIntervalMs;return typeof e=="number"&&Number.isFinite(e)&&e>=0?e:3e5}handleActivity=()=>{this.checkSession();};async checkSession(){if(this.state.status!=="ready"||!this.state.user)return;let e=this._api.apiKey;if(!e)return;let t=this.sessionCheckIntervalMs,i=Date.now()-this._storage.lastCheckedAt();if(t>0&&i>=0&&i<t)return;let r=this.redirectCacheKey,s=W.get(r);if(!s||s.token!==e){let o=this._api.checkConnectSession(window.location.origin).then(a=>(a!==false&&this._storage.load()?.jwt===e&&this._storage.markChecked(),a),()=>null).finally(()=>{W.get(r)?.promise===o&&W.delete(r);});s={token:e,promise:o},W.set(r,s);}await s.promise===false&&this.endSession(e);}endSession(e){this._api.apiKey===e&&(this._storage.load()?.jwt===e&&this._storage.clear(),this._api.apiKey=null,this._store.dispatch({type:"logout",reason:wt(e)?"expired":"revoked"}));}handleSessionRevoked=e=>{let{user:t,request:i}=e;if(!t||!i||i.action==="connect"||i.status!=="rejected"||i.error!==me)return;let r=this._api.apiKey;queueMicrotask(()=>{this.state.user!==t||this._api.apiKey!==r||this.revokeSession();});};revokeSession(){let e=this._storage.load();e&&e.principal===this.state.user?.principal&&e.jwt===this._api.apiKey&&this._storage.clear(),this._api.apiKey=null,this._store.dispatch({type:"logout",reason:"revoked"});}connect({open:e,requires_api:t,requires_delegation:i,targets:r,returnState:s}={requires_delegation:false,requires_api:false}){let o=Ed25519KeyIdentity.generate(),a=C(),u={requires_api:t,requires_delegation:i,targets:r},d={requires_api:!!t,requires_delegation:!!i,targets:r?[...r]:[]};this._store.dispatch({type:"request",request:{id:a,action:"connect",status:"pending",input:d,...s!==void 0?{returnState:s}:{}}});let c=this.createConnectUrl(o,a,u);return this._redirect.useRedirect?S(this._redirect.start(c,{path:"/authorize/connect",sessionKey:JSON.stringify(o.toJSON()),requires_delegation:d.requires_delegation,requires_api:d.requires_api,targets:r,returnState:s},a,()=>this._store.dispatch({type:"settle",id:a,status:"rejected",error:ee})).catch(f=>{throw this.settleError(a,"failed",f)})):(e&&(this._window.settings=e),S(new Promise((f,l)=>{let g=null,h=()=>{},O=async b=>{if(b.origin===this.origin&&b.source===g&&b.data?.path==="/authorize/connect"){if(window.removeEventListener("message",O),h(),b.data.message==="rejected"){let q=M(b.data.detail);this._store.dispatch({type:"settle",id:a,status:"rejected",...q?{error:q}:{}}),l(new Error("User rejected the connection"));return}let ae={requestId:a,...u},x;try{x=await this.verifyConnection(b.data.message,o,ae);}catch(q){l(this.settleError(a,"unverified",q));return}if(this._store.state.request?.id!==a){f(this.detachedUser(x));return}this.persistConnection(x,o,ae);let ce=this.bindConnection(x);this._store.dispatch({type:"settle",id:a,status:"success",user:ce}),f(ce);}};if(g=this._window.open(c),!g||g.closed||typeof g.closed>"u"){l(this.settleError(a,"failed",new Error("Failed to open authorize/connect window, please always allow popups and try again")));return}window.addEventListener("message",O),h=ne(g,a,this._store,()=>{window.removeEventListener("message",O),this._store.dispatch({type:"settle",id:a,status:"rejected",error:Q}),l(new Error("User rejected the connection"));});})))}settleError(e,t,i){let r=i instanceof Error?i:t==="unverified"?new m(String(i)):new Error(String(i));return this._store.dispatch({type:"settle",id:e,status:t,error:r.message}),r}createConnectUrl(e,t,{requires_api:i,requires_delegation:r,targets:s}){let o=this.createUrl("authorize/connect",t);return o.searchParams.append("requires_api",i?"1":"0"),o.searchParams.append("session_pubkey",ve(e)),o.searchParams.append("proof_v","2"),r&&(o.searchParams.append("requires_delegation","1"),o.searchParams.append("targets",s?.join(",")||"")),o}redirectOutcome(){let e=this.redirectCacheKey,t=K(),i=I.get(e);if(t!==null&&i?.fragment!==t){let r={fragment:t,promise:this.readRedirectResult(),settled:false};I.set(e,r);let s=()=>{r.settled=true,setTimeout(()=>{I.get(e)===r&&I.delete(e);},mt);};return r.promise.then(s,o=>{console.warn("OdinConnect: ignored a stale or foreign redirect result",o),s();}),r.promise}return i&&!i.settled?i.promise:null}bindConnection({principal:e,identity:t,jwt:i}){return this._api.apiKey=i,new v(e,t,this._api,this._odin)}get redirectCacheKey(){return `${this.slug}:${this.currentEnv}`}async readRedirectResult(){let e=this.disconnectGeneration,t=this._redirect.consume();if(!t)throw new Error("Unexpected OdinConnect redirect result");let{result:i,pending:r}=t,s=r.returnState!==void 0?{returnState:r.returnState}:{},o=r.path.replace(/^\/authorize\//,"");if(o==="connect"){let a={id:r.state,action:"connect",input:{requires_api:!!r.requires_api,requires_delegation:!!r.requires_delegation,targets:r.targets??[]},...s};if(i.message==="rejected"){let c=M(i.detail);return {request:{...a,status:"rejected",...c?{error:c}:{}}}}if(!r.sessionKey)return {request:{...a,status:"unverified",error:new m("the pending request has no session key").message}};let u=Ed25519KeyIdentity.fromJSON(r.sessionKey),d={requestId:r.state,requires_api:r.requires_api,requires_delegation:r.requires_delegation,targets:r.targets};try{let c=await this.verifyConnection(i.message,u,d);return e!==this.disconnectGeneration?{request:{...a,status:"success"}}:(this.persistConnection(c,u,d),{request:{...a,status:"success"},connected:c})}catch(c){return {request:{...a,status:"unverified",error:c instanceof Error?c.message:String(c)}}}}if(!(o in T))throw new Error("Unexpected OdinConnect redirect result");return {request:{id:r.state,action:o,input:r.input??{},...s,...te(o,i.message,i.detail)}}}detachedUser({principal:e,identity:t,jwt:i}){let r=new A(this.currentEnv);return r.apiKey=i,new v(e,t,r,this._odin)}get disconnectGeneration(){return re.get(this.redirectCacheKey)??0}async verifyConnection(e,t,{requestId:i,requires_api:r,requires_delegation:s,targets:o}){if(!e||typeof e.principal!="string")throw new m("the result has no principal");let{principal:a,proof:u}=e,d=window.location.origin;we(u,{principal:a,nonce:i,audience:d,requires_api:!!r,sessionPubkey:ve(t)});let c=null;s&&(c=Ce(e.delegationChain,{principal:a,sessionPublicKey:new Uint8Array(t.getPublicKey().toDer()),targets:o??[]}));let f=await _e(t,u.payload),l;try{l=await this._api.verifyConnect({payload:u.payload,signature:u.signature,delegation:u.delegation??null,publicKey:u.publicKey??null,audience:d,nonce:i,issue_jwt:!!r,client_signature:f});}catch(h){throw new m(`odin-api refused the proof (${h instanceof Error?h.message:String(h)})`)}if(l?.principal!==a)throw new m("odin-api verified a different principal");let g=null;if(r){if(typeof l.jwt!="string"||!l.jwt)throw new m("odin-api issued no API key");g=l.jwt;}return {principal:a,chain:c,identity:c?DelegationIdentity.fromDelegation(t,c):null,jwt:g}}persistConnection({principal:e,chain:t,jwt:i},r,{requires_api:s,requires_delegation:o}){this._storage.clear(),this._api.apiKey=null,(s||o)&&(this._storage.save({principal:e,sessionKey:JSON.stringify(r.toJSON()),delegationChain:t?JSON.stringify(t.toJSON()):null,jwt:i}),this._storage.markChecked());}get api(){return this._api}get odin(){return this._odin}get currentEnv(){return this._appInfo?.env||"prod"}restoreSession(){return this.state.status==="ready"?this.state.user:this.loadStoredSession()}loadStoredSession(){try{let e=this._storage.load();if(!e)return null;if(e.delegationChain&&!_(e.delegationChain))return this._storage.clear(),null;e.jwt&&(this._api.apiKey=e.jwt);let t=null;if(e.delegationChain&&e.sessionKey){let i=Ed25519KeyIdentity.fromJSON(e.sessionKey),r=DelegationChain.fromJSON(JSON.parse(e.delegationChain));t=DelegationIdentity.fromDelegation(i,r);}return new v(e.principal,t,this._api,this._odin)}catch{return this._storage.clear(),null}}disconnect(){let e=this.redirectCacheKey;re.set(e,(re.get(e)??0)+1),this._storage.clear(),this._api.apiKey=null,I.delete(e),this._store.dispatch({type:"disconnect"});}isSessionValid(){let e=this._storage.load();return e?e.delegationChain?_(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
|
|
3
|
+
export{P as INITIAL_ODIN_STATE,oe as OdinConnect,m as OdinConnectVerificationError,de as OdinUtils,H as isInAppBrowser};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odin-connect",
|
|
3
|
-
"version": "2.0
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -53,10 +53,10 @@
|
|
|
53
53
|
"@apimatic/json-bigint": "^1.2.0",
|
|
54
54
|
"@dfinity/identity": "^3.4.3",
|
|
55
55
|
"@dfinity/principal": "^3.4.3",
|
|
56
|
-
"axios": "^1.
|
|
56
|
+
"axios": "^1.20.0"
|
|
57
57
|
},
|
|
58
58
|
"overrides": {
|
|
59
|
-
"undici": "6.
|
|
59
|
+
"undici": "6.29.0",
|
|
60
60
|
"esbuild": "0.28.1"
|
|
61
61
|
},
|
|
62
62
|
"release-it": {
|
package/readme.md
CHANGED
|
@@ -17,6 +17,7 @@ A TypeScript SDK for integrating with the [Odin](https://odin.fun) decentralized
|
|
|
17
17
|
- [Wallet in-app browsers (redirect mode)](#wallet-in-app-browsers-redirect-mode)
|
|
18
18
|
- [State and sessions](#state-and-sessions)
|
|
19
19
|
- [Migrating to 2.0.0](#migrating-to-200)
|
|
20
|
+
- [Upgrading from 2.0 to 2.1](#upgrading-from-20-to-21)
|
|
20
21
|
- [Connected User Operations](#connected-user-operations)
|
|
21
22
|
- [Fetching User Data](#fetching-user-data)
|
|
22
23
|
- [Trading](#trading)
|
|
@@ -25,6 +26,7 @@ A TypeScript SDK for integrating with the [Odin](https://odin.fun) decentralized
|
|
|
25
26
|
- [Public API](#public-api)
|
|
26
27
|
- [Tokens](#tokens)
|
|
27
28
|
- [Users](#users)
|
|
29
|
+
- [Communities](#communities)
|
|
28
30
|
- [Utilities](#utilities)
|
|
29
31
|
- [Configuration](#configuration)
|
|
30
32
|
- [Types](#types)
|
|
@@ -245,9 +247,10 @@ and odin-api is asked once.
|
|
|
245
247
|
```typescript
|
|
246
248
|
const odinConnect = new OdinConnect({
|
|
247
249
|
name: "Demo App", // Your app name (shown in auth popup)
|
|
248
|
-
env: "prod", // "prod" | "dev" | "local" | "legacy"
|
|
250
|
+
env: "prod", // "prod" | "staging" | "dev" | "local" | "legacy"
|
|
249
251
|
lang: "en", // Popup UI language: "en" | "zh" (default "en")
|
|
250
252
|
mode: "auto", // "auto" (default) | "popup" | "redirect", see below
|
|
253
|
+
sessionCheckIntervalMs: 300_000, // session check interval (default 5 min), see below
|
|
251
254
|
});
|
|
252
255
|
```
|
|
253
256
|
|
|
@@ -328,7 +331,11 @@ X" (devtools, a crafted URL fragment) is rejected:
|
|
|
328
331
|
2. Odin signs an identity proof with the user's Odin identity, bound to your
|
|
329
332
|
origin (`aud`), to this request (`request_id` nonce) and to that session
|
|
330
333
|
key (`sk` = the `session_pubkey` string). The SDK rejects a proof whose
|
|
331
|
-
`sk` is missing or is not its own key.
|
|
334
|
+
`sk` is missing or is not its own key. Since 2.1.0 the SDK asks for a v2
|
|
335
|
+
proof (`proof_v=2`), which also carries the user's odin.fun session id
|
|
336
|
+
(`sid`) so odin-api can end the app's session when the user logs out on
|
|
337
|
+
odin.fun. Odin signs v1 (no `sid`) when it has no session id; the SDK
|
|
338
|
+
accepts both and rejects a v2 proof without a `sid`.
|
|
332
339
|
3. With `requires_delegation`, the SDK checks the chain locally: not expired,
|
|
333
340
|
issued to its own session key, rooted at the reported principal, and only
|
|
334
341
|
scoped to the `targets` you asked for.
|
|
@@ -490,6 +497,7 @@ type OdinState = {
|
|
|
490
497
|
status: "initializing" | "ready";
|
|
491
498
|
user: OdinConnectedUser | null;
|
|
492
499
|
request: OdinRequestState | null; // the latest request; a new one replaces it
|
|
500
|
+
logoutReason?: OdinLogoutReason; // "revoked" | "expired", see Logout on odin.fun
|
|
493
501
|
};
|
|
494
502
|
|
|
495
503
|
type OdinRequestState = {
|
|
@@ -553,6 +561,7 @@ leaves `error` unset. Popup promises still reject with the 1.6.0 text
|
|
|
553
561
|
| `missing_request_id` | No request id, or no identity, to bind the identity proof. |
|
|
554
562
|
| `unsupported_identity` | The user's wallet cannot sign the identity proof. |
|
|
555
563
|
| `no_action` | Odin has no authorize page for this action. |
|
|
564
|
+
| `session_revoked` | The user is logged out on odin.fun, so the action cannot run. The SDK logs the user out too (`state.user` becomes `null`, `state.logoutReason` is `"revoked"`); the request stays `"rejected"`. |
|
|
556
565
|
| `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
566
|
| `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
567
|
|
|
@@ -581,6 +590,54 @@ if (odinConnect.isSessionValid()) {
|
|
|
581
590
|
odinConnect.disconnect();
|
|
582
591
|
```
|
|
583
592
|
|
|
593
|
+
#### Logout on odin.fun
|
|
594
|
+
|
|
595
|
+
A stored session with an API key (`requires_api`) ends when odin-api stops
|
|
596
|
+
accepting its JWT: it expired, or the user logged out on odin.fun. The SDK
|
|
597
|
+
then logs the user out: `state.user` becomes `null` and the stored session and
|
|
598
|
+
API key are cleared, so apps that render from `state` need no code for it.
|
|
599
|
+
On `env: "legacy"` (legacy.odin.fun and odin-api `/v1`) this starts once
|
|
600
|
+
legacy.odin.fun and `/v1` support it; until then the user stays logged in
|
|
601
|
+
until a request sent with the API key is refused (even past the key's
|
|
602
|
+
expiry). Unlike `disconnect()`, `state.request` is kept, so a request in flight still
|
|
603
|
+
settles (e.g. a `createToken` whose image upload got the `401` ends as
|
|
604
|
+
`"failed"`).
|
|
605
|
+
|
|
606
|
+
- **Session check:** on page load and when the tab becomes visible or regains
|
|
607
|
+
focus, the SDK asks odin-api `GET /connect/session` whether the session is
|
|
608
|
+
still alive, at most once per `sessionCheckIntervalMs` (default 5 minutes,
|
|
609
|
+
`0` = every time). All tabs of the app share that timer. A logout on
|
|
610
|
+
odin.fun is noticed at the first load or focus after this time; nothing
|
|
611
|
+
checks while a tab just stays focused. Because the timer is shared, a
|
|
612
|
+
check in one tab also delays the next check in the others, even when they
|
|
613
|
+
hold an older session (for example after a re-connect in another tab), by
|
|
614
|
+
up to one interval.
|
|
615
|
+
- **Any API call:** a `401` on a request sent with the API key (for example
|
|
616
|
+
an image upload or a communities call) logs the user out at once.
|
|
617
|
+
- **Any action:** when Odin rejects an action with `session_revoked` (the
|
|
618
|
+
user is logged out on odin.fun), the SDK logs the user out at once, with or
|
|
619
|
+
without an API key. The request stays `"rejected"` with that `error`.
|
|
620
|
+
- Being offline, a `5xx` or a `403` is not a logout: the session is kept and
|
|
621
|
+
the next load or focus checks again. On `env: "legacy"`, a `404`
|
|
622
|
+
(odin-api `/v1` has no session check yet) is not a logout either; the SDK
|
|
623
|
+
then asks again after `sessionCheckIntervalMs`.
|
|
624
|
+
|
|
625
|
+
`state.logoutReason` says why, when the SDK logged the user out on its own:
|
|
626
|
+
`"revoked"` (the user is logged out on odin.fun: an action came back with
|
|
627
|
+
`session_revoked`, or odin-api refused a key that had not expired) or
|
|
628
|
+
`"expired"` (the key had reached its expiry time, within
|
|
629
|
+
5 minutes to allow for the device's clock). It is absent after your own
|
|
630
|
+
`disconnect()` and when a reload finds an expired stored session, cleared once
|
|
631
|
+
a user is connected again, and not persisted across reloads.
|
|
632
|
+
|
|
633
|
+
```typescript
|
|
634
|
+
odinConnect.subscribe((state) => {
|
|
635
|
+
if (state.logoutReason === "revoked") {
|
|
636
|
+
showToast("You were signed out on odin.fun");
|
|
637
|
+
}
|
|
638
|
+
});
|
|
639
|
+
```
|
|
640
|
+
|
|
584
641
|
### Custom app slug
|
|
585
642
|
|
|
586
643
|
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:
|
|
@@ -708,6 +765,34 @@ Relative to 1.6.0 and 1.7.0:
|
|
|
708
765
|
`popup_closed`) when Odin's "Back to app" or a closed popup ended it (see
|
|
709
766
|
[Rejection reasons](#rejection-reasons)).
|
|
710
767
|
|
|
768
|
+
### Upgrading from 2.0 to 2.1
|
|
769
|
+
|
|
770
|
+
2.1.0 ends the app's session when the user logs out on odin.fun. There is
|
|
771
|
+
no breaking change: `npm install odin-connect@^2.1.0` and nothing else is
|
|
772
|
+
required. What to know:
|
|
773
|
+
|
|
774
|
+
- **Upgrade before the v1 proof deadline.** 2.1 asks Odin for a v2 identity
|
|
775
|
+
proof (with the user's odin.fun session id, see
|
|
776
|
+
[Verified connect](#verified-connect)). odin-api will stop accepting v1
|
|
777
|
+
proofs on a date announced with this release (30 days after it). After
|
|
778
|
+
that date, connect fails with 2.0.x on `env` `"prod"`, `"staging"`, `"dev"`
|
|
779
|
+
and `"local"`. `"legacy"` (odin-api `/v1`) keeps accepting v1 proofs until a
|
|
780
|
+
separate date, announced later.
|
|
781
|
+
- **The SDK can log the user out on its own** (see
|
|
782
|
+
[Logout on odin.fun](#logout-on-odinfun)): `state.user` becomes `null`
|
|
783
|
+
without a call to `disconnect()`. Apps that render from `state` already
|
|
784
|
+
handle it. Code that kept its own copy of the user (or of the API key)
|
|
785
|
+
must clear it when `state.user` becomes `null`.
|
|
786
|
+
- **`state.logoutReason`** (`"revoked"` | `"expired"`, type
|
|
787
|
+
`OdinLogoutReason`) says why, so the app can show e.g. "You were signed
|
|
788
|
+
out on odin.fun". Do not start `connect()` automatically when it is set:
|
|
789
|
+
let the user sign in again.
|
|
790
|
+
- **`session_revoked`**: an action rejected because the user is logged out
|
|
791
|
+
on odin.fun ([Rejection reasons](#rejection-reasons)).
|
|
792
|
+
- **`sessionCheckIntervalMs`** (constructor option, default 5 minutes): how
|
|
793
|
+
often the SDK asks odin-api whether the session is still alive. The check
|
|
794
|
+
uses `api.odin.fun`, which the CSP must already allow since 2.0.
|
|
795
|
+
|
|
711
796
|
## Connected User Operations
|
|
712
797
|
|
|
713
798
|
Once connected, `odinConnect.user` (`state.user`) is a `ConnectedUser` with the following capabilities:
|
|
@@ -940,6 +1025,75 @@ const stats = await odinConnect.api.getUserStats(
|
|
|
940
1025
|
);
|
|
941
1026
|
```
|
|
942
1027
|
|
|
1028
|
+
### Communities
|
|
1029
|
+
|
|
1030
|
+
Communities are user accounts that opened a community page. Reads are public; when a user is connected with `requires_api: true` the SDK also sends their API key, so responses include the caller's `membership`, `chat_access` and (for owners/admins) `stats.fees_*`. Every method rejects with an `Error` carrying the API's message (for example the 403 on a private community you are not a member of), never a raw axios error.
|
|
1031
|
+
|
|
1032
|
+
```typescript
|
|
1033
|
+
// List public communities
|
|
1034
|
+
const communities = await odinConnect.api.communities.getCommunities(
|
|
1035
|
+
{ page: 1, limit: 10 }, // Pagination
|
|
1036
|
+
{ field: "member_count", direction: "desc" }, // Sort (optional)
|
|
1037
|
+
{ search: "odin" } // Filters (optional)
|
|
1038
|
+
);
|
|
1039
|
+
|
|
1040
|
+
// Communities the connected user belongs to (requires an API key)
|
|
1041
|
+
const mine = await odinConnect.api.communities.getCommunities(
|
|
1042
|
+
{ page: 1, limit: 10 },
|
|
1043
|
+
undefined,
|
|
1044
|
+
{ role_in: ["owner", "admin", "moderator", "member"] }
|
|
1045
|
+
);
|
|
1046
|
+
|
|
1047
|
+
// One community, with the caller's membership and chat access
|
|
1048
|
+
const community = await odinConnect.api.communities.getCommunity(principal);
|
|
1049
|
+
community.membership; // "owner" | "admin" | "moderator" | "member" | null
|
|
1050
|
+
community.chat_access.private.can_post; // boolean
|
|
1051
|
+
community.public_chat_threshold; // bigint (msats) or null
|
|
1052
|
+
|
|
1053
|
+
// Members (newest first), optionally filtered by role
|
|
1054
|
+
const members = await odinConnect.api.communities.getMembers(
|
|
1055
|
+
principal,
|
|
1056
|
+
{ page: 1, limit: 20 },
|
|
1057
|
+
"moderator"
|
|
1058
|
+
);
|
|
1059
|
+
|
|
1060
|
+
// Tokens the community recommends
|
|
1061
|
+
const picks = await odinConnect.api.communities.getRecommendedTokens(
|
|
1062
|
+
principal,
|
|
1063
|
+
{ page: 1, limit: 20 }
|
|
1064
|
+
);
|
|
1065
|
+
|
|
1066
|
+
// Banner image URL
|
|
1067
|
+
const banner = odinConnect.api.communities.getBannerImageUrl(principal);
|
|
1068
|
+
```
|
|
1069
|
+
|
|
1070
|
+
**Available sort fields:** `member_count`, `volume_7d`, `volume_30d`, `volume_6m`, `volume_total`, `power_users_7d`, `power_users_30d`, `power_users_6m`, `power_users_total`, `users_7d`, `users_30d`, `users_6m`, `users_total` (`fees_*` sorts are only honoured for platform admins)
|
|
1071
|
+
|
|
1072
|
+
**Available filters:**
|
|
1073
|
+
|
|
1074
|
+
| Filter | Type | Description |
|
|
1075
|
+
|--------|------|-------------|
|
|
1076
|
+
| `search` | `string` | Match username, bio or principal (max 128 chars) |
|
|
1077
|
+
| `role_in` | `OdinCommunityRole[]` | Only communities where the connected user holds one of these roles. Requires an API key (rejects with `"API key is not set"` otherwise); an empty array means no role filter. |
|
|
1078
|
+
|
|
1079
|
+
#### Member actions
|
|
1080
|
+
|
|
1081
|
+
These require the user to be connected with `requires_api: true` (the SDK sends the API key as a Bearer token) and reject with the API's error message otherwise (`"API key is not set"`, `"Already a member"`, ...). Role changes follow the hierarchy `owner > admin > moderator > member`: you can only act on roles below your own, and `owner` is never assignable.
|
|
1082
|
+
|
|
1083
|
+
```typescript
|
|
1084
|
+
const c = odinConnect.api.communities;
|
|
1085
|
+
|
|
1086
|
+
await c.join(principal); // public communities only
|
|
1087
|
+
await c.leave(principal); // the owner cannot leave
|
|
1088
|
+
await c.addMember(principal, userPrincipal, "moderator"); // owner/admin
|
|
1089
|
+
await c.updateMemberRole(principal, userPrincipal, "admin");
|
|
1090
|
+
await c.kickMember(principal, userPrincipal, "spam"); // admin+, reason optional
|
|
1091
|
+
await c.addRecommendedToken(principal, "2jjj", "Our token"); // owner/moderator
|
|
1092
|
+
await c.removeRecommendedToken(principal, "2jjj");
|
|
1093
|
+
```
|
|
1094
|
+
|
|
1095
|
+
Not covered yet: enabling/editing a community profile (multipart banner upload) and community chat (`/comments` with `context_type=community`).
|
|
1096
|
+
|
|
943
1097
|
## Utilities
|
|
944
1098
|
|
|
945
1099
|
OdinConnect exports utility functions under `OdinUtils`:
|
|
@@ -976,6 +1130,7 @@ OdinUtils.createTokenValidators.telegram("https://t.me/...");
|
|
|
976
1130
|
| Environment | Frontend URL | API Base URL |
|
|
977
1131
|
|-------------|-------------|-------------|
|
|
978
1132
|
| `prod` (default) | `https://odin.fun` | `https://api.odin.fun/v2` |
|
|
1133
|
+
| `staging` | `https://staging.odin.fun` | `https://api.odin.fun/v2` |
|
|
979
1134
|
| `dev` | `https://dev.odin.fun` | `https://api.odin.fun/dev` |
|
|
980
1135
|
| `local` | `http://localhost:5173` | `https://api.odin.fun/dev` |
|
|
981
1136
|
| `legacy` | `https://legacy.odin.fun` | `https://api.odin.fun/v1` |
|
|
@@ -1002,6 +1157,19 @@ import type {
|
|
|
1002
1157
|
OdinTransaction,
|
|
1003
1158
|
OdinAchievement,
|
|
1004
1159
|
OdinAchievementCategory,
|
|
1160
|
+
OdinCommunity,
|
|
1161
|
+
OdinCommunityListItem,
|
|
1162
|
+
OdinCommunityDetail,
|
|
1163
|
+
OdinCommunityProfile,
|
|
1164
|
+
OdinCommunityStats,
|
|
1165
|
+
OdinCommunityRole,
|
|
1166
|
+
OdinCommunityMember,
|
|
1167
|
+
OdinCommunityMemberBan,
|
|
1168
|
+
OdinCommunityRecommendedToken,
|
|
1169
|
+
OdinChatAccess,
|
|
1170
|
+
OdinChatAccessDenialReason,
|
|
1171
|
+
OdinCommunitySortableFields,
|
|
1172
|
+
OdinCommunityFilterFields,
|
|
1005
1173
|
OdinConnectedUser,
|
|
1006
1174
|
OdinState,
|
|
1007
1175
|
OdinRequestState,
|
|
@@ -1010,6 +1178,7 @@ import type {
|
|
|
1010
1178
|
OdinAction,
|
|
1011
1179
|
OdinActionDetail,
|
|
1012
1180
|
OdinRejectReason,
|
|
1181
|
+
OdinLogoutReason,
|
|
1013
1182
|
SessionData,
|
|
1014
1183
|
} from "odin-connect";
|
|
1015
1184
|
```
|