@monerium/sdk 3.5.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var G=require('crypto-js/enc-base64url.js'),Y=require('crypto-js/lib-typedarrays.js'),ee=require('crypto-js/sha256.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var G__default=/*#__PURE__*/_interopDefault(G);var Y__default=/*#__PURE__*/_interopDefault(Y);var ee__default=/*#__PURE__*/_interopDefault(ee);var g=class extends Error{code;status;errors;details;constructor(e){super(e.message),this.name="MoneriumApiError",this.code=e.code,this.status=e.status,this.errors=e.errors,this.details=e.details;}},x=class extends Error{type;cause;constructor(e,t,n){super(t),this.name="MoneriumSdkError",this.type=e,this.cause=n;}};var V=()=>{let r="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,n=0;for(;n<128;)r+=e.charAt(Math.floor(Math.random()*t)),n+=1;return r};var O=()=>{let r=window.location.href;if(!r||!r?.includes("?"))return;let[e,t]=r.split("?");t&&window.history.replaceState(null,"",e);},N=r=>r.code!=null,K=r=>r.refresh_token!=null,j=r=>r.client_secret!=null,$=()=>{let r=new Uint8Array(32);return crypto.getRandomValues(r),G__default.default.stringify(Y__default.default.create(r))},B=r=>G__default.default.stringify(ee__default.default(r));var D=async(r,e,t,n)=>{let i=await fetch(`${r}`,{method:e,headers:n,body:t}),s,o=await i.text();try{if(s=JSON.parse(o),Object.keys(s).length===0&&s.constructor===Object)switch(i.status){case 201:case 202:return {status:i.status,statusText:i.statusText}}}catch{throw o}if(!i.ok)throw s;return s};var U=[{production:{id:"ethereum",chainId:1},sandbox:{id:"sepolia",chainId:11155111}},{production:{id:"gnosis",chainId:100},sandbox:{id:"chiado",chainId:10200}},{production:{id:"polygon",chainId:137},sandbox:{id:"amoy",chainId:80002}},{production:{id:"arbitrum",chainId:42161},sandbox:{id:"arbitrumsepolia",chainId:421614}},{production:{id:"linea",chainId:59144},sandbox:{id:"lineasepolia",chainId:59141}},{production:{id:"scroll",chainId:534352},sandbox:{id:"scrollsepolia",chainId:534351}},{production:{id:"base",chainId:8453},sandbox:{id:"basesepolia",chainId:84532}},{production:{id:"camino",chainId:500},sandbox:{id:"columbus",chainId:501}}],F=new Map(U.flatMap(({production:r,sandbox:e})=>[[r.chainId,r.id],[e.chainId,e.id]])),Q=new Set(U.flatMap(({production:r,sandbox:e})=>[r.id,e.id])),L=new Map(U.map(({production:r,sandbox:e})=>[r.id,e.id]));var W=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(W||{}),re=(s=>(s.password="password",s.resource="resource",s.jwt="jwt",s.apiKey="apiKey",s.bearer="bearer",s))(re||{}),te=(t=>(t.corporate="corporate",t.personal="personal",t))(te||{}),ne=(t=>(t.read="read",t.write="write",t))(ne||{}),se=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(se||{}),ie=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(ie||{}),oe=(n=>(n.approved="approved",n.rejected="rejected",n.unknown="unknown",n))(oe||{}),ae=(s=>(s.requested="requested",s.approved="approved",s.pending="pending",s.rejected="rejected",s.closed="closed",s))(ae||{}),de=(i=>(i.iban="iban",i.scan="scan",i.chain="chain",i.account="account",i))(de||{}),ce=(n=>(n.passport="passport",n.nationalIdentityCard="nationalIdentityCard",n.drivingLicense="drivingLicense",n))(ce||{}),ue=(t=>(t.redeem="redeem",t.issue="issue",t))(ue||{}),le=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(le||{});var R=r=>{if(r.toString()==="Invalid Date")throw r;let e=n=>n<10?"0"+n:n,t=n=>{if(n===0)return "Z";let i=n>0?"-":"+";return n=Math.abs(n),i+e(Math.floor(n/60))+":"+e(n%60)};return r.getFullYear()+"-"+e(r.getMonth()+1)+"-"+e(r.getDate())+"T"+e(r.getHours())+":"+e(r.getMinutes())+":"+e(r.getSeconds())+t(r.getTimezoneOffset())},pe=r=>{switch(r){case "noble":case "noble-1":case "grand":case "grand-1":return true;default:return false}},ge=r=>Q.has(r),h=r=>{if(typeof r=="number")return z(r);if(pe(r))return r.split("-")[0];if(ge(r))return r;try{return z(parseInt(r))}catch{throw new Error(`Chain not supported: ${r}`)}},w=(r,e)=>h(J(e,r)),he=(r,e,t,n)=>{let i=`${e?.toUpperCase()||"EUR"}`;return n?`Send ${i} ${r} to ${t} on ${h(n)} at ${R(new Date)}`:i==="EUR"?`Send ${i} ${r} to ${H(t)} at ${R(new Date)}`:`Send ${i} ${r} to ${t} at ${R(new Date)}`},me=({domain:r,address:e,appName:t,redirectUri:n,chainId:i,issuedAt:s=new Date().toISOString(),expiryAt:o=new Date(Date.now()+1e3*60*5).toISOString(),privacyPolicyUrl:a,termsOfServiceUrl:d})=>`${r} wants you to sign in with your Ethereum account:
1
+ 'use strict';var S=require('crypto-js/enc-base64url.js'),B=require('crypto-js/lib-typedarrays.js'),F=require('crypto-js/sha256.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var S__default=/*#__PURE__*/_interopDefault(S);var B__default=/*#__PURE__*/_interopDefault(B);var F__default=/*#__PURE__*/_interopDefault(F);var c=class extends Error{code;status;errors;details;constructor(e){super(e.message),this.name="MoneriumApiError",this.code=e.code,this.status=e.status,this.errors=e.errors,this.details=e.details;}},u=class extends Error{type;cause;constructor(e,t,n){super(t),this.name="MoneriumSdkError",this.type=e,this.cause=n;}};var I=()=>{let r=new Uint8Array(32);return crypto.getRandomValues(r),S__default.default.stringify(B__default.default.create(r))},T=r=>S__default.default.stringify(F__default.default(r)),M=()=>{let r=I(),e=T(r);return {codeVerifier:r,codeChallenge:e}},R=r=>{if(typeof r!="string")return {};let e=r,t=e.includes("?")?e.split("?")[1]:e;if(!t)return {};let n={};for(let s of t.split("&")){let o=s.indexOf("=");if(o===-1)continue;let a=decodeURIComponent(s.slice(0,o)),p=decodeURIComponent(s.slice(o+1).replace(/\+/g," "));n[a]=p;}let i={};return n.code&&(i.code=n.code),n.state&&(i.state=n.state),n.error&&(i.error=n.error),n.error_description&&(i.errorDescription=n.error_description),i};var f=r=>{if(!r)return "";let e=Object.entries(r).filter(([,t])=>t!=null&&t!=="").flatMap(([t,n])=>Array.isArray(n)?n.map(i=>[t,String(i)]):[[t,String(n)]]);return new URLSearchParams(e).toString()},d=r=>{if(!r)return "";let e=f(r);return e?`?${e}`:""};var E={environments:{production:{name:"production",api:"https://api.monerium.app",web:"https://monerium.app"},sandbox:{name:"sandbox",api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev"}}};function N(r="sandbox"){return E.environments[r]}var k=async({method:r,url:e,headers:t,body:n,signal:i})=>{let s;try{s=await fetch(e,{method:r,headers:t,body:n,signal:i});}catch(a){throw new u("network_error","Network request failed",a)}let o=await s.text();return {status:s.status,bodyText:o}};var x=[{production:{id:"ethereum",chainId:1},sandbox:{id:"sepolia",chainId:11155111}},{production:{id:"gnosis",chainId:100},sandbox:{id:"chiado",chainId:10200}},{production:{id:"polygon",chainId:137},sandbox:{id:"amoy",chainId:80002}},{production:{id:"arbitrum",chainId:42161},sandbox:{id:"arbitrumsepolia",chainId:421614}},{production:{id:"linea",chainId:59144},sandbox:{id:"lineasepolia",chainId:59141}},{production:{id:"scroll",chainId:534352},sandbox:{id:"scrollsepolia",chainId:534351}},{production:{id:"base",chainId:8453},sandbox:{id:"basesepolia",chainId:84532}},{production:{id:"camino",chainId:500},sandbox:{id:"columbus",chainId:501}}],w=new Map(x.flatMap(({production:r,sandbox:e})=>[[r.chainId,r.id],[e.chainId,e.id]])),U=new Set(x.flatMap(({production:r,sandbox:e})=>[r.id,e.id]));new Map(x.map(({production:r,sandbox:e})=>[r.id,e.id]));var v=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(v||{}),V=(t=>(t.corporate="corporate",t.personal="personal",t))(V||{});var C=r=>{if(r.toString()==="Invalid Date")throw r;let e=n=>n<10?"0"+n:n,t=n=>{if(n===0)return "Z";let i=n>0?"-":"+";return n=Math.abs(n),i+e(Math.floor(n/60))+":"+e(n%60)};return r.getFullYear()+"-"+e(r.getMonth()+1)+"-"+e(r.getDate())+"T"+e(r.getHours())+":"+e(r.getMinutes())+":"+e(r.getSeconds())+t(r.getTimezoneOffset())},$=r=>{switch(r){case "noble":case "noble-1":case "grand":case "grand-1":return true;default:return false}},K=r=>U.has(r),l=r=>{if(typeof r=="number")return A(r);if($(r))return r.split("-")[0];if(K(r))return r;try{return A(parseInt(r))}catch{throw new Error(`Chain not supported: ${r}`)}};var L=(r,e,t,n)=>{let i=`${e?.toUpperCase()||"EUR"}`;return n?`Send ${i} ${r} to ${t} on ${l(n)} at ${C(new Date)}`:i==="EUR"?`Send ${i} ${r} to ${D(t)} at ${C(new Date)}`:`Send ${i} ${r} to ${t} at ${C(new Date)}`},q=({domain:r,address:e,appName:t,redirectUri:n,chainId:i,issuedAt:s=new Date().toISOString(),expiryAt:o=new Date(Date.now()+1e3*60*5).toISOString(),privacyPolicyUrl:a,termsOfServiceUrl:p})=>`${r} wants you to sign in with your Ethereum account:
2
2
  ${e}
3
3
 
4
4
  Allow ${t} to access my data on Monerium
@@ -6,11 +6,10 @@ Allow ${t} to access my data on Monerium
6
6
  URI: ${n}
7
7
  Version: 1
8
8
  Chain ID: ${i}
9
- Nonce: ${V().slice(0,16)}
9
+ Nonce: ${I().replace(/[^a-zA-Z0-9]/g,"").slice(0,16)}
10
10
  Issued At: ${s}
11
11
  Expiration Time: ${o}
12
12
  Resources:
13
13
  - https://monerium.com/siwe
14
14
  - ${a}
15
- - ${d}`,m=r=>r&&Object.entries(r)?.length>0?Object.entries(r).filter(([e,t])=>t!==""&&t!==void 0&&t!==null).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",z=r=>{let e=F.get(r);if(!e)throw new Error(`Chain not supported: ${r}`);return e},H=r=>{if(typeof r!="string"||!r?.length)return r;let e=r.replace(/\s/g,"");return r?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:r},fe=r=>typeof r!="string"||!r?.length?r:r?.length>11?`${r.substring(0,7)}...${r.substring(r.length-5)}`:r;var J=(r,e)=>e==="sandbox"&&typeof r=="string"?L.get(r)??r:r,A=(r,e)=>{if(e?.chain){let{chain:t,...n}=e;return {...n,chain:h(J(t,r))}}return e};var u=r=>{if(!r)return "";let e=m(r);return e?`?${e}`:""};var b={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 M=r=>Object.entries(r).filter(([t,n])=>n!=null).map(([t,n])=>`${t}-${n}`).join("-");function C(r="sandbox"){return b.environments[r]}var E=async({method:r,url:e,headers:t,body:n,signal:i})=>{let s;try{s=await fetch(e,{method:r,headers:t,body:n,signal:i});}catch(a){throw new x("network_error","Network request failed",a)}let o=await s.text();return {status:s.status,bodyText:o}};function I(r){return r?.chain!==void 0?{...r,chain:h(r.chain)}:r}function Ce(r){let e=C(r.environment),t=r.transport??E;async function n(){return "getAccessToken"in r&&r.getAccessToken?r.getAccessToken():"accessToken"in r&&r.accessToken?r.accessToken:null}async function i(o,a,d){let c=await n(),l={Accept:"application/vnd.monerium.api-v2+json"};c&&(l.Authorization=`Bearer ${c}`);let{status:p,bodyText:f}=await t({method:o.toUpperCase(),url:`${e.api}/${a}`,headers:l,body:d});if(!f)return {status:p};let P;try{P=JSON.parse(f);}catch{throw new g({code:p,status:"Parse Error",message:f})}if(p<200||p>=300)throw new g(P);return P}async function s(o,a,d){let c=await n(),l={Accept:"application/vnd.monerium.api-v2+json","Content-Type":"application/json"};if(c)l.Authorization=`Bearer ${c}`;else if(a!=="tokens")throw new x("authentication_required","No access token provided for authenticated endpoint");let{status:p,bodyText:f}=await t({method:o.toUpperCase(),url:`${e.api}/${a}`,headers:l,body:d?JSON.stringify(d):void 0});if(!f)return {status:p};let P;try{P=JSON.parse(f);}catch{throw new g({code:p,status:"Parse Error",message:f})}if(p<200||p>=300)throw new g(P);return P}return {getAuthContext:()=>s("GET","auth/context"),getProfile:o=>s("GET",`profiles/${o}`),getProfiles:o=>s("GET",`profiles${u(o)}`),submitProfileDetails:(o,a)=>s("PATCH",`profiles/${o}/details`,a),getAddress:o=>s("GET",`addresses/${o}`),getAddresses:o=>s("GET",`addresses${u(o?I(o):void 0)}`),getBalances:(o,a,d)=>{let c=h(a),l=Array.isArray(d)?d.map(p=>`currency=${p}`).join("&"):d?`currency=${d}`:"";return s("GET",`balances/${c}/${o}${l?`?${l}`:""}`)},linkAddress:o=>s("POST","addresses",I(o)),getIban:o=>s("GET",`ibans/${encodeURI(o)}`),getIbans:o=>{let a=o?I(o):void 0;return s("GET",`ibans${u(a)}`)},requestIban:({address:o,chain:a,emailNotifications:d=true})=>s("POST","ibans",{address:o,chain:h(a),emailNotifications:d}),moveIban:(o,{address:a,chain:d})=>s("PATCH",`ibans/${o}`,{address:a,chain:h(d)}),getOrder:o=>s("GET",`orders/${o}`),getOrders:o=>s("GET",`orders${u(o)}`),placeOrder:o=>{let a={kind:"redeem",...I(o),...o.counterpart&&{counterpart:{...o.counterpart,identifier:I(o.counterpart.identifier)}}};return s("POST","orders",a)},getTokens:()=>s("GET","tokens"),getSignatures:o=>{let a=o?I(o):void 0;return s("GET",`signatures${u(a)}`)},uploadSupportingDocument:(o,a)=>{let d=o instanceof Blob?o:new Blob([o]),c=new FormData;return c.append("file",d,a),i("POST","files",c)}}}var ye=r=>{let e=C(r.environment),t=u({client_id:r.clientId,redirect_uri:r.redirectUri,code_challenge:r.codeChallenge,code_challenge_method:"S256",response_type:"code",state:r.state,skip_kyc:r.skipKyc,email:r.email,address:r.address,signature:r.signature,chain:r.chain});return `${e.api}/auth${t}`},Pe=r=>{let e=C(r.environment),t=u({client_id:r.clientId,redirect_uri:r.redirectUri,message:r.message,signature:r.signature,code_challenge:r.codeChallenge,code_challenge_method:"S256",authentication_method:"siwe",state:r.state});return `${e.api}/auth${t}`};async function q(r,e,t=E){let n=m(Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))),{status:i,bodyText:s}=await t({method:"POST",url:r,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/vnd.monerium.api-v2+json"},body:n}),o;try{o=JSON.parse(s);}catch{throw new g({code:i,status:"Parse Error",message:s})}if(i<200||i>=300)throw new g(o);return o}var xe=r=>{let e=C(r.environment);return q(`${e.api}/auth/token`,{grant_type:"authorization_code",client_id:r.clientId,redirect_uri:r.redirectUri,code:r.code,code_verifier:r.codeVerifier},r.transport)},we=r=>{let e=C(r.environment);return q(`${e.api}/auth/token`,{grant_type:"refresh_token",client_id:r.clientId,refresh_token:r.refreshToken},r.transport)},Ae=r=>{let e=C(r.environment);return q(`${e.api}/auth/token`,{grant_type:"client_credentials",client_id:r.clientId,client_secret:r.clientSecret},r.transport)},be=r=>{if(typeof r!="string")return {};let e=r,t=e.includes("?")?e.split("?")[1]:e;if(!t)return {};let n={};for(let s of t.split("&")){let o=s.indexOf("=");if(o===-1)continue;let a=decodeURIComponent(s.slice(0,o)),d=decodeURIComponent(s.slice(o+1).replace(/\+/g," "));n[a]=d;}let i={};return n.code&&(i.code=n.code),n.state&&(i.state=n.state),n.error&&(i.error=n.error),n.error_description&&(i.errorDescription=n.error_description),i};var T={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 X=r=>r?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var {STORAGE_CODE_VERIFIER:_,STORAGE_ACCESS_TOKEN:k,STORAGE_ACCESS_EXPIRY:S}=T,y=typeof window>"u",v=class{#e;#i;bearerProfile;#s=new Map;isAuthorized=!!this.bearerProfile;#t=()=>{};#n;state;constructor(e){if(!e){this.#e=b.environments.sandbox;return}if(typeof e=="string")this.#e=b.environments[e];else if(this.#t=X(e.debug??false),this.#e=b.environments[e.environment||"sandbox"],!y&&!e?.clientSecret){let{clientId:t,redirectUri:n}=e;this.#n={clientId:t,redirectUri:n};}else if(y&&e?.clientSecret){this.#t("Client credentials detected");let{clientId:t,clientSecret:n}=e;this.#n={clientId:t,clientSecret:n};}}async authorize(e){let t=Z(),n=e?.address?{address:e?.address,signature:e?.signature,chain:e?.chain?w(this.#e.name,e?.chain):void 0}:{},i=m({client_id:this.#n?.clientId,redirect_uri:this.#n?.redirectUri,code_challenge:t,code_challenge_method:"S256",response_type:"code",state:e?.state,skip_kyc:e?.skipKyc,email:e?.email,...n}),s=`${this.#e.api}/auth?${i}`;this.#t(`Auth flow URL: ${s}`),window.location.assign(s);}async siwe(e){let t=Z(),n=m({client_id:this.#n?.clientId,redirect_uri:this.#n?.redirectUri,message:e.message,signature:e.signature,code_challenge:t,code_challenge_method:"S256",authentication_method:"siwe",state:e?.state}),i=`${this.#e.api}/auth?${n}`;this.#t(`Auth flow SIWE URL: ${i}`),window.location.assign(i);}async getAccess(e){let t=this.#n?.clientId;if(this.#n?.clientSecret){if(y)return await this.#d(this.#n),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let i=this.#n?.redirectUri;if(!t)throw new Error("Missing ClientId");if(y)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("error")||void 0,o=new URLSearchParams(window.location.search).get("error_description")||void 0;if(s||o)throw new Error(o);let a=new URLSearchParams(window.location.search).get("code")||void 0,d=new URLSearchParams(window.location.search).get("state")||void 0,c=window.localStorage.getItem(k),l=window.localStorage.getItem(S);if(a)return this.#t("Using auth code from auth flow to authorize"),await this.#a(t,i,a,d),this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#t("Using refresh token to authorize"),await this.#c(t,e),this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(c&&l){let p=new Date;if(parseInt(l)<p.getTime())throw window.localStorage.removeItem(k),window.localStorage.removeItem(S),this.isAuthorized=false,this.bearerProfile=void 0,new Error("Access token has expired");this.#t("Access token should still be valid, checking if it is authorized...");try{return this.#i=`Bearer ${c}`,this.isAuthorized=!0,await this.getTokens(),this.#t("Authorized"),!0}catch{throw this.#t("Access token is invalid."),window.localStorage.removeItem(k),window.localStorage.removeItem(S),this.isAuthorized=false,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let t;if(N(e))t={...e,grant_type:"authorization_code"};else if(K(e))t={...e,grant_type:"refresh_token"};else if(j(e))t={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#r("post","auth/token",t,true).then(n=>{if(this.bearerProfile=n,this.isAuthorized=!!n,this.#i=`Bearer ${n?.access_token}`,!y){let s=new Date().getTime()+n?.expires_in*1e3;window.localStorage.setItem(k,n?.access_token||""),window.localStorage.setItem(S,s?.toString());}}).catch(n=>{throw y||(localStorage.removeItem(_),localStorage.removeItem(k),localStorage.removeItem(S),O()),new Error(n?.message)}),N(e)&&O(),this.bearerProfile}getAuthContext(){return this.#r("get","auth/context")}getProfile(e){return this.#r("get",`profiles/${e}`)}getProfiles(e){return this.#r("get",`profiles${u(e)}`)}getAddress(e){return this.#r("get",`addresses/${e}`)}getAddresses(e){e=A(this.#e.name,e);let t=e?m(e):void 0,n=t?`addresses?${t}`:"addresses";return this.#r("get",n)}getBalances(e,t,n){let i=Array.isArray(n)?n.map(o=>`currency=${o}`).join("&"):n?`currency=${n}`:"",s=w(this.#e.name,t);return this.#r("get",`balances/${s}/${e}${i?`?${i}`:""}`)}getIban(e){return this.#r("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:t,chain:n}=e||{},i=u({profile:t,chain:n?w(this.#e.name,n):""});return this.#r("get",`ibans${i}`)}getOrders(e){return this.#r("get",`orders${u(e)}`)}getOrder(e){return this.#r("get",`orders/${e}`)}getTokens(){return this.#r("get","tokens")}getSignatures(e){let t=e?A(this.#e.name,e):void 0;return this.#r("get",`signatures${u(t)}`)}linkAddress(e){return e=A(this.#e.name,e),this.#r("post","addresses",JSON.stringify(e))}placeOrder(e){let t={kind:"redeem",...A(this.#e.name,e),counterpart:{...e.counterpart,identifier:A(this.#e.name,e.counterpart.identifier)}};return this.#r("post","orders",JSON.stringify(t))}moveIban(e,{address:t,chain:n}){return this.#r("patch",`ibans/${e}`,JSON.stringify({address:t,chain:w(this.#e.name,n)}))}requestIban({address:e,chain:t,emailNotifications:n=true}){return this.#r("post","ibans",JSON.stringify({address:e,chain:w(this.#e.name,t),emailNotifications:n}))}submitProfileDetails(e,t){return this.#r("put",`profiles/${e}/details`,JSON.stringify(t))}uploadSupportingDocument(e){let t=new FormData;return t.append("file",e),D(`${this.#e.api}/files`,"post",t,{Authorization:this.#i||""})}async#r(e,t,n,i){let s={Authorization:this.#i||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`};return D(`${this.#e.api}/${t}`,e.toUpperCase(),i?m(n):n,s)}#a=async(e,t,n,i)=>{let s=localStorage.getItem(_)||"";if(!s)throw new Error("Code verifier not found");return this.#t("Use code verifier to authorize"),this.state=i,localStorage.removeItem(_),await this.#o({code:n,redirect_uri:t,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:t})=>await this.#o({client_id:e,client_secret:t});#c=async(e,t)=>await this.#o({refresh_token:t,client_id:e});subscribeOrderNotifications({filter:e,onMessage:t,onError:n}={}){if(!this.bearerProfile?.access_token)return;let{profile:i,state:s}=e||{},o=u({access_token:this.bearerProfile?.access_token,profile:i,state:s}),a,d=M({profile:i,state:s});if(this.#s?.has(d))a=this.#s.get(d);else {let c=`${this.#e.wss}/orders${o}`;a=new WebSocket(c),this.#s?.set(d,a);}return a.onopen=()=>{console.log("Connected to WebSocket server");},a.onmessage=c=>{let l=JSON.parse(c.data);t&&t(l);},a.onclose=()=>{console.log("WebSocket connection closed"),this.#s?.delete(o);},a.onerror=c=>{n&&n(c),console.error("WebSocket error:",c);},a}unsubscribeOrderNotifications(e){if(e){let t=M({profile:e?.profile,state:e?.state}),n=this.#s?.get(t);n&&(n.close(),this.#s?.delete(t));}else this.#s?.forEach(t=>{t?.close();}),this.#s?.clear(),this.#s=void 0;}async disconnect(){y||localStorage.removeItem(_),this.unsubscribeOrderNotifications(),this.#i=void 0,this.bearerProfile=void 0;}async revokeAccess(){y||(localStorage.removeItem(k),localStorage.removeItem(S)),this.disconnect();}getEnvironment=()=>this.#e},Z=()=>{let r=$(),e=B(r);return localStorage.setItem(T.STORAGE_CODE_VERIFIER,r),e};var xr=v;
16
- exports.AccountState=ae;exports.Currency=W;exports.IdDocumentKind=ce;exports.KYCOutcome=oe;exports.KYCState=ie;exports.Method=re;exports.MoneriumApiError=g;exports.MoneriumClient=v;exports.MoneriumSdkError=x;exports.OrderKind=ue;exports.OrderState=le;exports.PaymentStandard=de;exports.Permission=ne;exports.ProfileState=se;exports.ProfileType=te;exports.authorizationCodeGrant=xe;exports.buildAuthorizationUrl=ye;exports.buildSiweAuthorizationUrl=Pe;exports.calculatePKCECodeChallenge=B;exports.clientCredentialsGrant=Ae;exports.constants=T;exports.createMoneriumClient=Ce;exports.default=xr;exports.getChain=z;exports.parseAuthorizationResponse=be;exports.parseChain=h;exports.placeOrderMessage=he;exports.randomPKCECodeVerifier=$;exports.refreshTokenGrant=we;exports.rfc3339=R;exports.shortenAddress=fe;exports.shortenIban=H;exports.siweMessage=me;
15
+ - ${p}`,A=r=>{let e=w.get(r);if(!e)throw new Error(`Chain not supported: ${r}`);return e},D=r=>{if(typeof r!="string"||!r?.length)return r;let e=r.replace(/\s/g,"");return r?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:r},z=r=>typeof r!="string"||!r?.length?r:r?.length>11?`${r.substring(0,7)}...${r.substring(r.length-5)}`:r;function g(r){return r?.chain!==void 0?{...r,chain:l(r.chain)}:r}var m=class{options;env;transport;constructor(e){this.options=e,this.env=N(e.environment),this.transport=e.transport??k;}async getToken(){return this.options.getAccessToken()}async request(e,t,n,i="application/json"){let s=t.startsWith("tokens")||t.startsWith("auth/token"),o=s?null:await this.getToken(),a={Accept:"application/vnd.monerium.api-v2+json","Content-Type":i};if(o)a.Authorization=`Bearer ${o}`;else if(!s)throw new u("authentication_required","No access token provided for authenticated endpoint");let{status:p,bodyText:P}=await this.transport({method:e.toUpperCase(),url:`${this.env.api}/${t}`,headers:a,body:n?i==="application/json"?JSON.stringify(n):n:void 0});if(!P)return {status:p};let b;try{b=JSON.parse(P);}catch{throw new c({code:p,status:"Parse Error",message:P})}if(p<200||p>=300)throw new c(b);return b}async requestFormData(e,t,n){let i=await this.getToken(),s={Accept:"application/vnd.monerium.api-v2+json"};i&&(s.Authorization=`Bearer ${i}`);let{status:o,bodyText:a}=await this.transport({method:e.toUpperCase(),url:`${this.env.api}/${t}`,headers:s,body:n});if(!a)return {status:o};let p;try{p=JSON.parse(a);}catch{throw new c({code:o,status:"Parse Error",message:a})}if(o<200||o>=300)throw new c(p);return p}async getAuthContext(){return this.request("GET","auth/context")}async getProfile(e){return this.request("GET",`profiles/${e}`)}async getProfiles(e){return this.request("GET",`profiles${d(e)}`)}async getAddress(e){return this.request("GET",`addresses/${e}`)}async getAddresses(e){let t=e?g(e):void 0;return this.request("GET",`addresses${d(t)}`)}async linkAddress(e){return this.request("POST","addresses",g(e))}async getBalances(e){let{address:t,chain:n,currencies:i}=e,s=l(n);return this.request("GET",`balances/${s}/${t}${d({currency:i})}`)}async getIban(e){return this.request("GET",`ibans/${encodeURIComponent(e)}`)}async getIbans(e){let t=e?g(e):void 0;return this.request("GET",`ibans${d(t)}`)}async requestIban(e){return this.request("POST","ibans",{address:e.address,chain:l(e.chain),emailNotifications:e.emailNotifications??true})}async moveIban(e){return this.request("PATCH",`ibans/${e.iban}`,{address:e.address,chain:l(e.chain)})}async getOrder(e){return this.request("GET",`orders/${e}`)}async getOrders(e){return this.request("GET",`orders${d(e)}`)}async placeOrder(e){let t={kind:"redeem",...g(e),...e.counterpart&&{counterpart:{...e.counterpart,identifier:g(e.counterpart.identifier)}}};return this.request("POST","orders",t)}async getTokens(){return this.request("GET","tokens")}async getSignatures(e){let t=e?g(e):void 0;return this.request("GET",`signatures${d(t)}`)}async uploadSupportingDocument(e,t){let n=e instanceof Blob?e:new Blob([e]),i=new FormData;return i.append("file",n,t??("name"in e?String(e.name):"document")),this.requestFormData("POST","files",i)}},h=class extends m{async clientCredentialsGrant(e,t){let n=f({grant_type:"client_credentials",client_id:e,client_secret:t});return this.request("POST","auth/token",n,"application/x-www-form-urlencoded")}async getSubscriptions(){return this.request("GET","webhooks")}async createSubscription(e){return this.request("POST","webhooks",e)}async updateSubscription(e){let{subscription:t,...n}=e;return this.request("PATCH",`webhooks/${t}`,n)}},y=class extends h{},O=class extends m{buildAuthorizationUrl(e){let t=d({client_id:e.clientId,redirect_uri:e.redirectUri,code_challenge:e.codeChallenge,code_challenge_method:"S256",response_type:"code",state:e.state,skip_kyc:e.skipKyc,email:e.email,auth_mode:e.authMode});return `${this.env.api}/auth${t}`}buildSiweAuthorizationUrl(e){let t=d({client_id:e.clientId,redirect_uri:e.redirectUri,message:e.message,signature:e.signature,code_challenge:e.codeChallenge,code_challenge_method:"S256",authentication_method:"siwe",state:e.state});return `${this.env.api}/auth${t}`}async authorizationCodeGrant(e){let t=f({grant_type:"authorization_code",client_id:e.clientId,redirect_uri:e.redirectUri,code:e.code,code_verifier:e.codeVerifier});return this.request("POST","auth/token",t,"application/x-www-form-urlencoded")}async refreshTokenGrant(e){let t=f({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken});return this.request("POST","auth/token",t,"application/x-www-form-urlencoded")}parseAuthorizationResponse(e){return R(e)}},_=class extends h{async createProfile(e){return this.request("POST","profiles",e)}async shareProfileKYC(e){let{profile:t,...n}=e;return this.request("POST",`profiles/${t}/share`,n)}async updateProfileDetails(e){let{profile:t,...n}=e;return this.request("PATCH",`profiles/${t}/details`,n)}async updateProfileForm(e){let{profile:t,...n}=e;return this.request("PATCH",`profiles/${t}/form`,n)}async updateProfileVerifications(e){let{profile:t,...n}=e;return this.request("PATCH",`profiles/${t}/verifications`,n)}};var W={LINK_MESSAGE:"I hereby declare that I am the address owner."};exports.Currency=v;exports.MoneriumApiError=c;exports.MoneriumBaseClient=m;exports.MoneriumOAuthClient=O;exports.MoneriumPrivateClient=y;exports.MoneriumSdkError=u;exports.MoneriumServerClient=h;exports.MoneriumWhitelabelClient=_;exports.ProfileType=V;exports.calculatePKCECodeChallenge=T;exports.constants=W;exports.generatePKCE=M;exports.getChain=A;exports.parseAuthorizationResponse=R;exports.parseChain=l;exports.placeOrderMessage=L;exports.randomPKCECodeVerifier=I;exports.rfc3339=C;exports.shortenAddress=z;exports.shortenIban=D;exports.siweMessage=q;
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import G from'crypto-js/enc-base64url.js';import Y from'crypto-js/lib-typedarrays.js';import ee from'crypto-js/sha256.js';var g=class extends Error{code;status;errors;details;constructor(e){super(e.message),this.name="MoneriumApiError",this.code=e.code,this.status=e.status,this.errors=e.errors,this.details=e.details;}},x=class extends Error{type;cause;constructor(e,t,n){super(t),this.name="MoneriumSdkError",this.type=e,this.cause=n;}};var V=()=>{let r="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,n=0;for(;n<128;)r+=e.charAt(Math.floor(Math.random()*t)),n+=1;return r};var O=()=>{let r=window.location.href;if(!r||!r?.includes("?"))return;let[e,t]=r.split("?");t&&window.history.replaceState(null,"",e);},N=r=>r.code!=null,K=r=>r.refresh_token!=null,j=r=>r.client_secret!=null,$=()=>{let r=new Uint8Array(32);return crypto.getRandomValues(r),G.stringify(Y.create(r))},B=r=>G.stringify(ee(r));var D=async(r,e,t,n)=>{let i=await fetch(`${r}`,{method:e,headers:n,body:t}),s,o=await i.text();try{if(s=JSON.parse(o),Object.keys(s).length===0&&s.constructor===Object)switch(i.status){case 201:case 202:return {status:i.status,statusText:i.statusText}}}catch{throw o}if(!i.ok)throw s;return s};var U=[{production:{id:"ethereum",chainId:1},sandbox:{id:"sepolia",chainId:11155111}},{production:{id:"gnosis",chainId:100},sandbox:{id:"chiado",chainId:10200}},{production:{id:"polygon",chainId:137},sandbox:{id:"amoy",chainId:80002}},{production:{id:"arbitrum",chainId:42161},sandbox:{id:"arbitrumsepolia",chainId:421614}},{production:{id:"linea",chainId:59144},sandbox:{id:"lineasepolia",chainId:59141}},{production:{id:"scroll",chainId:534352},sandbox:{id:"scrollsepolia",chainId:534351}},{production:{id:"base",chainId:8453},sandbox:{id:"basesepolia",chainId:84532}},{production:{id:"camino",chainId:500},sandbox:{id:"columbus",chainId:501}}],F=new Map(U.flatMap(({production:r,sandbox:e})=>[[r.chainId,r.id],[e.chainId,e.id]])),Q=new Set(U.flatMap(({production:r,sandbox:e})=>[r.id,e.id])),L=new Map(U.map(({production:r,sandbox:e})=>[r.id,e.id]));var W=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(W||{}),re=(s=>(s.password="password",s.resource="resource",s.jwt="jwt",s.apiKey="apiKey",s.bearer="bearer",s))(re||{}),te=(t=>(t.corporate="corporate",t.personal="personal",t))(te||{}),ne=(t=>(t.read="read",t.write="write",t))(ne||{}),se=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(se||{}),ie=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(ie||{}),oe=(n=>(n.approved="approved",n.rejected="rejected",n.unknown="unknown",n))(oe||{}),ae=(s=>(s.requested="requested",s.approved="approved",s.pending="pending",s.rejected="rejected",s.closed="closed",s))(ae||{}),de=(i=>(i.iban="iban",i.scan="scan",i.chain="chain",i.account="account",i))(de||{}),ce=(n=>(n.passport="passport",n.nationalIdentityCard="nationalIdentityCard",n.drivingLicense="drivingLicense",n))(ce||{}),ue=(t=>(t.redeem="redeem",t.issue="issue",t))(ue||{}),le=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(le||{});var R=r=>{if(r.toString()==="Invalid Date")throw r;let e=n=>n<10?"0"+n:n,t=n=>{if(n===0)return "Z";let i=n>0?"-":"+";return n=Math.abs(n),i+e(Math.floor(n/60))+":"+e(n%60)};return r.getFullYear()+"-"+e(r.getMonth()+1)+"-"+e(r.getDate())+"T"+e(r.getHours())+":"+e(r.getMinutes())+":"+e(r.getSeconds())+t(r.getTimezoneOffset())},pe=r=>{switch(r){case "noble":case "noble-1":case "grand":case "grand-1":return true;default:return false}},ge=r=>Q.has(r),h=r=>{if(typeof r=="number")return z(r);if(pe(r))return r.split("-")[0];if(ge(r))return r;try{return z(parseInt(r))}catch{throw new Error(`Chain not supported: ${r}`)}},w=(r,e)=>h(J(e,r)),he=(r,e,t,n)=>{let i=`${e?.toUpperCase()||"EUR"}`;return n?`Send ${i} ${r} to ${t} on ${h(n)} at ${R(new Date)}`:i==="EUR"?`Send ${i} ${r} to ${H(t)} at ${R(new Date)}`:`Send ${i} ${r} to ${t} at ${R(new Date)}`},me=({domain:r,address:e,appName:t,redirectUri:n,chainId:i,issuedAt:s=new Date().toISOString(),expiryAt:o=new Date(Date.now()+1e3*60*5).toISOString(),privacyPolicyUrl:a,termsOfServiceUrl:d})=>`${r} wants you to sign in with your Ethereum account:
1
+ import S from'crypto-js/enc-base64url.js';import B from'crypto-js/lib-typedarrays.js';import F from'crypto-js/sha256.js';var c=class extends Error{code;status;errors;details;constructor(e){super(e.message),this.name="MoneriumApiError",this.code=e.code,this.status=e.status,this.errors=e.errors,this.details=e.details;}},u=class extends Error{type;cause;constructor(e,t,n){super(t),this.name="MoneriumSdkError",this.type=e,this.cause=n;}};var I=()=>{let r=new Uint8Array(32);return crypto.getRandomValues(r),S.stringify(B.create(r))},T=r=>S.stringify(F(r)),M=()=>{let r=I(),e=T(r);return {codeVerifier:r,codeChallenge:e}},R=r=>{if(typeof r!="string")return {};let e=r,t=e.includes("?")?e.split("?")[1]:e;if(!t)return {};let n={};for(let s of t.split("&")){let o=s.indexOf("=");if(o===-1)continue;let a=decodeURIComponent(s.slice(0,o)),p=decodeURIComponent(s.slice(o+1).replace(/\+/g," "));n[a]=p;}let i={};return n.code&&(i.code=n.code),n.state&&(i.state=n.state),n.error&&(i.error=n.error),n.error_description&&(i.errorDescription=n.error_description),i};var f=r=>{if(!r)return "";let e=Object.entries(r).filter(([,t])=>t!=null&&t!=="").flatMap(([t,n])=>Array.isArray(n)?n.map(i=>[t,String(i)]):[[t,String(n)]]);return new URLSearchParams(e).toString()},d=r=>{if(!r)return "";let e=f(r);return e?`?${e}`:""};var E={environments:{production:{name:"production",api:"https://api.monerium.app",web:"https://monerium.app"},sandbox:{name:"sandbox",api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev"}}};function N(r="sandbox"){return E.environments[r]}var k=async({method:r,url:e,headers:t,body:n,signal:i})=>{let s;try{s=await fetch(e,{method:r,headers:t,body:n,signal:i});}catch(a){throw new u("network_error","Network request failed",a)}let o=await s.text();return {status:s.status,bodyText:o}};var x=[{production:{id:"ethereum",chainId:1},sandbox:{id:"sepolia",chainId:11155111}},{production:{id:"gnosis",chainId:100},sandbox:{id:"chiado",chainId:10200}},{production:{id:"polygon",chainId:137},sandbox:{id:"amoy",chainId:80002}},{production:{id:"arbitrum",chainId:42161},sandbox:{id:"arbitrumsepolia",chainId:421614}},{production:{id:"linea",chainId:59144},sandbox:{id:"lineasepolia",chainId:59141}},{production:{id:"scroll",chainId:534352},sandbox:{id:"scrollsepolia",chainId:534351}},{production:{id:"base",chainId:8453},sandbox:{id:"basesepolia",chainId:84532}},{production:{id:"camino",chainId:500},sandbox:{id:"columbus",chainId:501}}],w=new Map(x.flatMap(({production:r,sandbox:e})=>[[r.chainId,r.id],[e.chainId,e.id]])),U=new Set(x.flatMap(({production:r,sandbox:e})=>[r.id,e.id]));new Map(x.map(({production:r,sandbox:e})=>[r.id,e.id]));var v=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(v||{}),V=(t=>(t.corporate="corporate",t.personal="personal",t))(V||{});var C=r=>{if(r.toString()==="Invalid Date")throw r;let e=n=>n<10?"0"+n:n,t=n=>{if(n===0)return "Z";let i=n>0?"-":"+";return n=Math.abs(n),i+e(Math.floor(n/60))+":"+e(n%60)};return r.getFullYear()+"-"+e(r.getMonth()+1)+"-"+e(r.getDate())+"T"+e(r.getHours())+":"+e(r.getMinutes())+":"+e(r.getSeconds())+t(r.getTimezoneOffset())},$=r=>{switch(r){case "noble":case "noble-1":case "grand":case "grand-1":return true;default:return false}},K=r=>U.has(r),l=r=>{if(typeof r=="number")return A(r);if($(r))return r.split("-")[0];if(K(r))return r;try{return A(parseInt(r))}catch{throw new Error(`Chain not supported: ${r}`)}};var L=(r,e,t,n)=>{let i=`${e?.toUpperCase()||"EUR"}`;return n?`Send ${i} ${r} to ${t} on ${l(n)} at ${C(new Date)}`:i==="EUR"?`Send ${i} ${r} to ${D(t)} at ${C(new Date)}`:`Send ${i} ${r} to ${t} at ${C(new Date)}`},q=({domain:r,address:e,appName:t,redirectUri:n,chainId:i,issuedAt:s=new Date().toISOString(),expiryAt:o=new Date(Date.now()+1e3*60*5).toISOString(),privacyPolicyUrl:a,termsOfServiceUrl:p})=>`${r} wants you to sign in with your Ethereum account:
2
2
  ${e}
3
3
 
4
4
  Allow ${t} to access my data on Monerium
@@ -6,11 +6,10 @@ Allow ${t} to access my data on Monerium
6
6
  URI: ${n}
7
7
  Version: 1
8
8
  Chain ID: ${i}
9
- Nonce: ${V().slice(0,16)}
9
+ Nonce: ${I().replace(/[^a-zA-Z0-9]/g,"").slice(0,16)}
10
10
  Issued At: ${s}
11
11
  Expiration Time: ${o}
12
12
  Resources:
13
13
  - https://monerium.com/siwe
14
14
  - ${a}
15
- - ${d}`,m=r=>r&&Object.entries(r)?.length>0?Object.entries(r).filter(([e,t])=>t!==""&&t!==void 0&&t!==null).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",z=r=>{let e=F.get(r);if(!e)throw new Error(`Chain not supported: ${r}`);return e},H=r=>{if(typeof r!="string"||!r?.length)return r;let e=r.replace(/\s/g,"");return r?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:r},fe=r=>typeof r!="string"||!r?.length?r:r?.length>11?`${r.substring(0,7)}...${r.substring(r.length-5)}`:r;var J=(r,e)=>e==="sandbox"&&typeof r=="string"?L.get(r)??r:r,A=(r,e)=>{if(e?.chain){let{chain:t,...n}=e;return {...n,chain:h(J(t,r))}}return e};var u=r=>{if(!r)return "";let e=m(r);return e?`?${e}`:""};var b={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 M=r=>Object.entries(r).filter(([t,n])=>n!=null).map(([t,n])=>`${t}-${n}`).join("-");function C(r="sandbox"){return b.environments[r]}var E=async({method:r,url:e,headers:t,body:n,signal:i})=>{let s;try{s=await fetch(e,{method:r,headers:t,body:n,signal:i});}catch(a){throw new x("network_error","Network request failed",a)}let o=await s.text();return {status:s.status,bodyText:o}};function I(r){return r?.chain!==void 0?{...r,chain:h(r.chain)}:r}function Ce(r){let e=C(r.environment),t=r.transport??E;async function n(){return "getAccessToken"in r&&r.getAccessToken?r.getAccessToken():"accessToken"in r&&r.accessToken?r.accessToken:null}async function i(o,a,d){let c=await n(),l={Accept:"application/vnd.monerium.api-v2+json"};c&&(l.Authorization=`Bearer ${c}`);let{status:p,bodyText:f}=await t({method:o.toUpperCase(),url:`${e.api}/${a}`,headers:l,body:d});if(!f)return {status:p};let P;try{P=JSON.parse(f);}catch{throw new g({code:p,status:"Parse Error",message:f})}if(p<200||p>=300)throw new g(P);return P}async function s(o,a,d){let c=await n(),l={Accept:"application/vnd.monerium.api-v2+json","Content-Type":"application/json"};if(c)l.Authorization=`Bearer ${c}`;else if(a!=="tokens")throw new x("authentication_required","No access token provided for authenticated endpoint");let{status:p,bodyText:f}=await t({method:o.toUpperCase(),url:`${e.api}/${a}`,headers:l,body:d?JSON.stringify(d):void 0});if(!f)return {status:p};let P;try{P=JSON.parse(f);}catch{throw new g({code:p,status:"Parse Error",message:f})}if(p<200||p>=300)throw new g(P);return P}return {getAuthContext:()=>s("GET","auth/context"),getProfile:o=>s("GET",`profiles/${o}`),getProfiles:o=>s("GET",`profiles${u(o)}`),submitProfileDetails:(o,a)=>s("PATCH",`profiles/${o}/details`,a),getAddress:o=>s("GET",`addresses/${o}`),getAddresses:o=>s("GET",`addresses${u(o?I(o):void 0)}`),getBalances:(o,a,d)=>{let c=h(a),l=Array.isArray(d)?d.map(p=>`currency=${p}`).join("&"):d?`currency=${d}`:"";return s("GET",`balances/${c}/${o}${l?`?${l}`:""}`)},linkAddress:o=>s("POST","addresses",I(o)),getIban:o=>s("GET",`ibans/${encodeURI(o)}`),getIbans:o=>{let a=o?I(o):void 0;return s("GET",`ibans${u(a)}`)},requestIban:({address:o,chain:a,emailNotifications:d=true})=>s("POST","ibans",{address:o,chain:h(a),emailNotifications:d}),moveIban:(o,{address:a,chain:d})=>s("PATCH",`ibans/${o}`,{address:a,chain:h(d)}),getOrder:o=>s("GET",`orders/${o}`),getOrders:o=>s("GET",`orders${u(o)}`),placeOrder:o=>{let a={kind:"redeem",...I(o),...o.counterpart&&{counterpart:{...o.counterpart,identifier:I(o.counterpart.identifier)}}};return s("POST","orders",a)},getTokens:()=>s("GET","tokens"),getSignatures:o=>{let a=o?I(o):void 0;return s("GET",`signatures${u(a)}`)},uploadSupportingDocument:(o,a)=>{let d=o instanceof Blob?o:new Blob([o]),c=new FormData;return c.append("file",d,a),i("POST","files",c)}}}var ye=r=>{let e=C(r.environment),t=u({client_id:r.clientId,redirect_uri:r.redirectUri,code_challenge:r.codeChallenge,code_challenge_method:"S256",response_type:"code",state:r.state,skip_kyc:r.skipKyc,email:r.email,address:r.address,signature:r.signature,chain:r.chain});return `${e.api}/auth${t}`},Pe=r=>{let e=C(r.environment),t=u({client_id:r.clientId,redirect_uri:r.redirectUri,message:r.message,signature:r.signature,code_challenge:r.codeChallenge,code_challenge_method:"S256",authentication_method:"siwe",state:r.state});return `${e.api}/auth${t}`};async function q(r,e,t=E){let n=m(Object.fromEntries(Object.entries(e).filter(([,a])=>a!==void 0))),{status:i,bodyText:s}=await t({method:"POST",url:r,headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/vnd.monerium.api-v2+json"},body:n}),o;try{o=JSON.parse(s);}catch{throw new g({code:i,status:"Parse Error",message:s})}if(i<200||i>=300)throw new g(o);return o}var xe=r=>{let e=C(r.environment);return q(`${e.api}/auth/token`,{grant_type:"authorization_code",client_id:r.clientId,redirect_uri:r.redirectUri,code:r.code,code_verifier:r.codeVerifier},r.transport)},we=r=>{let e=C(r.environment);return q(`${e.api}/auth/token`,{grant_type:"refresh_token",client_id:r.clientId,refresh_token:r.refreshToken},r.transport)},Ae=r=>{let e=C(r.environment);return q(`${e.api}/auth/token`,{grant_type:"client_credentials",client_id:r.clientId,client_secret:r.clientSecret},r.transport)},be=r=>{if(typeof r!="string")return {};let e=r,t=e.includes("?")?e.split("?")[1]:e;if(!t)return {};let n={};for(let s of t.split("&")){let o=s.indexOf("=");if(o===-1)continue;let a=decodeURIComponent(s.slice(0,o)),d=decodeURIComponent(s.slice(o+1).replace(/\+/g," "));n[a]=d;}let i={};return n.code&&(i.code=n.code),n.state&&(i.state=n.state),n.error&&(i.error=n.error),n.error_description&&(i.errorDescription=n.error_description),i};var T={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 X=r=>r?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var {STORAGE_CODE_VERIFIER:_,STORAGE_ACCESS_TOKEN:k,STORAGE_ACCESS_EXPIRY:S}=T,y=typeof window>"u",v=class{#e;#i;bearerProfile;#s=new Map;isAuthorized=!!this.bearerProfile;#t=()=>{};#n;state;constructor(e){if(!e){this.#e=b.environments.sandbox;return}if(typeof e=="string")this.#e=b.environments[e];else if(this.#t=X(e.debug??false),this.#e=b.environments[e.environment||"sandbox"],!y&&!e?.clientSecret){let{clientId:t,redirectUri:n}=e;this.#n={clientId:t,redirectUri:n};}else if(y&&e?.clientSecret){this.#t("Client credentials detected");let{clientId:t,clientSecret:n}=e;this.#n={clientId:t,clientSecret:n};}}async authorize(e){let t=Z(),n=e?.address?{address:e?.address,signature:e?.signature,chain:e?.chain?w(this.#e.name,e?.chain):void 0}:{},i=m({client_id:this.#n?.clientId,redirect_uri:this.#n?.redirectUri,code_challenge:t,code_challenge_method:"S256",response_type:"code",state:e?.state,skip_kyc:e?.skipKyc,email:e?.email,...n}),s=`${this.#e.api}/auth?${i}`;this.#t(`Auth flow URL: ${s}`),window.location.assign(s);}async siwe(e){let t=Z(),n=m({client_id:this.#n?.clientId,redirect_uri:this.#n?.redirectUri,message:e.message,signature:e.signature,code_challenge:t,code_challenge_method:"S256",authentication_method:"siwe",state:e?.state}),i=`${this.#e.api}/auth?${n}`;this.#t(`Auth flow SIWE URL: ${i}`),window.location.assign(i);}async getAccess(e){let t=this.#n?.clientId;if(this.#n?.clientSecret){if(y)return await this.#d(this.#n),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let i=this.#n?.redirectUri;if(!t)throw new Error("Missing ClientId");if(y)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("error")||void 0,o=new URLSearchParams(window.location.search).get("error_description")||void 0;if(s||o)throw new Error(o);let a=new URLSearchParams(window.location.search).get("code")||void 0,d=new URLSearchParams(window.location.search).get("state")||void 0,c=window.localStorage.getItem(k),l=window.localStorage.getItem(S);if(a)return this.#t("Using auth code from auth flow to authorize"),await this.#a(t,i,a,d),this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#t("Using refresh token to authorize"),await this.#c(t,e),this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(c&&l){let p=new Date;if(parseInt(l)<p.getTime())throw window.localStorage.removeItem(k),window.localStorage.removeItem(S),this.isAuthorized=false,this.bearerProfile=void 0,new Error("Access token has expired");this.#t("Access token should still be valid, checking if it is authorized...");try{return this.#i=`Bearer ${c}`,this.isAuthorized=!0,await this.getTokens(),this.#t("Authorized"),!0}catch{throw this.#t("Access token is invalid."),window.localStorage.removeItem(k),window.localStorage.removeItem(S),this.isAuthorized=false,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let t;if(N(e))t={...e,grant_type:"authorization_code"};else if(K(e))t={...e,grant_type:"refresh_token"};else if(j(e))t={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#r("post","auth/token",t,true).then(n=>{if(this.bearerProfile=n,this.isAuthorized=!!n,this.#i=`Bearer ${n?.access_token}`,!y){let s=new Date().getTime()+n?.expires_in*1e3;window.localStorage.setItem(k,n?.access_token||""),window.localStorage.setItem(S,s?.toString());}}).catch(n=>{throw y||(localStorage.removeItem(_),localStorage.removeItem(k),localStorage.removeItem(S),O()),new Error(n?.message)}),N(e)&&O(),this.bearerProfile}getAuthContext(){return this.#r("get","auth/context")}getProfile(e){return this.#r("get",`profiles/${e}`)}getProfiles(e){return this.#r("get",`profiles${u(e)}`)}getAddress(e){return this.#r("get",`addresses/${e}`)}getAddresses(e){e=A(this.#e.name,e);let t=e?m(e):void 0,n=t?`addresses?${t}`:"addresses";return this.#r("get",n)}getBalances(e,t,n){let i=Array.isArray(n)?n.map(o=>`currency=${o}`).join("&"):n?`currency=${n}`:"",s=w(this.#e.name,t);return this.#r("get",`balances/${s}/${e}${i?`?${i}`:""}`)}getIban(e){return this.#r("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:t,chain:n}=e||{},i=u({profile:t,chain:n?w(this.#e.name,n):""});return this.#r("get",`ibans${i}`)}getOrders(e){return this.#r("get",`orders${u(e)}`)}getOrder(e){return this.#r("get",`orders/${e}`)}getTokens(){return this.#r("get","tokens")}getSignatures(e){let t=e?A(this.#e.name,e):void 0;return this.#r("get",`signatures${u(t)}`)}linkAddress(e){return e=A(this.#e.name,e),this.#r("post","addresses",JSON.stringify(e))}placeOrder(e){let t={kind:"redeem",...A(this.#e.name,e),counterpart:{...e.counterpart,identifier:A(this.#e.name,e.counterpart.identifier)}};return this.#r("post","orders",JSON.stringify(t))}moveIban(e,{address:t,chain:n}){return this.#r("patch",`ibans/${e}`,JSON.stringify({address:t,chain:w(this.#e.name,n)}))}requestIban({address:e,chain:t,emailNotifications:n=true}){return this.#r("post","ibans",JSON.stringify({address:e,chain:w(this.#e.name,t),emailNotifications:n}))}submitProfileDetails(e,t){return this.#r("put",`profiles/${e}/details`,JSON.stringify(t))}uploadSupportingDocument(e){let t=new FormData;return t.append("file",e),D(`${this.#e.api}/files`,"post",t,{Authorization:this.#i||""})}async#r(e,t,n,i){let s={Authorization:this.#i||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`};return D(`${this.#e.api}/${t}`,e.toUpperCase(),i?m(n):n,s)}#a=async(e,t,n,i)=>{let s=localStorage.getItem(_)||"";if(!s)throw new Error("Code verifier not found");return this.#t("Use code verifier to authorize"),this.state=i,localStorage.removeItem(_),await this.#o({code:n,redirect_uri:t,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:t})=>await this.#o({client_id:e,client_secret:t});#c=async(e,t)=>await this.#o({refresh_token:t,client_id:e});subscribeOrderNotifications({filter:e,onMessage:t,onError:n}={}){if(!this.bearerProfile?.access_token)return;let{profile:i,state:s}=e||{},o=u({access_token:this.bearerProfile?.access_token,profile:i,state:s}),a,d=M({profile:i,state:s});if(this.#s?.has(d))a=this.#s.get(d);else {let c=`${this.#e.wss}/orders${o}`;a=new WebSocket(c),this.#s?.set(d,a);}return a.onopen=()=>{console.log("Connected to WebSocket server");},a.onmessage=c=>{let l=JSON.parse(c.data);t&&t(l);},a.onclose=()=>{console.log("WebSocket connection closed"),this.#s?.delete(o);},a.onerror=c=>{n&&n(c),console.error("WebSocket error:",c);},a}unsubscribeOrderNotifications(e){if(e){let t=M({profile:e?.profile,state:e?.state}),n=this.#s?.get(t);n&&(n.close(),this.#s?.delete(t));}else this.#s?.forEach(t=>{t?.close();}),this.#s?.clear(),this.#s=void 0;}async disconnect(){y||localStorage.removeItem(_),this.unsubscribeOrderNotifications(),this.#i=void 0,this.bearerProfile=void 0;}async revokeAccess(){y||(localStorage.removeItem(k),localStorage.removeItem(S)),this.disconnect();}getEnvironment=()=>this.#e},Z=()=>{let r=$(),e=B(r);return localStorage.setItem(T.STORAGE_CODE_VERIFIER,r),e};var xr=v;
16
- export{ae as AccountState,W as Currency,ce as IdDocumentKind,oe as KYCOutcome,ie as KYCState,re as Method,g as MoneriumApiError,v as MoneriumClient,x as MoneriumSdkError,ue as OrderKind,le as OrderState,de as PaymentStandard,ne as Permission,se as ProfileState,te as ProfileType,xe as authorizationCodeGrant,ye as buildAuthorizationUrl,Pe as buildSiweAuthorizationUrl,B as calculatePKCECodeChallenge,Ae as clientCredentialsGrant,T as constants,Ce as createMoneriumClient,xr as default,z as getChain,be as parseAuthorizationResponse,h as parseChain,he as placeOrderMessage,$ as randomPKCECodeVerifier,we as refreshTokenGrant,R as rfc3339,fe as shortenAddress,H as shortenIban,me as siweMessage};
15
+ - ${p}`,A=r=>{let e=w.get(r);if(!e)throw new Error(`Chain not supported: ${r}`);return e},D=r=>{if(typeof r!="string"||!r?.length)return r;let e=r.replace(/\s/g,"");return r?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:r},z=r=>typeof r!="string"||!r?.length?r:r?.length>11?`${r.substring(0,7)}...${r.substring(r.length-5)}`:r;function g(r){return r?.chain!==void 0?{...r,chain:l(r.chain)}:r}var m=class{options;env;transport;constructor(e){this.options=e,this.env=N(e.environment),this.transport=e.transport??k;}async getToken(){return this.options.getAccessToken()}async request(e,t,n,i="application/json"){let s=t.startsWith("tokens")||t.startsWith("auth/token"),o=s?null:await this.getToken(),a={Accept:"application/vnd.monerium.api-v2+json","Content-Type":i};if(o)a.Authorization=`Bearer ${o}`;else if(!s)throw new u("authentication_required","No access token provided for authenticated endpoint");let{status:p,bodyText:P}=await this.transport({method:e.toUpperCase(),url:`${this.env.api}/${t}`,headers:a,body:n?i==="application/json"?JSON.stringify(n):n:void 0});if(!P)return {status:p};let b;try{b=JSON.parse(P);}catch{throw new c({code:p,status:"Parse Error",message:P})}if(p<200||p>=300)throw new c(b);return b}async requestFormData(e,t,n){let i=await this.getToken(),s={Accept:"application/vnd.monerium.api-v2+json"};i&&(s.Authorization=`Bearer ${i}`);let{status:o,bodyText:a}=await this.transport({method:e.toUpperCase(),url:`${this.env.api}/${t}`,headers:s,body:n});if(!a)return {status:o};let p;try{p=JSON.parse(a);}catch{throw new c({code:o,status:"Parse Error",message:a})}if(o<200||o>=300)throw new c(p);return p}async getAuthContext(){return this.request("GET","auth/context")}async getProfile(e){return this.request("GET",`profiles/${e}`)}async getProfiles(e){return this.request("GET",`profiles${d(e)}`)}async getAddress(e){return this.request("GET",`addresses/${e}`)}async getAddresses(e){let t=e?g(e):void 0;return this.request("GET",`addresses${d(t)}`)}async linkAddress(e){return this.request("POST","addresses",g(e))}async getBalances(e){let{address:t,chain:n,currencies:i}=e,s=l(n);return this.request("GET",`balances/${s}/${t}${d({currency:i})}`)}async getIban(e){return this.request("GET",`ibans/${encodeURIComponent(e)}`)}async getIbans(e){let t=e?g(e):void 0;return this.request("GET",`ibans${d(t)}`)}async requestIban(e){return this.request("POST","ibans",{address:e.address,chain:l(e.chain),emailNotifications:e.emailNotifications??true})}async moveIban(e){return this.request("PATCH",`ibans/${e.iban}`,{address:e.address,chain:l(e.chain)})}async getOrder(e){return this.request("GET",`orders/${e}`)}async getOrders(e){return this.request("GET",`orders${d(e)}`)}async placeOrder(e){let t={kind:"redeem",...g(e),...e.counterpart&&{counterpart:{...e.counterpart,identifier:g(e.counterpart.identifier)}}};return this.request("POST","orders",t)}async getTokens(){return this.request("GET","tokens")}async getSignatures(e){let t=e?g(e):void 0;return this.request("GET",`signatures${d(t)}`)}async uploadSupportingDocument(e,t){let n=e instanceof Blob?e:new Blob([e]),i=new FormData;return i.append("file",n,t??("name"in e?String(e.name):"document")),this.requestFormData("POST","files",i)}},h=class extends m{async clientCredentialsGrant(e,t){let n=f({grant_type:"client_credentials",client_id:e,client_secret:t});return this.request("POST","auth/token",n,"application/x-www-form-urlencoded")}async getSubscriptions(){return this.request("GET","webhooks")}async createSubscription(e){return this.request("POST","webhooks",e)}async updateSubscription(e){let{subscription:t,...n}=e;return this.request("PATCH",`webhooks/${t}`,n)}},y=class extends h{},O=class extends m{buildAuthorizationUrl(e){let t=d({client_id:e.clientId,redirect_uri:e.redirectUri,code_challenge:e.codeChallenge,code_challenge_method:"S256",response_type:"code",state:e.state,skip_kyc:e.skipKyc,email:e.email,auth_mode:e.authMode});return `${this.env.api}/auth${t}`}buildSiweAuthorizationUrl(e){let t=d({client_id:e.clientId,redirect_uri:e.redirectUri,message:e.message,signature:e.signature,code_challenge:e.codeChallenge,code_challenge_method:"S256",authentication_method:"siwe",state:e.state});return `${this.env.api}/auth${t}`}async authorizationCodeGrant(e){let t=f({grant_type:"authorization_code",client_id:e.clientId,redirect_uri:e.redirectUri,code:e.code,code_verifier:e.codeVerifier});return this.request("POST","auth/token",t,"application/x-www-form-urlencoded")}async refreshTokenGrant(e){let t=f({grant_type:"refresh_token",client_id:e.clientId,refresh_token:e.refreshToken});return this.request("POST","auth/token",t,"application/x-www-form-urlencoded")}parseAuthorizationResponse(e){return R(e)}},_=class extends h{async createProfile(e){return this.request("POST","profiles",e)}async shareProfileKYC(e){let{profile:t,...n}=e;return this.request("POST",`profiles/${t}/share`,n)}async updateProfileDetails(e){let{profile:t,...n}=e;return this.request("PATCH",`profiles/${t}/details`,n)}async updateProfileForm(e){let{profile:t,...n}=e;return this.request("PATCH",`profiles/${t}/form`,n)}async updateProfileVerifications(e){let{profile:t,...n}=e;return this.request("PATCH",`profiles/${t}/verifications`,n)}};var W={LINK_MESSAGE:"I hereby declare that I am the address owner."};export{v as Currency,c as MoneriumApiError,m as MoneriumBaseClient,O as MoneriumOAuthClient,y as MoneriumPrivateClient,u as MoneriumSdkError,h as MoneriumServerClient,_ as MoneriumWhitelabelClient,V as ProfileType,T as calculatePKCECodeChallenge,W as constants,M as generatePKCE,A as getChain,R as parseAuthorizationResponse,l as parseChain,L as placeOrderMessage,I as randomPKCECodeVerifier,C as rfc3339,z as shortenAddress,D as shortenIban,q as siweMessage};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@monerium/sdk",
3
- "version": "3.5.0",
4
- "description": "Essential tools to interact with the Monerium API, an electronic money issuer.",
3
+ "version": "4.0.0",
4
+ "description": "Essential tools to interact with the Monerium API, an electronic money issuer. Node.js and server-side runtimes first.",
5
5
  "repository": {
6
6
  "type": "git",
7
7
  "url": "git+https://github.com/monerium/js-monorepo.git",
@@ -32,7 +32,6 @@
32
32
  "devDependencies": {
33
33
  "@types/crypto-js": "^4.2.2",
34
34
  "jest-fetch-mock": "^3.0.3",
35
- "jest-localstorage-mock": "^2.4.26",
36
35
  "timezone-mock": "^1.3.6"
37
36
  },
38
37
  "engines": {
@@ -40,7 +39,7 @@
40
39
  },
41
40
  "scripts": {
42
41
  "dev": "tsup --watch",
43
- "build": "tsup",
42
+ "build": "tsc --noEmit && tsup",
44
43
  "typedoc": "typedoc",
45
44
  "type-map": "tsc --emitDeclarationOnly --declaration",
46
45
  "lint": "eslint . --fix",