odin-connect 2.0.1 → 2.0.2

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
@@ -138,6 +138,15 @@ interface Transaction {
138
138
  amount: bigint;
139
139
  }
140
140
 
141
+ declare const ORIGINS: {
142
+ local: string;
143
+ prod: string;
144
+ dev: string;
145
+ legacy: string;
146
+ staging: string;
147
+ };
148
+ type Environment = keyof typeof ORIGINS;
149
+
141
150
  type Pagination = {
142
151
  page: number;
143
152
  limit: number;
@@ -179,8 +188,8 @@ declare class OdinApiClient {
179
188
  private _apiKey;
180
189
  private _httpClient;
181
190
  readonly BASE_URL: string;
182
- readonly ENV: "prod" | "dev" | "legacy";
183
- constructor(env?: "prod" | "dev" | "legacy");
191
+ readonly ENV: Environment;
192
+ constructor(env?: Environment);
184
193
  getUser(id: string): Promise<User>;
185
194
  getUserAvatarUrl(principal: string): string;
186
195
  getBalances(principal: string, pagination: Pagination): Promise<readonly Balance[]>;
@@ -687,14 +696,6 @@ declare class ConnectedUser {
687
696
  swap(params: Omit<SwapOptions, "principal">): Promise<boolean>;
688
697
  }
689
698
 
690
- declare const ORIGINS: {
691
- local: string;
692
- prod: string;
693
- dev: string;
694
- legacy: string;
695
- };
696
- type Environment = keyof typeof ORIGINS;
697
-
698
699
  type OdinLang = "en" | "zh";
699
700
 
700
701
  interface AppInitOptions {
@@ -826,7 +827,6 @@ declare class Connect {
826
827
  * client, so its JWT never becomes this instance's API key.
827
828
  */
828
829
  private detachedUser;
829
- private get apiEnv();
830
830
  private get disconnectGeneration();
831
831
  /** Every local and odin-api check; no side effects. */
832
832
  private verifyConnection;
@@ -837,7 +837,7 @@ declare class Connect {
837
837
  private persistConnection;
838
838
  get api(): OdinApiClient;
839
839
  get odin(): OdinCanisterClient;
840
- get currentEnv(): "legacy" | "dev" | "prod" | "local";
840
+ get currentEnv(): "legacy" | "local" | "prod" | "dev" | "staging";
841
841
  /**
842
842
  * @deprecated Since 2.0.0: use `(await odin.ready()).user`, or `state` /
843
843
  * `subscribe()`. Kept with its 1.6.0 behavior: synchronous, returns the
@@ -885,13 +885,7 @@ interface InAppBrowserEnv {
885
885
  }
886
886
  declare function isInAppBrowser(env?: InAppBrowserEnv): boolean;
887
887
 
888
- declare const IMAGE_CDN_ENV: {
889
- dev: string;
890
- prod: string;
891
- local: string;
892
- legacy: string;
893
- };
894
- type OdinEnv = keyof typeof IMAGE_CDN_ENV;
888
+ type OdinEnv = Environment;
895
889
 
896
890
  declare function isDelegationValid(chainJson: string): boolean;
897
891
 
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- import me from'axios';import ye from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';import {Principal}from'@dfinity/principal';var he=Object.defineProperty;var fe=(n,e)=>{for(var t in e)he(n,t,{get:e[t],enumerable:true});};var _e=n=>{try{return ye.parse(n)}catch(e){return console.error("Error parsing response:",e),n}},P=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let i={transformResponse:[_e],...t};return (await me(e,i)).data}async post(e,t,i){return this.fetch(e,{method:"POST",data:t,...i})}async put(e,t,i){return this.fetch(e,{method:"PUT",data:t,...i})}async delete(e,t){return this.fetch(e,{method:"DELETE",...t})}};var re={};fe(re,{DEFAULT_LANG:()=>y,buildTokenImageUrl:()=>Oe,convertToOdinAmount:()=>Ce,createTokenValidators:()=>b,isDelegationValid:()=>_,normalizeOdinLang:()=>v});var ie={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1"},q={dev:"https://images.odin.fun/dev",prod:"https://images.odin.fun/v2",local:"https://images.odin.fun/dev",legacy:"https://images.odin.fun"};function _(n){try{let e=DelegationChain.fromJSON(JSON.parse(n)),t=BigInt(Date.now())*1000000n;return e.delegations.every(i=>i.delegation.expiration==null||i.delegation.expiration>t)}catch{return false}}var y="en";function v(n){return n==="en"||n==="zh"?n:(n!==void 0&&console.warn(`[odin-connect] Unsupported lang "${n}", falling back to "${y}"`),y)}function Oe(n,e="prod"){return `${q[e]}/token/${n}`}function Ce(n,e={decimals:3,divisibility:8}){let t=e.decimals+e.divisibility;if(n=typeof n=="string"?n.trim():String(n),isNaN(+n))return 0n;let[i,r=""]=n.split(".");return r=r.slice(0,t),r=r.padEnd(t,"0"),i=i.replace(/^0+(?=\d)/,""),i===""&&(i="0"),BigInt(i+r)}var b={name:be,image:Se,ticker:Ae,vanity_ticker:ve,description:Re,twitter:ke,website:Ee,telegram:Te};function be(n){if(typeof n!="string")return "Name must be a string.";if(!n||n.trim()==="")return "Name is required.";if(n.length<3||n.length>30)return "Name must be between 3 and 30 characters."}function Re(n){if(n){if(typeof n!="string")return "Description must be a string.";if(n&&n.length>100)return "Description must not exceed 100 characters."}}function Ae(n){if(typeof n!="string")return "Ticker must be a string.";if(!n||n.trim()==="")return "Ticker is required.";if(n.length<3||n.length>10)return "Ticker must be between 3 and 10 characters.";if(!/^[A-Z0-9]+$/.test(n))return "Ticker must be alphanumeric characters in uppercase only.";if(!/(?=(.*[A-Z].*[A-Z]))/.test(n))return "Ticker must have at least 2 alpha characters."}function ve(n){if(!(n==null||n==="")){if(typeof n!="string")return "Vanity ticker must be a string.";if(n.trim()!==n)return "Vanity ticker must not have leading or trailing whitespace.";if([...n].length>10)return "Vanity ticker must be below 10 characters."}}function Se(n){if(!(n instanceof File))return "Image must be a file.";let e=["image/png","image/jpeg","image/webp","image/svg","image/gif","image/avif"],t=200*1024;if(!n)return "Image file is required.";if(!e.includes(n.type))return `Invalid file type. Allowed types are: ${e.join(", ")}`;if(n.size>t)return `File size exceeds the maximum limit of ${t/1024}KB.`}function ke(n){if(n){if(typeof n!="string")return "Twitter handle must be a string.";if(n&&!/^https?:\/\/(www\.)?(twitter\.com|x\.com)\/[A-Za-z0-9_]{1,15}\/?$/.test(n))return "Twitter must be a valid twitter URL."}}function Ee(n){if(n){if(typeof n!="string")return "Website must be a string.";if(n&&!/^(https?:\/\/)?([\w-]+(\.[\w-]+)+)(\/[\w-./?%&=]*)?$/.test(n))return "Website must be a valid URL."}}function Te(n){if(n){if(typeof n!="string")return "Telegram must be a string.";if(n&&!/^(https?:\/\/)?(t\.me|telegram\.me|telegram\.org)\/[A-Za-z0-9_]{5,32}\/?$/.test(n))return "Telegram must be a valid telegram URL."}}var S=class{_apiKey=null;_httpClient;BASE_URL;ENV;constructor(e="prod"){this._httpClient=new P,this.BASE_URL=ie[e],this.ENV=e;}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${q[this.ENV]}/user/${e}`}async getBalances(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{...t}})).data}async getBalance(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{token_in:t}})).data.find(r=>r.id===t)??null}getTokens(e,t={field:"marketcap",direction:"desc"},i={}){return this._httpClient.get(`${this.BASE_URL}/tokens`,{params:{...e,sort:`${t.field}:${t.direction}`,...i}})}getToken(e){return this._httpClient.get(`${this.BASE_URL}/token/${e}`)}async uploadImage(e){if(!this._apiKey)throw new Error("API key is not set");try{let t=b.image?.(e);if(t)throw new Error(t);let i=new FormData;return i.append("file",e),(await this._httpClient.post(`${this.BASE_URL}/upload`,i,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})).data.upload}catch(t){if(t instanceof Error)if(t.name==="AxiosError"){let i=t;throw new Error(i.response?.data?.message||i.message)}else throw new Error(t.message);else throw new Error("Image upload failed")}}updateTokenImage(e,t){if(!this._apiKey)throw new Error("API key is not set");try{return this._httpClient.post(`${this.BASE_URL}/token/${e}/image`,{image:t},{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})}catch(i){if(i instanceof Error&&i.name==="AxiosError"){let r=i;throw new Error(r.response?.data?.message||r.message)}else throw new Error("Image update failed")}}getUserActivity(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/activity`,{params:{...t}})}async getUserTokens(e,t){let i=await this._httpClient.get(`${this.BASE_URL}/user/${e}/tokens`,{params:{...t}});return {...i,data:i.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserLiquidity(e,t){let i=await this._httpClient.get(`${this.BASE_URL}/user/${e}/liquidity`,{params:{...t}});return {...i,data:i.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserAchievements(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/achievements`,{params:{...t}})).data}getUserTransactions(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/transactions`,{params:{...t}})}getUserCreatedTokens(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/created`,{params:{...t}})}getUserStats(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}/stats`)}async verifyConnect(e){try{return await this._httpClient.post(`${this.BASE_URL}/connect/verify`,e)}catch(t){if(t instanceof Error&&t.name==="AxiosError"){let i=t,r=i.response?.data?.message;throw new Error(typeof r=="string"&&r?r:i.message)}throw t instanceof Error?t:new Error("Connect verification failed")}}set apiKey(e){this._apiKey=e;}get apiKey(){return this._apiKey}};var R=class{_identity;_api;_principal;_odin;constructor(e,t,i,r){this._principal=e,this._identity=t,this._api=i,this._odin=r;}get principal(){return this._principal}set principal(e){this._principal=e;}getIdentity(){return this._identity}getUser(){return this._api.getUser(this.principal)}buildAvatarImageUrl(){return this._api.getUserAvatarUrl(this.principal)}getBalances(e){return this._api.getBalances(this.principal,e)}getBalance(e){return this._api.getBalance(this.principal,e)}getTokens(e){return this._api.getUserTokens(this.principal,e)}getCreatedTokens(e){return this._api.getUserCreatedTokens(this.principal,e)}getActivity(e){return this._api.getUserActivity(this.principal,e)}getLiquidity(e){return this._api.getUserLiquidity(this.principal,e)}getAchievements(e){return this._api.getUserAchievements(this.principal,e)}getTransactions(e){return this._api.getUserTransactions(this.principal,e)}getStats(){return this._api.getUserStats(this.principal)}sell(e){return this._odin.sell({...e,principal:this.principal})}buy(e){return this._odin.buy({...e,principal:this.principal})}addLiquidity(e){return this._odin.addLiquidity({...e,principal:this.principal})}removeLiquidity(e){return this._odin.removeLiquidity({...e,principal:this.principal})}transfer(e){return this._odin.transfer({...e,principal:this.principal})}createToken(e){return this._odin.createToken({...e,principal:this.principal})}icrcApprove(e){return this._odin.icrcApprove({...e,principal:this.principal})}swap(e){return this._odin.swap({...e,principal:this.principal})}};var z={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun"};var U=class{_settings;constructor(e){this._settings={target:e?.target||"_blank",settings:e?.settings||""};}get settings(){return this._settings}set settings(e){this._settings={...this._settings,...e};}open(e){return window.open(e,this._settings?.target||"_blank",this._settings?.settings)}navigate(e){window.location.assign(e.href);}};var xe=[/\bOKApp\b/i],Ie=["XverseProviders","btc_providers","unisat","okxwallet","phantom","LeatherProvider","magicEden","wizz","oyl","ethereum","solana"];function Pe(n,e){return /Android|iPhone|iPad|iPod|Mobile/i.test(n)?true:/Macintosh/.test(n)&&e>1}function qe(n,e){return /Android/i.test(n)&&/;\s*wv\)/.test(n)?true:(/iPhone|iPad|iPod/i.test(n)||/Macintosh/.test(n)&&e>1)&&/AppleWebKit/i.test(n)&&!/Safari\//.test(n)}function Ue(n){return Ie.some(e=>n[e]!=null)}function W(n={}){let e=n.userAgent??(typeof navigator>"u"?"":navigator.userAgent),t=n.maxTouchPoints??(typeof navigator>"u"?0:navigator.maxTouchPoints||0),i=n.globals??(typeof window>"u"?{}:window);return xe.some(r=>r.test(e))||qe(e,t)?true:Pe(e,t)&&Ue(i)}var Le="odin_connect",De=600*1e3,G="$odin_bigint";function Be(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?{[G]:t.toString()}:t)}function Ne(n){return JSON.parse(n,(e,t)=>t!==null&&typeof t=="object"&&Object.keys(t).length===1&&typeof t[G]=="string"?BigInt(t[G]):t)}var L=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:pending_redirect`;}save(e){let t=Be(e);try{return sessionStorage.setItem(this._key,t),sessionStorage.getItem(this._key)===t}catch{return false}}peek(){try{let e=sessionStorage.getItem(this._key);if(!e)return null;let t=Ne(e);return typeof t?.state!="string"||typeof t?.path!="string"?null:t}catch{return null}}take(){let e=this.peek();try{sessionStorage.removeItem(this._key);}catch{}return e}dropIfOlderThan(e){let t=this.peek();if(!t)return;(typeof t.createdAt=="number"?Date.now()-t.createdAt:1/0)>e&&this.take();}};function J(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(){return J(crypto.getRandomValues(new Uint8Array(24)))}function $e(){return window.location.origin+window.location.pathname}function Ve(){let n=new URL(window.location.href);return n.hash="",n.href}function D(){let n=window.location.hash.replace(/^#/,"");return n?new URLSearchParams(n).get(Le):null}function se(n){let e=new URL(window.location.href);if(e.hash="",typeof n=="string")try{let t=new URL(n);t.origin===e.origin&&t.pathname===e.pathname&&(e.search=t.search);}catch{}window.history.replaceState(window.history.state,"",e.href);}function Ke(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=Uint8Array.from(atob(e),r=>r.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(t));return typeof i?.path!="string"||typeof i?.state!="string"?null:i}catch{return null}}var B=class{constructor(e,t){this._window=e;this._pending=t;}_window;_pending;mode="auto";get useRedirect(){return this.mode==="redirect"||this.mode==="auto"&&W()}start(e,t,i,r){let s;try{s=this._pending.save({...t,state:i,createdAt:Date.now(),returnHref:Ve()});}catch{return Promise.reject(new Error("returnState must be JSON-serializable (bigints are allowed)"))}if(!s)return Promise.reject(new Error("Redirect mode needs sessionStorage, which is unavailable"));if(e.searchParams.append("return_url",$e()),e.searchParams.append("state",i),r&&typeof window<"u"){let o=a=>{a.persisted&&(window.removeEventListener("pageshow",o),!D()&&(this._pending.peek()?.state===i&&this._pending.take(),r()));};window.addEventListener("pageshow",o);}return this._window.navigate(e),new Promise(()=>{})}consume(){let e=D();if(e===null)return this._pending.dropIfOlderThan(De),null;let t=Ke(e),i=this._pending.take();if(!t||!i||i.state!==t.state||i.path!==t.path)throw se(),new Error("Unexpected OdinConnect redirect result");return se(i.returnHref),{result:t,pending:i}}};var k={buy:{path:"authorize/buy",success:"purchased",failure:"Purchase failed or was cancelled"},sell:{path:"authorize/sell",success:"sold",failure:"Sell failed or was cancelled"},transfer:{path:"authorize/transfer",success:"transferred",failure:"Transfer failed or was cancelled"},swap:{path:"authorize/swap",success:"swapped",failure:"Swap failed or was cancelled"},add_liquidity:{path:"authorize/add_liquidity",success:"addedLiquidity",failure:"Add liquidity failed or was cancelled"},remove_liquidity:{path:"authorize/remove_liquidity",success:"removedLiquidity",failure:"Remove liquidity failed or was cancelled"},icrc_approve:{path:"authorize/icrc_approve",success:"approved",failure:"ICRC approve failed or was cancelled"},create_token:{path:"authorize/create_token",success:"tokenCreated",failure:"Token creation failed or was cancelled"}};function oe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}var M="popup_closed",H="navigated_back",je=/^[a-z0-9_]{1,64}$/;function $(n){let e=oe(n)?.reason;return typeof e=="string"&&je.test(e)?e:void 0}function Z(n,e,t){if(e===k[n].success){let i=oe(t);return {status:"success",...i?{detail:i}:{}}}if(e==="rejected"){let i=$(t);return {status:"rejected",...i?{error:i}:{}}}return {status:"failed",error:k[n].failure}}function A(n){return n.catch(()=>{}),n}var ze=500,We=1500;function X(n,e,t,i){let r=false,s=null,o=null,a=()=>{if(!t)return true;let{request:c}=t.state;return c?.id===e&&c.status==="pending"},p=()=>{r||(r=true,clearInterval(d),o!==null&&clearTimeout(o),s?.());},d=setInterval(()=>{!n.closed||o!==null||(clearInterval(d),o=setTimeout(()=>{let c=a();p(),c&&i();},We));},ze);return s=t?.subscribe(()=>{a()||p();})??null,p}var N=class{_window;_appInfo;_api;_redirect;_store;origin;constructor(e,t,i,r,s=null,o=null){this._window=e,this._redirect=s,this._api=t,this._appInfo=i,this.origin=r,this._store=o;}get appInfo(){return this._appInfo}createUrl(e,t=w()){let i=new URL(`${this.origin}/${e}`);return i.searchParams.append("v","2"),i.searchParams.append("request_id",t),this._appInfo?.name&&i.searchParams.append("app_name",this._appInfo.name),i.searchParams.append("referrer",window.location.origin),i.searchParams.append("lang",this._appInfo?.lang||y),i}startRequest(e,t,i,r){this._store?.dispatch({type:"request",request:{id:e,action:t,status:"pending",input:i,...r!==void 0?{returnState:r}:{}}});}fail(e,t){let i=t instanceof Error?t:new Error(String(t));return this._store?.dispatch({type:"settle",id:e,status:"failed",error:i.message}),i}baseAction({action:e,input:t,params:i,returnState:r,requestId:s=w()}){let{path:o,failure:a}=k[e];this.startRequest(s,e,t,r);let p=this.createUrl(o,s);for(let d in i)i[d]&&p.searchParams.append(d,i[d]);return this._redirect?.useRedirect?A(this._redirect.start(p,{path:"/"+o,input:t,returnState:r},s,()=>this._store?.dispatch({type:"settle",id:s,status:"rejected",error:H})).catch(d=>{throw this.fail(s,d)})):A(new Promise((d,c)=>{let m=()=>{},u=h=>{if(h.origin===this.origin&&h.data?.path==="/"+o){window.removeEventListener("message",u),m();let O=Z(e,h.data.message,h.data.detail);this._store?.dispatch({type:"settle",id:s,...O}),O.status==="success"?d(true):c(new Error(a));}},g=this._window.open(p);if(!g||g.closed||typeof g.closed>"u"){c(this.fail(s,`Failed to open ${o} window, please always allow popups and try again`));return}window.addEventListener("message",u),m=X(g,s,this._store,()=>{window.removeEventListener("message",u),this._store?.dispatch({type:"settle",id:s,status:"rejected",error:M}),c(new Error(a));});}))}sell({token:e,tokenAmount:t,principal:i,returnState:r}){return this.baseAction({action:"sell",input:{token:e,tokenAmount:t},params:{principal:i,token:e,amount:t.toString()},returnState:r})}buy({principal:e,token:t,btcAmount:i,returnState:r}){return this.baseAction({action:"buy",input:{token:t,btcAmount:i},params:{principal:e,token:t,amount:i.toString()},returnState:r})}transfer({principal:e,token:t,amount:i,destination:r,returnState:s}){return this.baseAction({action:"transfer",input:{token:t,amount:i,destination:r},params:{principal:e,token:t,amount:i.toString(),destination:r},returnState:s})}addLiquidity({principal:e,btcAmount:t,token:i,returnState:r}){return this.baseAction({action:"add_liquidity",input:{token:i,btcAmount:t},params:{principal:e,amount:t.toString(),token:i},returnState:r})}removeLiquidity({principal:e,lpAmount:t,token:i,returnState:r}){return this.baseAction({action:"remove_liquidity",input:{token:i,lpAmount:t},params:{principal:e,amount:t.toString(),token:i},returnState:r})}swap({principal:e,fromToken:t,toToken:i,fromAmount:r,returnState:s}){return this.baseAction({action:"swap",input:{fromToken:t,toToken:i,fromAmount:r},params:{principal:e,from:t,to:i,amount:r.toString()},returnState:s})}icrcApprove({principal:e,token:t,spender:i,amount:r,returnState:s}){return this.baseAction({action:"icrc_approve",input:{token:t,spender:i,amount:r},params:{principal:e,token:t,spender:i,amount:r.toString()},returnState:s})}createToken({image:e,returnState:t,principal:i,...r}){let s=w(),o={...r};return this.startRequest(s,"create_token",o,t),A((async()=>{let a;try{for(let p in b)if(p in r){let c=b[p]?.(r[p]||null);if(c)throw new Error(c)}if(r.discount&&!/^[A-Za-z0-9]{10}$/.test(r.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");a=await this._api.uploadImage(e);}catch(p){throw this.fail(s,p)}return this.baseAction({action:"create_token",input:{...o,image:a},params:{...r,principal:i,image:a,buy:r.buy?.toString()},returnState:t,requestId:s})})())}};var V=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:session`;}save(e){try{localStorage.setItem(this._key,JSON.stringify(e));}catch{}}load(){try{let e=localStorage.getItem(this._key);if(!e)return null;let t=JSON.parse(e);return this.isValidSessionData(t)?t:null}catch{return null}}isValidSessionData(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.principal=="string"&&typeof t.sessionKey=="string"&&(t.delegationChain===null||typeof t.delegationChain=="string")&&(t.jwt===null||typeof t.jwt=="string")}clear(){try{localStorage.removeItem(this._key);}catch{}}};var f=class extends Error{constructor(e){super(`OdinConnect could not verify the connection: ${e}`),this.name="ConnectVerificationError";}};function l(n){throw new f(n)}function Ge(n,e){if(n.byteLength!==e.byteLength)return false;for(let t=0;t<n.byteLength;t++)if(n[t]!==e[t])return false;return true}function Je(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Fe(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Me=`odin-connect-verify:v1
2
- `;async function pe(n,e){let t=await n.sign(new TextEncoder().encode(Me+e));return Fe(new Uint8Array(t))}function He(n){try{if(n.delegation)return new Uint8Array(DelegationChain.fromJSON(JSON.parse(n.delegation)).publicKey);if(n.publicKey)return Je(n.publicKey)}catch{}l("the identity proof has no readable signer");}function de(n,e){(!n||typeof n.payload!="string"||typeof n.signature!="string")&&l("the result carries no identity proof");let t;try{t=JSON.parse(n.payload);}catch{l("the identity proof payload is malformed");}(t?.typ!=="odin-connect-identity"||t.v!==1)&&l("the identity proof has an unknown type"),t.nonce!==e.nonce&&l("the identity proof belongs to another request"),t.aud!==e.audience&&l("the identity proof was issued to another origin"),t.principal!==e.principal&&l("the identity proof is for another principal"),typeof t.sk!="string"&&l("the identity proof is not bound to a session key"),t.sk!==e.sessionPubkey&&l("the identity proof was issued to another session key"),e.requires_api&&t.api!==true&&l("API access was not granted");let i=He(n);Principal.selfAuthenticating(i).toText()!==e.principal&&l("the identity proof signer does not match the principal");}function le(n,e){n||l("the delegation chain is missing");let t;try{t=DelegationChain.fromJSON(n);}catch{l("the delegation chain is malformed");}t.delegations.length===0&&l("the delegation chain is empty"),_(JSON.stringify(t.toJSON()))||l("the delegation chain has expired");let i=t.delegations[t.delegations.length-1].delegation;Ge(new Uint8Array(i.pubkey),e.sessionPublicKey)||l("the delegation chain was issued to another session key");let r=new Uint8Array(t.publicKey);Principal.selfAuthenticating(r).toText()!==e.principal&&l("the delegation chain belongs to another principal");let s=new Set(e.targets);for(let{delegation:o}of t.delegations)o.targets?.some(a=>!s.has(a.toText()))&&l("the delegation chain targets canisters that were not requested");return t}function Ze(n){return Object.isFrozen(n)?n:(Object.freeze(n.input),n.detail&&Object.freeze(n.detail),Object.freeze(n))}function K(n){return Object.freeze({...n,request:n.request?Ze(n.request):null})}function Xe(n,e){switch(e.type){case "ready":return K({status:"ready",user:n.user??e.user,request:n.request??e.request});case "request":return K({...n,request:{...e.request}});case "settle":{let t=n.request;if(!t||t.id!==e.id)return n;let i={...t,status:e.status,...e.detail?{detail:e.detail}:{},...e.error!==void 0?{error:e.error}:{}};return K({...n,user:e.user??n.user,request:i})}case "disconnect":return n.user===null&&n.request===null?n:K({...n,user:null,request:null})}}var E=Object.freeze({status:"initializing",user:null,request:null}),j=class{_state=E;_listeners=new Set;get state(){return this._state}dispatch(e){let t=Xe(this._state,e);if(t!==this._state){this._state=t;for(let i of [...this._listeners])if(this._listeners.has(i))try{i(t);}catch(r){queueMicrotask(()=>{throw r});}}}subscribe(e){let t=i=>e(i);return this._listeners.add(t),()=>{this._listeners.delete(t);}}};var T=new Map,Qe=1e4,Q=new Map;function et(n){let e=0;for(let t=0;t<n.length;t++)e=e*31+n.charCodeAt(t)|0;return (e>>>0).toString(36).slice(0,3).padStart(3,"0")}function ge(n){return J(new Uint8Array(n.getPublicKey().toDer()))}function tt(n){return `${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${et(n)}`}var ee=class{static serverState=E;_appInfo=null;_api;_window;_odin;_storage;_redirect;_store=new j;_ready=null;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||tt(this._appInfo.name),this._appInfo.lang=v(this._appInfo.lang),this._api=new S(this.apiEnv),this._window=new U,this._redirect=new B(this._window,new L(this._appInfo.slug,this._appInfo.env||"prod")),this._redirect.mode=this._appInfo.mode||"auto",this._odin=new N(this._window,this._api,this._appInfo,z[this._appInfo.env||"prod"],this._redirect,this._store),this._storage=new V(this._appInfo.slug,this._appInfo.env||"prod"),typeof window<"u"&&this.ready();}createUrl(e,t=w()){let i=new URL(`${this.origin}/${e}`);return i.searchParams.append("v","2"),i.searchParams.append("request_id",t),this._appInfo?.name&&i.searchParams.append("app_name",this._appInfo.name),i.searchParams.append("referrer",window.location.origin),i.searchParams.append("lang",this.lang),i}get origin(){return z[this._appInfo?.env||"prod"]}get lang(){return this._appInfo?.lang||y}set lang(e){this._appInfo&&(this._appInfo.lang=v(e));}get mode(){return this._redirect.mode}set mode(e){this._redirect.mode=e,this._appInfo&&(this._appInfo.mode=e);}get appInfo(){return this._appInfo}get slug(){return this._appInfo?.slug||""}ready(){return typeof window>"u"?Promise.resolve(this.state):(this._ready||(this._ready=this.initialize()),this._ready.then(()=>this.state))}get state(){return this._store.state}getState=()=>this._store.state;getServerState=()=>E;subscribe=e=>this._store.subscribe(e);get user(){return this._store.state.user}initialize(){let e=this.disconnectGeneration,t=null;try{t=this.redirectOutcome(),t||this._redirect.consume();}catch{}return this.finishReady(t,e)}async finishReady(e,t){let i=null,r=null;if(e)try{let s=await e;t===this.disconnectGeneration&&(i=s.request,s.connected&&(r=this.bindConnection(s.connected)));}catch{}this._store.dispatch({type:"ready",user:r??this.loadStoredSession(),request:i});}connect({open:e,requires_api:t,requires_delegation:i,targets:r,returnState:s}={requires_delegation:false,requires_api:false}){let o=Ed25519KeyIdentity.generate(),a=w(),p={requires_api:t,requires_delegation:i,targets:r},d={requires_api:!!t,requires_delegation:!!i,targets:r?[...r]:[]};this._store.dispatch({type:"request",request:{id:a,action:"connect",status:"pending",input:d,...s!==void 0?{returnState:s}:{}}});let c=this.createConnectUrl(o,a,p);return this._redirect.useRedirect?A(this._redirect.start(c,{path:"/authorize/connect",sessionKey:JSON.stringify(o.toJSON()),requires_delegation:d.requires_delegation,requires_api:d.requires_api,targets:r,returnState:s},a,()=>this._store.dispatch({type:"settle",id:a,status:"rejected",error:H})).catch(m=>{throw this.settleError(a,"failed",m)})):(e&&(this._window.settings=e),A(new Promise((m,u)=>{let g=null,h=()=>{},O=async C=>{if(C.origin===this.origin&&C.source===g&&C.data?.path==="/authorize/connect"){if(window.removeEventListener("message",O),h(),C.data.message==="rejected"){let I=$(C.data.detail);this._store.dispatch({type:"settle",id:a,status:"rejected",...I?{error:I}:{}}),u(new Error("User rejected the connection"));return}let te={requestId:a,...p},x;try{x=await this.verifyConnection(C.data.message,o,te);}catch(I){u(this.settleError(a,"unverified",I));return}if(this._store.state.request?.id!==a){m(this.detachedUser(x));return}this.persistConnection(x,o,te);let ne=this.bindConnection(x);this._store.dispatch({type:"settle",id:a,status:"success",user:ne}),m(ne);}};if(g=this._window.open(c),!g||g.closed||typeof g.closed>"u"){u(this.settleError(a,"failed",new Error("Failed to open authorize/connect window, please always allow popups and try again")));return}window.addEventListener("message",O),h=X(g,a,this._store,()=>{window.removeEventListener("message",O),this._store.dispatch({type:"settle",id:a,status:"rejected",error:M}),u(new Error("User rejected the connection"));});})))}settleError(e,t,i){let r=i instanceof Error?i:t==="unverified"?new f(String(i)):new Error(String(i));return this._store.dispatch({type:"settle",id:e,status:t,error:r.message}),r}createConnectUrl(e,t,{requires_api:i,requires_delegation:r,targets:s}){let o=this.createUrl("authorize/connect",t);return o.searchParams.append("requires_api",i?"1":"0"),o.searchParams.append("session_pubkey",ge(e)),r&&(o.searchParams.append("requires_delegation","1"),o.searchParams.append("targets",s?.join(",")||"")),o}redirectOutcome(){let e=this.redirectCacheKey,t=D(),i=T.get(e);if(t!==null&&i?.fragment!==t){let r={fragment:t,promise:this.readRedirectResult(),settled:false};T.set(e,r);let s=()=>{r.settled=true,setTimeout(()=>{T.get(e)===r&&T.delete(e);},Qe);};return r.promise.then(s,o=>{console.warn("OdinConnect: ignored a stale or foreign redirect result",o),s();}),r.promise}return i&&!i.settled?i.promise:null}bindConnection({principal:e,identity:t,jwt:i}){return this._api.apiKey=i,new R(e,t,this._api,this._odin)}get redirectCacheKey(){return `${this.slug}:${this.currentEnv}`}async readRedirectResult(){let e=this.disconnectGeneration,t=this._redirect.consume();if(!t)throw new Error("Unexpected OdinConnect redirect result");let{result:i,pending:r}=t,s=r.returnState!==void 0?{returnState:r.returnState}:{},o=r.path.replace(/^\/authorize\//,"");if(o==="connect"){let a={id:r.state,action:"connect",input:{requires_api:!!r.requires_api,requires_delegation:!!r.requires_delegation,targets:r.targets??[]},...s};if(i.message==="rejected"){let c=$(i.detail);return {request:{...a,status:"rejected",...c?{error:c}:{}}}}if(!r.sessionKey)return {request:{...a,status:"unverified",error:new f("the pending request has no session key").message}};let p=Ed25519KeyIdentity.fromJSON(r.sessionKey),d={requestId:r.state,requires_api:r.requires_api,requires_delegation:r.requires_delegation,targets:r.targets};try{let c=await this.verifyConnection(i.message,p,d);return e!==this.disconnectGeneration?{request:{...a,status:"success"}}:(this.persistConnection(c,p,d),{request:{...a,status:"success"},connected:c})}catch(c){return {request:{...a,status:"unverified",error:c instanceof Error?c.message:String(c)}}}}if(!(o in k))throw new Error("Unexpected OdinConnect redirect result");return {request:{id:r.state,action:o,input:r.input??{},...s,...Z(o,i.message,i.detail)}}}detachedUser({principal:e,identity:t,jwt:i}){let r=new S(this.apiEnv);return r.apiKey=i,new R(e,t,r,this._odin)}get apiEnv(){let e=this._appInfo?.env;return e==="prod"?"prod":e==="legacy"?"legacy":"dev"}get disconnectGeneration(){return Q.get(this.redirectCacheKey)??0}async verifyConnection(e,t,{requestId:i,requires_api:r,requires_delegation:s,targets:o}){if(!e||typeof e.principal!="string")throw new f("the result has no principal");let{principal:a,proof:p}=e,d=window.location.origin;de(p,{principal:a,nonce:i,audience:d,requires_api:!!r,sessionPubkey:ge(t)});let c=null;s&&(c=le(e.delegationChain,{principal:a,sessionPublicKey:new Uint8Array(t.getPublicKey().toDer()),targets:o??[]}));let m=await pe(t,p.payload),u;try{u=await this._api.verifyConnect({payload:p.payload,signature:p.signature,delegation:p.delegation??null,publicKey:p.publicKey??null,audience:d,nonce:i,issue_jwt:!!r,client_signature:m});}catch(h){throw new f(`odin-api refused the proof (${h instanceof Error?h.message:String(h)})`)}if(u?.principal!==a)throw new f("odin-api verified a different principal");let g=null;if(r){if(typeof u.jwt!="string"||!u.jwt)throw new f("odin-api issued no API key");g=u.jwt;}return {principal:a,chain:c,identity:c?DelegationIdentity.fromDelegation(t,c):null,jwt:g}}persistConnection({principal:e,chain:t,jwt:i},r,{requires_api:s,requires_delegation:o}){this._storage.clear(),this._api.apiKey=null,(s||o)&&this._storage.save({principal:e,sessionKey:JSON.stringify(r.toJSON()),delegationChain:t?JSON.stringify(t.toJSON()):null,jwt:i});}get api(){return this._api}get odin(){return this._odin}get currentEnv(){return this._appInfo?.env||"prod"}restoreSession(){return this.state.status==="ready"?this.state.user:this.loadStoredSession()}loadStoredSession(){try{let e=this._storage.load();if(!e)return null;if(e.delegationChain&&!_(e.delegationChain))return this._storage.clear(),null;e.jwt&&(this._api.apiKey=e.jwt);let t=null;if(e.delegationChain&&e.sessionKey){let i=Ed25519KeyIdentity.fromJSON(e.sessionKey),r=DelegationChain.fromJSON(JSON.parse(e.delegationChain));t=DelegationIdentity.fromDelegation(i,r);}return new R(e.principal,t,this._api,this._odin)}catch{return this._storage.clear(),null}}disconnect(){let e=this.redirectCacheKey;Q.set(e,(Q.get(e)??0)+1),this._storage.clear(),this._api.apiKey=null,T.delete(e),this._store.dispatch({type:"disconnect"});}isSessionValid(){let e=this._storage.load();return e?e.delegationChain?_(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
3
- export{E as INITIAL_ODIN_STATE,ee as OdinConnect,f as OdinConnectVerificationError,re as OdinUtils,W as isInAppBrowser};
1
+ import me from'axios';import ye from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';import {Principal}from'@dfinity/principal';var he=Object.defineProperty;var fe=(n,e)=>{for(var t in e)he(n,t,{get:e[t],enumerable:true});};var _e=n=>{try{return ye.parse(n)}catch(e){return console.error("Error parsing response:",e),n}},I=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let i={transformResponse:[_e],...t};return (await me(e,i)).data}async post(e,t,i){return this.fetch(e,{method:"POST",data:t,...i})}async put(e,t,i){return this.fetch(e,{method:"PUT",data:t,...i})}async delete(e,t){return this.fetch(e,{method:"DELETE",...t})}};var re={};fe(re,{DEFAULT_LANG:()=>y,buildTokenImageUrl:()=>Oe,convertToOdinAmount:()=>Ce,createTokenValidators:()=>b,isDelegationValid:()=>_,normalizeOdinLang:()=>v});var ie={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1",staging:"https://api.odin.fun/v2"},q={dev:"https://images.odin.fun/dev",prod:"https://images.odin.fun/v2",local:"https://images.odin.fun/dev",legacy:"https://images.odin.fun",staging:"https://images.odin.fun/v2"};function _(n){try{let e=DelegationChain.fromJSON(JSON.parse(n)),t=BigInt(Date.now())*1000000n;return e.delegations.every(i=>i.delegation.expiration==null||i.delegation.expiration>t)}catch{return false}}var y="en";function v(n){return n==="en"||n==="zh"?n:(n!==void 0&&console.warn(`[odin-connect] Unsupported lang "${n}", falling back to "${y}"`),y)}function Oe(n,e="prod"){return `${q[e]}/token/${n}`}function Ce(n,e={decimals:3,divisibility:8}){let t=e.decimals+e.divisibility;if(n=typeof n=="string"?n.trim():String(n),isNaN(+n))return 0n;let[i,r=""]=n.split(".");return r=r.slice(0,t),r=r.padEnd(t,"0"),i=i.replace(/^0+(?=\d)/,""),i===""&&(i="0"),BigInt(i+r)}var b={name:be,image:Se,ticker:Ae,vanity_ticker:ve,description:Re,twitter:Ee,website:ke,telegram:Te};function be(n){if(typeof n!="string")return "Name must be a string.";if(!n||n.trim()==="")return "Name is required.";if(n.length<3||n.length>30)return "Name must be between 3 and 30 characters."}function Re(n){if(n){if(typeof n!="string")return "Description must be a string.";if(n&&n.length>100)return "Description must not exceed 100 characters."}}function Ae(n){if(typeof n!="string")return "Ticker must be a string.";if(!n||n.trim()==="")return "Ticker is required.";if(n.length<3||n.length>10)return "Ticker must be between 3 and 10 characters.";if(!/^[A-Z0-9]+$/.test(n))return "Ticker must be alphanumeric characters in uppercase only.";if(!/(?=(.*[A-Z].*[A-Z]))/.test(n))return "Ticker must have at least 2 alpha characters."}function ve(n){if(!(n==null||n==="")){if(typeof n!="string")return "Vanity ticker must be a string.";if(n.trim()!==n)return "Vanity ticker must not have leading or trailing whitespace.";if([...n].length>10)return "Vanity ticker must be below 10 characters."}}function Se(n){if(!(n instanceof File))return "Image must be a file.";let e=["image/png","image/jpeg","image/webp","image/svg","image/gif","image/avif"],t=200*1024;if(!n)return "Image file is required.";if(!e.includes(n.type))return `Invalid file type. Allowed types are: ${e.join(", ")}`;if(n.size>t)return `File size exceeds the maximum limit of ${t/1024}KB.`}function Ee(n){if(n){if(typeof n!="string")return "Twitter handle must be a string.";if(n&&!/^https?:\/\/(www\.)?(twitter\.com|x\.com)\/[A-Za-z0-9_]{1,15}\/?$/.test(n))return "Twitter must be a valid twitter URL."}}function ke(n){if(n){if(typeof n!="string")return "Website must be a string.";if(n&&!/^(https?:\/\/)?([\w-]+(\.[\w-]+)+)(\/[\w-./?%&=]*)?$/.test(n))return "Website must be a valid URL."}}function Te(n){if(n){if(typeof n!="string")return "Telegram must be a string.";if(n&&!/^(https?:\/\/)?(t\.me|telegram\.me|telegram\.org)\/[A-Za-z0-9_]{5,32}\/?$/.test(n))return "Telegram must be a valid telegram URL."}}var S=class{_apiKey=null;_httpClient;BASE_URL;ENV;constructor(e="prod"){this._httpClient=new I,this.BASE_URL=ie[e],this.ENV=e;}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${q[this.ENV]}/user/${e}`}async getBalances(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{...t}})).data}async getBalance(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{token_in:t}})).data.find(r=>r.id===t)??null}getTokens(e,t={field:"marketcap",direction:"desc"},i={}){return this._httpClient.get(`${this.BASE_URL}/tokens`,{params:{...e,sort:`${t.field}:${t.direction}`,...i}})}getToken(e){return this._httpClient.get(`${this.BASE_URL}/token/${e}`)}async uploadImage(e){if(!this._apiKey)throw new Error("API key is not set");try{let t=b.image?.(e);if(t)throw new Error(t);let i=new FormData;return i.append("file",e),(await this._httpClient.post(`${this.BASE_URL}/upload`,i,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})).data.upload}catch(t){if(t instanceof Error)if(t.name==="AxiosError"){let i=t;throw new Error(i.response?.data?.message||i.message)}else throw new Error(t.message);else throw new Error("Image upload failed")}}updateTokenImage(e,t){if(!this._apiKey)throw new Error("API key is not set");try{return this._httpClient.post(`${this.BASE_URL}/token/${e}/image`,{image:t},{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})}catch(i){if(i instanceof Error&&i.name==="AxiosError"){let r=i;throw new Error(r.response?.data?.message||r.message)}else throw new Error("Image update failed")}}getUserActivity(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/activity`,{params:{...t}})}async getUserTokens(e,t){let i=await this._httpClient.get(`${this.BASE_URL}/user/${e}/tokens`,{params:{...t}});return {...i,data:i.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserLiquidity(e,t){let i=await this._httpClient.get(`${this.BASE_URL}/user/${e}/liquidity`,{params:{...t}});return {...i,data:i.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserAchievements(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/achievements`,{params:{...t}})).data}getUserTransactions(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/transactions`,{params:{...t}})}getUserCreatedTokens(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/created`,{params:{...t}})}getUserStats(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}/stats`)}async verifyConnect(e){try{return await this._httpClient.post(`${this.BASE_URL}/connect/verify`,e)}catch(t){if(t instanceof Error&&t.name==="AxiosError"){let i=t,r=i.response?.data?.message;throw new Error(typeof r=="string"&&r?r:i.message)}throw t instanceof Error?t:new Error("Connect verification failed")}}set apiKey(e){this._apiKey=e;}get apiKey(){return this._apiKey}};var R=class{_identity;_api;_principal;_odin;constructor(e,t,i,r){this._principal=e,this._identity=t,this._api=i,this._odin=r;}get principal(){return this._principal}set principal(e){this._principal=e;}getIdentity(){return this._identity}getUser(){return this._api.getUser(this.principal)}buildAvatarImageUrl(){return this._api.getUserAvatarUrl(this.principal)}getBalances(e){return this._api.getBalances(this.principal,e)}getBalance(e){return this._api.getBalance(this.principal,e)}getTokens(e){return this._api.getUserTokens(this.principal,e)}getCreatedTokens(e){return this._api.getUserCreatedTokens(this.principal,e)}getActivity(e){return this._api.getUserActivity(this.principal,e)}getLiquidity(e){return this._api.getUserLiquidity(this.principal,e)}getAchievements(e){return this._api.getUserAchievements(this.principal,e)}getTransactions(e){return this._api.getUserTransactions(this.principal,e)}getStats(){return this._api.getUserStats(this.principal)}sell(e){return this._odin.sell({...e,principal:this.principal})}buy(e){return this._odin.buy({...e,principal:this.principal})}addLiquidity(e){return this._odin.addLiquidity({...e,principal:this.principal})}removeLiquidity(e){return this._odin.removeLiquidity({...e,principal:this.principal})}transfer(e){return this._odin.transfer({...e,principal:this.principal})}createToken(e){return this._odin.createToken({...e,principal:this.principal})}icrcApprove(e){return this._odin.icrcApprove({...e,principal:this.principal})}swap(e){return this._odin.swap({...e,principal:this.principal})}};var z={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun",staging:"https://staging.odin.fun"};var U=class{_settings;constructor(e){this._settings={target:e?.target||"_blank",settings:e?.settings||""};}get settings(){return this._settings}set settings(e){this._settings={...this._settings,...e};}open(e){return window.open(e,this._settings?.target||"_blank",this._settings?.settings)}navigate(e){window.location.assign(e.href);}};var xe=[/\bOKApp\b/i],Pe=["XverseProviders","btc_providers","unisat","okxwallet","phantom","LeatherProvider","magicEden","wizz","oyl","ethereum","solana"];function Ie(n,e){return /Android|iPhone|iPad|iPod|Mobile/i.test(n)?true:/Macintosh/.test(n)&&e>1}function qe(n,e){return /Android/i.test(n)&&/;\s*wv\)/.test(n)?true:(/iPhone|iPad|iPod/i.test(n)||/Macintosh/.test(n)&&e>1)&&/AppleWebKit/i.test(n)&&!/Safari\//.test(n)}function Ue(n){return Pe.some(e=>n[e]!=null)}function W(n={}){let e=n.userAgent??(typeof navigator>"u"?"":navigator.userAgent),t=n.maxTouchPoints??(typeof navigator>"u"?0:navigator.maxTouchPoints||0),i=n.globals??(typeof window>"u"?{}:window);return xe.some(r=>r.test(e))||qe(e,t)?true:Ie(e,t)&&Ue(i)}var Le="odin_connect",De=600*1e3,J="$odin_bigint";function Be(n){return JSON.stringify(n,(e,t)=>typeof t=="bigint"?{[J]:t.toString()}:t)}function Ne(n){return JSON.parse(n,(e,t)=>t!==null&&typeof t=="object"&&Object.keys(t).length===1&&typeof t[J]=="string"?BigInt(t[J]):t)}var L=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:pending_redirect`;}save(e){let t=Be(e);try{return sessionStorage.setItem(this._key,t),sessionStorage.getItem(this._key)===t}catch{return false}}peek(){try{let e=sessionStorage.getItem(this._key);if(!e)return null;let t=Ne(e);return typeof t?.state!="string"||typeof t?.path!="string"?null:t}catch{return null}}take(){let e=this.peek();try{sessionStorage.removeItem(this._key);}catch{}return e}dropIfOlderThan(e){let t=this.peek();if(!t)return;(typeof t.createdAt=="number"?Date.now()-t.createdAt:1/0)>e&&this.take();}};function F(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function w(){return F(crypto.getRandomValues(new Uint8Array(24)))}function $e(){return window.location.origin+window.location.pathname}function Ve(){let n=new URL(window.location.href);return n.hash="",n.href}function D(){let n=window.location.hash.replace(/^#/,"");return n?new URLSearchParams(n).get(Le):null}function se(n){let e=new URL(window.location.href);if(e.hash="",typeof n=="string")try{let t=new URL(n);t.origin===e.origin&&t.pathname===e.pathname&&(e.search=t.search);}catch{}window.history.replaceState(window.history.state,"",e.href);}function Ke(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=Uint8Array.from(atob(e),r=>r.charCodeAt(0)),i=JSON.parse(new TextDecoder().decode(t));return typeof i?.path!="string"||typeof i?.state!="string"?null:i}catch{return null}}var B=class{constructor(e,t){this._window=e;this._pending=t;}_window;_pending;mode="auto";get useRedirect(){return this.mode==="redirect"||this.mode==="auto"&&W()}start(e,t,i,r){let s;try{s=this._pending.save({...t,state:i,createdAt:Date.now(),returnHref:Ve()});}catch{return Promise.reject(new Error("returnState must be JSON-serializable (bigints are allowed)"))}if(!s)return Promise.reject(new Error("Redirect mode needs sessionStorage, which is unavailable"));if(e.searchParams.append("return_url",$e()),e.searchParams.append("state",i),r&&typeof window<"u"){let o=a=>{a.persisted&&(window.removeEventListener("pageshow",o),!D()&&(this._pending.peek()?.state===i&&this._pending.take(),r()));};window.addEventListener("pageshow",o);}return this._window.navigate(e),new Promise(()=>{})}consume(){let e=D();if(e===null)return this._pending.dropIfOlderThan(De),null;let t=Ke(e),i=this._pending.take();if(!t||!i||i.state!==t.state||i.path!==t.path)throw se(),new Error("Unexpected OdinConnect redirect result");return se(i.returnHref),{result:t,pending:i}}};var E={buy:{path:"authorize/buy",success:"purchased",failure:"Purchase failed or was cancelled"},sell:{path:"authorize/sell",success:"sold",failure:"Sell failed or was cancelled"},transfer:{path:"authorize/transfer",success:"transferred",failure:"Transfer failed or was cancelled"},swap:{path:"authorize/swap",success:"swapped",failure:"Swap failed or was cancelled"},add_liquidity:{path:"authorize/add_liquidity",success:"addedLiquidity",failure:"Add liquidity failed or was cancelled"},remove_liquidity:{path:"authorize/remove_liquidity",success:"removedLiquidity",failure:"Remove liquidity failed or was cancelled"},icrc_approve:{path:"authorize/icrc_approve",success:"approved",failure:"ICRC approve failed or was cancelled"},create_token:{path:"authorize/create_token",success:"tokenCreated",failure:"Token creation failed or was cancelled"}};function oe(n){return n!==null&&typeof n=="object"&&!Array.isArray(n)?n:void 0}var M="popup_closed",H="navigated_back",je=/^[a-z0-9_]{1,64}$/;function $(n){let e=oe(n)?.reason;return typeof e=="string"&&je.test(e)?e:void 0}function Z(n,e,t){if(e===E[n].success){let i=oe(t);return {status:"success",...i?{detail:i}:{}}}if(e==="rejected"){let i=$(t);return {status:"rejected",...i?{error:i}:{}}}return {status:"failed",error:E[n].failure}}function A(n){return n.catch(()=>{}),n}var ze=500,We=1500;function X(n,e,t,i){let r=false,s=null,o=null,a=()=>{if(!t)return true;let{request:c}=t.state;return c?.id===e&&c.status==="pending"},p=()=>{r||(r=true,clearInterval(d),o!==null&&clearTimeout(o),s?.());},d=setInterval(()=>{!n.closed||o!==null||(clearInterval(d),o=setTimeout(()=>{let c=a();p(),c&&i();},We));},ze);return s=t?.subscribe(()=>{a()||p();})??null,p}var N=class{_window;_appInfo;_api;_redirect;_store;origin;constructor(e,t,i,r,s=null,o=null){this._window=e,this._redirect=s,this._api=t,this._appInfo=i,this.origin=r,this._store=o;}get appInfo(){return this._appInfo}createUrl(e,t=w()){let i=new URL(`${this.origin}/${e}`);return i.searchParams.append("v","2"),i.searchParams.append("request_id",t),this._appInfo?.name&&i.searchParams.append("app_name",this._appInfo.name),i.searchParams.append("referrer",window.location.origin),i.searchParams.append("lang",this._appInfo?.lang||y),i}startRequest(e,t,i,r){this._store?.dispatch({type:"request",request:{id:e,action:t,status:"pending",input:i,...r!==void 0?{returnState:r}:{}}});}fail(e,t){let i=t instanceof Error?t:new Error(String(t));return this._store?.dispatch({type:"settle",id:e,status:"failed",error:i.message}),i}baseAction({action:e,input:t,params:i,returnState:r,requestId:s=w()}){let{path:o,failure:a}=E[e];this.startRequest(s,e,t,r);let p=this.createUrl(o,s);for(let d in i)i[d]&&p.searchParams.append(d,i[d]);return this._redirect?.useRedirect?A(this._redirect.start(p,{path:"/"+o,input:t,returnState:r},s,()=>this._store?.dispatch({type:"settle",id:s,status:"rejected",error:H})).catch(d=>{throw this.fail(s,d)})):A(new Promise((d,c)=>{let m=()=>{},u=h=>{if(h.origin===this.origin&&h.data?.path==="/"+o){window.removeEventListener("message",u),m();let O=Z(e,h.data.message,h.data.detail);this._store?.dispatch({type:"settle",id:s,...O}),O.status==="success"?d(true):c(new Error(a));}},g=this._window.open(p);if(!g||g.closed||typeof g.closed>"u"){c(this.fail(s,`Failed to open ${o} window, please always allow popups and try again`));return}window.addEventListener("message",u),m=X(g,s,this._store,()=>{window.removeEventListener("message",u),this._store?.dispatch({type:"settle",id:s,status:"rejected",error:M}),c(new Error(a));});}))}sell({token:e,tokenAmount:t,principal:i,returnState:r}){return this.baseAction({action:"sell",input:{token:e,tokenAmount:t},params:{principal:i,token:e,amount:t.toString()},returnState:r})}buy({principal:e,token:t,btcAmount:i,returnState:r}){return this.baseAction({action:"buy",input:{token:t,btcAmount:i},params:{principal:e,token:t,amount:i.toString()},returnState:r})}transfer({principal:e,token:t,amount:i,destination:r,returnState:s}){return this.baseAction({action:"transfer",input:{token:t,amount:i,destination:r},params:{principal:e,token:t,amount:i.toString(),destination:r},returnState:s})}addLiquidity({principal:e,btcAmount:t,token:i,returnState:r}){return this.baseAction({action:"add_liquidity",input:{token:i,btcAmount:t},params:{principal:e,amount:t.toString(),token:i},returnState:r})}removeLiquidity({principal:e,lpAmount:t,token:i,returnState:r}){return this.baseAction({action:"remove_liquidity",input:{token:i,lpAmount:t},params:{principal:e,amount:t.toString(),token:i},returnState:r})}swap({principal:e,fromToken:t,toToken:i,fromAmount:r,returnState:s}){return this.baseAction({action:"swap",input:{fromToken:t,toToken:i,fromAmount:r},params:{principal:e,from:t,to:i,amount:r.toString()},returnState:s})}icrcApprove({principal:e,token:t,spender:i,amount:r,returnState:s}){return this.baseAction({action:"icrc_approve",input:{token:t,spender:i,amount:r},params:{principal:e,token:t,spender:i,amount:r.toString()},returnState:s})}createToken({image:e,returnState:t,principal:i,...r}){let s=w(),o={...r};return this.startRequest(s,"create_token",o,t),A((async()=>{let a;try{for(let p in b)if(p in r){let c=b[p]?.(r[p]||null);if(c)throw new Error(c)}if(r.discount&&!/^[A-Za-z0-9]{10}$/.test(r.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");a=await this._api.uploadImage(e);}catch(p){throw this.fail(s,p)}return this.baseAction({action:"create_token",input:{...o,image:a},params:{...r,principal:i,image:a,buy:r.buy?.toString()},returnState:t,requestId:s})})())}};var V=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:session`;}save(e){try{localStorage.setItem(this._key,JSON.stringify(e));}catch{}}load(){try{let e=localStorage.getItem(this._key);if(!e)return null;let t=JSON.parse(e);return this.isValidSessionData(t)?t:null}catch{return null}}isValidSessionData(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.principal=="string"&&typeof t.sessionKey=="string"&&(t.delegationChain===null||typeof t.delegationChain=="string")&&(t.jwt===null||typeof t.jwt=="string")}clear(){try{localStorage.removeItem(this._key);}catch{}}};var f=class extends Error{constructor(e){super(`OdinConnect could not verify the connection: ${e}`),this.name="ConnectVerificationError";}};function l(n){throw new f(n)}function Je(n,e){if(n.byteLength!==e.byteLength)return false;for(let t=0;t<n.byteLength;t++)if(n[t]!==e[t])return false;return true}function Fe(n){return Uint8Array.from(atob(n),e=>e.charCodeAt(0))}function Ge(n){let e="";for(let t of n)e+=String.fromCharCode(t);return btoa(e)}var Me=`odin-connect-verify:v1
2
+ `;async function pe(n,e){let t=await n.sign(new TextEncoder().encode(Me+e));return Ge(new Uint8Array(t))}function He(n){try{if(n.delegation)return new Uint8Array(DelegationChain.fromJSON(JSON.parse(n.delegation)).publicKey);if(n.publicKey)return Fe(n.publicKey)}catch{}l("the identity proof has no readable signer");}function de(n,e){(!n||typeof n.payload!="string"||typeof n.signature!="string")&&l("the result carries no identity proof");let t;try{t=JSON.parse(n.payload);}catch{l("the identity proof payload is malformed");}(t?.typ!=="odin-connect-identity"||t.v!==1)&&l("the identity proof has an unknown type"),t.nonce!==e.nonce&&l("the identity proof belongs to another request"),t.aud!==e.audience&&l("the identity proof was issued to another origin"),t.principal!==e.principal&&l("the identity proof is for another principal"),typeof t.sk!="string"&&l("the identity proof is not bound to a session key"),t.sk!==e.sessionPubkey&&l("the identity proof was issued to another session key"),e.requires_api&&t.api!==true&&l("API access was not granted");let i=He(n);Principal.selfAuthenticating(i).toText()!==e.principal&&l("the identity proof signer does not match the principal");}function le(n,e){n||l("the delegation chain is missing");let t;try{t=DelegationChain.fromJSON(n);}catch{l("the delegation chain is malformed");}t.delegations.length===0&&l("the delegation chain is empty"),_(JSON.stringify(t.toJSON()))||l("the delegation chain has expired");let i=t.delegations[t.delegations.length-1].delegation;Je(new Uint8Array(i.pubkey),e.sessionPublicKey)||l("the delegation chain was issued to another session key");let r=new Uint8Array(t.publicKey);Principal.selfAuthenticating(r).toText()!==e.principal&&l("the delegation chain belongs to another principal");let s=new Set(e.targets);for(let{delegation:o}of t.delegations)o.targets?.some(a=>!s.has(a.toText()))&&l("the delegation chain targets canisters that were not requested");return t}function Ze(n){return Object.isFrozen(n)?n:(Object.freeze(n.input),n.detail&&Object.freeze(n.detail),Object.freeze(n))}function K(n){return Object.freeze({...n,request:n.request?Ze(n.request):null})}function Xe(n,e){switch(e.type){case "ready":return K({status:"ready",user:n.user??e.user,request:n.request??e.request});case "request":return K({...n,request:{...e.request}});case "settle":{let t=n.request;if(!t||t.id!==e.id)return n;let i={...t,status:e.status,...e.detail?{detail:e.detail}:{},...e.error!==void 0?{error:e.error}:{}};return K({...n,user:e.user??n.user,request:i})}case "disconnect":return n.user===null&&n.request===null?n:K({...n,user:null,request:null})}}var k=Object.freeze({status:"initializing",user:null,request:null}),j=class{_state=k;_listeners=new Set;get state(){return this._state}dispatch(e){let t=Xe(this._state,e);if(t!==this._state){this._state=t;for(let i of [...this._listeners])if(this._listeners.has(i))try{i(t);}catch(r){queueMicrotask(()=>{throw r});}}}subscribe(e){let t=i=>e(i);return this._listeners.add(t),()=>{this._listeners.delete(t);}}};var T=new Map,Qe=1e4,Q=new Map;function et(n){let e=0;for(let t=0;t<n.length;t++)e=e*31+n.charCodeAt(t)|0;return (e>>>0).toString(36).slice(0,3).padStart(3,"0")}function ge(n){return F(new Uint8Array(n.getPublicKey().toDer()))}function tt(n){return `${n.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${et(n)}`}var ee=class{static serverState=k;_appInfo=null;_api;_window;_odin;_storage;_redirect;_store=new j;_ready=null;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||tt(this._appInfo.name),this._appInfo.lang=v(this._appInfo.lang),this._api=new S(this.currentEnv),this._window=new U,this._redirect=new B(this._window,new L(this._appInfo.slug,this._appInfo.env||"prod")),this._redirect.mode=this._appInfo.mode||"auto",this._odin=new N(this._window,this._api,this._appInfo,z[this._appInfo.env||"prod"],this._redirect,this._store),this._storage=new V(this._appInfo.slug,this._appInfo.env||"prod"),typeof window<"u"&&this.ready();}createUrl(e,t=w()){let i=new URL(`${this.origin}/${e}`);return i.searchParams.append("v","2"),i.searchParams.append("request_id",t),this._appInfo?.name&&i.searchParams.append("app_name",this._appInfo.name),i.searchParams.append("referrer",window.location.origin),i.searchParams.append("lang",this.lang),i}get origin(){return z[this._appInfo?.env||"prod"]}get lang(){return this._appInfo?.lang||y}set lang(e){this._appInfo&&(this._appInfo.lang=v(e));}get mode(){return this._redirect.mode}set mode(e){this._redirect.mode=e,this._appInfo&&(this._appInfo.mode=e);}get appInfo(){return this._appInfo}get slug(){return this._appInfo?.slug||""}ready(){return typeof window>"u"?Promise.resolve(this.state):(this._ready||(this._ready=this.initialize()),this._ready.then(()=>this.state))}get state(){return this._store.state}getState=()=>this._store.state;getServerState=()=>k;subscribe=e=>this._store.subscribe(e);get user(){return this._store.state.user}initialize(){let e=this.disconnectGeneration,t=null;try{t=this.redirectOutcome(),t||this._redirect.consume();}catch{}return this.finishReady(t,e)}async finishReady(e,t){let i=null,r=null;if(e)try{let s=await e;t===this.disconnectGeneration&&(i=s.request,s.connected&&(r=this.bindConnection(s.connected)));}catch{}this._store.dispatch({type:"ready",user:r??this.loadStoredSession(),request:i});}connect({open:e,requires_api:t,requires_delegation:i,targets:r,returnState:s}={requires_delegation:false,requires_api:false}){let o=Ed25519KeyIdentity.generate(),a=w(),p={requires_api:t,requires_delegation:i,targets:r},d={requires_api:!!t,requires_delegation:!!i,targets:r?[...r]:[]};this._store.dispatch({type:"request",request:{id:a,action:"connect",status:"pending",input:d,...s!==void 0?{returnState:s}:{}}});let c=this.createConnectUrl(o,a,p);return this._redirect.useRedirect?A(this._redirect.start(c,{path:"/authorize/connect",sessionKey:JSON.stringify(o.toJSON()),requires_delegation:d.requires_delegation,requires_api:d.requires_api,targets:r,returnState:s},a,()=>this._store.dispatch({type:"settle",id:a,status:"rejected",error:H})).catch(m=>{throw this.settleError(a,"failed",m)})):(e&&(this._window.settings=e),A(new Promise((m,u)=>{let g=null,h=()=>{},O=async C=>{if(C.origin===this.origin&&C.source===g&&C.data?.path==="/authorize/connect"){if(window.removeEventListener("message",O),h(),C.data.message==="rejected"){let P=$(C.data.detail);this._store.dispatch({type:"settle",id:a,status:"rejected",...P?{error:P}:{}}),u(new Error("User rejected the connection"));return}let te={requestId:a,...p},x;try{x=await this.verifyConnection(C.data.message,o,te);}catch(P){u(this.settleError(a,"unverified",P));return}if(this._store.state.request?.id!==a){m(this.detachedUser(x));return}this.persistConnection(x,o,te);let ne=this.bindConnection(x);this._store.dispatch({type:"settle",id:a,status:"success",user:ne}),m(ne);}};if(g=this._window.open(c),!g||g.closed||typeof g.closed>"u"){u(this.settleError(a,"failed",new Error("Failed to open authorize/connect window, please always allow popups and try again")));return}window.addEventListener("message",O),h=X(g,a,this._store,()=>{window.removeEventListener("message",O),this._store.dispatch({type:"settle",id:a,status:"rejected",error:M}),u(new Error("User rejected the connection"));});})))}settleError(e,t,i){let r=i instanceof Error?i:t==="unverified"?new f(String(i)):new Error(String(i));return this._store.dispatch({type:"settle",id:e,status:t,error:r.message}),r}createConnectUrl(e,t,{requires_api:i,requires_delegation:r,targets:s}){let o=this.createUrl("authorize/connect",t);return o.searchParams.append("requires_api",i?"1":"0"),o.searchParams.append("session_pubkey",ge(e)),r&&(o.searchParams.append("requires_delegation","1"),o.searchParams.append("targets",s?.join(",")||"")),o}redirectOutcome(){let e=this.redirectCacheKey,t=D(),i=T.get(e);if(t!==null&&i?.fragment!==t){let r={fragment:t,promise:this.readRedirectResult(),settled:false};T.set(e,r);let s=()=>{r.settled=true,setTimeout(()=>{T.get(e)===r&&T.delete(e);},Qe);};return r.promise.then(s,o=>{console.warn("OdinConnect: ignored a stale or foreign redirect result",o),s();}),r.promise}return i&&!i.settled?i.promise:null}bindConnection({principal:e,identity:t,jwt:i}){return this._api.apiKey=i,new R(e,t,this._api,this._odin)}get redirectCacheKey(){return `${this.slug}:${this.currentEnv}`}async readRedirectResult(){let e=this.disconnectGeneration,t=this._redirect.consume();if(!t)throw new Error("Unexpected OdinConnect redirect result");let{result:i,pending:r}=t,s=r.returnState!==void 0?{returnState:r.returnState}:{},o=r.path.replace(/^\/authorize\//,"");if(o==="connect"){let a={id:r.state,action:"connect",input:{requires_api:!!r.requires_api,requires_delegation:!!r.requires_delegation,targets:r.targets??[]},...s};if(i.message==="rejected"){let c=$(i.detail);return {request:{...a,status:"rejected",...c?{error:c}:{}}}}if(!r.sessionKey)return {request:{...a,status:"unverified",error:new f("the pending request has no session key").message}};let p=Ed25519KeyIdentity.fromJSON(r.sessionKey),d={requestId:r.state,requires_api:r.requires_api,requires_delegation:r.requires_delegation,targets:r.targets};try{let c=await this.verifyConnection(i.message,p,d);return e!==this.disconnectGeneration?{request:{...a,status:"success"}}:(this.persistConnection(c,p,d),{request:{...a,status:"success"},connected:c})}catch(c){return {request:{...a,status:"unverified",error:c instanceof Error?c.message:String(c)}}}}if(!(o in E))throw new Error("Unexpected OdinConnect redirect result");return {request:{id:r.state,action:o,input:r.input??{},...s,...Z(o,i.message,i.detail)}}}detachedUser({principal:e,identity:t,jwt:i}){let r=new S(this.currentEnv);return r.apiKey=i,new R(e,t,r,this._odin)}get disconnectGeneration(){return Q.get(this.redirectCacheKey)??0}async verifyConnection(e,t,{requestId:i,requires_api:r,requires_delegation:s,targets:o}){if(!e||typeof e.principal!="string")throw new f("the result has no principal");let{principal:a,proof:p}=e,d=window.location.origin;de(p,{principal:a,nonce:i,audience:d,requires_api:!!r,sessionPubkey:ge(t)});let c=null;s&&(c=le(e.delegationChain,{principal:a,sessionPublicKey:new Uint8Array(t.getPublicKey().toDer()),targets:o??[]}));let m=await pe(t,p.payload),u;try{u=await this._api.verifyConnect({payload:p.payload,signature:p.signature,delegation:p.delegation??null,publicKey:p.publicKey??null,audience:d,nonce:i,issue_jwt:!!r,client_signature:m});}catch(h){throw new f(`odin-api refused the proof (${h instanceof Error?h.message:String(h)})`)}if(u?.principal!==a)throw new f("odin-api verified a different principal");let g=null;if(r){if(typeof u.jwt!="string"||!u.jwt)throw new f("odin-api issued no API key");g=u.jwt;}return {principal:a,chain:c,identity:c?DelegationIdentity.fromDelegation(t,c):null,jwt:g}}persistConnection({principal:e,chain:t,jwt:i},r,{requires_api:s,requires_delegation:o}){this._storage.clear(),this._api.apiKey=null,(s||o)&&this._storage.save({principal:e,sessionKey:JSON.stringify(r.toJSON()),delegationChain:t?JSON.stringify(t.toJSON()):null,jwt:i});}get api(){return this._api}get odin(){return this._odin}get currentEnv(){return this._appInfo?.env||"prod"}restoreSession(){return this.state.status==="ready"?this.state.user:this.loadStoredSession()}loadStoredSession(){try{let e=this._storage.load();if(!e)return null;if(e.delegationChain&&!_(e.delegationChain))return this._storage.clear(),null;e.jwt&&(this._api.apiKey=e.jwt);let t=null;if(e.delegationChain&&e.sessionKey){let i=Ed25519KeyIdentity.fromJSON(e.sessionKey),r=DelegationChain.fromJSON(JSON.parse(e.delegationChain));t=DelegationIdentity.fromDelegation(i,r);}return new R(e.principal,t,this._api,this._odin)}catch{return this._storage.clear(),null}}disconnect(){let e=this.redirectCacheKey;Q.set(e,(Q.get(e)??0)+1),this._storage.clear(),this._api.apiKey=null,T.delete(e),this._store.dispatch({type:"disconnect"});}isSessionValid(){let e=this._storage.load();return e?e.delegationChain?_(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
3
+ export{k as INITIAL_ODIN_STATE,ee as OdinConnect,f as OdinConnectVerificationError,re as OdinUtils,W as isInAppBrowser};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "odin-connect",
3
- "version": "2.0.1",
3
+ "version": "2.0.2",
4
4
  "description": "",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -53,10 +53,10 @@
53
53
  "@apimatic/json-bigint": "^1.2.0",
54
54
  "@dfinity/identity": "^3.4.3",
55
55
  "@dfinity/principal": "^3.4.3",
56
- "axios": "^1.12.0"
56
+ "axios": "^1.20.0"
57
57
  },
58
58
  "overrides": {
59
- "undici": "6.24.1",
59
+ "undici": "6.29.0",
60
60
  "esbuild": "0.28.1"
61
61
  },
62
62
  "release-it": {
package/readme.md CHANGED
@@ -245,7 +245,7 @@ and odin-api is asked once.
245
245
  ```typescript
246
246
  const odinConnect = new OdinConnect({
247
247
  name: "Demo App", // Your app name (shown in auth popup)
248
- env: "prod", // "prod" | "dev" | "local" | "legacy"
248
+ env: "prod", // "prod" | "staging" | "dev" | "local" | "legacy"
249
249
  lang: "en", // Popup UI language: "en" | "zh" (default "en")
250
250
  mode: "auto", // "auto" (default) | "popup" | "redirect", see below
251
251
  });
@@ -976,6 +976,7 @@ OdinUtils.createTokenValidators.telegram("https://t.me/...");
976
976
  | Environment | Frontend URL | API Base URL |
977
977
  |-------------|-------------|-------------|
978
978
  | `prod` (default) | `https://odin.fun` | `https://api.odin.fun/v2` |
979
+ | `staging` | `https://staging.odin.fun` | `https://api.odin.fun/v2` |
979
980
  | `dev` | `https://dev.odin.fun` | `https://api.odin.fun/dev` |
980
981
  | `local` | `http://localhost:5173` | `https://api.odin.fun/dev` |
981
982
  | `legacy` | `https://legacy.odin.fun` | `https://api.odin.fun/v1` |