odin-connect 1.7.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
@@ -235,6 +235,18 @@ interface PendingRedirect {
235
235
  sessionKey?: string;
236
236
  /** connect only */
237
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;
238
250
  }
239
251
  interface RedirectResult {
240
252
  path: string;
@@ -244,7 +256,10 @@ interface RedirectResult {
244
256
  declare class PendingRedirectStorage {
245
257
  private _key;
246
258
  constructor(slug: string, env: string);
247
- /** Save and read back; false when sessionStorage is unusable. */
259
+ /**
260
+ * Save and read back; false when sessionStorage is unusable. Throws when
261
+ * `returnState` is not serializable (e.g. circular references).
262
+ */
248
263
  save(pending: PendingRedirect): boolean;
249
264
  /** Load without deleting. */
250
265
  peek(): PendingRedirect | null;
@@ -282,45 +297,45 @@ declare class RedirectClient {
282
297
  } | null;
283
298
  }
284
299
 
285
- interface SellOptions {
300
+ interface SellOptions extends RedirectCallOptions {
286
301
  principal: string;
287
302
  token: string;
288
303
  tokenAmount: bigint;
289
304
  }
290
- interface BuyOptions {
305
+ interface BuyOptions extends RedirectCallOptions {
291
306
  principal: string;
292
307
  token: string;
293
308
  btcAmount: bigint;
294
309
  }
295
- interface TransferOptions {
310
+ interface TransferOptions extends RedirectCallOptions {
296
311
  principal: string;
297
312
  token: string;
298
313
  amount: bigint;
299
314
  destination: string;
300
315
  }
301
- interface AddLiquidityOptions {
316
+ interface AddLiquidityOptions extends RedirectCallOptions {
302
317
  principal: string;
303
318
  btcAmount: bigint;
304
319
  token: string;
305
320
  }
306
- interface RemoveLiquidityOptions {
321
+ interface RemoveLiquidityOptions extends RedirectCallOptions {
307
322
  principal: string;
308
323
  lpAmount: bigint;
309
324
  token: string;
310
325
  }
311
- interface SwapOptions {
326
+ interface SwapOptions extends RedirectCallOptions {
312
327
  principal: string;
313
328
  fromToken: string;
314
329
  toToken: string;
315
330
  fromAmount: bigint;
316
331
  }
317
- interface IcrcApproveOptions {
332
+ interface IcrcApproveOptions extends RedirectCallOptions {
318
333
  principal: string;
319
334
  token: string;
320
335
  spender: string;
321
336
  amount: bigint;
322
337
  }
323
- interface CreateTokenParams {
338
+ interface CreateTokenParams extends RedirectCallOptions {
324
339
  principal: string;
325
340
  name: string;
326
341
  ticker: string;
@@ -343,14 +358,14 @@ declare class OdinCanisterClient {
343
358
  get appInfo(): AppInitOptions;
344
359
  private createUrl;
345
360
  private baseAction;
346
- sell({ token, tokenAmount, principal }: SellOptions): Promise<boolean>;
347
- buy({ principal, token, btcAmount }: BuyOptions): Promise<boolean>;
348
- transfer({ principal, token, amount, destination }: TransferOptions): Promise<boolean>;
349
- addLiquidity({ principal, btcAmount, token }: AddLiquidityOptions): Promise<boolean>;
350
- removeLiquidity({ principal, lpAmount, token }: RemoveLiquidityOptions): Promise<boolean>;
351
- swap({ principal, fromToken: from, toToken: to, fromAmount }: SwapOptions): Promise<boolean>;
352
- icrcApprove({ principal, token, spender, amount }: IcrcApproveOptions): Promise<boolean>;
353
- 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>;
354
369
  }
355
370
 
356
371
  declare class ConnectedUser {
@@ -449,8 +464,12 @@ interface AppInitOptions {
449
464
  }
450
465
  /** Authorize actions that can come back through `handleRedirectResult()`. */
451
466
  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 = {
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> = ({
454
473
  action: "connect";
455
474
  status: "connected";
456
475
  user: ConnectedUser;
@@ -460,8 +479,10 @@ type OdinRedirectResult = {
460
479
  } | {
461
480
  action: OdinAction;
462
481
  status: "success" | "failed";
482
+ }) & {
483
+ returnState: ReturnState | undefined;
463
484
  };
464
- interface BaseConnectOptions {
485
+ interface BaseConnectOptions extends RedirectCallOptions {
465
486
  open?: WindowClientSettings;
466
487
  requires_api?: boolean;
467
488
  }
@@ -492,7 +513,7 @@ declare class Connect {
492
513
  set mode(value: ConnectMode);
493
514
  get appInfo(): AppInitOptions | null;
494
515
  get slug(): string;
495
- connect({ open, requires_api, requires_delegation, targets, }?: ConnectOptions | undefined): Promise<ConnectedUser>;
516
+ connect({ open, requires_api, requires_delegation, targets, returnState, }?: ConnectOptions | undefined): Promise<ConnectedUser>;
496
517
  private createConnectUrl;
497
518
  private connectByRedirect;
498
519
  /**
@@ -505,7 +526,7 @@ declare class Connect {
505
526
  * `restoreSession()` handles connect results itself, so call this first if
506
527
  * you need to tell "rejected" from "not connected" or read action results.
507
528
  */
508
- handleRedirectResult(): OdinRedirectResult | null;
529
+ handleRedirectResult<ReturnState = unknown>(): OdinRedirectResult<ReturnState> | null;
509
530
  private completeConnection;
510
531
  get api(): OdinApiClient;
511
532
  get odin(): OdinCanisterClient;
@@ -574,4 +595,4 @@ interface SessionData {
574
595
  jwt: string | null;
575
596
  }
576
597
 
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 };
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 $ 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};
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.7.0",
3
+ "version": "2.0.0",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
package/readme.md CHANGED
@@ -271,8 +271,8 @@ await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
271
271
  in `sessionStorage` and removes it from the address bar.
272
272
  - `restoreSession()` finishes a redirected `connect()` on its own, but leaves
273
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).
274
+ - Page state is lost across the round trip. Pass what the page needs to
275
+ resume as `returnState` (see below).
276
276
  - `requires_api` is not supported in redirect mode (it rejects), so the JWT
277
277
  never lands in a URL. Use a delegation instead.
278
278
  - `"auto"` redirects when `isInAppBrowser()` is true: a known wallet user
@@ -282,6 +282,36 @@ await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
282
282
  toward redirect, which works everywhere. Call `isInAppBrowser()` yourself
283
283
  if you want to choose the mode.
284
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
+
285
315
  ## Session Restoration
286
316
 
287
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.