odin-connect 1.6.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 +128 -2
- package/dist/index.js +2 -2
- package/package.json +1 -1
- package/readme.md +54 -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 {
|
|
@@ -267,8 +337,9 @@ declare class OdinCanisterClient {
|
|
|
267
337
|
private _window;
|
|
268
338
|
private _appInfo;
|
|
269
339
|
private _api;
|
|
340
|
+
private _redirect;
|
|
270
341
|
origin: string;
|
|
271
|
-
constructor(windowClient: WindowClient, apiClient: OdinApiClient, appInfo: AppInitOptions, origin: string);
|
|
342
|
+
constructor(windowClient: WindowClient, apiClient: OdinApiClient, appInfo: AppInitOptions, origin: string, redirectClient?: RedirectClient | null);
|
|
272
343
|
get appInfo(): AppInitOptions;
|
|
273
344
|
private createUrl;
|
|
274
345
|
private baseAction;
|
|
@@ -370,7 +441,26 @@ interface AppInitOptions {
|
|
|
370
441
|
env?: Environment;
|
|
371
442
|
slug?: string;
|
|
372
443
|
lang?: OdinLang;
|
|
444
|
+
/**
|
|
445
|
+
* How `connect()` and every action reach Odin: `"popup"` (default),
|
|
446
|
+
* `"redirect"` or `"auto"`. See `ConnectMode`.
|
|
447
|
+
*/
|
|
448
|
+
mode?: ConnectMode;
|
|
373
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
|
+
};
|
|
374
464
|
interface BaseConnectOptions {
|
|
375
465
|
open?: WindowClientSettings;
|
|
376
466
|
requires_api?: boolean;
|
|
@@ -391,14 +481,32 @@ declare class Connect {
|
|
|
391
481
|
private _window;
|
|
392
482
|
private _odin;
|
|
393
483
|
private _storage;
|
|
484
|
+
private _redirect;
|
|
394
485
|
constructor(appInfo?: Partial<AppInitOptions>);
|
|
395
486
|
private createUrl;
|
|
396
487
|
get origin(): string;
|
|
397
488
|
get lang(): OdinLang;
|
|
398
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);
|
|
399
493
|
get appInfo(): AppInitOptions | null;
|
|
400
494
|
get slug(): string;
|
|
401
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;
|
|
402
510
|
get api(): OdinApiClient;
|
|
403
511
|
get odin(): OdinCanisterClient;
|
|
404
512
|
get currentEnv(): "legacy" | "dev" | "prod" | "local";
|
|
@@ -408,6 +516,24 @@ declare class Connect {
|
|
|
408
516
|
hello(): void;
|
|
409
517
|
}
|
|
410
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
|
+
|
|
411
537
|
declare const IMAGE_CDN_ENV: {
|
|
412
538
|
dev: string;
|
|
413
539
|
prod: string;
|
|
@@ -448,4 +574,4 @@ interface SessionData {
|
|
|
448
574
|
jwt: string | null;
|
|
449
575
|
}
|
|
450
576
|
|
|
451
|
-
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 OdinLang, 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 D from'axios';import N from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';var $=Object.defineProperty;var B=(i,e)=>{for(var t in e)$(i,t,{get:e[t],enumerable:true});};var q=i=>{try{return N.parse(i)}catch(e){return console.error("Error parsing response:",e),i}},y=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let n={transformResponse:[q],...t};return (await D(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 U={};B(U,{DEFAULT_LANG:()=>l,buildTokenImageUrl:()=>F,convertToOdinAmount:()=>z,createTokenValidators:()=>g,isDelegationValid:()=>h,normalizeOdinLang:()=>m});var I={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1"},_={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(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}}var l="en";function m(i){return i==="en"||i==="zh"?i:(i!==void 0&&console.warn(`[odin-connect] Unsupported lang "${i}", falling back to "${l}"`),l)}function F(i,e="prod"){return `${_[e]}/token/${i}`}function z(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 g={name:K,image:G,ticker:J,vanity_ticker:M,description:W,twitter:j,website:Z,telegram:H};function K(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 W(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 J(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 M(i){if(!(i==null||i==="")){if(typeof i!="string")return "Vanity ticker must be a string.";if(i.trim()!==i)return "Vanity ticker must not have leading or trailing whitespace.";if([...i].length>10)return "Vanity ticker must be below 10 characters."}}function G(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 Z(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 H(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 w=class{_apiKey=null;_httpClient;BASE_URL;ENV;constructor(e="prod"){this._httpClient=new y,this.BASE_URL=I[e],this.ENV=e;}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${_[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=g.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 d=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 k={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun"};var v=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 T=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.searchParams.append("lang",this._appInfo?.lang||l),t}baseAction({params:e,odinPath:t,receivedMessageFromOrigin:n,resolve:r}){return new Promise((p,c)=>{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)):c(new Error(r.failure)));},u=this.createUrl(t);for(let s in e)e[s]&&u.searchParams.append(s,e[s]);let o=this._window.open(u);if(!o||o.closed||typeof o.closed>"u"){c(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 g)if(p in t){let a=g[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 A=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 Q(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 X(i){return `${i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${Q(i)}`}var C=class{_appInfo=null;_api;_window;_odin;_storage;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||X(this._appInfo.name),this._appInfo.lang=m(this._appInfo.lang),this._api=new w(this._appInfo.env==="prod"?"prod":this._appInfo.env==="legacy"?"legacy":"dev"),this._window=new v,this._odin=new T(this._window,this._api,this._appInfo,k[this._appInfo.env||"prod"]),this._storage=new A(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 k[this._appInfo?.env||"prod"]}get lang(){return this._appInfo?.lang||l}set lang(e){this._appInfo&&(this._appInfo.lang=m(e));}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,c)=>{e&&(this._window.settings=e);let a=Ed25519KeyIdentity.generate(),u=async s=>{if(s.origin===this.origin&&s.data.path==="/authorize/connect")if(window.removeEventListener("message",u),s.data.message!="rejected"){let O;try{let S=s.data.message,{principal:b,jwt:E,delegationChain:f}=S;if(t&&(this._api.apiKey=E),n){if(!f)throw new Error("Delegation chain is missing");let P=DelegationIdentity.fromDelegation(a,DelegationChain.fromJSON(f));O=new d(b,P,this.api,this._odin);}else O=new d(b,null,this.api,this._odin);(t||n)&&this._storage.save({principal:b,sessionKey:JSON.stringify(a.toJSON()),delegationChain:f?JSON.stringify(f):null,jwt:E||null}),p(O);}catch{c(new Error("Failed to fetch user data"));}}else c(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",u);})}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&&!h(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 d(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{
|
|
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
package/readme.md
CHANGED
|
@@ -228,6 +228,60 @@ const identity = user.getIdentity();
|
|
|
228
228
|
>
|
|
229
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
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
|
+
|
|
231
285
|
## Session Restoration
|
|
232
286
|
|
|
233
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.
|