odin-connect 1.6.0 → 2.0.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 CHANGED
@@ -210,47 +210,132 @@ 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;
213
215
  }
214
216
 
215
- interface SellOptions {
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
+ /** App data handed back by `handleRedirectResult()` (redirect mode only). */
239
+ returnState?: unknown;
240
+ }
241
+ /**
242
+ * Per-call option shared by `connect()` and every action. In redirect mode
243
+ * the page unloads, so anything the app needs to resume (current step, token,
244
+ * amounts) can ride along here and comes back as `result.returnState` from
245
+ * `handleRedirectResult()`. Must be JSON-serializable; bigints are preserved.
246
+ * Ignored in popup mode, where the awaited call simply resolves.
247
+ */
248
+ interface RedirectCallOptions {
249
+ returnState?: unknown;
250
+ }
251
+ interface RedirectResult {
252
+ path: string;
253
+ message: unknown;
254
+ state: string;
255
+ }
256
+ declare class PendingRedirectStorage {
257
+ private _key;
258
+ constructor(slug: string, env: string);
259
+ /**
260
+ * Save and read back; false when sessionStorage is unusable. Throws when
261
+ * `returnState` is not serializable (e.g. circular references).
262
+ */
263
+ save(pending: PendingRedirect): boolean;
264
+ /** Load without deleting. */
265
+ peek(): PendingRedirect | null;
266
+ /** Load and delete (single-use). */
267
+ take(): PendingRedirect | null;
268
+ }
269
+ /**
270
+ * Owns the mode and the pending request for one `OdinConnect` instance, so
271
+ * `connect()` and the canister actions share one redirect implementation.
272
+ */
273
+ declare class RedirectClient {
274
+ private _window;
275
+ private _pending;
276
+ mode: ConnectMode;
277
+ constructor(_window: WindowClient, _pending: PendingRedirectStorage);
278
+ /** Whether the next authorize request should redirect instead of popup. */
279
+ get useRedirect(): boolean;
280
+ /**
281
+ * Save the pending request, then navigate this tab to `url` with
282
+ * `return_url` + `state`. The returned promise never settles (the page
283
+ * unloads) unless sessionStorage is unusable, in which case it rejects
284
+ * before navigating.
285
+ */
286
+ start<T>(url: URL, pending: Omit<PendingRedirect, "state">): Promise<T>;
287
+ /** Path of the pending request when the URL carries its result. */
288
+ pendingPath(): string | null;
289
+ /**
290
+ * Consume the URL's redirect result and its pending request. Returns null
291
+ * when the URL carries no result; throws when the result does not match
292
+ * the pending request (stale, foreign or replayed).
293
+ */
294
+ consume(): {
295
+ result: RedirectResult;
296
+ pending: PendingRedirect;
297
+ } | null;
298
+ }
299
+
300
+ interface SellOptions extends RedirectCallOptions {
216
301
  principal: string;
217
302
  token: string;
218
303
  tokenAmount: bigint;
219
304
  }
