odin-connect 2.0.0 → 2.0.1
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/MIGRATION-2.0.md +327 -0
- package/dist/index.d.ts +393 -63
- package/dist/index.js +3 -2
- package/package.json +4 -2
- package/readme.md +454 -103
package/dist/index.js
CHANGED
|
@@ -1,2 +1,3 @@
|
|
|
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};
|
|
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};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odin-connect",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.1",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -15,7 +15,8 @@
|
|
|
15
15
|
}
|
|
16
16
|
},
|
|
17
17
|
"files": [
|
|
18
|
-
"dist"
|
|
18
|
+
"dist",
|
|
19
|
+
"MIGRATION-2.0.md"
|
|
19
20
|
],
|
|
20
21
|
"scripts": {
|
|
21
22
|
"build": "tsup",
|
|
@@ -51,6 +52,7 @@
|
|
|
51
52
|
"dependencies": {
|
|
52
53
|
"@apimatic/json-bigint": "^1.2.0",
|
|
53
54
|
"@dfinity/identity": "^3.4.3",
|
|
55
|
+
"@dfinity/principal": "^3.4.3",
|
|
54
56
|
"axios": "^1.12.0"
|
|
55
57
|
},
|
|
56
58
|
"overrides": {
|