odin-connect 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +14 -3
- package/dist/index.js +2 -2
- package/package.json +2 -1
- package/readme.md +22 -0
package/dist/index.d.ts
CHANGED
|
@@ -255,6 +255,7 @@ interface CreateTokenParams {
|
|
|
255
255
|
name: string;
|
|
256
256
|
ticker: string;
|
|
257
257
|
image: File;
|
|
258
|
+
vanity_ticker?: string;
|
|
258
259
|
description?: string;
|
|
259
260
|
website?: string;
|
|
260
261
|
twitter?: string;
|
|
@@ -361,11 +362,14 @@ declare const ORIGINS: {
|
|
|
361
362
|
};
|
|
362
363
|
type Environment = keyof typeof ORIGINS;
|
|
363
364
|
|
|
365
|
+
type OdinLang = "en" | "zh";
|
|
366
|
+
|
|
364
367
|
interface AppInitOptions {
|
|
365
368
|
name: string;
|
|
366
369
|
icon?: string;
|
|
367
370
|
env?: Environment;
|
|
368
371
|
slug?: string;
|
|
372
|
+
lang?: OdinLang;
|
|
369
373
|
}
|
|
370
374
|
interface BaseConnectOptions {
|
|
371
375
|
open?: WindowClientSettings;
|
|
@@ -390,6 +394,8 @@ declare class Connect {
|
|
|
390
394
|
constructor(appInfo?: Partial<AppInitOptions>);
|
|
391
395
|
private createUrl;
|
|
392
396
|
get origin(): string;
|
|
397
|
+
get lang(): OdinLang;
|
|
398
|
+
set lang(value: OdinLang);
|
|
393
399
|
get appInfo(): AppInitOptions | null;
|
|
394
400
|
get slug(): string;
|
|
395
401
|
connect({ open, requires_api, requires_delegation, targets, }?: ConnectOptions | undefined): Promise<ConnectedUser>;
|
|
@@ -412,6 +418,9 @@ type OdinEnv = keyof typeof IMAGE_CDN_ENV;
|
|
|
412
418
|
|
|
413
419
|
declare function isDelegationValid(chainJson: string): boolean;
|
|
414
420
|
|
|
421
|
+
declare const DEFAULT_LANG: OdinLang;
|
|
422
|
+
declare function normalizeOdinLang(value?: string): OdinLang;
|
|
423
|
+
|
|
415
424
|
/**
|
|
416
425
|
* Build a token's image URL from its id using the env-aware image CDN.
|
|
417
426
|
* @param tokenId Token id (e.g. `Token.id`).
|
|
@@ -420,14 +429,16 @@ declare function isDelegationValid(chainJson: string): boolean;
|
|
|
420
429
|
declare function buildTokenImageUrl(tokenId: string, env?: OdinEnv): string;
|
|
421
430
|
declare function convertToOdinAmount(numberStr: string | number, token?: Pick<BaseToken, "decimals" | "divisibility">): bigint;
|
|
422
431
|
type TokenValue = string | File | null | bigint;
|
|
423
|
-
declare const createTokenValidators: Partial<Record<keyof Token, (value: TokenValue) => string | undefined>>;
|
|
432
|
+
declare const createTokenValidators: Partial<Record<keyof Token | "vanity_ticker", (value: TokenValue) => string | undefined>>;
|
|
424
433
|
|
|
434
|
+
declare const index_DEFAULT_LANG: typeof DEFAULT_LANG;
|
|
425
435
|
declare const index_buildTokenImageUrl: typeof buildTokenImageUrl;
|
|
426
436
|
declare const index_convertToOdinAmount: typeof convertToOdinAmount;
|
|
427
437
|
declare const index_createTokenValidators: typeof createTokenValidators;
|
|
428
438
|
declare const index_isDelegationValid: typeof isDelegationValid;
|
|
439
|
+
declare const index_normalizeOdinLang: typeof normalizeOdinLang;
|
|
429
440
|
declare namespace index {
|
|
430
|
-
export { index_buildTokenImageUrl as buildTokenImageUrl, index_convertToOdinAmount as convertToOdinAmount, index_createTokenValidators as createTokenValidators, index_isDelegationValid as isDelegationValid };
|
|
441
|
+
export { index_DEFAULT_LANG as DEFAULT_LANG, index_buildTokenImageUrl as buildTokenImageUrl, index_convertToOdinAmount as convertToOdinAmount, index_createTokenValidators as createTokenValidators, index_isDelegationValid as isDelegationValid, index_normalizeOdinLang as normalizeOdinLang };
|
|
431
442
|
}
|
|
432
443
|
|
|
433
444
|
interface SessionData {
|
|
@@ -437,4 +448,4 @@ interface SessionData {
|
|
|
437
448
|
jwt: string | null;
|
|
438
449
|
}
|
|
439
450
|
|
|
440
|
-
export { type Achievement as OdinAchievement, type AchievementCategory as OdinAchievementCategory, type Activity as OdinActivity, type Balance as OdinBalance, type BaseToken as OdinBaseToken, Connect as OdinConnect, ConnectedUser as OdinConnectedUser, type Token as OdinToken, type TokenWithBalance as OdinTokenWithBalance, type Transaction as OdinTransaction, type User as OdinUser, index as OdinUtils, type SessionData };
|
|
451
|
+
export { type Achievement as OdinAchievement, type AchievementCategory as OdinAchievementCategory, type Activity as OdinActivity, type Balance as OdinBalance, type BaseToken as OdinBaseToken, Connect as OdinConnect, ConnectedUser as OdinConnectedUser, type OdinLang, type Token as OdinToken, type TokenWithBalance as OdinTokenWithBalance, type Transaction as OdinTransaction, type User as OdinUser, index as OdinUtils, type SessionData };
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import $ from'axios';import L from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';var P=Object.defineProperty;var B=(i,e)=>{for(var t in e)P(i,t,{get:e[t],enumerable:true});};var D=i=>{try{return L.parse(i)}catch(e){return console.error("Error parsing response:",e),i}},m=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let n={transformResponse:[D],...t};return (await $(e,n)).data}async post(e,t,n){return this.fetch(e,{method:"POST",data:t,...n})}async put(e,t,n){return this.fetch(e,{method:"PUT",data:t,...n})}async delete(e,t){return this.fetch(e,{method:"DELETE",...t})}};var E={};B(E,{buildTokenImageUrl:()=>N,convertToOdinAmount:()=>V,createTokenValidators:()=>c,isDelegationValid:()=>u});var S={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1"},f={dev:"https://images.odin.fun/dev",prod:"https://images.odin.fun/v2",local:"https://images.odin.fun/dev",legacy:"https://images.odin.fun"};function u(i){try{let e=DelegationChain.fromJSON(JSON.parse(i)),t=BigInt(Date.now())*1000000n;return e.delegations.every(n=>n.delegation.expiration==null||n.delegation.expiration>t)}catch{return false}}function N(i,e="prod"){return `${f[e]}/token/${i}`}function V(i,e={decimals:3,divisibility:8}){let t=e.decimals+e.divisibility;if(i=typeof i=="string"?i.trim():String(i),isNaN(+i))return 0n;let[n,r=""]=i.split(".");return r=r.slice(0,t),r=r.padEnd(t,"0"),n=n.replace(/^0+(?=\d)/,""),n===""&&(n="0"),BigInt(n+r)}var c={name:F,image:W,ticker:K,description:z,twitter:J,website:M,telegram:j};function F(i){if(typeof i!="string")return "Name must be a string.";if(!i||i.trim()==="")return "Name is required.";if(i.length<3||i.length>30)return "Name must be between 3 and 30 characters."}function z(i){if(i){if(typeof i!="string")return "Description must be a string.";if(i&&i.length>100)return "Description must not exceed 100 characters."}}function K(i){if(typeof i!="string")return "Ticker must be a string.";if(!i||i.trim()==="")return "Ticker is required.";if(i.length<3||i.length>10)return "Ticker must be between 3 and 10 characters.";if(!/^[A-Z0-9]+$/.test(i))return "Ticker must be alphanumeric characters in uppercase only.";if(!/(?=(.*[A-Z].*[A-Z]))/.test(i))return "Ticker must have at least 2 alpha characters."}function W(i){if(!(i instanceof File))return "Image must be a file.";let e=["image/png","image/jpeg","image/webp","image/svg","image/gif","image/avif"],t=200*1024;if(!i)return "Image file is required.";if(!e.includes(i.type))return `Invalid file type. Allowed types are: ${e.join(", ")}`;if(i.size>t)return `File size exceeds the maximum limit of ${t/1024}KB.`}function J(i){if(i){if(typeof i!="string")return "Twitter handle must be a string.";if(i&&!/^https?:\/\/(www\.)?(twitter\.com|x\.com)\/[A-Za-z0-9_]{1,15}\/?$/.test(i))return "Twitter must be a valid twitter URL."}}function M(i){if(i){if(typeof i!="string")return "Website must be a string.";if(i&&!/^(https?:\/\/)?([\w-]+(\.[\w-]+)+)(\/[\w-./?%&=]*)?$/.test(i))return "Website must be a valid URL."}}function j(i){if(i){if(typeof i!="string")return "Telegram must be a string.";if(i&&!/^(https?:\/\/)?(t\.me|telegram\.me|telegram\.org)\/[A-Za-z0-9_]{5,32}\/?$/.test(i))return "Telegram must be a valid telegram URL."}}var y=class{_apiKey=null;_httpClient;BASE_URL;ENV;constructor(e="prod"){this._httpClient=new m,this.BASE_URL=S[e],this.ENV=e;}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${f[this.ENV]}/user/${e}`}async getBalances(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{...t}})).data}async getBalance(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{token_in:t}})).data.find(r=>r.id===t)??null}getTokens(e,t={field:"marketcap",direction:"desc"},n={}){return this._httpClient.get(`${this.BASE_URL}/tokens`,{params:{...e,sort:`${t.field}:${t.direction}`,...n}})}getToken(e){return this._httpClient.get(`${this.BASE_URL}/token/${e}`)}async uploadImage(e){if(!this._apiKey)throw new Error("API key is not set");try{let t=c.image?.(e);if(t)throw new Error(t);let n=new FormData;return n.append("file",e),(await this._httpClient.post(`${this.BASE_URL}/upload`,n,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})).data.upload}catch(t){if(t instanceof Error)if(t.name==="AxiosError"){let n=t;throw new Error(n.response?.data?.message||n.message)}else throw new Error(t.message);else throw new Error("Image upload failed")}}updateTokenImage(e,t){if(!this._apiKey)throw new Error("API key is not set");try{return this._httpClient.post(`${this.BASE_URL}/token/${e}/image`,{image:t},{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})}catch(n){if(n instanceof Error&&n.name==="AxiosError"){let r=n;throw new Error(r.response?.data?.message||r.message)}else throw new Error("Image update failed")}}getUserActivity(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/activity`,{params:{...t}})}async getUserTokens(e,t){let n=await this._httpClient.get(`${this.BASE_URL}/user/${e}/tokens`,{params:{...t}});return {...n,data:n.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserLiquidity(e,t){let n=await this._httpClient.get(`${this.BASE_URL}/user/${e}/liquidity`,{params:{...t}});return {...n,data:n.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserAchievements(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/achievements`,{params:{...t}})).data}getUserTransactions(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/transactions`,{params:{...t}})}getUserCreatedTokens(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/created`,{params:{...t}})}getUserStats(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}/stats`)}set apiKey(e){this._apiKey=e;}get apiKey(){return this._apiKey}};var g=class{_identity;_api;_principal;_odin;constructor(e,t,n,r){this._principal=e,this._identity=t,this._api=n,this._odin=r;}get principal(){return this._principal}set principal(e){this._principal=e;}getIdentity(){return this._identity}getUser(){return this._api.getUser(this.principal)}buildAvatarImageUrl(){return this._api.getUserAvatarUrl(this.principal)}getBalances(e){return this._api.getBalances(this.principal,e)}getBalance(e){return this._api.getBalance(this.principal,e)}getTokens(e){return this._api.getUserTokens(this.principal,e)}getCreatedTokens(e){return this._api.getUserCreatedTokens(this.principal,e)}getActivity(e){return this._api.getUserActivity(this.principal,e)}getLiquidity(e){return this._api.getUserLiquidity(this.principal,e)}getAchievements(e){return this._api.getUserAchievements(this.principal,e)}getTransactions(e){return this._api.getUserTransactions(this.principal,e)}getStats(){return this._api.getUserStats(this.principal)}sell(e){return this._odin.sell({...e,principal:this.principal})}buy(e){return this._odin.buy({...e,principal:this.principal})}addLiquidity(e){return this._odin.addLiquidity({...e,principal:this.principal})}removeLiquidity(e){return this._odin.removeLiquidity({...e,principal:this.principal})}transfer(e){return this._odin.transfer({...e,principal:this.principal})}createToken(e){return this._odin.createToken({...e,principal:this.principal})}icrcApprove(e){return this._odin.icrcApprove({...e,principal:this.principal})}swap(e){return this._odin.swap({...e,principal:this.principal})}};var O={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun"};var _=class{_settings;constructor(e){this._settings={target:e?.target||"_blank",settings:e?.settings||""};}get settings(){return this._settings}set settings(e){this._settings={...this._settings,...e};}open(e){return window.open(e,this._settings?.target||"_blank",this._settings?.settings)}};var w=class{_window;_appInfo;_api;origin;constructor(e,t,n,r){this._window=e,this._api=t,this._appInfo=n,this.origin=r;}get appInfo(){return this._appInfo}createUrl(e){let t=new URL(`${this.origin}/${e}`);return this._appInfo?.name&&t.searchParams.append("app_name",this._appInfo.name),t.searchParams.append("referrer",window.location.origin),t}baseAction({params:e,odinPath:t,receivedMessageFromOrigin:n,resolve:r}){return new Promise((p,l)=>{let a=async s=>{s.origin===this.origin&&s.data.path==="/"+t&&(window.removeEventListener("message",a),(typeof n=="function"?n(s.data.message):n===s.data.message)?p(r.success(s.data.message)):l(new Error(r.failure)));},d=this.createUrl(t);for(let s in e)e[s]&&d.searchParams.append(s,e[s]);let o=this._window.open(d);if(!o||o.closed||typeof o.closed>"u"){l(new Error(r.didnotopen??`Failed to open ${t} window, please always allow popups and try again`));return}window.addEventListener("message",a);})}sell({token:e,tokenAmount:t,principal:n}){return this.baseAction({params:{principal:n,token:e,amount:t.toString()},odinPath:"authorize/sell",receivedMessageFromOrigin:"sold",resolve:{success:()=>true,failure:"Sell failed or was cancelled",close:"User closed the window"}})}buy({principal:e,token:t,btcAmount:n}){return this.baseAction({params:{principal:e,token:t,amount:n.toString()},odinPath:"authorize/buy",receivedMessageFromOrigin:"purchased",resolve:{success:()=>true,failure:"Purchase failed or was cancelled",close:"User closed the window"}})}transfer({principal:e,token:t,amount:n,destination:r}){return this.baseAction({params:{principal:e,token:t,amount:n.toString(),destination:r},odinPath:"authorize/transfer",receivedMessageFromOrigin:"transferred",resolve:{success:()=>true,failure:"Transfer failed or was cancelled",close:"User closed the window"}})}addLiquidity({principal:e,btcAmount:t,token:n}){return this.baseAction({params:{principal:e,amount:t.toString(),token:n},odinPath:"authorize/add_liquidity",receivedMessageFromOrigin:"addedLiquidity",resolve:{success:()=>true,failure:"Add liquidity failed or was cancelled",close:"User closed the window"}})}removeLiquidity({principal:e,lpAmount:t,token:n}){return this.baseAction({params:{principal:e,amount:t.toString(),token:n},odinPath:"authorize/remove_liquidity",receivedMessageFromOrigin:"removedLiquidity",resolve:{success:()=>true,failure:"Remove liquidity failed or was cancelled",close:"User closed the window"}})}swap({principal:e,fromToken:t,toToken:n,fromAmount:r}){return this.baseAction({params:{principal:e,from:t,to:n,amount:r.toString()},odinPath:"authorize/swap",receivedMessageFromOrigin:"swapped",resolve:{success:()=>true,failure:"Swap failed or was cancelled",close:"User closed the window"}})}icrcApprove({principal:e,token:t,spender:n,amount:r}){return this.baseAction({params:{principal:e,token:t,spender:n,amount:r.toString()},odinPath:"authorize/icrc_approve",receivedMessageFromOrigin:"approved",resolve:{success:()=>true,failure:"ICRC approve failed or was cancelled",close:"User closed the window"}})}async createToken({image:e,...t}){for(let p in c)if(p in t){let a=c[p]?.(t[p]||null);if(a)throw new Error(a)}if(t.discount&&!/^[A-Za-z0-9]{10}$/.test(t.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");let n=await this._api.uploadImage(e);if(!await this.baseAction({params:{...t,image:n,buy:t.buy?.toString()},odinPath:"authorize/create_token",receivedMessageFromOrigin:"tokenCreated",resolve:{success:()=>true,failure:"Token creation failed or was cancelled",close:"User closed the window"}}))throw new Error("Token creation failed. Please try again.");return true}};var 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{}}};function G(i){let e=0;for(let t=0;t<i.length;t++)e=e*31+i.charCodeAt(t)|0;return (e>>>0).toString(36).slice(0,3).padStart(3,"0")}function Z(i){return `${i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${G(i)}`}var b=class{_appInfo=null;_api;_window;_odin;_storage;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||Z(this._appInfo.name),this._api=new y(this._appInfo.env==="prod"?"prod":this._appInfo.env==="legacy"?"legacy":"dev"),this._window=new _,this._odin=new w(this._window,this._api,this._appInfo,O[this._appInfo.env||"prod"]),this._storage=new v(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}get origin(){return O[this._appInfo?.env||"prod"]}get appInfo(){return this._appInfo}get slug(){return this._appInfo?.slug||""}connect({open:e,requires_api:t,requires_delegation:n,targets:r}={requires_delegation:false,requires_api:false}){return new Promise((p,l)=>{e&&(this._window.settings=e);let a=Ed25519KeyIdentity.generate(),d=async s=>{if(s.origin===this.origin&&s.data.path==="/authorize/connect")if(window.removeEventListener("message",d),s.data.message!="rejected"){let T;try{let C=s.data.message,{principal:A,jwt:k,delegationChain:h}=C;if(t&&(this._api.apiKey=k),n){if(!h)throw new Error("Delegation chain is missing");let x=DelegationIdentity.fromDelegation(a,DelegationChain.fromJSON(h));T=new g(A,x,this.api,this._odin);}else T=new g(A,null,this.api,this._odin);(t||n)&&this._storage.save({principal:A,sessionKey:JSON.stringify(a.toJSON()),delegationChain:h?JSON.stringify(h):null,jwt:k||null}),p(T);}catch{l(new Error("Failed to fetch user data"));}}else l(new Error("User rejected the connection"));},o=this.createUrl("authorize/connect");if(o.searchParams.append("requires_api",t?"1":"0"),n){o.searchParams.append("requires_delegation","1");let s=btoa(JSON.stringify(a.toJSON()));o.searchParams.append("session_key",s),o.searchParams.append("targets",r?.join(",")||"");}this._window.open(o),window.addEventListener("message",d);})}get api(){return this._api}get odin(){return this._odin}get currentEnv(){return this._appInfo?.env||"prod"}restoreSession(){try{let e=this._storage.load();if(!e)return null;if(e.delegationChain&&!u(e.delegationChain))return this._storage.clear(),null;e.jwt&&(this._api.apiKey=e.jwt);let t=null;if(e.delegationChain&&e.sessionKey){let n=Ed25519KeyIdentity.fromJSON(e.sessionKey),r=DelegationChain.fromJSON(JSON.parse(e.delegationChain));t=DelegationIdentity.fromDelegation(n,r);}return new g(e.principal,t,this._api,this._odin)}catch{return this._storage.clear(),null}}disconnect(){this._storage.clear(),this._api.apiKey=null;}isSessionValid(){let e=this._storage.load();return e?e.delegationChain?u(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
|
|
2
|
-
export{
|
|
1
|
+
import D from'axios';import N from'@apimatic/json-bigint';import {DelegationChain,Ed25519KeyIdentity,DelegationIdentity}from'@dfinity/identity';var $=Object.defineProperty;var B=(i,e)=>{for(var t in e)$(i,t,{get:e[t],enumerable:true});};var q=i=>{try{return N.parse(i)}catch(e){return console.error("Error parsing response:",e),i}},y=class{async get(e,t){return this.fetch(e,{method:"GET",...t})}async fetch(e,t){let n={transformResponse:[q],...t};return (await D(e,n)).data}async post(e,t,n){return this.fetch(e,{method:"POST",data:t,...n})}async put(e,t,n){return this.fetch(e,{method:"PUT",data:t,...n})}async delete(e,t){return this.fetch(e,{method:"DELETE",...t})}};var U={};B(U,{DEFAULT_LANG:()=>l,buildTokenImageUrl:()=>F,convertToOdinAmount:()=>z,createTokenValidators:()=>g,isDelegationValid:()=>h,normalizeOdinLang:()=>m});var I={dev:"https://api.odin.fun/dev",prod:"https://api.odin.fun/v2",local:"https://api.odin.fun/dev",legacy:"https://api.odin.fun/v1"},_={dev:"https://images.odin.fun/dev",prod:"https://images.odin.fun/v2",local:"https://images.odin.fun/dev",legacy:"https://images.odin.fun"};function h(i){try{let e=DelegationChain.fromJSON(JSON.parse(i)),t=BigInt(Date.now())*1000000n;return e.delegations.every(n=>n.delegation.expiration==null||n.delegation.expiration>t)}catch{return false}}var l="en";function m(i){return i==="en"||i==="zh"?i:(i!==void 0&&console.warn(`[odin-connect] Unsupported lang "${i}", falling back to "${l}"`),l)}function F(i,e="prod"){return `${_[e]}/token/${i}`}function z(i,e={decimals:3,divisibility:8}){let t=e.decimals+e.divisibility;if(i=typeof i=="string"?i.trim():String(i),isNaN(+i))return 0n;let[n,r=""]=i.split(".");return r=r.slice(0,t),r=r.padEnd(t,"0"),n=n.replace(/^0+(?=\d)/,""),n===""&&(n="0"),BigInt(n+r)}var g={name:K,image:G,ticker:J,vanity_ticker:M,description:W,twitter:j,website:Z,telegram:H};function K(i){if(typeof i!="string")return "Name must be a string.";if(!i||i.trim()==="")return "Name is required.";if(i.length<3||i.length>30)return "Name must be between 3 and 30 characters."}function W(i){if(i){if(typeof i!="string")return "Description must be a string.";if(i&&i.length>100)return "Description must not exceed 100 characters."}}function J(i){if(typeof i!="string")return "Ticker must be a string.";if(!i||i.trim()==="")return "Ticker is required.";if(i.length<3||i.length>10)return "Ticker must be between 3 and 10 characters.";if(!/^[A-Z0-9]+$/.test(i))return "Ticker must be alphanumeric characters in uppercase only.";if(!/(?=(.*[A-Z].*[A-Z]))/.test(i))return "Ticker must have at least 2 alpha characters."}function M(i){if(!(i==null||i==="")){if(typeof i!="string")return "Vanity ticker must be a string.";if(i.trim()!==i)return "Vanity ticker must not have leading or trailing whitespace.";if([...i].length>10)return "Vanity ticker must be below 10 characters."}}function G(i){if(!(i instanceof File))return "Image must be a file.";let e=["image/png","image/jpeg","image/webp","image/svg","image/gif","image/avif"],t=200*1024;if(!i)return "Image file is required.";if(!e.includes(i.type))return `Invalid file type. Allowed types are: ${e.join(", ")}`;if(i.size>t)return `File size exceeds the maximum limit of ${t/1024}KB.`}function j(i){if(i){if(typeof i!="string")return "Twitter handle must be a string.";if(i&&!/^https?:\/\/(www\.)?(twitter\.com|x\.com)\/[A-Za-z0-9_]{1,15}\/?$/.test(i))return "Twitter must be a valid twitter URL."}}function Z(i){if(i){if(typeof i!="string")return "Website must be a string.";if(i&&!/^(https?:\/\/)?([\w-]+(\.[\w-]+)+)(\/[\w-./?%&=]*)?$/.test(i))return "Website must be a valid URL."}}function H(i){if(i){if(typeof i!="string")return "Telegram must be a string.";if(i&&!/^(https?:\/\/)?(t\.me|telegram\.me|telegram\.org)\/[A-Za-z0-9_]{5,32}\/?$/.test(i))return "Telegram must be a valid telegram URL."}}var w=class{_apiKey=null;_httpClient;BASE_URL;ENV;constructor(e="prod"){this._httpClient=new y,this.BASE_URL=I[e],this.ENV=e;}getUser(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}`)}getUserAvatarUrl(e){return `${_[this.ENV]}/user/${e}`}async getBalances(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{...t}})).data}async getBalance(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/balances`,{params:{token_in:t}})).data.find(r=>r.id===t)??null}getTokens(e,t={field:"marketcap",direction:"desc"},n={}){return this._httpClient.get(`${this.BASE_URL}/tokens`,{params:{...e,sort:`${t.field}:${t.direction}`,...n}})}getToken(e){return this._httpClient.get(`${this.BASE_URL}/token/${e}`)}async uploadImage(e){if(!this._apiKey)throw new Error("API key is not set");try{let t=g.image?.(e);if(t)throw new Error(t);let n=new FormData;return n.append("file",e),(await this._httpClient.post(`${this.BASE_URL}/upload`,n,{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})).data.upload}catch(t){if(t instanceof Error)if(t.name==="AxiosError"){let n=t;throw new Error(n.response?.data?.message||n.message)}else throw new Error(t.message);else throw new Error("Image upload failed")}}updateTokenImage(e,t){if(!this._apiKey)throw new Error("API key is not set");try{return this._httpClient.post(`${this.BASE_URL}/token/${e}/image`,{image:t},{headers:{"Content-Type":"multipart/form-data",Authorization:`Bearer ${this._apiKey}`}})}catch(n){if(n instanceof Error&&n.name==="AxiosError"){let r=n;throw new Error(r.response?.data?.message||r.message)}else throw new Error("Image update failed")}}getUserActivity(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/activity`,{params:{...t}})}async getUserTokens(e,t){let n=await this._httpClient.get(`${this.BASE_URL}/user/${e}/tokens`,{params:{...t}});return {...n,data:n.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserLiquidity(e,t){let n=await this._httpClient.get(`${this.BASE_URL}/user/${e}/liquidity`,{params:{...t}});return {...n,data:n.data.map(r=>({...r,balance:BigInt(r.balance)}))}}async getUserAchievements(e,t){return (await this._httpClient.get(`${this.BASE_URL}/user/${e}/achievements`,{params:{...t}})).data}getUserTransactions(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/transactions`,{params:{...t}})}getUserCreatedTokens(e,t){return this._httpClient.get(`${this.BASE_URL}/user/${e}/created`,{params:{...t}})}getUserStats(e){return this._httpClient.get(`${this.BASE_URL}/user/${e}/stats`)}set apiKey(e){this._apiKey=e;}get apiKey(){return this._apiKey}};var d=class{_identity;_api;_principal;_odin;constructor(e,t,n,r){this._principal=e,this._identity=t,this._api=n,this._odin=r;}get principal(){return this._principal}set principal(e){this._principal=e;}getIdentity(){return this._identity}getUser(){return this._api.getUser(this.principal)}buildAvatarImageUrl(){return this._api.getUserAvatarUrl(this.principal)}getBalances(e){return this._api.getBalances(this.principal,e)}getBalance(e){return this._api.getBalance(this.principal,e)}getTokens(e){return this._api.getUserTokens(this.principal,e)}getCreatedTokens(e){return this._api.getUserCreatedTokens(this.principal,e)}getActivity(e){return this._api.getUserActivity(this.principal,e)}getLiquidity(e){return this._api.getUserLiquidity(this.principal,e)}getAchievements(e){return this._api.getUserAchievements(this.principal,e)}getTransactions(e){return this._api.getUserTransactions(this.principal,e)}getStats(){return this._api.getUserStats(this.principal)}sell(e){return this._odin.sell({...e,principal:this.principal})}buy(e){return this._odin.buy({...e,principal:this.principal})}addLiquidity(e){return this._odin.addLiquidity({...e,principal:this.principal})}removeLiquidity(e){return this._odin.removeLiquidity({...e,principal:this.principal})}transfer(e){return this._odin.transfer({...e,principal:this.principal})}createToken(e){return this._odin.createToken({...e,principal:this.principal})}icrcApprove(e){return this._odin.icrcApprove({...e,principal:this.principal})}swap(e){return this._odin.swap({...e,principal:this.principal})}};var k={local:"http://localhost:5173",prod:"https://odin.fun",dev:"https://dev.odin.fun",legacy:"https://legacy.odin.fun"};var v=class{_settings;constructor(e){this._settings={target:e?.target||"_blank",settings:e?.settings||""};}get settings(){return this._settings}set settings(e){this._settings={...this._settings,...e};}open(e){return window.open(e,this._settings?.target||"_blank",this._settings?.settings)}};var T=class{_window;_appInfo;_api;origin;constructor(e,t,n,r){this._window=e,this._api=t,this._appInfo=n,this.origin=r;}get appInfo(){return this._appInfo}createUrl(e){let t=new URL(`${this.origin}/${e}`);return this._appInfo?.name&&t.searchParams.append("app_name",this._appInfo.name),t.searchParams.append("referrer",window.location.origin),t.searchParams.append("lang",this._appInfo?.lang||l),t}baseAction({params:e,odinPath:t,receivedMessageFromOrigin:n,resolve:r}){return new Promise((p,c)=>{let a=async s=>{s.origin===this.origin&&s.data.path==="/"+t&&(window.removeEventListener("message",a),(typeof n=="function"?n(s.data.message):n===s.data.message)?p(r.success(s.data.message)):c(new Error(r.failure)));},u=this.createUrl(t);for(let s in e)e[s]&&u.searchParams.append(s,e[s]);let o=this._window.open(u);if(!o||o.closed||typeof o.closed>"u"){c(new Error(r.didnotopen??`Failed to open ${t} window, please always allow popups and try again`));return}window.addEventListener("message",a);})}sell({token:e,tokenAmount:t,principal:n}){return this.baseAction({params:{principal:n,token:e,amount:t.toString()},odinPath:"authorize/sell",receivedMessageFromOrigin:"sold",resolve:{success:()=>true,failure:"Sell failed or was cancelled",close:"User closed the window"}})}buy({principal:e,token:t,btcAmount:n}){return this.baseAction({params:{principal:e,token:t,amount:n.toString()},odinPath:"authorize/buy",receivedMessageFromOrigin:"purchased",resolve:{success:()=>true,failure:"Purchase failed or was cancelled",close:"User closed the window"}})}transfer({principal:e,token:t,amount:n,destination:r}){return this.baseAction({params:{principal:e,token:t,amount:n.toString(),destination:r},odinPath:"authorize/transfer",receivedMessageFromOrigin:"transferred",resolve:{success:()=>true,failure:"Transfer failed or was cancelled",close:"User closed the window"}})}addLiquidity({principal:e,btcAmount:t,token:n}){return this.baseAction({params:{principal:e,amount:t.toString(),token:n},odinPath:"authorize/add_liquidity",receivedMessageFromOrigin:"addedLiquidity",resolve:{success:()=>true,failure:"Add liquidity failed or was cancelled",close:"User closed the window"}})}removeLiquidity({principal:e,lpAmount:t,token:n}){return this.baseAction({params:{principal:e,amount:t.toString(),token:n},odinPath:"authorize/remove_liquidity",receivedMessageFromOrigin:"removedLiquidity",resolve:{success:()=>true,failure:"Remove liquidity failed or was cancelled",close:"User closed the window"}})}swap({principal:e,fromToken:t,toToken:n,fromAmount:r}){return this.baseAction({params:{principal:e,from:t,to:n,amount:r.toString()},odinPath:"authorize/swap",receivedMessageFromOrigin:"swapped",resolve:{success:()=>true,failure:"Swap failed or was cancelled",close:"User closed the window"}})}icrcApprove({principal:e,token:t,spender:n,amount:r}){return this.baseAction({params:{principal:e,token:t,spender:n,amount:r.toString()},odinPath:"authorize/icrc_approve",receivedMessageFromOrigin:"approved",resolve:{success:()=>true,failure:"ICRC approve failed or was cancelled",close:"User closed the window"}})}async createToken({image:e,...t}){for(let p in g)if(p in t){let a=g[p]?.(t[p]||null);if(a)throw new Error(a)}if(t.discount&&!/^[A-Za-z0-9]{10}$/.test(t.discount))throw new Error("Discount code must be alphanumeric and exactly 10 characters long.");let n=await this._api.uploadImage(e);if(!await this.baseAction({params:{...t,image:n,buy:t.buy?.toString()},odinPath:"authorize/create_token",receivedMessageFromOrigin:"tokenCreated",resolve:{success:()=>true,failure:"Token creation failed or was cancelled",close:"User closed the window"}}))throw new Error("Token creation failed. Please try again.");return true}};var A=class{_key;constructor(e,t){this._key=`odin_connect:${e}:${t}:session`;}save(e){try{localStorage.setItem(this._key,JSON.stringify(e));}catch{}}load(){try{let e=localStorage.getItem(this._key);if(!e)return null;let t=JSON.parse(e);return this.isValidSessionData(t)?t:null}catch{return null}}isValidSessionData(e){if(typeof e!="object"||e===null)return false;let t=e;return typeof t.principal=="string"&&typeof t.sessionKey=="string"&&(t.delegationChain===null||typeof t.delegationChain=="string")&&(t.jwt===null||typeof t.jwt=="string")}clear(){try{localStorage.removeItem(this._key);}catch{}}};function Q(i){let e=0;for(let t=0;t<i.length;t++)e=e*31+i.charCodeAt(t)|0;return (e>>>0).toString(36).slice(0,3).padStart(3,"0")}function X(i){return `${i.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}-${Q(i)}`}var C=class{_appInfo=null;_api;_window;_odin;_storage;constructor(e){this._appInfo={env:"prod",name:"app_name",...e},this._appInfo.slug=this._appInfo.slug||X(this._appInfo.name),this._appInfo.lang=m(this._appInfo.lang),this._api=new w(this._appInfo.env==="prod"?"prod":this._appInfo.env==="legacy"?"legacy":"dev"),this._window=new v,this._odin=new T(this._window,this._api,this._appInfo,k[this._appInfo.env||"prod"]),this._storage=new A(this._appInfo.slug,this._appInfo.env||"prod");}createUrl(e){let t=new URL(`${this.origin}/${e}`);return this._appInfo?.name&&t.searchParams.append("app_name",this._appInfo.name),t.searchParams.append("referrer",window.location.origin),t.searchParams.append("lang",this.lang),t}get origin(){return k[this._appInfo?.env||"prod"]}get lang(){return this._appInfo?.lang||l}set lang(e){this._appInfo&&(this._appInfo.lang=m(e));}get appInfo(){return this._appInfo}get slug(){return this._appInfo?.slug||""}connect({open:e,requires_api:t,requires_delegation:n,targets:r}={requires_delegation:false,requires_api:false}){return new Promise((p,c)=>{e&&(this._window.settings=e);let a=Ed25519KeyIdentity.generate(),u=async s=>{if(s.origin===this.origin&&s.data.path==="/authorize/connect")if(window.removeEventListener("message",u),s.data.message!="rejected"){let O;try{let S=s.data.message,{principal:b,jwt:E,delegationChain:f}=S;if(t&&(this._api.apiKey=E),n){if(!f)throw new Error("Delegation chain is missing");let P=DelegationIdentity.fromDelegation(a,DelegationChain.fromJSON(f));O=new d(b,P,this.api,this._odin);}else O=new d(b,null,this.api,this._odin);(t||n)&&this._storage.save({principal:b,sessionKey:JSON.stringify(a.toJSON()),delegationChain:f?JSON.stringify(f):null,jwt:E||null}),p(O);}catch{c(new Error("Failed to fetch user data"));}}else c(new Error("User rejected the connection"));},o=this.createUrl("authorize/connect");if(o.searchParams.append("requires_api",t?"1":"0"),n){o.searchParams.append("requires_delegation","1");let s=btoa(JSON.stringify(a.toJSON()));o.searchParams.append("session_key",s),o.searchParams.append("targets",r?.join(",")||"");}this._window.open(o),window.addEventListener("message",u);})}get api(){return this._api}get odin(){return this._odin}get currentEnv(){return this._appInfo?.env||"prod"}restoreSession(){try{let e=this._storage.load();if(!e)return null;if(e.delegationChain&&!h(e.delegationChain))return this._storage.clear(),null;e.jwt&&(this._api.apiKey=e.jwt);let t=null;if(e.delegationChain&&e.sessionKey){let n=Ed25519KeyIdentity.fromJSON(e.sessionKey),r=DelegationChain.fromJSON(JSON.parse(e.delegationChain));t=DelegationIdentity.fromDelegation(n,r);}return new d(e.principal,t,this._api,this._odin)}catch{return this._storage.clear(),null}}disconnect(){this._storage.clear(),this._api.apiKey=null;}isSessionValid(){let e=this._storage.load();return e?e.delegationChain?h(e.delegationChain):true:false}hello(){console.log("Hello from Odin Connect!");}};
|
|
2
|
+
export{C as OdinConnect,U as OdinUtils};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "odin-connect",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.6.0",
|
|
4
4
|
"description": "",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -21,6 +21,7 @@
|
|
|
21
21
|
"build": "tsup",
|
|
22
22
|
"prepublishOnly": "npm run build",
|
|
23
23
|
"test": "vitest",
|
|
24
|
+
"audit": "npm audit --omit=dev --audit-level=moderate",
|
|
24
25
|
"demo:update": "npm run build && cd demo && npm install ../ && cd ..",
|
|
25
26
|
"demo:start": "cd demo && npm run dev",
|
|
26
27
|
"demo:build": "npm run demo:update && cd demo && npm run build",
|
package/readme.md
CHANGED
|
@@ -175,9 +175,24 @@ await user.buy({ token: "2jjj", btcAmount: 10_000_000n });
|
|
|
175
175
|
const odinConnect = new OdinConnect({
|
|
176
176
|
name: "Demo App", // Your app name (shown in auth popup)
|
|
177
177
|
env: "prod", // "prod" | "dev" | "local" | "legacy"
|
|
178
|
+
lang: "en", // Popup UI language: "en" | "zh" (default "en")
|
|
178
179
|
});
|
|
179
180
|
```
|
|
180
181
|
|
|
182
|
+
### Popup language
|
|
183
|
+
|
|
184
|
+
All auth and action popups render in the language set via `lang`. It can be
|
|
185
|
+
changed at runtime; the new value applies to the next popup opened:
|
|
186
|
+
|
|
187
|
+
```typescript
|
|
188
|
+
const odinConnect = new OdinConnect({ name: "Demo App", lang: "zh" });
|
|
189
|
+
|
|
190
|
+
odinConnect.lang = "en"; // next popup renders in English
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
Unsupported values fall back to `"en"`. The SDK does not persist `lang` —
|
|
194
|
+
pass it on each construction from your app's own i18n state.
|
|
195
|
+
|
|
181
196
|
### Connecting a user
|
|
182
197
|
|
|
183
198
|
```typescript
|
|
@@ -208,6 +223,11 @@ const identity = user.getIdentity();
|
|
|
208
223
|
// Use identity with @dfinity/agent
|
|
209
224
|
```
|
|
210
225
|
|
|
226
|
+
> [!IMPORTANT]
|
|
227
|
+
> **Every target canister must trust your app's origin.** Each canister listed in `targets` must return your app's origin from its [`icrc28_trusted_origins()`](https://github.com/dfinity/wg-identity-authentication) method. The Odin frontend verifies this against **all** targets before issuing a delegation.
|
|
228
|
+
>
|
|
229
|
+
> **Failure mode:** if any target does not list your origin (or does not implement ICRC-28), the authorize popup silently hides the action — no delegation is issued and no error is surfaced to your app. Ensure each target canister declares your origin before requesting `requires_delegation: true`.
|
|
230
|
+
|
|
211
231
|
## Session Restoration
|
|
212
232
|
|
|
213
233
|
OdinConnect automatically persists session data to `localStorage` after a successful `connect()`. This allows you to restore sessions on page load without requiring user action.
|
|
@@ -399,6 +419,7 @@ await user.createToken({
|
|
|
399
419
|
principal: "veyov-kjgrf-hke6v-6d63i-sdwae-oldgg-huau6-ke5g3-rllp2-5jhca-uqe",
|
|
400
420
|
name: "Test Token", // 3-30 characters
|
|
401
421
|
ticker: "TEST", // 3-10 uppercase alphanumeric, at least 2 letters
|
|
422
|
+
vanity_ticker: "", // Optional, 1-10 characters (any unicode), no surrounding whitespace
|
|
402
423
|
description: "A test token", // Optional, max 100 characters
|
|
403
424
|
website: "https://example.com", // Optional, valid URL
|
|
404
425
|
telegram: "", // Optional, valid Telegram URL
|
|
@@ -512,6 +533,7 @@ import { OdinUtils } from "odin-connect";
|
|
|
512
533
|
|
|
513
534
|
OdinUtils.createTokenValidators.name("My Token"); // 3-30 chars
|
|
514
535
|
OdinUtils.createTokenValidators.ticker("TEST"); // 3-10 uppercase alphanumeric
|
|
536
|
+
OdinUtils.createTokenValidators.vanity_ticker("Tëst🚀"); // Optional, max 10 unicode code points, no surrounding whitespace
|
|
515
537
|
OdinUtils.createTokenValidators.image(file); // PNG/JPEG/WebP/GIF/SVG/AVIF, max 200KB
|
|
516
538
|
OdinUtils.createTokenValidators.description("A token"); // Max 100 chars
|
|
517
539
|
OdinUtils.createTokenValidators.website("https://..."); // Valid URL
|