220
- interface BuyOptions {
305
+ interface BuyOptions extends RedirectCallOptions {
221
306
  principal: string;
222
307
  token: string;
223
308
  btcAmount: bigint;
224
309
  }
225
- interface TransferOptions {
310
+ interface TransferOptions extends RedirectCallOptions {
226
311
  principal: string;
227
312
  token: string;
228
313
  amount: bigint;
229
314
  destination: string;
230
315
  }
231
- interface AddLiquidityOptions {
316
+ interface AddLiquidityOptions extends RedirectCallOptions {
232
317
  principal: string;
233
318
  btcAmount: bigint;
234
319
  token: string;
235
320
  }
236
- interface RemoveLiquidityOptions {
321
+ interface RemoveLiquidityOptions extends RedirectCallOptions {
237
322
  principal: string;
238
323
  lpAmount: bigint;
239
324
  token: string;
240
325
  }
241
- interface SwapOptions {
326
+ interface SwapOptions extends RedirectCallOptions {
242
327
  principal: string;
243
328
  fromToken: string;
244
329
  toToken: string;
245
330
  fromAmount: bigint;
246
331
  }
247
- interface IcrcApproveOptions {
332
+ interface IcrcApproveOptions extends RedirectCallOptions {
248
333
  principal: string;
249
334
  token: string;
250
335
  spender: string;
251
336
  amount: bigint;
252
337
  }
253
- interface CreateTokenParams {
338
+ interface CreateTokenParams extends RedirectCallOptions {
254
339
  principal: string;
255
340
  name: string;
256
341
  ticker: string;
@@ -267,19 +352,20 @@ declare class OdinCanisterClient {
267
352
  private _window;
268
353
  private _appInfo;
269
354
  private _api;
355
+ private _redirect;
270
356
  origin: string;
271
- constructor(windowClient: WindowClient, apiClient: OdinApiClient, appInfo: AppInitOptions, origin: string);
357
+ constructor(windowClient: WindowClient, apiClient: OdinApiClient, appInfo: AppInitOptions, origin: string, redirectClient?: RedirectClient | null);
272
358
  get appInfo(): AppInitOptions;
273
359
  private createUrl;
274
360
  private baseAction;
275
- sell({ token, tokenAmount, principal }: SellOptions): Promise<boolean>;
276
- buy({ principal, token, btcAmount }: BuyOptions): Promise<boolean>;
277
- transfer({ principal, token, amount, destination }: TransferOptions): Promise<boolean>;
278
- addLiquidity({ principal, btcAmount, token }: AddLiquidityOptions): Promise<boolean>;
279
- removeLiquidity({ principal, lpAmount, token }: RemoveLiquidityOptions): Promise<boolean>;
280
- swap({ principal, fromToken: from, toToken: to, fromAmount }: SwapOptions): Promise<boolean>;
281
- icrcApprove({ principal, token, spender, amount }: IcrcApproveOptions): Promise<boolean>;
282
- createToken({ image, ...params }: CreateTokenParams): Promise<boolean>;
361
+ sell({ token, tokenAmount, principal, returnState }: SellOptions): Promise<boolean>;
362
+ buy({ principal, token, btcAmount, returnState }: BuyOptions): Promise<boolean>;
363
+ transfer({ principal, token, amount, destination, returnState, }: TransferOptions): Promise<boolean>;
364
+ addLiquidity({ principal, btcAmount, token, returnState, }: AddLiquidityOptions): Promise<boolean>;
365
+ removeLiquidity({ principal, lpAmount, token, returnState, }: RemoveLiquidityOptions): Promise<boolean>;
366
+ swap({ principal, fromToken: from, toToken: to, fromAmount, returnState, }: SwapOptions): Promise<boolean>;
367
+ icrcApprove({ principal, token, spender, amount, returnState, }: IcrcApproveOptions): Promise<boolean>;
368
+ createToken({ image, returnState, ...params }: CreateTokenParams): Promise<boolean>;
283
369
  }
284
370
 
285
371
  declare class ConnectedUser {
@@ -370,8 +456,33 @@ interface AppInitOptions {
370
456
  env?: Environment;
371
457
  slug?: string;
372
458
  lang?: OdinLang;
459
+ /**
460
+ * How `connect()` and every action reach Odin: `"popup"` (default),
461
+ * `"redirect"` or `"auto"`. See `ConnectMode`.
462
+ */
463
+ mode?: ConnectMode;
373
464
  }
374
- interface BaseConnectOptions {
465
+ /** Authorize actions that can come back through `handleRedirectResult()`. */
466
+ type OdinAction = "buy" | "sell" | "transfer" | "swap" | "add_liquidity" | "remove_liquidity" | "icrc_approve" | "create_token";
467
+ /**
468
+ * What `handleRedirectResult()` found in the URL after a redirect.
469
+ * `returnState` is whatever was passed as `returnState` to the call that
470
+ * redirected (undefined if none).
471
+ */
472
+ type OdinRedirectResult<ReturnState = unknown> = ({
473
+ action: "connect";
474
+ status: "connected";
475
+ user: ConnectedUser;
476
+ } | {
477
+ action: "connect";
478
+ status: "rejected";
479
+ } | {
480
+ action: OdinAction;
481
+ status: "success" | "failed";
482
+ }) & {
483
+ returnState: ReturnState | undefined;
484
+ };
485
+ interface BaseConnectOptions extends RedirectCallOptions {
375
486
  open?: WindowClientSettings;
376
487
  requires_api?: boolean;
377
488
  }
@@ -391,14 +502,32 @@ declare class Connect {
391
502
  private _window;
392
503
  private _odin;
393
504
  private _storage;
505
+ private _redirect;
394
506
  constructor(appInfo?: Partial<AppInitOptions>);
395
507
  private createUrl;
396
508
  get origin(): string;
397
509
  get lang(): OdinLang;
398
510
  set lang(value: OdinLang);
511
+ /** Current mode for `connect()` and actions; can be changed at runtime. */
512
+ get mode(): ConnectMode;
513
+ set mode(value: ConnectMode);
399
514
  get appInfo(): AppInitOptions | null;
400
515
  get slug(): string;
401
- connect({ open, requires_api, requires_delegation, targets, }?: ConnectOptions | undefined): Promise<ConnectedUser>;
516
+ connect({ open, requires_api, requires_delegation, targets, returnState, }?: ConnectOptions | undefined): Promise<ConnectedUser>;
517
+ private createConnectUrl;
518
+ private connectByRedirect;
519
+ /**
520
+ * Read the result of a redirect-mode `connect()` or action after Odin sends
521
+ * the user back. Call once on page load. Returns null when the URL carries
522
+ * no redirect result; throws when the result does not match the pending
523
+ * request (stale, foreign or replayed).
524
+ *
525
+ * A successful connect is also persisted like a popup connect, and
526
+ * `restoreSession()` handles connect results itself, so call this first if
527
+ * you need to tell "rejected" from "not connected" or read action results.
528
+ */
529
+ handleRedirectResult<ReturnState = unknown>(): OdinRedirectResult<ReturnState> | null;
530
+ private completeConnection;
402
531
  get api(): OdinApiClient;
403
532
  get odin(): OdinCanisterClient;
404
533
  get currentEnv(): "legacy" | "dev" | "prod" | "local";
@@ -408,6 +537,24 @@ declare class Connect {
408
537
  hello(): void;
409
538
  }
410
539
 
540
+ /**
541
+ * Best-effort detection of wallet in-app browsers and app webviews, where
542
+ * `window.open` targets load as a detached page with no `window.opener`, so a
543
+ * popup's `postMessage` result never reaches the app.
544
+ * `new OdinConnect({ mode: "auto" })` uses redirect mode when this is true.
545
+ *
546
+ * Redirect mode works in every browser, so this errs toward true: a false
547
+ * positive costs a page reload, a miss leaves Authorize doing nothing.
548
+ */
549
+ interface InAppBrowserEnv {
550
+ userAgent?: string;
551
+ /** Checked for injected wallet globals. */
552
+ globals?: object;
553
+ /** Distinguishes iPadOS (which reports a Mac user agent) from macOS. */
554
+ maxTouchPoints?: number;
555
+ }
556
+ declare function isInAppBrowser(env?: InAppBrowserEnv): boolean;
557
+
411
558
  declare const IMAGE_CDN_ENV: {
412
559
  dev: string;
413
560
  prod: string;
@@ -448,4 +595,4 @@ interface SessionData {
448
595
  jwt: string | null;
449
596
  }
450
597
 
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 };
598
+ 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 RedirectCallOptions as OdinRedirectCallOptions, 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{C as OdinConnect,U as OdinUtils};
1
+ import D from'axios';import N from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';var $=Object.defineProperty;var q=(n,e)=>{for(var t in e)$(n,t,{get:e[t],enumerable:true});};var V=n=>{try{return N.parse(n)}catch(e){return console.error("Error parsing response:",e),n}},y=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let i={transformResponse:[V],...t};return (await D(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={};q(U,{DEFAULT_LANG:()=>l,buildTokenImageUrl:()=>K,convertToOdinAmount:()=>M,createTokenValidators:()=>d,isDelegationValid:()=>f,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 f(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 l="en";function m(n){return n==="en"||n==="zh"?n:(n!==void 0&&console.warn(`[odin-connect] Unsupported lang "${n}", falling back to "${l}"`),l)}function K(n,e="prod"){return `${_[e]}/token/${n}`}function M(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:F,image:G,ticker:J,vanity_ticker:j,description:W,twitter:Z,website:H,telegram:X};function F(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 W(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 J(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 j(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 G(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 Z(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 H(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 X(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 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"},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 u=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 O=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 C=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||l),t}baseAction({params:e,odinPath:t,receivedMessageFromOrigin:i,resolve:r,returnState:s}){if(this._redirect?.useRedirect){let o=this.createUrl(t);for(let a in e)e[a]&&o.searchParams.append(a,e[a]);return this._redirect.start(o,{path:"/"+t,successMessage:typeof i=="string"?i:void 0,returnState:s})}return new Promise((o,a)=>{let c=async p=>{p.origin===this.origin&&p.data.path==="/"+t&&(window.removeEventListener("message",c),(typeof i=="function"?i(p.data.message):i===p.data.message)?o(r.success(p.data.message)):a(new Error(r.failure)));},g=this.createUrl(t);for(let p in e)e[p]&&g.searchParams.append(p,e[p]);let h=this._window.open(g);if(!h||h.closed||typeof h.closed>"u"){a(new Error(r.didnotopen??`Failed to open ${t} window, please always allow popups and try again`));return}window.addEventListener("message",c);})}sell({token:e,tokenAmount:t,principal:i,returnState:r}){return this.baseAction({params:{principal:i,token:e,amount:t.toString()},odinPath:"authorize/sell",returnState:r,receivedMessageFromOrigin:"sold",resolve:{success:()=>true,failure:"Sell failed or was cancelled",close:"User closed the window"}})}buy({principal:e,token:t,btcAmount:i,returnState:r}){return this.baseAction({params:{principal:e,token:t,amount:i.toString()},odinPath:"authorize/buy",returnState:r,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,returnState:s}){return this.baseAction({params:{principal:e,token:t,amount:i.toString(),destination:r},odinPath:"authorize/transfer",returnState:s,receivedMessageFromOrigin:"transferred",resolve:{success:()=>true,failure:"Transfer failed or was cancelled",close:"User closed the window"}})}addLiquidity({principal:e,btcAmount:t,token:i,returnState:r}){return this.baseAction({params:{principal:e,amount:t.toString(),token:i},odinPath:"authorize/add_liquidity",returnState:r,receivedMessageFromOrigin:"addedLiquidity",resolve:{success:()=>true,failure:"Add liquidity failed or was cancelled",close:"User closed the window"}})}removeLiquidity({principal:e,lpAmount:t,token:i,returnState:r}){return this.baseAction({params:{principal:e,amount:t.toString(),token:i},odinPath:"authorize/remove_liquidity",returnState:r,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,returnState:s}){return this.baseAction({params:{principal:e,from:t,to:i,amount:r.toString()},odinPath:"authorize/swap",returnState:s,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,returnState:s}){return this.baseAction({params:{principal:e,token:t,spender:i,amount:r.toString()},odinPath:"authorize/icrc_approve",returnState:s,receivedMessageFromOrigin:"approved",resolve:{success:()=>true,failure:"ICRC approve failed or was cancelled",close:"User closed the window"}})}async createToken({image:e,returnState:t,...i}){for(let o in d)if(o in i){let c=d[o]?.(i[o]||null);if(c)throw new Error(c)}if(i.discount&&!/^[A-Za-z0-9]{10}$/.test(i.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");let r=await this._api.uploadImage(e);if(!await this.baseAction({params:{...i,image:r,buy:i.buy?.toString()},odinPath:"authorize/create_token",returnState:t,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 Y=[/\bOKApp\b/i],Q=["XverseProviders","btc_providers","unisat","okxwallet","phantom","LeatherProvider","magicEden","wizz","oyl","ethereum","solana"];function ee(n,e){return /Android|iPhone|iPad|iPod|Mobile/i.test(n)?true:/Macintosh/.test(n)&&e>1}function te(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 ne(n){return Q.some(e=>n[e]!=null)}function k(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 Y.some(r=>r.test(e))||te(e,t)?true:ee(e,t)&&ne(i)}var ie="odin_connect",S="$odin_bigint";function re(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?{[S]:t.toString()}:t)}function se(n){return JSON.parse(n,(e,t)=>t!==null&&typeof t=="object"&&Object.keys(t).length===1&&typeof t[S]=="string"?BigInt(t[S]):t)}var v=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:pending_redirect`;}save(e){let t=re(e);try{return sessionStorage.setItem(this._key,t),sessionStorage.getItem(this._key)===t}catch{return false}}peek(){try{let e=sessionStorage.getItem(this._key);if(!e)return null;let t=se(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 oe(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function ae(){return oe(crypto.getRandomValues(new Uint8Array(24)))}function pe(){let n=new URL(window.location.href);return n.hash="",n.href}function P(){let n=window.location.hash.replace(/^#/,"");return n?new URLSearchParams(n).get(ie):null}function E(){return P()!==null}function ce(){let n=P();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 R=class{constructor(e,t){this._window=e;this._pending=t;}_window;_pending;mode="popup";get useRedirect(){return this.mode==="redirect"||this.mode==="auto"&&k()}start(e,t){let i=ae(),r;try{r=this._pending.save({...t,state:i});}catch{return Promise.reject(new Error("returnState must be JSON-serializable (bigints are allowed)"))}return r?(e.searchParams.append("return_url",pe()),e.searchParams.append("state",i),this._window.navigate(e),new Promise(()=>{})):Promise.reject(new Error("Redirect mode needs sessionStorage, which is unavailable"))}pendingPath(){return E()?this._pending.peek()?.path??null:null}consume(){if(!E())return null;let e=ce(),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 le(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 de(n){return `${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${le(n)}`}var x=class{_appInfo=null;_api;_window;_odin;_storage;_redirect;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||de(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 O,this._redirect=new R(this._window,new v(this._appInfo.slug,this._appInfo.env||"prod")),this._redirect.mode=this._appInfo.mode||"popup",this._odin=new C(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||l}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,returnState:s}={requires_delegation:false,requires_api:false}){return this._redirect.useRedirect?this.connectByRedirect({requires_api:t,requires_delegation:i,targets:r,returnState:s}):new Promise((o,a)=>{e&&(this._window.settings=e);let c=Ed25519KeyIdentity.generate(),g=async p=>{if(p.origin===this.origin&&p.data.path==="/authorize/connect")if(window.removeEventListener("message",g),p.data.message!="rejected")try{o(this.completeConnection(p.data.message,c,{requires_api:t,requires_delegation:i}));}catch{a(new Error("Failed to fetch user data"));}else a(new Error("User rejected the connection"));},h=this.createConnectUrl(c,{requires_api:t,requires_delegation:i,targets:r});this._window.open(h),window.addEventListener("message",g);})}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,returnState:e.returnState})}handleRedirectResult(){let e=this._redirect.consume();if(!e)return null;let{result:t,pending:i}=e,r=i.returnState,s=i.path.replace(/^\/authorize\//,"");return s==="connect"?t.message==="rejected"||!i.sessionKey?{action:"connect",status:"rejected",returnState:r}:{action:"connect",status:"connected",user:this.completeConnection(t.message,Ed25519KeyIdentity.fromJSON(i.sessionKey),{requires_api:false,requires_delegation:i.requires_delegation}),returnState:r}:{action:s,status:i.successMessage!==void 0&&t.message===i.successMessage?"success":"failed",returnState:r}}completeConnection({principal:e,jwt:t,delegationChain:i},r,{requires_api:s,requires_delegation:o}){let a;if(s&&(this._api.apiKey=t),o){if(!i)throw new Error("Delegation chain is missing");let c=DelegationIdentity.fromDelegation(r,DelegationChain.fromJSON(i));a=new u(e,c,this.api,this._odin);}else a=new u(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}),a}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&&!f(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 u(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?f(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
2
+ export{x as OdinConnect,U as OdinUtils,k as isInAppBrowser};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odin-connect",
3
- "version": "1.6.0",
3
+ "version": "2.0.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/readme.md CHANGED
@@ -228,6 +228,90 @@ 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. Pass what the page needs to
275
+ resume as `returnState` (see below).
276
+ - `requires_api` is not supported in redirect mode (it rejects), so the JWT
277
+ never lands in a URL. Use a delegation instead.
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
+
285
+ #### Resuming after a redirect (`returnState`)
286
+
287
+ In redirect mode the page reloads, so an awaited `connect()` / action never
288
+ returns and in-memory state is gone. Pass anything you need to continue as
289
+ `returnState`; it is kept with the one-time nonce in `sessionStorage` (never
290
+ sent to Odin) and comes back on `handleRedirectResult()`. Any JSON value
291
+ works, and bigints are preserved. In popup mode it is ignored and the awaited
292
+ call resolves as usual, so the same code works in both modes:
293
+
294
+ ```typescript
295
+ type Resume = { step: "approve"; token: string; amount: bigint };
296
+
297
+ // 1. Start the action with what the page needs to resume.
298
+ const ok = await user.icrcApprove({
299
+ token,
300
+ spender,
301
+ amount,
302
+ returnState: { step: "approve", token, amount } satisfies Resume,
303
+ });
304
+ if (ok) goToStep("commit"); // popup mode lands here
305
+
306
+ // 2. On page load (redirect mode lands here instead).
307
+ const result = odinConnect.handleRedirectResult<Resume>();
308
+ if (result?.action === "icrc_approve" && result.returnState) {
309
+ const { token, amount } = result.returnState;
310
+ if (result.status === "success") goToStep("commit", { token, amount });
311
+ else showError("Approval was rejected");
312
+ }
313
+ ```
314
+
231
315
  ## Session Restoration
232
316
 
233
317
  OdinConnect automatically persists session data to `localStorage` after a successful `connect()`. This allows you to restore sessions on page load without requiring user action.