odin-connect 1.5.0 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +141 -4
- package/dist/index.js +2 -2
- package/package.json +2 -1
- package/readme.md +76 -0
package/dist/index.d.ts
CHANGED
|
@@ -210,6 +210,76 @@ declare class WindowClient {
|
|
|
210
210
|
get settings(): Partial<WindowClientSettings>;
|
|
211
211
|
set settings(settings: Partial<WindowClientSettings>);
|
|
212
212
|
open(url: URL): Window | null;
|
|
213
|
+
/** Navigate the current tab (redirect mode). */
|
|
214
|
+
navigate(url: URL): void;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* How the SDK reaches the Odin authorize pages, for `connect()` and actions.
|
|
219
|
+
* - `"popup"` (default): `window.open` + `postMessage`.
|
|
220
|
+
* - `"redirect"`: navigate this tab to Odin and back. For wallet in-app
|
|
221
|
+
* browsers (OKX) that open popups without `window.opener`. The returned
|
|
222
|
+
* promise never settles because the page unloads; read the result with
|
|
223
|
+
* `handleRedirectResult()` when the app loads again.
|
|
224
|
+
* - `"auto"`: `"redirect"` inside a wallet in-app browser or app webview
|
|
225
|
+
* (see `isInAppBrowser()`), else `"popup"`.
|
|
226
|
+
*/
|
|
227
|
+
type ConnectMode = "popup" | "redirect" | "auto";
|
|
228
|
+
interface PendingRedirect {
|
|
229
|
+
state: string;
|
|
230
|
+
/** Authorize path, e.g. `/authorize/connect` or `/authorize/buy`. */
|
|
231
|
+
path: string;
|
|
232
|
+
/** Action message that means success (e.g. `"purchased"`). */
|
|
233
|
+
successMessage?: string;
|
|
234
|
+
/** connect only */
|
|
235
|
+
sessionKey?: string;
|
|
236
|
+
/** connect only */
|
|
237
|
+
requires_delegation?: boolean;
|
|
238
|
+
}
|
|
239
|
+
interface RedirectResult {
|
|
240
|
+
path: string;
|
|
241
|
+
message: unknown;
|
|
242
|
+
state: string;
|
|
243
|
+
}
|
|
244
|
+
declare class PendingRedirectStorage {
|
|
245
|
+
private _key;
|
|
246
|
+
constructor(slug: string, env: string);
|
|
247
|
+
/** Save and read back; false when sessionStorage is unusable. */
|
|
248
|
+
save(pending: PendingRedirect): boolean;
|
|
249
|
+
/** Load without deleting. */
|
|
250
|
+
peek(): PendingRedirect | null;
|
|
251
|
+
/** Load and delete (single-use). */
|
|
252
|
+
take(): PendingRedirect | null;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Owns the mode and the pending request for one `OdinConnect` instance, so
|
|
256
|
+
* `connect()` and the canister actions share one redirect implementation.
|
|
257
|
+
*/
|
|
258
|
+
declare class RedirectClient {
|
|
259
|
+
private _window;
|
|
260
|
+
private _pending;
|
|
261
|
+
mode: ConnectMode;
|
|
262
|
+
constructor(_window: WindowClient, _pending: PendingRedirectStorage);
|
|
263
|
+
/** Whether the next authorize request should redirect instead of popup. */
|
|
264
|
+
get useRedirect(): boolean;
|
|
265
|
+
/**
|
|
266
|
+
* Save the pending request, then navigate this tab to `url` with
|
|
267
|
+
* `return_url` + `state`. The returned promise never settles (the page
|
|
268
|
+
* unloads) unless sessionStorage is unusable, in which case it rejects
|
|
269
|
+
* before navigating.
|
|
270
|
+
*/
|
|
271
|
+
start<T>(url: URL, pending: Omit<PendingRedirect, "state">): Promise<T>;
|
|
272
|
+
/** Path of the pending request when the URL carries its result. */
|
|
273
|
+
pendingPath(): string | null;
|
|
274
|
+
/**
|
|
275
|
+
* Consume the URL's redirect result and its pending request. Returns null
|
|
276
|
+
* when the URL carries no result; throws when the result does not match
|
|
277
|
+
* the pending request (stale, foreign or replayed).
|
|
278
|
+
*/
|
|
279
|
+
consume(): {
|
|
280
|
+
result: RedirectResult;
|
|
281
|
+
pending: PendingRedirect;
|
|
282
|
+
} | null;
|
|
213
283
|
}
|
|
214
284
|
|
|
215
285
|
interface SellOptions {
|
|
@@ -255,6 +325,7 @@ interface CreateTokenParams {
|
|
|
255
325
|
name: string;
|
|
256
326
|
ticker: string;
|
|
257
327
|
image: File;
|
|
328
|
+
vanity_ticker?: string;
|
|
258
329
|
description?: string;
|
|
259
330
|
website?: string;
|
|
260
331
|
twitter?: string;
|
|
@@ -266,8 +337,9 @@ declare class OdinCanisterClient {
|
|
|
266
337
|
private _window;
|
|
267
338
|
private _appInfo;
|
|
268
339
|
private _api;
|
|
340
|
+
private _redirect;
|
|
269
341
|
origin: string;
|
|
270
|
-
constructor(windowClient: WindowClient, apiClient: OdinApiClient, appInfo: AppInitOptions, origin: string);
|
|
342
|
+
constructor(windowClient: WindowClient, apiClient: OdinApiClient, appInfo: AppInitOptions, origin: string, redirectClient?: RedirectClient | null);
|
|
271
343
|
get appInfo(): AppInitOptions;
|
|
272
344
|
private createUrl;
|
|
273
345
|
private baseAction;
|
|
@@ -361,12 +433,34 @@ declare const ORIGINS: {
|
|
|
361
433
|
};
|
|
362
434
|
type Environment = keyof typeof ORIGINS;
|
|
363
435
|
|
|
436
|
+
type OdinLang = "en" | "zh";
|
|
437
|
+
|
|
364
438
|
interface AppInitOptions {
|
|
365
439
|
name: string;
|
|
366
440
|
icon?: string;
|
|
367
441
|
env?: Environment;
|
|
368
442
|
slug?: string;
|
|
443
|
+
lang?: OdinLang;
|
|
444
|
+
/**
|
|
445
|
+
* How `connect()` and every action reach Odin: `"popup"` (default),
|
|
446
|
+
* `"redirect"` or `"auto"`. See `ConnectMode`.
|
|
447
|
+
*/
|
|
448
|
+
mode?: ConnectMode;
|
|
369
449
|
}
|
|
450
|
+
/** Authorize actions that can come back through `handleRedirectResult()`. */
|
|
451
|
+
type OdinAction = "buy" | "sell" | "transfer" | "swap" | "add_liquidity" | "remove_liquidity" | "icrc_approve" | "create_token";
|
|
452
|
+
/** What `handleRedirectResult()` found in the URL after a redirect. */
|
|
453
|
+
type OdinRedirectResult = {
|
|
454
|
+
action: "connect";
|
|
455
|
+
status: "connected";
|
|
456
|
+
user: ConnectedUser;
|
|
457
|
+
} | {
|
|
458
|
+
action: "connect";
|
|
459
|
+
status: "rejected";
|
|
460
|
+
} | {
|
|
461
|
+
action: OdinAction;
|
|
462
|
+
status: "success" | "failed";
|
|
463
|
+
};
|
|
370
464
|
interface BaseConnectOptions {
|
|
371
465
|
open?: WindowClientSettings;
|
|
372
466
|
requires_api?: boolean;
|
|
@@ -387,12 +481,32 @@ declare class Connect {
|
|
|
387
481
|
private _window;
|
|
388
482
|
private _odin;
|
|
389
483
|
private _storage;
|
|
484
|
+
private _redirect;
|
|
390
485
|
constructor(appInfo?: Partial<AppInitOptions>);
|
|
391
486
|
private createUrl;
|
|
392
487
|
get origin(): string;
|
|
488
|
+
get lang(): OdinLang;
|
|
489
|
+
set lang(value: OdinLang);
|
|
490
|
+
/** Current mode for `connect()` and actions; can be changed at runtime. */
|
|
491
|
+
get mode(): ConnectMode;
|
|
492
|
+
set mode(value: ConnectMode);
|
|
393
493
|
get appInfo(): AppInitOptions | null;
|
|
394
494
|
get slug(): string;
|
|
395
495
|
connect({ open, requires_api, requires_delegation, targets, }?: ConnectOptions | undefined): Promise<ConnectedUser>;
|
|
496
|
+
private createConnectUrl;
|
|
497
|
+
private connectByRedirect;
|
|
498
|
+
/**
|
|
499
|
+
* Read the result of a redirect-mode `connect()` or action after Odin sends
|
|
500
|
+
* the user back. Call once on page load. Returns null when the URL carries
|
|
501
|
+
* no redirect result; throws when the result does not match the pending
|
|
502
|
+
* request (stale, foreign or replayed).
|
|
503
|
+
*
|
|
504
|
+
* A successful connect is also persisted like a popup connect, and
|
|
505
|
+
* `restoreSession()` handles connect results itself, so call this first if
|
|
506
|
+
* you need to tell "rejected" from "not connected" or read action results.
|
|
507
|
+
*/
|
|
508
|
+
handleRedirectResult(): OdinRedirectResult | null;
|
|
509
|
+
private completeConnection;
|
|
396
510
|
get api(): OdinApiClient;
|
|
397
511
|
get odin(): OdinCanisterClient;
|
|
398
512
|
get currentEnv(): "legacy" | "dev" | "prod" | "local";
|
|
@@ -402,6 +516,24 @@ declare class Connect {
|
|
|
402
516
|
hello(): void;
|
|
403
517
|
}
|
|
404
518
|
|
|
519
|
+
/**
|
|
520
|
+
* Best-effort detection of wallet in-app browsers and app webviews, where
|
|
521
|
+
* `window.open` targets load as a detached page with no `window.opener`, so a
|
|
522
|
+
* popup's `postMessage` result never reaches the app.
|
|
523
|
+
* `new OdinConnect({ mode: "auto" })` uses redirect mode when this is true.
|
|
524
|
+
*
|
|
525
|
+
* Redirect mode works in every browser, so this errs toward true: a false
|
|
526
|
+
* positive costs a page reload, a miss leaves Authorize doing nothing.
|
|
527
|
+
*/
|
|
528
|
+
interface InAppBrowserEnv {
|
|
529
|
+
userAgent?: string;
|
|
530
|
+
/** Checked for injected wallet globals. */
|
|
531
|
+
globals?: object;
|
|
532
|
+
/** Distinguishes iPadOS (which reports a Mac user agent) from macOS. */
|
|
533
|
+
maxTouchPoints?: number;
|
|
534
|
+
}
|
|
535
|
+
declare function isInAppBrowser(env?: InAppBrowserEnv): boolean;
|
|
536
|
+
|
|
405
537
|
declare const IMAGE_CDN_ENV: {
|
|
406
538
|
dev: string;
|
|
407
539
|
prod: string;
|
|
@@ -412,6 +544,9 @@ type OdinEnv = keyof typeof IMAGE_CDN_ENV;
|
|
|
412
544
|
|
|
413
545
|
declare function isDelegationValid(chainJson: string): boolean;
|
|
414
546
|
|
|
547
|
+
declare const DEFAULT_LANG: OdinLang;
|
|
548
|
+
declare function normalizeOdinLang(value?: string): OdinLang;
|
|
549
|
+
|
|
415
550
|
/**
|
|
416
551
|
* Build a token's image URL from its id using the env-aware image CDN.
|
|
417
552
|
* @param tokenId Token id (e.g. `Token.id`).
|
|
@@ -420,14 +555,16 @@ declare function isDelegationValid(chainJson: string): boolean;
|
|
|
420
555
|
declare function buildTokenImageUrl(tokenId: string, env?: OdinEnv): string;
|
|
421
556
|
declare function convertToOdinAmount(numberStr: string | number, token?: Pick<BaseToken, "decimals" | "divisibility">): bigint;
|
|
422
557
|
type TokenValue = string | File | null | bigint;
|
|
423
|
-
declare const createTokenValidators: Partial<Record<keyof Token, (value: TokenValue) => string | undefined>>;
|
|
558
|
+
declare const createTokenValidators: Partial<Record<keyof Token | "vanity_ticker", (value: TokenValue) => string | undefined>>;
|
|
424
559
|
|
|
560
|
+
declare const index_DEFAULT_LANG: typeof DEFAULT_LANG;
|
|
425
561
|
declare const index_buildTokenImageUrl: typeof buildTokenImageUrl;
|
|
426
562
|
declare const index_convertToOdinAmount: typeof convertToOdinAmount;
|
|
427
563
|
declare const index_createTokenValidators: typeof createTokenValidators;
|
|
428
564
|
declare const index_isDelegationValid: typeof isDelegationValid;
|
|
565
|
+
declare const index_normalizeOdinLang: typeof normalizeOdinLang;
|
|
429
566
|
declare namespace index {
|
|
430
|
-
export { index_buildTokenImageUrl as buildTokenImageUrl, index_convertToOdinAmount as convertToOdinAmount, index_createTokenValidators as createTokenValidators, index_isDelegationValid as isDelegationValid };
|
|
567
|
+
export { index_DEFAULT_LANG as DEFAULT_LANG, index_buildTokenImageUrl as buildTokenImageUrl, index_convertToOdinAmount as convertToOdinAmount, index_createTokenValidators as createTokenValidators, index_isDelegationValid as isDelegationValid, index_normalizeOdinLang as normalizeOdinLang };
|
|
431
568
|
}
|
|
432
569
|
|
|
433
570
|
interface SessionData {
|
|
@@ -437,4 +574,4 @@ interface SessionData {
|
|
|
437
574
|
jwt: string | null;
|
|
438
575
|
}
|
|
439
576
|
|
|
440
|
-
export { type Achievement as OdinAchievement, type AchievementCategory as OdinAchievementCategory, type Activity as OdinActivity, type Balance as OdinBalance, type BaseToken as OdinBaseToken, Connect as OdinConnect, ConnectedUser as OdinConnectedUser, type Token as OdinToken, type TokenWithBalance as OdinTokenWithBalance, type Transaction as OdinTransaction, type User as OdinUser, index as OdinUtils, type SessionData };
|
|
577
|
+
export { type Achievement as OdinAchievement, type AchievementCategory as OdinAchievementCategory, type OdinAction, type Activity as OdinActivity, type Balance as OdinBalance, type BaseToken as OdinBaseToken, Connect as OdinConnect, type ConnectMode as OdinConnectMode, ConnectedUser as OdinConnectedUser, type OdinLang, type OdinRedirectResult, 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,2 +1,2 @@
|
|
|
1
|
-
import $ from'axios';import L from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';var P=Object.defineProperty;var B=(i,e)=>{for(var t in e)P(i,t,{get:e[t],enumerable:true});};var D=i=>{try{return L.parse(i)}catch(e){return console.error("Error parsing response:",e),i}},m=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let n={transformResponse:[D],...t};return (await $(e,n)).data}async post(e,t,n){return this.fetch(e,{method:"POST",data:t,...n})}async put(e,t,n){return this.fetch(e,{method:"PUT",data:t,...n})}async delete(e,t){return this.fetch(e,{method:"DELETE",...t})}};var E={};B(E,{buildTokenImageUrl:()=>N,convertToOdinAmount:()=>V,createTokenValidators:()=>c,isDelegationValid:()=>u});var S={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1"},f={dev:"https://images.odin.fun/dev",prod:"https://images.odin.fun/v2",local:"https://images.odin.fun/dev",legacy:"https://images.odin.fun"};function u(i){try{let e=DelegationChain.fromJSON(JSON.parse(i)),t=BigInt(Date.now())*1000000n;return e.delegations.every(n=>n.delegation.expiration==null||n.delegation.expiration>t)}catch{return false}}function N(i,e="prod"){return `${f[e]}/token/${i}`}function V(i,e={decimals:3,divisibility:8}){let t=e.decimals+e.divisibility;if(i=typeof i=="string"?i.trim():String(i),isNaN(+i))return 0n;let[n,r=""]=i.split(".");return r=r.slice(0,t),r=r.padEnd(t,"0"),n=n.replace(/^0+(?=\d)/,""),n===""&&(n="0"),BigInt(n+r)}var c={name:F,image:W,ticker:K,description:z,twitter:J,website:M,telegram:j};function F(i){if(typeof i!="string")return "Name must be a string.";if(!i||i.trim()==="")return "Name is required.";if(i.length<3||i.length>30)return "Name must be between 3 and 30 characters."}function z(i){if(i){if(typeof i!="string")return "Description must be a string.";if(i&&i.length>100)return "Description must not exceed 100 characters."}}function K(i){if(typeof i!="string")return "Ticker must be a string.";if(!i||i.trim()==="")return "Ticker is required.";if(i.length<3||i.length>10)return "Ticker must be between 3 and 10 characters.";if(!/^[A-Z0-9]+$/.test(i))return "Ticker must be alphanumeric characters in uppercase only.";if(!/(?=(.*[A-Z].*[A-Z]))/.test(i))return "Ticker must have at least 2 alpha characters."}function W(i){if(!(i 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(!i)return "Image file is required.";if(!e.includes(i.type))return `Invalid file type. Allowed types are: ${e.join(", ")}`;if(i.size>t)return `File size exceeds the maximum limit of ${t/1024}KB.`}function J(i){if(i){if(typeof i!="string")return "Twitter handle must be a string.";if(i&&!/^https?:\/\/(www\.)?(twitter\.com|x\.com)\/[A-Za-z0-9_]{1,15}\/?$/.test(i))return "Twitter must be a valid twitter URL."}}function M(i){if(i){if(typeof i!="string")return "Website must be a string.";if(i&&!/^(https?:\/\/)?([\w-]+(\.[\w-]+)+)(\/[\w-./?%&=]*)?$/.test(i))return "Website must be a valid URL."}}function j(i){if(i){if(typeof i!="string")return "Telegram must be a string.";if(i&&!/^(https?:\/\/)?(t\.me|telegram\.me|telegram\.org)\/[A-Za-z0-9_]{5,32}\/?$/.test(i))return "Telegram must be a valid telegram URL."}}var y=class{_apiKey=null;_httpClient;BASE_URL;ENV;constructor(e="prod"){this._httpClient=new m,this.BASE_URL=S[e],this.ENV=e;}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${f[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"},n={}){return this._httpClient.get(`${this.BASE_URL}/tokens`,{params:{...e,sort:`${t.field}:${t.direction}`,...n}})}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=c.image?.(e);if(t)throw new Error(t);let n=new FormData;return n.append("file",e),(await this._httpClient.post(`${this.BASE_URL}/upload`,n,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})).data.upload}catch(t){if(t instanceof Error)if(t.name==="AxiosError"){let n=t;throw new Error(n.response?.data?.message||n.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(n){if(n instanceof Error&&n.name==="AxiosError"){let r=n;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 n=await this._httpClient.get(`${this.BASE_URL}/user/${e}/tokens`,{params:{...t}});return {...n,data:n.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserLiquidity(e,t){let n=await this._httpClient.get(`${this.BASE_URL}/user/${e}/liquidity`,{params:{...t}});return {...n,data:n.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`)}set apiKey(e){this._apiKey=e;}get apiKey(){return this._apiKey}};var g=class{_identity;_api;_principal;_odin;constructor(e,t,n,r){this._principal=e,this._identity=t,this._api=n,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 O={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun"};var _=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)}};var w=class{_window;_appInfo;_api;origin;constructor(e,t,n,r){this._window=e,this._api=t,this._appInfo=n,this.origin=r;}get appInfo(){return this._appInfo}createUrl(e){let t=new URL(`${this.origin}/${e}`);return this._appInfo?.name&&t.searchParams.append("app_name",this._appInfo.name),t.searchParams.append("referrer",window.location.origin),t}baseAction({params:e,odinPath:t,receivedMessageFromOrigin:n,resolve:r}){return new Promise((p,l)=>{let a=async s=>{s.origin===this.origin&&s.data.path==="/"+t&&(window.removeEventListener("message",a),(typeof n=="function"?n(s.data.message):n===s.data.message)?p(r.success(s.data.message)):l(new Error(r.failure)));},d=this.createUrl(t);for(let s in e)e[s]&&d.searchParams.append(s,e[s]);let o=this._window.open(d);if(!o||o.closed||typeof o.closed>"u"){l(new Error(r.didnotopen??`Failed to open ${t} window, please always allow popups and try again`));return}window.addEventListener("message",a);})}sell({token:e,tokenAmount:t,principal:n}){return this.baseAction({params:{principal:n,token:e,amount:t.toString()},odinPath:"authorize/sell",receivedMessageFromOrigin:"sold",resolve:{success:()=>true,failure:"Sell failed or was cancelled",close:"User closed the window"}})}buy({principal:e,token:t,btcAmount:n}){return this.baseAction({params:{principal:e,token:t,amount:n.toString()},odinPath:"authorize/buy",receivedMessageFromOrigin:"purchased",resolve:{success:()=>true,failure:"Purchase failed or was cancelled",close:"User closed the window"}})}transfer({principal:e,token:t,amount:n,destination:r}){return this.baseAction({params:{principal:e,token:t,amount:n.toString(),destination:r},odinPath:"authorize/transfer",receivedMessageFromOrigin:"transferred",resolve:{success:()=>true,failure:"Transfer failed or was cancelled",close:"User closed the window"}})}addLiquidity({principal:e,btcAmount:t,token:n}){return this.baseAction({params:{principal:e,amount:t.toString(),token:n},odinPath:"authorize/add_liquidity",receivedMessageFromOrigin:"addedLiquidity",resolve:{success:()=>true,failure:"Add liquidity failed or was cancelled",close:"User closed the window"}})}removeLiquidity({principal:e,lpAmount:t,token:n}){return this.baseAction({params:{principal:e,amount:t.toString(),token:n},odinPath:"authorize/remove_liquidity",receivedMessageFromOrigin:"removedLiquidity",resolve:{success:()=>true,failure:"Remove liquidity failed or was cancelled",close:"User closed the window"}})}swap({principal:e,fromToken:t,toToken:n,fromAmount:r}){return this.baseAction({params:{principal:e,from:t,to:n,amount:r.toString()},odinPath:"authorize/swap",receivedMessageFromOrigin:"swapped",resolve:{success:()=>true,failure:"Swap failed or was cancelled",close:"User closed the window"}})}icrcApprove({principal:e,token:t,spender:n,amount:r}){return this.baseAction({params:{principal:e,token:t,spender:n,amount:r.toString()},odinPath:"authorize/icrc_approve",receivedMessageFromOrigin:"approved",resolve:{success:()=>true,failure:"ICRC approve failed or was cancelled",close:"User closed the window"}})}async createToken({image:e,...t}){for(let p in c)if(p in t){let a=c[p]?.(t[p]||null);if(a)throw new Error(a)}if(t.discount&&!/^[A-Za-z0-9]{10}$/.test(t.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");let n=await this._api.uploadImage(e);if(!await this.baseAction({params:{...t,image:n,buy:t.buy?.toString()},odinPath:"authorize/create_token",receivedMessageFromOrigin:"tokenCreated",resolve:{success:()=>true,failure:"Token creation failed or was cancelled",close:"User closed the window"}}))throw new Error("Token creation failed. Please try again.");return true}};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{}}};function G(i){let e=0;for(let t=0;t<i.length;t++)e=e*31+i.charCodeAt(t)|0;return (e>>>0).toString(36).slice(0,3).padStart(3,"0")}function Z(i){return `${i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${G(i)}`}var b=class{_appInfo=null;_api;_window;_odin;_storage;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||Z(this._appInfo.name),this._api=new y(this._appInfo.env==="prod"?"prod":this._appInfo.env==="legacy"?"legacy":"dev"),this._window=new _,this._odin=new w(this._window,this._api,this._appInfo,O[this._appInfo.env||"prod"]),this._storage=new v(this._appInfo.slug,this._appInfo.env||"prod");}createUrl(e){let t=new URL(`${this.origin}/${e}`);return this._appInfo?.name&&t.searchParams.append("app_name",this._appInfo.name),t.searchParams.append("referrer",window.location.origin),t}get origin(){return O[this._appInfo?.env||"prod"]}get appInfo(){return this._appInfo}get slug(){return this._appInfo?.slug||""}connect({open:e,requires_api:t,requires_delegation:n,targets:r}={requires_delegation:false,requires_api:false}){return new Promise((p,l)=>{e&&(this._window.settings=e);let a=Ed25519KeyIdentity.generate(),d=async s=>{if(s.origin===this.origin&&s.data.path==="/authorize/connect")if(window.removeEventListener("message",d),s.data.message!="rejected"){let T;try{let C=s.data.message,{principal:A,jwt:k,delegationChain:h}=C;if(t&&(this._api.apiKey=k),n){if(!h)throw new Error("Delegation chain is missing");let x=DelegationIdentity.fromDelegation(a,DelegationChain.fromJSON(h));T=new g(A,x,this.api,this._odin);}else T=new g(A,null,this.api,this._odin);(t||n)&&this._storage.save({principal:A,sessionKey:JSON.stringify(a.toJSON()),delegationChain:h?JSON.stringify(h):null,jwt:k||null}),p(T);}catch{l(new Error("Failed to fetch user data"));}}else l(new Error("User rejected the connection"));},o=this.createUrl("authorize/connect");if(o.searchParams.append("requires_api",t?"1":"0"),n){o.searchParams.append("requires_delegation","1");let s=btoa(JSON.stringify(a.toJSON()));o.searchParams.append("session_key",s),o.searchParams.append("targets",r?.join(",")||"");}this._window.open(o),window.addEventListener("message",d);})}get api(){return this._api}get odin(){return this._odin}get currentEnv(){return this._appInfo?.env||"prod"}restoreSession(){try{let e=this._storage.load();if(!e)return null;if(e.delegationChain&&!u(e.delegationChain))return this._storage.clear(),null;e.jwt&&(this._api.apiKey=e.jwt);let t=null;if(e.delegationChain&&e.sessionKey){let n=Ed25519KeyIdentity.fromJSON(e.sessionKey),r=DelegationChain.fromJSON(JSON.parse(e.delegationChain));t=DelegationIdentity.fromDelegation(n,r);}return new g(e.principal,t,this._api,this._odin)}catch{return this._storage.clear(),null}}disconnect(){this._storage.clear(),this._api.apiKey=null;}isSessionValid(){let e=this._storage.load();return e?e.delegationChain?u(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
|
|
2
|
-
export{
|
|
1
|
+
import $ from'axios';import q from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';var L=Object.defineProperty;var B=(n,e)=>{for(var t in e)L(n,t,{get:e[t],enumerable:true});};var D=n=>{try{return q.parse(n)}catch(e){return console.error("Error parsing response:",e),n}},f=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let i={transformResponse:[D],...t};return (await $(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 U={};B(U,{DEFAULT_LANG:()=>c,buildTokenImageUrl:()=>V,convertToOdinAmount:()=>z,createTokenValidators:()=>d,isDelegationValid:()=>h,normalizeOdinLang:()=>m});var S={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1"},y={dev:"https://images.odin.fun/dev",prod:"https://images.odin.fun/v2",local:"https://images.odin.fun/dev",legacy:"https://images.odin.fun"};function h(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 c="en";function m(n){return n==="en"||n==="zh"?n:(n!==void 0&&console.warn(`[odin-connect] Unsupported lang "${n}", falling back to "${c}"`),c)}function V(n,e="prod"){return `${y[e]}/token/${n}`}function z(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 d={name:K,image:J,ticker:F,vanity_ticker:W,description:M,twitter:j,website:G,telegram:Z};function K(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 M(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 F(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 W(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 J(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 j(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 G(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 Z(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 _=class{_apiKey=null;_httpClient;BASE_URL;ENV;constructor(e="prod"){this._httpClient=new f,this.BASE_URL=S[e],this.ENV=e;}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${y[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=d.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`)}set apiKey(e){this._apiKey=e;}get apiKey(){return this._apiKey}};var g=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 T={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun"};var w=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 v=class{_window;_appInfo;_api;_redirect;origin;constructor(e,t,i,r,s=null){this._window=e,this._redirect=s,this._api=t,this._appInfo=i,this.origin=r;}get appInfo(){return this._appInfo}createUrl(e){let t=new URL(`${this.origin}/${e}`);return this._appInfo?.name&&t.searchParams.append("app_name",this._appInfo.name),t.searchParams.append("referrer",window.location.origin),t.searchParams.append("lang",this._appInfo?.lang||c),t}baseAction({params:e,odinPath:t,receivedMessageFromOrigin:i,resolve:r}){if(this._redirect?.useRedirect){let s=this.createUrl(t);for(let o in e)e[o]&&s.searchParams.append(o,e[o]);return this._redirect.start(s,{path:"/"+t,successMessage:typeof i=="string"?i:void 0})}return new Promise((s,o)=>{let p=async a=>{a.origin===this.origin&&a.data.path==="/"+t&&(window.removeEventListener("message",p),(typeof i=="function"?i(a.data.message):i===a.data.message)?s(r.success(a.data.message)):o(new Error(r.failure)));},l=this.createUrl(t);for(let a in e)e[a]&&l.searchParams.append(a,e[a]);let u=this._window.open(l);if(!u||u.closed||typeof u.closed>"u"){o(new Error(r.didnotopen??`Failed to open ${t} window, please always allow popups and try again`));return}window.addEventListener("message",p);})}sell({token:e,tokenAmount:t,principal:i}){return this.baseAction({params:{principal:i,token:e,amount:t.toString()},odinPath:"authorize/sell",receivedMessageFromOrigin:"sold",resolve:{success:()=>true,failure:"Sell failed or was cancelled",close:"User closed the window"}})}buy({principal:e,token:t,btcAmount:i}){return this.baseAction({params:{principal:e,token:t,amount:i.toString()},odinPath:"authorize/buy",receivedMessageFromOrigin:"purchased",resolve:{success:()=>true,failure:"Purchase failed or was cancelled",close:"User closed the window"}})}transfer({principal:e,token:t,amount:i,destination:r}){return this.baseAction({params:{principal:e,token:t,amount:i.toString(),destination:r},odinPath:"authorize/transfer",receivedMessageFromOrigin:"transferred",resolve:{success:()=>true,failure:"Transfer failed or was cancelled",close:"User closed the window"}})}addLiquidity({principal:e,btcAmount:t,token:i}){return this.baseAction({params:{principal:e,amount:t.toString(),token:i},odinPath:"authorize/add_liquidity",receivedMessageFromOrigin:"addedLiquidity",resolve:{success:()=>true,failure:"Add liquidity failed or was cancelled",close:"User closed the window"}})}removeLiquidity({principal:e,lpAmount:t,token:i}){return this.baseAction({params:{principal:e,amount:t.toString(),token:i},odinPath:"authorize/remove_liquidity",receivedMessageFromOrigin:"removedLiquidity",resolve:{success:()=>true,failure:"Remove liquidity failed or was cancelled",close:"User closed the window"}})}swap({principal:e,fromToken:t,toToken:i,fromAmount:r}){return this.baseAction({params:{principal:e,from:t,to:i,amount:r.toString()},odinPath:"authorize/swap",receivedMessageFromOrigin:"swapped",resolve:{success:()=>true,failure:"Swap failed or was cancelled",close:"User closed the window"}})}icrcApprove({principal:e,token:t,spender:i,amount:r}){return this.baseAction({params:{principal:e,token:t,spender:i,amount:r.toString()},odinPath:"authorize/icrc_approve",receivedMessageFromOrigin:"approved",resolve:{success:()=>true,failure:"ICRC approve failed or was cancelled",close:"User closed the window"}})}async createToken({image:e,...t}){for(let s in d)if(s in t){let p=d[s]?.(t[s]||null);if(p)throw new Error(p)}if(t.discount&&!/^[A-Za-z0-9]{10}$/.test(t.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");let i=await this._api.uploadImage(e);if(!await this.baseAction({params:{...t,image:i,buy:t.buy?.toString()},odinPath:"authorize/create_token",receivedMessageFromOrigin:"tokenCreated",resolve:{success:()=>true,failure:"Token creation failed or was cancelled",close:"User closed the window"}}))throw new Error("Token creation failed. Please try again.");return true}};var b=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 H=[/\bOKApp\b/i],X=["XverseProviders","btc_providers","unisat","okxwallet","phantom","LeatherProvider","magicEden","wizz","oyl","ethereum","solana"];function Y(n,e){return /Android|iPhone|iPad|iPod|Mobile/i.test(n)?true:/Macintosh/.test(n)&&e>1}function Q(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 ee(n){return X.some(e=>n[e]!=null)}function R(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 H.some(r=>r.test(e))||Q(e,t)?true:Y(e,t)&&ee(i)}var te="odin_connect",A=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:pending_redirect`;}save(e){try{let t=JSON.stringify(e);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=JSON.parse(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}};function ne(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ie(){return ne(crypto.getRandomValues(new Uint8Array(24)))}function re(){let n=new URL(window.location.href);return n.hash="",n.href}function E(){let n=window.location.hash.replace(/^#/,"");return n?new URLSearchParams(n).get(te):null}function I(){return E()!==null}function se(){let n=E();if(!n)return null;let e=new URL(window.location.href);e.hash="",window.history.replaceState(window.history.state,"",e.href);try{let t=n.replace(/-/g,"+").replace(/_/g,"/"),i=Uint8Array.from(atob(t),s=>s.charCodeAt(0)),r=JSON.parse(new TextDecoder().decode(i));return typeof r?.path!="string"||typeof r?.state!="string"?null:r}catch{return null}}var C=class{constructor(e,t){this._window=e;this._pending=t;}_window;_pending;mode="popup";get useRedirect(){return this.mode==="redirect"||this.mode==="auto"&&R()}start(e,t){let i=ie();return this._pending.save({...t,state:i})?(e.searchParams.append("return_url",re()),e.searchParams.append("state",i),this._window.navigate(e),new Promise(()=>{})):Promise.reject(new Error("Redirect mode needs sessionStorage, which is unavailable"))}pendingPath(){return I()?this._pending.peek()?.path??null:null}consume(){if(!I())return null;let e=se(),t=this._pending.take();if(!e||!t||t.state!==e.state||t.path!==e.path)throw new Error("Unexpected OdinConnect redirect result");return {result:e,pending:t}}};function oe(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 ae(n){return `${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${oe(n)}`}var k=class{_appInfo=null;_api;_window;_odin;_storage;_redirect;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||ae(this._appInfo.name),this._appInfo.lang=m(this._appInfo.lang),this._api=new _(this._appInfo.env==="prod"?"prod":this._appInfo.env==="legacy"?"legacy":"dev"),this._window=new w,this._redirect=new C(this._window,new A(this._appInfo.slug,this._appInfo.env||"prod")),this._redirect.mode=this._appInfo.mode||"popup",this._odin=new v(this._window,this._api,this._appInfo,T[this._appInfo.env||"prod"],this._redirect),this._storage=new b(this._appInfo.slug,this._appInfo.env||"prod");}createUrl(e){let t=new URL(`${this.origin}/${e}`);return this._appInfo?.name&&t.searchParams.append("app_name",this._appInfo.name),t.searchParams.append("referrer",window.location.origin),t.searchParams.append("lang",this.lang),t}get origin(){return T[this._appInfo?.env||"prod"]}get lang(){return this._appInfo?.lang||c}set lang(e){this._appInfo&&(this._appInfo.lang=m(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||""}connect({open:e,requires_api:t,requires_delegation:i,targets:r}={requires_delegation:false,requires_api:false}){return this._redirect.useRedirect?this.connectByRedirect({requires_api:t,requires_delegation:i,targets:r}):new Promise((s,o)=>{e&&(this._window.settings=e);let p=Ed25519KeyIdentity.generate(),l=async a=>{if(a.origin===this.origin&&a.data.path==="/authorize/connect")if(window.removeEventListener("message",l),a.data.message!="rejected")try{s(this.completeConnection(a.data.message,p,{requires_api:t,requires_delegation:i}));}catch{o(new Error("Failed to fetch user data"));}else o(new Error("User rejected the connection"));},u=this.createConnectUrl(p,{requires_api:t,requires_delegation:i,targets:r});this._window.open(u),window.addEventListener("message",l);})}createConnectUrl(e,{requires_api:t,requires_delegation:i,targets:r}){let s=this.createUrl("authorize/connect");if(s.searchParams.append("requires_api",t?"1":"0"),i){s.searchParams.append("requires_delegation","1");let o=btoa(JSON.stringify(e.toJSON()));s.searchParams.append("session_key",o),s.searchParams.append("targets",r?.join(",")||"");}return s}connectByRedirect(e){if(e.requires_api)return Promise.reject(new Error("requires_api is not supported in redirect mode"));let t=Ed25519KeyIdentity.generate();return this._redirect.start(this.createConnectUrl(t,e),{path:"/authorize/connect",sessionKey:JSON.stringify(t.toJSON()),requires_delegation:!!e.requires_delegation})}handleRedirectResult(){let e=this._redirect.consume();if(!e)return null;let{result:t,pending:i}=e,r=i.path.replace(/^\/authorize\//,"");return r==="connect"?t.message==="rejected"||!i.sessionKey?{action:"connect",status:"rejected"}:{action:"connect",status:"connected",user:this.completeConnection(t.message,Ed25519KeyIdentity.fromJSON(i.sessionKey),{requires_api:false,requires_delegation:i.requires_delegation})}:{action:r,status:i.successMessage!==void 0&&t.message===i.successMessage?"success":"failed"}}completeConnection({principal:e,jwt:t,delegationChain:i},r,{requires_api:s,requires_delegation:o}){let p;if(s&&(this._api.apiKey=t),o){if(!i)throw new Error("Delegation chain is missing");let l=DelegationIdentity.fromDelegation(r,DelegationChain.fromJSON(i));p=new g(e,l,this.api,this._odin);}else p=new g(e,null,this.api,this._odin);return (s||o)&&this._storage.save({principal:e,sessionKey:JSON.stringify(r.toJSON()),delegationChain:i?JSON.stringify(i):null,jwt:t||null}),p}get api(){return this._api}get odin(){return this._odin}get currentEnv(){return this._appInfo?.env||"prod"}restoreSession(){if(this._redirect.pendingPath()==="/authorize/connect")try{let e=this.handleRedirectResult();if(e?.action==="connect"&&e.status==="connected")return e.user}catch{}try{let e=this._storage.load();if(!e)return null;if(e.delegationChain&&!h(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 g(e.principal,t,this._api,this._odin)}catch{return this._storage.clear(),null}}disconnect(){this._storage.clear(),this._api.apiKey=null;}isSessionValid(){let e=this._storage.load();return e?e.delegationChain?h(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
|
|
2
|
+
export{k as OdinConnect,U as OdinUtils,R as isInAppBrowser};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odin-connect",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.7.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"build": "tsup",
|
|
22
22
|
"prepublishOnly": "npm run build",
|
|
23
23
|
"test": "vitest",
|
|
24
|
+
"audit": "npm audit --omit=dev --audit-level=moderate",
|
|
24
25
|
"demo:update": "npm run build && cd demo && npm install ../ && cd ..",
|
|
25
26
|
"demo:start": "cd demo && npm run dev",
|
|
26
27
|
"demo:build": "npm run demo:update && cd demo && npm run build",
|
package/readme.md
CHANGED
|
@@ -175,9 +175,24 @@ await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
|
|
|
175
175
|
const odinConnect = new OdinConnect({
|
|
176
176
|
name: "Demo App", // Your app name (shown in auth popup)
|
|
177
177
|
env: "prod", // "prod" | "dev" | "local" | "legacy"
|
|
178
|
+
lang: "en", // Popup UI language: "en" | "zh" (default "en")
|
|
178
179
|
});
|
|
179
180
|
```
|
|
180
181
|
|
|
182
|
+
### Popup language
|
|
183
|
+
|
|
184
|
+
All auth and action popups render in the language set via `lang`. It can be
|
|
185
|
+
changed at runtime; the new value applies to the next popup opened:
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
const odinConnect = new OdinConnect({ name: "Demo App", lang: "zh" });
|
|
189
|
+
|
|
190
|
+
odinConnect.lang = "en"; // next popup renders in English
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Unsupported values fall back to `"en"`. The SDK does not persist `lang` —
|
|
194
|
+
pass it on each construction from your app's own i18n state.
|
|
195
|
+
|
|
181
196
|
### Connecting a user
|
|
182
197
|
|
|
183
198
|
```typescript
|
|
@@ -208,6 +223,65 @@ const identity = user.getIdentity();
|
|
|
208
223
|
// Use identity with @dfinity/agent
|
|
209
224
|
```
|
|
210
225
|
|
|
226
|
+
> [!IMPORTANT]
|
|
227
|
+
> **Every target canister must trust your app's origin.** Each canister listed in `targets` must return your app's origin from its [`icrc28_trusted_origins()`](https://github.com/dfinity/wg-identity-authentication) method. The Odin frontend verifies this against **all** targets before issuing a delegation.
|
|
228
|
+
>
|
|
229
|
+
> **Failure mode:** if any target does not list your origin (or does not implement ICRC-28), the authorize popup silently hides the action — no delegation is issued and no error is surfaced to your app. Ensure each target canister declares your origin before requesting `requires_delegation: true`.
|
|
230
|
+
|
|
231
|
+
### Wallet in-app browsers (redirect mode)
|
|
232
|
+
|
|
233
|
+
Some wallet in-app browsers (OKX) open `window.open` targets as a detached
|
|
234
|
+
page with no `window.opener`, so a popup can never send its result back.
|
|
235
|
+
Set `mode` on the instance; it applies to `connect()` **and every action**
|
|
236
|
+
(buy, sell, transfer, swap, liquidity, ICRC-2 approve, create token):
|
|
237
|
+
|
|
238
|
+
```typescript
|
|
239
|
+
const odinConnect = new OdinConnect({
|
|
240
|
+
name: "My App",
|
|
241
|
+
env: "prod",
|
|
242
|
+
mode: "auto", // "popup" (default) | "redirect" | "auto" (redirect in wallet browsers)
|
|
243
|
+
});
|
|
244
|
+
|
|
245
|
+
// On page load: read the outcome of the redirect this load returned from.
|
|
246
|
+
try {
|
|
247
|
+
const result = odinConnect.handleRedirectResult();
|
|
248
|
+
if (result?.action === "connect" && result.status === "connected") {
|
|
249
|
+
user = result.user;
|
|
250
|
+
} else if (result?.action === "connect") {
|
|
251
|
+
// Rejected. Show that, and do NOT call connect() automatically on this
|
|
252
|
+
// load, or a user who taps Reject is sent straight back to Odin.
|
|
253
|
+
} else if (result) {
|
|
254
|
+
// An action: { action: "buy", status: "success" | "failed" }
|
|
255
|
+
}
|
|
256
|
+
} catch (error) {
|
|
257
|
+
// Stale or foreign result; ignore.
|
|
258
|
+
}
|
|
259
|
+
user ??= odinConnect.restoreSession();
|
|
260
|
+
|
|
261
|
+
// From a button click. In redirect mode these navigate this tab to Odin and
|
|
262
|
+
// back, and the promise never settles; the outcome arrives via
|
|
263
|
+
// handleRedirectResult() above.
|
|
264
|
+
await odinConnect.connect({ requires_delegation: true, targets: ["aaaa-aa"] });
|
|
265
|
+
await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
- `mode` can be changed at runtime: `odinConnect.mode = "redirect"`.
|
|
269
|
+
- The result comes back in the URL fragment of the page that started the
|
|
270
|
+
request. `handleRedirectResult()` checks it against a one-time nonce kept
|
|
271
|
+
in `sessionStorage` and removes it from the address bar.
|
|
272
|
+
- `restoreSession()` finishes a redirected `connect()` on its own, but leaves
|
|
273
|
+
action results for `handleRedirectResult()`.
|
|
274
|
+
- Page state is lost across the round trip, so persist anything the page
|
|
275
|
+
needs to show after an action (e.g. the token being traded).
|
|
276
|
+
- `requires_api` is not supported in redirect mode (it rejects), so the JWT
|
|
277
|
+
never lands in a URL. Use a delegation instead.
|
|
278
|
+
- `"auto"` redirects when `isInAppBrowser()` is true: a known wallet user
|
|
279
|
+
agent (OKX), an app webview (Android `; wv)`, iOS WebKit without
|
|
280
|
+
`Safari/`), or a mobile browser with an injected wallet (`XverseProviders`,
|
|
281
|
+
`btc_providers`, `unisat`, `okxwallet`, `phantom`, `ethereum`, ...). It errs
|
|
282
|
+
toward redirect, which works everywhere. Call `isInAppBrowser()` yourself
|
|
283
|
+
if you want to choose the mode.
|
|
284
|
+
|
|
211
285
|
## Session Restoration
|
|
212
286
|
|
|
213
287
|
OdinConnect automatically persists session data to `localStorage` after a successful `connect()`. This allows you to restore sessions on page load without requiring user action.
|
|
@@ -399,6 +473,7 @@ await user.createToken({
|
|
|
399
473
|
principal: "veyov-kjgrf-hke6v-6d63i-sdwae-oldgg-huau6-ke5g3-rllp2-5jhca-uqe",
|
|
400
474
|
name: "Test Token", // 3-30 characters
|
|
401
475
|
ticker: "TEST", // 3-10 uppercase alphanumeric, at least 2 letters
|
|
476
|
+
vanity_ticker: "", // Optional, 1-10 characters (any unicode), no surrounding whitespace
|
|
402
477
|
description: "A test token", // Optional, max 100 characters
|
|
403
478
|
website: "https://example.com", // Optional, valid URL
|
|
404
479
|
telegram: "", // Optional, valid Telegram URL
|
|
@@ -512,6 +587,7 @@ import { OdinUtils } from "odin-connect";
|
|
|
512
587
|
|
|
513
588
|
OdinUtils.createTokenValidators.name("My Token"); // 3-30 chars
|
|
514
589
|
OdinUtils.createTokenValidators.ticker("TEST"); // 3-10 uppercase alphanumeric
|
|
590
|
+
OdinUtils.createTokenValidators.vanity_ticker("Tëst🚀"); // Optional, max 10 unicode code points, no surrounding whitespace
|
|
515
591
|
OdinUtils.createTokenValidators.image(file); // PNG/JPEG/WebP/GIF/SVG/AVIF, max 200KB
|
|
516
592
|
OdinUtils.createTokenValidators.description("A token"); // Max 100 chars
|
|
517
593
|
OdinUtils.createTokenValidators.website("https://..."); // Valid URL
|