@monerium/sdk 3.1.0 → 3.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -82,6 +82,8 @@ type PKCERequest = {
82
82
  state?: string;
83
83
  /** the redirect uri of the application */
84
84
  redirect_uri: string;
85
+ /** the email of the user to prefill the login form */
86
+ email?: string;
85
87
  /** the scope of the application */
86
88
  scope?: string;
87
89
  /** the address of the wallet to automatically link */
@@ -446,6 +448,8 @@ interface AuthFlowOptions {
446
448
  clientId?: string;
447
449
  /** the redirect URI defined by your application */
448
450
  redirectUri?: string;
451
+ /** the email of the user to prefill the login form */
452
+ email?: string;
449
453
  /** the address your customer should link in auth flow */
450
454
  address?: string;
451
455
  /** the signature of the address */
package/dist/index.js CHANGED
@@ -2,33 +2,33 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var X = require('crypto-js/enc-base64url.js');
6
- var Z = require('crypto-js/sha256.js');
5
+ var Z = require('crypto-js/enc-base64url.js');
6
+ var Y = require('crypto-js/sha256.js');
7
7
 
8
8
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
9
9
 
10
- var X__default = /*#__PURE__*/_interopDefault(X);
11
10
  var Z__default = /*#__PURE__*/_interopDefault(Z);
11
+ var Y__default = /*#__PURE__*/_interopDefault(Y);
12
12
 
13
- var P={environments:{production:{name:"production",api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},sandbox:{name:"sandbox",api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev",wss:"wss://api.monerium.dev"}}};var f={LINK_MESSAGE:"I hereby declare that I am the address owner.",STORAGE_CODE_VERIFIER:"monerium.sdk.code_verifier",STORAGE_ACCESS_TOKEN:"monerium.sdk.access_token",STORAGE_ACCESS_EXPIRY:"monerium.sdk.access_expiry"};var v=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(v||{}),U=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(U||{}),z=(r=>(r.corporate="corporate",r.personal="personal",r))(z||{}),q=(r=>(r.read="read",r.write="write",r))(q||{}),j=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(j||{}),M=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(M||{}),F=(t=>(t.approved="approved",t.rejected="rejected",t.unknown="unknown",t))(F||{}),K=(t=>(t.requested="requested",t.approved="approved",t.pending="pending",t))(K||{}),L=(t=>(t.iban="iban",t.scan="scan",t.chain="chain",t))(L||{}),Q=(t=>(t.passport="passport",t.nationalIdentityCard="nationalIdentityCard",t.drivingLicense="drivingLicense",t))(Q||{}),V=(r=>(r.redeem="redeem",r.issue="issue",r))(V||{}),G=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(G||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=t=>t<10?"0"+t:t,r=t=>{if(t===0)return "Z";let i=t>0?"-":"+";return t=Math.abs(t),i+e(Math.floor(t/60))+":"+e(t%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+r(n.getTimezoneOffset())},J=n=>{switch(n){case"noble":case"noble-1":case"grand":case"grand-1":return !0;default:return !1}},W=n=>{switch(n){case"ethereum":case"sepolia":case"polygon":case"amoy":case"gnosis":case"chiado":case"arbitrum":case"arbitrumsepolia":case"linea":case"lineasepolia":return !0;default:return !1}},b=n=>{if(typeof n=="number")return I(n);if(J(n))return n.split("-")[0];if(W(n))return n;try{return I(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},m=(n,e)=>b(N(e,n)),H=(n,e,r,t)=>{let i=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${r} on ${b(t)} at ${x(new Date)}`:i==="EUR"?`Send ${i} ${n} to ${O(r)} at ${x(new Date)}`:`Send ${i} ${n} to ${r} at ${x(new Date)}`},C=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,r])=>r!==void 0).map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"):"",I=n=>{switch(n){case 1:return "ethereum";case 11155111:return "sepolia";case 100:return "gnosis";case 10200:return "chiado";case 137:return "polygon";case 80002:return "amoy";case 42161:return "arbitrum";case 421614:return "arbitrumsepolia";case 59144:return "linea";case 59141:return "lineasepolia";default:throw new Error(`Chain not supported: ${n}`)}},O=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var N=(n,e)=>{if(e==="sandbox")switch(n){case"ethereum":return "sepolia";case"polygon":return "amoy";case"gnosis":return "chiado";case"arbitrum":return "arbitrumsepolia";case"noble":return "grand";default:return n}return n},l=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:b(N(r,n))}}return e};var Y=(n,e)=>{let{client_id:r,redirect_uri:t,scope:i,state:s,address:a,signature:o,chain:c,skip_create_account:d,skip_kyc:h}=n,D=a?{address:a,...o!==void 0?{signature:o}:{},...c!==void 0?{chain:c}:{}}:{};return C({client_id:r,redirect_uri:t,...i!==void 0?{scope:i}:{},...s!==void 0?{state:s}:{},...d!==void 0?{skip_create_account:d}:{},...h!==void 0?{skip_kyc:h}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...D})},ee=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=e.length,t=0;for(;t<128;)n+=e.charAt(Math.floor(Math.random()*r)),t+=1;return n},te=n=>X__default.default.stringify(Z__default.default(n)),k=(n,e)=>{let r=ee(),t=te(r);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,r||""),`${n.api}/auth?${Y(l(n.name,e),t)}`},R=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,r]=n.split("?");r&&window.history.replaceState(null,"",e);},_=n=>n.code!=null,$=n=>n.refresh_token!=null,T=n=>n.client_secret!=null;var S=async(n,e,r,t)=>{let i=await fetch(`${n}`,{method:e,headers:t,body:r}),s,a=await i.text();try{if(s=JSON.parse(a),Object.keys(s).length===0&&s.constructor===Object)switch(i.status){case 201:case 202:return {status:i.status,statusText:i.statusText}}}catch{throw a}if(!i.ok)throw s;return s};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([r,t])=>t!==""&&t!==void 0&&t!==null).map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&");return e?"?"+e:""};var B=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var E=n=>Object.entries(n).filter(([r,t])=>t!=null).map(([r,t])=>`${r}-${t}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",w=class{#e;#s;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#r=()=>{};#i;state;constructor(e){if(!e){this.#e=P.environments.sandbox;return}if(typeof e=="string")this.#e=P.environments[e];else if(this.#r=B(e.debug??!1),this.#e=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#i={clientId:r,redirectUri:t};}else {this.#r("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:r,clientSecret:t}=e;this.#i={clientId:r,clientSecret:t};}}async authorize(e){let r=e?.clientId||this.#i?.clientId,t=e?.redirectUri||this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");let i=k(this.#e,{client_id:r,redirect_uri:t,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#r(`Authorization URL: ${i}`),window.location.assign(i);}async getAccess(e){let r=this.#i?.clientId;if(this.#i?.clientSecret){if(u)return await this.#d(this.#i),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let i=this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||void 0,a=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),c=window.localStorage.getItem(g);if(s)return this.#r("Using auth code from auth flow to authorize"),await this.#a(r,i,s,a),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#r("Using refresh token to authorize"),await this.#c(r,e),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(o&&c){let d=new Date;if(parseInt(c)<d.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token has expired");this.#r("Access token should still be valid, checking if it is authorized...");try{return this.#s=`Bearer ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#r("Authorized"),!0}catch{throw this.#r("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let r;if(_(e))r={...e,grant_type:"authorization_code"};else if($(e))r={...e,grant_type:"refresh_token"};else if(T(e))r={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#t("post","auth/token",r,!0).then(t=>{if(this.bearerProfile=t,this.isAuthorized=!!t,this.#s=`Bearer ${t?.access_token}`,!u){let s=new Date().getTime()+t?.expires_in*1e3;window.localStorage.setItem(p,t?.access_token||""),window.localStorage.setItem(g,s?.toString());}}).catch(t=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),R()),new Error(t?.message)}),_(e)&&R(),this.bearerProfile}getProfile(e){return this.#t("get",`profiles/${e}`)}getProfiles(e){return this.#t("get",`profiles${y(e)}`)}getAddress(e){return this.#t("get",`addresses/${e}`)}getAddresses(e){e=l(this.#e.name,e);let r=e?C(e):void 0,t=r?`addresses?${r}`:"addresses";return this.#t("get",t)}getBalances(e,r,t){let i=Array.isArray(t)?t.map(a=>`currency=${a}`).join("&"):t?`currency=${t}`:"",s=m(this.#e.name,r);return this.#t("get",`balances/${s}/${e}${i?`?${i}`:""}`)}getIban(e){return this.#t("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:r,chain:t}=e||{},i=y({profile:r,chain:t?m(this.#e.name,t):""});return this.#t("get",`ibans${i}`)}getOrders(e){return this.#t("get",`orders${y(e)}`)}getOrder(e){return this.#t("get",`orders/${e}`)}getTokens(){return this.#t("get","tokens")}linkAddress(e){return e=l(this.#e.name,e),this.#t("post","addresses",JSON.stringify(e))}placeOrder(e){let r={kind:"redeem",...l(this.#e.name,e),counterpart:{...e.counterpart,identifier:l(this.#e.name,e.counterpart.identifier)}};return this.#t("post","orders",JSON.stringify(r))}moveIban(e,{address:r,chain:t}){return this.#t("patch",`ibans/${e}`,JSON.stringify({address:r,chain:m(this.#e.name,t)}))}requestIban({address:e,chain:r,emailNotifications:t=!0}){return this.#t("post","ibans",JSON.stringify({address:e,chain:m(this.#e.name,r),emailNotifications:t}))}submitProfileDetails(e,r){return this.#t("put",`profiles/${e}/details`,JSON.stringify(r))}uploadSupportingDocument(e){let r=new FormData;return r.append("file",e),S(`${this.#e.api}/files`,"post",r,{Authorization:this.#s||""})}async#t(e,r,t,i){let s={Authorization:this.#s||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`};return S(`${this.#e.api}/${r}`,e.toUpperCase(),i?C(t):t,s)}#a=async(e,r,t,i)=>{let s=localStorage.getItem(A)||"";if(!s)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=i,localStorage.removeItem(A),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:r})=>await this.#o({client_id:e,client_secret:r});#c=async(e,r)=>await this.#o({refresh_token:r,client_id:e});subscribeOrderNotifications({filter:e,onMessage:r,onError:t}={}){if(!this.bearerProfile?.access_token)return;let{profile:i,state:s}=e||{},a=y({access_token:this.bearerProfile?.access_token,profile:i,state:s}),o,c=E({profile:i,state:s});if(this.#n?.has(c))o=this.#n.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#n?.set(c,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=d=>{let h=JSON.parse(d.data);r&&r(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(a);},o.onerror=d=>{t&&t(d),console.error("WebSocket error:",d);},o}unsubscribeOrderNotifications(e){if(e){let r=E({profile:e?.profile,state:e?.state}),t=this.#n?.get(r);t&&(t.close(),this.#n?.delete(r));}else this.#n?.forEach(r=>{r?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#s=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e;getAuthFlowURI=e=>k(this.#e,l(this.#e.name,e))};var Ne=w;
13
+ var P={environments:{production:{name:"production",api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},sandbox:{name:"sandbox",api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev",wss:"wss://api.monerium.dev"}}};var f={LINK_MESSAGE:"I hereby declare that I am the address owner.",STORAGE_CODE_VERIFIER:"monerium.sdk.code_verifier",STORAGE_ACCESS_TOKEN:"monerium.sdk.access_token",STORAGE_ACCESS_EXPIRY:"monerium.sdk.access_expiry"};var O=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(O||{}),z=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(z||{}),q=(r=>(r.corporate="corporate",r.personal="personal",r))(q||{}),j=(r=>(r.read="read",r.write="write",r))(j||{}),M=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(M||{}),F=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(F||{}),K=(t=>(t.approved="approved",t.rejected="rejected",t.unknown="unknown",t))(K||{}),L=(t=>(t.requested="requested",t.approved="approved",t.pending="pending",t))(L||{}),Q=(t=>(t.iban="iban",t.scan="scan",t.chain="chain",t))(Q||{}),V=(t=>(t.passport="passport",t.nationalIdentityCard="nationalIdentityCard",t.drivingLicense="drivingLicense",t))(V||{}),G=(r=>(r.redeem="redeem",r.issue="issue",r))(G||{}),J=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(J||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=t=>t<10?"0"+t:t,r=t=>{if(t===0)return "Z";let i=t>0?"-":"+";return t=Math.abs(t),i+e(Math.floor(t/60))+":"+e(t%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+r(n.getTimezoneOffset())},W=n=>{switch(n){case"noble":case"noble-1":case"grand":case"grand-1":return !0;default:return !1}},H=n=>{switch(n){case"ethereum":case"sepolia":case"polygon":case"amoy":case"gnosis":case"chiado":case"arbitrum":case"arbitrumsepolia":case"linea":case"lineasepolia":return !0;default:return !1}},b=n=>{if(typeof n=="number")return I(n);if(W(n))return n.split("-")[0];if(H(n))return n;try{return I(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},m=(n,e)=>b($(e,n)),X=(n,e,r,t)=>{let i=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${r} on ${b(t)} at ${x(new Date)}`:i==="EUR"?`Send ${i} ${n} to ${N(r)} at ${x(new Date)}`:`Send ${i} ${n} to ${r} at ${x(new Date)}`},C=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,r])=>r!==void 0).map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"):"",I=n=>{switch(n){case 1:return "ethereum";case 11155111:return "sepolia";case 100:return "gnosis";case 10200:return "chiado";case 137:return "polygon";case 80002:return "amoy";case 42161:return "arbitrum";case 421614:return "arbitrumsepolia";case 59144:return "linea";case 59141:return "lineasepolia";default:throw new Error(`Chain not supported: ${n}`)}},N=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var $=(n,e)=>{if(e==="sandbox")switch(n){case"ethereum":return "sepolia";case"polygon":return "amoy";case"gnosis":return "chiado";case"arbitrum":return "arbitrumsepolia";case"noble":return "grand";default:return n}return n},l=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:b($(r,n))}}return e};var ee=(n,e)=>{let{client_id:r,redirect_uri:t,scope:i,state:s,address:a,signature:o,chain:c,email:d,skip_create_account:h,skip_kyc:v}=n,U=a?{address:a,...o!==void 0?{signature:o}:{},...c!==void 0?{chain:c}:{}}:{};return C({client_id:r,redirect_uri:t,...i!==void 0?{scope:i}:{},...d!==void 0?{email:d}:{},...s!==void 0?{state:s}:{},...h!==void 0?{skip_create_account:h}:{},...v!==void 0?{skip_kyc:v}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...U})},te=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=e.length,t=0;for(;t<128;)n+=e.charAt(Math.floor(Math.random()*r)),t+=1;return n},re=n=>Z__default.default.stringify(Y__default.default(n)),k=(n,e)=>{let r=te(),t=re(r);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,r||""),`${n.api}/auth?${ee(l(n.name,e),t)}`},R=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,r]=n.split("?");r&&window.history.replaceState(null,"",e);},_=n=>n.code!=null,T=n=>n.refresh_token!=null,B=n=>n.client_secret!=null;var S=async(n,e,r,t)=>{let i=await fetch(`${n}`,{method:e,headers:t,body:r}),s,a=await i.text();try{if(s=JSON.parse(a),Object.keys(s).length===0&&s.constructor===Object)switch(i.status){case 201:case 202:return {status:i.status,statusText:i.statusText}}}catch{throw a}if(!i.ok)throw s;return s};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([r,t])=>t!==""&&t!==void 0&&t!==null).map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&");return e?"?"+e:""};var D=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var E=n=>Object.entries(n).filter(([r,t])=>t!=null).map(([r,t])=>`${r}-${t}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",w=class{#e;#s;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#r=()=>{};#i;state;constructor(e){if(!e){this.#e=P.environments.sandbox;return}if(typeof e=="string")this.#e=P.environments[e];else if(this.#r=D(e.debug??!1),this.#e=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#i={clientId:r,redirectUri:t};}else {this.#r("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:r,clientSecret:t}=e;this.#i={clientId:r,clientSecret:t};}}async authorize(e){let r=e?.clientId||this.#i?.clientId,t=e?.redirectUri||this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");let i=k(this.#e,{client_id:r,redirect_uri:t,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,email:e?.email,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#r(`Authorization URL: ${i}`),window.location.assign(i);}async getAccess(e){let r=this.#i?.clientId;if(this.#i?.clientSecret){if(u)return await this.#d(this.#i),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let i=this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||void 0,a=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),c=window.localStorage.getItem(g);if(s)return this.#r("Using auth code from auth flow to authorize"),await this.#a(r,i,s,a),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#r("Using refresh token to authorize"),await this.#c(r,e),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(o&&c){let d=new Date;if(parseInt(c)<d.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token has expired");this.#r("Access token should still be valid, checking if it is authorized...");try{return this.#s=`Bearer ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#r("Authorized"),!0}catch{throw this.#r("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let r;if(_(e))r={...e,grant_type:"authorization_code"};else if(T(e))r={...e,grant_type:"refresh_token"};else if(B(e))r={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#t("post","auth/token",r,!0).then(t=>{if(this.bearerProfile=t,this.isAuthorized=!!t,this.#s=`Bearer ${t?.access_token}`,!u){let s=new Date().getTime()+t?.expires_in*1e3;window.localStorage.setItem(p,t?.access_token||""),window.localStorage.setItem(g,s?.toString());}}).catch(t=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),R()),new Error(t?.message)}),_(e)&&R(),this.bearerProfile}getProfile(e){return this.#t("get",`profiles/${e}`)}getProfiles(e){return this.#t("get",`profiles${y(e)}`)}getAddress(e){return this.#t("get",`addresses/${e}`)}getAddresses(e){e=l(this.#e.name,e);let r=e?C(e):void 0,t=r?`addresses?${r}`:"addresses";return this.#t("get",t)}getBalances(e,r,t){let i=Array.isArray(t)?t.map(a=>`currency=${a}`).join("&"):t?`currency=${t}`:"",s=m(this.#e.name,r);return this.#t("get",`balances/${s}/${e}${i?`?${i}`:""}`)}getIban(e){return this.#t("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:r,chain:t}=e||{},i=y({profile:r,chain:t?m(this.#e.name,t):""});return this.#t("get",`ibans${i}`)}getOrders(e){return this.#t("get",`orders${y(e)}`)}getOrder(e){return this.#t("get",`orders/${e}`)}getTokens(){return this.#t("get","tokens")}linkAddress(e){return e=l(this.#e.name,e),this.#t("post","addresses",JSON.stringify(e))}placeOrder(e){let r={kind:"redeem",...l(this.#e.name,e),counterpart:{...e.counterpart,identifier:l(this.#e.name,e.counterpart.identifier)}};return this.#t("post","orders",JSON.stringify(r))}moveIban(e,{address:r,chain:t}){return this.#t("patch",`ibans/${e}`,JSON.stringify({address:r,chain:m(this.#e.name,t)}))}requestIban({address:e,chain:r,emailNotifications:t=!0}){return this.#t("post","ibans",JSON.stringify({address:e,chain:m(this.#e.name,r),emailNotifications:t}))}submitProfileDetails(e,r){return this.#t("put",`profiles/${e}/details`,JSON.stringify(r))}uploadSupportingDocument(e){let r=new FormData;return r.append("file",e),S(`${this.#e.api}/files`,"post",r,{Authorization:this.#s||""})}async#t(e,r,t,i){let s={Authorization:this.#s||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`};return S(`${this.#e.api}/${r}`,e.toUpperCase(),i?C(t):t,s)}#a=async(e,r,t,i)=>{let s=localStorage.getItem(A)||"";if(!s)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=i,localStorage.removeItem(A),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:r})=>await this.#o({client_id:e,client_secret:r});#c=async(e,r)=>await this.#o({refresh_token:r,client_id:e});subscribeOrderNotifications({filter:e,onMessage:r,onError:t}={}){if(!this.bearerProfile?.access_token)return;let{profile:i,state:s}=e||{},a=y({access_token:this.bearerProfile?.access_token,profile:i,state:s}),o,c=E({profile:i,state:s});if(this.#n?.has(c))o=this.#n.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#n?.set(c,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=d=>{let h=JSON.parse(d.data);r&&r(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(a);},o.onerror=d=>{t&&t(d),console.error("WebSocket error:",d);},o}unsubscribeOrderNotifications(e){if(e){let r=E({profile:e?.profile,state:e?.state}),t=this.#n?.get(r);t&&(t.close(),this.#n?.delete(r));}else this.#n?.forEach(r=>{r?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#s=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e;getAuthFlowURI=e=>k(this.#e,l(this.#e.name,e))};var $e=w;
14
14
 
15
- exports.AccountState = K;
16
- exports.Currency = v;
17
- exports.IdDocumentKind = Q;
18
- exports.KYCOutcome = F;
19
- exports.KYCState = M;
20
- exports.Method = U;
15
+ exports.AccountState = L;
16
+ exports.Currency = O;
17
+ exports.IdDocumentKind = V;
18
+ exports.KYCOutcome = K;
19
+ exports.KYCState = F;
20
+ exports.Method = z;
21
21
  exports.MoneriumClient = w;
22
- exports.OrderKind = V;
23
- exports.OrderState = G;
24
- exports.PaymentStandard = L;
25
- exports.Permission = q;
26
- exports.ProfileState = j;
27
- exports.ProfileType = z;
22
+ exports.OrderKind = G;
23
+ exports.OrderState = J;
24
+ exports.PaymentStandard = Q;
25
+ exports.Permission = j;
26
+ exports.ProfileState = M;
27
+ exports.ProfileType = q;
28
28
  exports.constants = f;
29
- exports.default = Ne;
29
+ exports.default = $e;
30
30
  exports.getChain = I;
31
31
  exports.parseChain = b;
32
- exports.placeOrderMessage = H;
32
+ exports.placeOrderMessage = X;
33
33
  exports.rfc3339 = x;
34
- exports.shortenIban = O;
34
+ exports.shortenIban = N;
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import X from 'crypto-js/enc-base64url.js';
2
- import Z from 'crypto-js/sha256.js';
1
+ import Z from 'crypto-js/enc-base64url.js';
2
+ import Y from 'crypto-js/sha256.js';
3
3
 
4
- var P={environments:{production:{name:"production",api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},sandbox:{name:"sandbox",api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev",wss:"wss://api.monerium.dev"}}};var f={LINK_MESSAGE:"I hereby declare that I am the address owner.",STORAGE_CODE_VERIFIER:"monerium.sdk.code_verifier",STORAGE_ACCESS_TOKEN:"monerium.sdk.access_token",STORAGE_ACCESS_EXPIRY:"monerium.sdk.access_expiry"};var v=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(v||{}),U=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(U||{}),z=(r=>(r.corporate="corporate",r.personal="personal",r))(z||{}),q=(r=>(r.read="read",r.write="write",r))(q||{}),j=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(j||{}),M=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(M||{}),F=(t=>(t.approved="approved",t.rejected="rejected",t.unknown="unknown",t))(F||{}),K=(t=>(t.requested="requested",t.approved="approved",t.pending="pending",t))(K||{}),L=(t=>(t.iban="iban",t.scan="scan",t.chain="chain",t))(L||{}),Q=(t=>(t.passport="passport",t.nationalIdentityCard="nationalIdentityCard",t.drivingLicense="drivingLicense",t))(Q||{}),V=(r=>(r.redeem="redeem",r.issue="issue",r))(V||{}),G=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(G||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=t=>t<10?"0"+t:t,r=t=>{if(t===0)return "Z";let i=t>0?"-":"+";return t=Math.abs(t),i+e(Math.floor(t/60))+":"+e(t%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+r(n.getTimezoneOffset())},J=n=>{switch(n){case"noble":case"noble-1":case"grand":case"grand-1":return !0;default:return !1}},W=n=>{switch(n){case"ethereum":case"sepolia":case"polygon":case"amoy":case"gnosis":case"chiado":case"arbitrum":case"arbitrumsepolia":case"linea":case"lineasepolia":return !0;default:return !1}},b=n=>{if(typeof n=="number")return I(n);if(J(n))return n.split("-")[0];if(W(n))return n;try{return I(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},m=(n,e)=>b(N(e,n)),H=(n,e,r,t)=>{let i=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${r} on ${b(t)} at ${x(new Date)}`:i==="EUR"?`Send ${i} ${n} to ${O(r)} at ${x(new Date)}`:`Send ${i} ${n} to ${r} at ${x(new Date)}`},C=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,r])=>r!==void 0).map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"):"",I=n=>{switch(n){case 1:return "ethereum";case 11155111:return "sepolia";case 100:return "gnosis";case 10200:return "chiado";case 137:return "polygon";case 80002:return "amoy";case 42161:return "arbitrum";case 421614:return "arbitrumsepolia";case 59144:return "linea";case 59141:return "lineasepolia";default:throw new Error(`Chain not supported: ${n}`)}},O=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var N=(n,e)=>{if(e==="sandbox")switch(n){case"ethereum":return "sepolia";case"polygon":return "amoy";case"gnosis":return "chiado";case"arbitrum":return "arbitrumsepolia";case"noble":return "grand";default:return n}return n},l=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:b(N(r,n))}}return e};var Y=(n,e)=>{let{client_id:r,redirect_uri:t,scope:i,state:s,address:a,signature:o,chain:c,skip_create_account:d,skip_kyc:h}=n,D=a?{address:a,...o!==void 0?{signature:o}:{},...c!==void 0?{chain:c}:{}}:{};return C({client_id:r,redirect_uri:t,...i!==void 0?{scope:i}:{},...s!==void 0?{state:s}:{},...d!==void 0?{skip_create_account:d}:{},...h!==void 0?{skip_kyc:h}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...D})},ee=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=e.length,t=0;for(;t<128;)n+=e.charAt(Math.floor(Math.random()*r)),t+=1;return n},te=n=>X.stringify(Z(n)),k=(n,e)=>{let r=ee(),t=te(r);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,r||""),`${n.api}/auth?${Y(l(n.name,e),t)}`},R=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,r]=n.split("?");r&&window.history.replaceState(null,"",e);},_=n=>n.code!=null,$=n=>n.refresh_token!=null,T=n=>n.client_secret!=null;var S=async(n,e,r,t)=>{let i=await fetch(`${n}`,{method:e,headers:t,body:r}),s,a=await i.text();try{if(s=JSON.parse(a),Object.keys(s).length===0&&s.constructor===Object)switch(i.status){case 201:case 202:return {status:i.status,statusText:i.statusText}}}catch{throw a}if(!i.ok)throw s;return s};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([r,t])=>t!==""&&t!==void 0&&t!==null).map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&");return e?"?"+e:""};var B=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var E=n=>Object.entries(n).filter(([r,t])=>t!=null).map(([r,t])=>`${r}-${t}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",w=class{#e;#s;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#r=()=>{};#i;state;constructor(e){if(!e){this.#e=P.environments.sandbox;return}if(typeof e=="string")this.#e=P.environments[e];else if(this.#r=B(e.debug??!1),this.#e=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#i={clientId:r,redirectUri:t};}else {this.#r("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:r,clientSecret:t}=e;this.#i={clientId:r,clientSecret:t};}}async authorize(e){let r=e?.clientId||this.#i?.clientId,t=e?.redirectUri||this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");let i=k(this.#e,{client_id:r,redirect_uri:t,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#r(`Authorization URL: ${i}`),window.location.assign(i);}async getAccess(e){let r=this.#i?.clientId;if(this.#i?.clientSecret){if(u)return await this.#d(this.#i),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let i=this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||void 0,a=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),c=window.localStorage.getItem(g);if(s)return this.#r("Using auth code from auth flow to authorize"),await this.#a(r,i,s,a),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#r("Using refresh token to authorize"),await this.#c(r,e),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(o&&c){let d=new Date;if(parseInt(c)<d.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token has expired");this.#r("Access token should still be valid, checking if it is authorized...");try{return this.#s=`Bearer ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#r("Authorized"),!0}catch{throw this.#r("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let r;if(_(e))r={...e,grant_type:"authorization_code"};else if($(e))r={...e,grant_type:"refresh_token"};else if(T(e))r={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#t("post","auth/token",r,!0).then(t=>{if(this.bearerProfile=t,this.isAuthorized=!!t,this.#s=`Bearer ${t?.access_token}`,!u){let s=new Date().getTime()+t?.expires_in*1e3;window.localStorage.setItem(p,t?.access_token||""),window.localStorage.setItem(g,s?.toString());}}).catch(t=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),R()),new Error(t?.message)}),_(e)&&R(),this.bearerProfile}getProfile(e){return this.#t("get",`profiles/${e}`)}getProfiles(e){return this.#t("get",`profiles${y(e)}`)}getAddress(e){return this.#t("get",`addresses/${e}`)}getAddresses(e){e=l(this.#e.name,e);let r=e?C(e):void 0,t=r?`addresses?${r}`:"addresses";return this.#t("get",t)}getBalances(e,r,t){let i=Array.isArray(t)?t.map(a=>`currency=${a}`).join("&"):t?`currency=${t}`:"",s=m(this.#e.name,r);return this.#t("get",`balances/${s}/${e}${i?`?${i}`:""}`)}getIban(e){return this.#t("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:r,chain:t}=e||{},i=y({profile:r,chain:t?m(this.#e.name,t):""});return this.#t("get",`ibans${i}`)}getOrders(e){return this.#t("get",`orders${y(e)}`)}getOrder(e){return this.#t("get",`orders/${e}`)}getTokens(){return this.#t("get","tokens")}linkAddress(e){return e=l(this.#e.name,e),this.#t("post","addresses",JSON.stringify(e))}placeOrder(e){let r={kind:"redeem",...l(this.#e.name,e),counterpart:{...e.counterpart,identifier:l(this.#e.name,e.counterpart.identifier)}};return this.#t("post","orders",JSON.stringify(r))}moveIban(e,{address:r,chain:t}){return this.#t("patch",`ibans/${e}`,JSON.stringify({address:r,chain:m(this.#e.name,t)}))}requestIban({address:e,chain:r,emailNotifications:t=!0}){return this.#t("post","ibans",JSON.stringify({address:e,chain:m(this.#e.name,r),emailNotifications:t}))}submitProfileDetails(e,r){return this.#t("put",`profiles/${e}/details`,JSON.stringify(r))}uploadSupportingDocument(e){let r=new FormData;return r.append("file",e),S(`${this.#e.api}/files`,"post",r,{Authorization:this.#s||""})}async#t(e,r,t,i){let s={Authorization:this.#s||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`};return S(`${this.#e.api}/${r}`,e.toUpperCase(),i?C(t):t,s)}#a=async(e,r,t,i)=>{let s=localStorage.getItem(A)||"";if(!s)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=i,localStorage.removeItem(A),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:r})=>await this.#o({client_id:e,client_secret:r});#c=async(e,r)=>await this.#o({refresh_token:r,client_id:e});subscribeOrderNotifications({filter:e,onMessage:r,onError:t}={}){if(!this.bearerProfile?.access_token)return;let{profile:i,state:s}=e||{},a=y({access_token:this.bearerProfile?.access_token,profile:i,state:s}),o,c=E({profile:i,state:s});if(this.#n?.has(c))o=this.#n.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#n?.set(c,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=d=>{let h=JSON.parse(d.data);r&&r(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(a);},o.onerror=d=>{t&&t(d),console.error("WebSocket error:",d);},o}unsubscribeOrderNotifications(e){if(e){let r=E({profile:e?.profile,state:e?.state}),t=this.#n?.get(r);t&&(t.close(),this.#n?.delete(r));}else this.#n?.forEach(r=>{r?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#s=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e;getAuthFlowURI=e=>k(this.#e,l(this.#e.name,e))};var Ne=w;
4
+ var P={environments:{production:{name:"production",api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},sandbox:{name:"sandbox",api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev",wss:"wss://api.monerium.dev"}}};var f={LINK_MESSAGE:"I hereby declare that I am the address owner.",STORAGE_CODE_VERIFIER:"monerium.sdk.code_verifier",STORAGE_ACCESS_TOKEN:"monerium.sdk.access_token",STORAGE_ACCESS_EXPIRY:"monerium.sdk.access_expiry"};var O=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(O||{}),z=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(z||{}),q=(r=>(r.corporate="corporate",r.personal="personal",r))(q||{}),j=(r=>(r.read="read",r.write="write",r))(j||{}),M=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(M||{}),F=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(F||{}),K=(t=>(t.approved="approved",t.rejected="rejected",t.unknown="unknown",t))(K||{}),L=(t=>(t.requested="requested",t.approved="approved",t.pending="pending",t))(L||{}),Q=(t=>(t.iban="iban",t.scan="scan",t.chain="chain",t))(Q||{}),V=(t=>(t.passport="passport",t.nationalIdentityCard="nationalIdentityCard",t.drivingLicense="drivingLicense",t))(V||{}),G=(r=>(r.redeem="redeem",r.issue="issue",r))(G||{}),J=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(J||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=t=>t<10?"0"+t:t,r=t=>{if(t===0)return "Z";let i=t>0?"-":"+";return t=Math.abs(t),i+e(Math.floor(t/60))+":"+e(t%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+r(n.getTimezoneOffset())},W=n=>{switch(n){case"noble":case"noble-1":case"grand":case"grand-1":return !0;default:return !1}},H=n=>{switch(n){case"ethereum":case"sepolia":case"polygon":case"amoy":case"gnosis":case"chiado":case"arbitrum":case"arbitrumsepolia":case"linea":case"lineasepolia":return !0;default:return !1}},b=n=>{if(typeof n=="number")return I(n);if(W(n))return n.split("-")[0];if(H(n))return n;try{return I(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},m=(n,e)=>b($(e,n)),X=(n,e,r,t)=>{let i=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${r} on ${b(t)} at ${x(new Date)}`:i==="EUR"?`Send ${i} ${n} to ${N(r)} at ${x(new Date)}`:`Send ${i} ${n} to ${r} at ${x(new Date)}`},C=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,r])=>r!==void 0).map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"):"",I=n=>{switch(n){case 1:return "ethereum";case 11155111:return "sepolia";case 100:return "gnosis";case 10200:return "chiado";case 137:return "polygon";case 80002:return "amoy";case 42161:return "arbitrum";case 421614:return "arbitrumsepolia";case 59144:return "linea";case 59141:return "lineasepolia";default:throw new Error(`Chain not supported: ${n}`)}},N=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var $=(n,e)=>{if(e==="sandbox")switch(n){case"ethereum":return "sepolia";case"polygon":return "amoy";case"gnosis":return "chiado";case"arbitrum":return "arbitrumsepolia";case"noble":return "grand";default:return n}return n},l=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:b($(r,n))}}return e};var ee=(n,e)=>{let{client_id:r,redirect_uri:t,scope:i,state:s,address:a,signature:o,chain:c,email:d,skip_create_account:h,skip_kyc:v}=n,U=a?{address:a,...o!==void 0?{signature:o}:{},...c!==void 0?{chain:c}:{}}:{};return C({client_id:r,redirect_uri:t,...i!==void 0?{scope:i}:{},...d!==void 0?{email:d}:{},...s!==void 0?{state:s}:{},...h!==void 0?{skip_create_account:h}:{},...v!==void 0?{skip_kyc:v}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...U})},te=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=e.length,t=0;for(;t<128;)n+=e.charAt(Math.floor(Math.random()*r)),t+=1;return n},re=n=>Z.stringify(Y(n)),k=(n,e)=>{let r=te(),t=re(r);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,r||""),`${n.api}/auth?${ee(l(n.name,e),t)}`},R=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,r]=n.split("?");r&&window.history.replaceState(null,"",e);},_=n=>n.code!=null,T=n=>n.refresh_token!=null,B=n=>n.client_secret!=null;var S=async(n,e,r,t)=>{let i=await fetch(`${n}`,{method:e,headers:t,body:r}),s,a=await i.text();try{if(s=JSON.parse(a),Object.keys(s).length===0&&s.constructor===Object)switch(i.status){case 201:case 202:return {status:i.status,statusText:i.statusText}}}catch{throw a}if(!i.ok)throw s;return s};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([r,t])=>t!==""&&t!==void 0&&t!==null).map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&");return e?"?"+e:""};var D=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var E=n=>Object.entries(n).filter(([r,t])=>t!=null).map(([r,t])=>`${r}-${t}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",w=class{#e;#s;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#r=()=>{};#i;state;constructor(e){if(!e){this.#e=P.environments.sandbox;return}if(typeof e=="string")this.#e=P.environments[e];else if(this.#r=D(e.debug??!1),this.#e=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#i={clientId:r,redirectUri:t};}else {this.#r("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:r,clientSecret:t}=e;this.#i={clientId:r,clientSecret:t};}}async authorize(e){let r=e?.clientId||this.#i?.clientId,t=e?.redirectUri||this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");let i=k(this.#e,{client_id:r,redirect_uri:t,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,email:e?.email,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#r(`Authorization URL: ${i}`),window.location.assign(i);}async getAccess(e){let r=this.#i?.clientId;if(this.#i?.clientSecret){if(u)return await this.#d(this.#i),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let i=this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||void 0,a=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),c=window.localStorage.getItem(g);if(s)return this.#r("Using auth code from auth flow to authorize"),await this.#a(r,i,s,a),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#r("Using refresh token to authorize"),await this.#c(r,e),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(o&&c){let d=new Date;if(parseInt(c)<d.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token has expired");this.#r("Access token should still be valid, checking if it is authorized...");try{return this.#s=`Bearer ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#r("Authorized"),!0}catch{throw this.#r("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let r;if(_(e))r={...e,grant_type:"authorization_code"};else if(T(e))r={...e,grant_type:"refresh_token"};else if(B(e))r={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#t("post","auth/token",r,!0).then(t=>{if(this.bearerProfile=t,this.isAuthorized=!!t,this.#s=`Bearer ${t?.access_token}`,!u){let s=new Date().getTime()+t?.expires_in*1e3;window.localStorage.setItem(p,t?.access_token||""),window.localStorage.setItem(g,s?.toString());}}).catch(t=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),R()),new Error(t?.message)}),_(e)&&R(),this.bearerProfile}getProfile(e){return this.#t("get",`profiles/${e}`)}getProfiles(e){return this.#t("get",`profiles${y(e)}`)}getAddress(e){return this.#t("get",`addresses/${e}`)}getAddresses(e){e=l(this.#e.name,e);let r=e?C(e):void 0,t=r?`addresses?${r}`:"addresses";return this.#t("get",t)}getBalances(e,r,t){let i=Array.isArray(t)?t.map(a=>`currency=${a}`).join("&"):t?`currency=${t}`:"",s=m(this.#e.name,r);return this.#t("get",`balances/${s}/${e}${i?`?${i}`:""}`)}getIban(e){return this.#t("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:r,chain:t}=e||{},i=y({profile:r,chain:t?m(this.#e.name,t):""});return this.#t("get",`ibans${i}`)}getOrders(e){return this.#t("get",`orders${y(e)}`)}getOrder(e){return this.#t("get",`orders/${e}`)}getTokens(){return this.#t("get","tokens")}linkAddress(e){return e=l(this.#e.name,e),this.#t("post","addresses",JSON.stringify(e))}placeOrder(e){let r={kind:"redeem",...l(this.#e.name,e),counterpart:{...e.counterpart,identifier:l(this.#e.name,e.counterpart.identifier)}};return this.#t("post","orders",JSON.stringify(r))}moveIban(e,{address:r,chain:t}){return this.#t("patch",`ibans/${e}`,JSON.stringify({address:r,chain:m(this.#e.name,t)}))}requestIban({address:e,chain:r,emailNotifications:t=!0}){return this.#t("post","ibans",JSON.stringify({address:e,chain:m(this.#e.name,r),emailNotifications:t}))}submitProfileDetails(e,r){return this.#t("put",`profiles/${e}/details`,JSON.stringify(r))}uploadSupportingDocument(e){let r=new FormData;return r.append("file",e),S(`${this.#e.api}/files`,"post",r,{Authorization:this.#s||""})}async#t(e,r,t,i){let s={Authorization:this.#s||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`};return S(`${this.#e.api}/${r}`,e.toUpperCase(),i?C(t):t,s)}#a=async(e,r,t,i)=>{let s=localStorage.getItem(A)||"";if(!s)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=i,localStorage.removeItem(A),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:r})=>await this.#o({client_id:e,client_secret:r});#c=async(e,r)=>await this.#o({refresh_token:r,client_id:e});subscribeOrderNotifications({filter:e,onMessage:r,onError:t}={}){if(!this.bearerProfile?.access_token)return;let{profile:i,state:s}=e||{},a=y({access_token:this.bearerProfile?.access_token,profile:i,state:s}),o,c=E({profile:i,state:s});if(this.#n?.has(c))o=this.#n.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#n?.set(c,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=d=>{let h=JSON.parse(d.data);r&&r(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(a);},o.onerror=d=>{t&&t(d),console.error("WebSocket error:",d);},o}unsubscribeOrderNotifications(e){if(e){let r=E({profile:e?.profile,state:e?.state}),t=this.#n?.get(r);t&&(t.close(),this.#n?.delete(r));}else this.#n?.forEach(r=>{r?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#s=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e;getAuthFlowURI=e=>k(this.#e,l(this.#e.name,e))};var $e=w;
5
5
 
6
- export { K as AccountState, v as Currency, Q as IdDocumentKind, F as KYCOutcome, M as KYCState, U as Method, w as MoneriumClient, V as OrderKind, G as OrderState, L as PaymentStandard, q as Permission, j as ProfileState, z as ProfileType, f as constants, Ne as default, I as getChain, b as parseChain, H as placeOrderMessage, x as rfc3339, O as shortenIban };
6
+ export { L as AccountState, O as Currency, V as IdDocumentKind, K as KYCOutcome, F as KYCState, z as Method, w as MoneriumClient, G as OrderKind, J as OrderState, Q as PaymentStandard, j as Permission, M as ProfileState, q as ProfileType, f as constants, $e as default, I as getChain, b as parseChain, X as placeOrderMessage, x as rfc3339, N as shortenIban };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monerium/sdk",
3
- "version": "3.1.0",
3
+ "version": "3.2.0",
4
4
  "description": "Essential tools to interact with the Monerium API, an electronic money issuer.",
5
5
  "repository": {
6
6
  "type": "git",