@monerium/sdk 3.2.1 → 3.3.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
@@ -27,7 +27,6 @@ type TokenSymbol = 'EURe' | 'GBPe' | 'USDe' | 'ISKe';
27
27
  type Ticker = 'EUR' | 'GBP' | 'USD' | 'ISK';
28
28
  type CurrencyCode = 'eur' | 'gbp' | 'usd' | 'isk';
29
29
  type AuthArgs = Omit<AuthCodePayload, 'grant_type'> | Omit<RefreshTokenPayload, 'grant_type'> | Omit<ClientCredentialsPayload, 'grant_type'>;
30
- type OpenArgs = Omit<AuthCodePayload, 'grant_type' | 'code' | 'code_verifier'> | Omit<RefreshTokenPayload, 'grant_type'> | Omit<ClientCredentialsPayload, 'grant_type'> | PKCERequestArgs;
31
30
  /** One of the options for the {@link AuthArgs}.
32
31
  *
33
32
  * [Auth endpoint in API documentation:](https://monerium.dev/api-docs#operation/auth).
@@ -65,26 +64,28 @@ interface BearerProfile {
65
64
  profile: string;
66
65
  userId: string;
67
66
  }
68
- /**
69
- * @returns A {@link PKCERequest} object with properties omitted that are automatically computed in by the SDK.
70
- */
71
- type PKCERequestArgs = Omit<PKCERequest, 'code_challenge' | 'code_challenge_method' | 'response_type'>;
72
- type PKCERequest = {
67
+ interface PKCERequestShared {
73
68
  /** the authentication flow client id of the application */
74
69
  client_id: string;
70
+ /** the redirect uri of the application */
71
+ redirect_uri?: string;
75
72
  /** the code challenge automatically generated by the SDK */
76
73
  code_challenge: string;
77
74
  /** the code challenge method for the authentication flow , handled by the SDK */
78
75
  code_challenge_method: 'S256';
79
- /** the response type of the authentication flow, handled by the SDK */
80
- response_type: 'code';
81
76
  /** the state of the application */
82
77
  state?: string;
83
- /** the redirect uri of the application */
84
- redirect_uri: string;
78
+ }
79
+ /**
80
+ * @returns A {@link PKCERequest} object with properties omitted that are automatically computed in by the SDK.
81
+ */
82
+ type PKCERequestArgs = Omit<PKCERequest, 'code_challenge' | 'code_challenge_method' | 'response_type'>;
83
+ interface PKCERequest extends PKCERequestShared {
84
+ /** the response type of the authentication flow, handled by the SDK */
85
+ response_type: 'code';
85
86
  /** the email of the user to prefill the login form */
86
87
  email?: string;
87
- /** the scope of the application */
88
+ /** @deprecated: will be removed, the scope of the application */
88
89
  scope?: string;
89
90
  /** the address of the wallet to automatically link */
90
91
  address?: string;
@@ -96,7 +97,24 @@ type PKCERequest = {
96
97
  skip_create_account?: boolean;
97
98
  /** You can skip the KYC onboarding steps in the Authorization Flow and use the the details, additional data, and verifications API endpoints after you have gotten the authorization. */
98
99
  skip_kyc?: boolean;
99
- };
100
+ }
101
+ /**
102
+ * @returns A {@link PKCESIWERequest} object with properties omitted that are automatically computed in by the SDK.
103
+ */
104
+ type PKCERSIWERequestArgs = Omit<PKCESIWERequest, 'code_challenge' | 'code_challenge_method' | 'authentication_method'>;
105
+ interface PKCESIWERequest extends PKCERequestShared {
106
+ /**
107
+ * Authentication method used. The default is to redirect the user to Monerium login screen, where the user can either sign in, or go through the register flow.
108
+ * `siwe` is only applicable for existing Monerium customers who have already linked at least one of their addresses with Monerium.
109
+ **/
110
+ authentication_method: 'siwe';
111
+ /** An EIP-4361 compatible message. https://eips.ethereum.org/EIPS/eip-4361
112
+ * https://monerium.com/siwe
113
+ * */
114
+ message: string;
115
+ /** Signature for the SIWE message. Must include the 0x prefix. */
116
+ signature: string;
117
+ }
100
118
  declare enum Method {
101
119
  password = "password",
102
120
  resource = "resource",
@@ -443,25 +461,33 @@ type ClassOptions = {
443
461
  environment?: ENV;
444
462
  debug?: boolean;
445
463
  } & BearerTokenCredentials;
446
- interface AuthFlowOptions {
447
- /** the auth flow client ID for your application */
448
- clientId?: string;
449
- /** the redirect URI defined by your application */
450
- redirectUri?: string;
464
+ interface AuthFlowOptionsShared {
465
+ /** the state oauth parameter */
466
+ state?: string;
467
+ }
468
+ interface AuthFlowOptions extends AuthFlowOptionsShared {
451
469
  /** the email of the user to prefill the login form */
452
470
  email?: string;
471
+ /** skip account creation in auth flow */
472
+ skipCreateAccount?: boolean;
473
+ /** skip KYC in auth flow */
474
+ skipKyc?: boolean;
453
475
  /** the address your customer should link in auth flow */
454
476
  address?: string;
455
477
  /** the signature of the address */
456
478
  signature?: string;
457
479
  /** the chain of the address */
458
480
  chain?: Chain | ChainId;
459
- /** the state oauth parameter */
460
- state?: string;
461
- /** skip account creation in auth flow */
462
- skipCreateAccount?: boolean;
463
- /** skip KYC in auth flow */
464
- skipKyc?: boolean;
481
+ }
482
+ interface AuthFlowSIWEOptions extends AuthFlowOptionsShared {
483
+ /** Signature for the SIWE message. Must include the 0x prefix. */
484
+ signature: string;
485
+ /**
486
+ * An EIP-4361 compatible message. https://eips.ethereum.org/EIPS/eip-4361
487
+ *
488
+ * https://monerium.com/siwe
489
+ * */
490
+ message: string;
465
491
  }
466
492
  interface ClientCredentials {
467
493
  clientId: string;
@@ -515,17 +541,38 @@ declare class MoneriumClient {
515
541
  * */
516
542
  constructor(envOrOptions?: ENV | ClassOptions);
517
543
  /**
518
- * Construct the url to the authorization code flow and redirects,
544
+ * Constructs the url to the authorization code flow and redirects,
519
545
  * Code Verifier needed for the code challenge is stored in local storage
520
546
  * For automatic wallet link, add the following properties: `address`, `signature` & `chain`
521
547
  *
548
+ * This authorization code is then used to request an access token via the token endpoint. (https://monerium.dev/api-docs#operation/auth-token)
549
+ *
522
550
  * @group Authentication
523
551
  * @see {@link https://monerium.dev/api-docs-v2#tag/auth/operation/auth | API Documentation}
524
552
  * @param {AuthFlowOptions} [params] - the auth flow params
525
- * @returns string
553
+ * @returns void
526
554
  *
527
555
  */
528
556
  authorize(params?: AuthFlowOptions): Promise<void>;
557
+ /**
558
+ * Constructs the url to the authorization code flow and redirects,
559
+ * Code Verifier needed for the code challenge is stored in local storage
560
+ *
561
+ * "Sign in with Ethereum" (SIWE) flow can be used for existing Monerium customers.
562
+ * In this case the payload must include a valid EIP-4361 (https://eips.ethereum.org/EIPS/eip-4361) message and signature.
563
+ * On successful authorization the authorization code is returned at once.
564
+ *
565
+ * This authorization code is then used to request an access token via the token endpoint.
566
+ *
567
+ * https://monerium.com/siwe
568
+ *
569
+ * @group Authentication
570
+ * @see {@link https://monerium.dev/api-docs-v2#tag/auth/operation/auth | API Documentation}
571
+ * @param {AuthFlowSIWEOptions} [params] - the auth flow SIWE params
572
+ * @returns void
573
+ *
574
+ */
575
+ siwe(params: AuthFlowSIWEOptions): Promise<void>;
529
576
  /**
530
577
  * Will use the authorization code flow code to get access token
531
578
  *
@@ -696,11 +743,6 @@ declare class MoneriumClient {
696
743
  * @hidden
697
744
  */
698
745
  getEnvironment: () => Environment;
699
- /**
700
- *
701
- * @hidden
702
- */
703
- getAuthFlowURI: (args: PKCERequestArgs) => string;
704
746
  }
705
747
 
706
748
  declare const _default: {
@@ -757,6 +799,20 @@ declare const parseChain: (chain: Chain | ChainId) => Chain;
757
799
  * @example `Send EUR 1 to IS1234123412341234 at 2023-04-30T12:00:00+01:00`
758
800
  */
759
801
  declare const placeOrderMessage: (amount: string | number, currency: Currency, receiver: string, chain?: ChainId | Chain) => string;
802
+ /**
803
+ * https://monerium.com/siwe
804
+ */
805
+ declare const siweMessage: ({ domain, address, appName, redirectUri, chainId, issuedAt, expiryAt, privacyPolicyUrl, termsOfServiceUrl, }: {
806
+ domain: string;
807
+ address: string;
808
+ appName: string;
809
+ redirectUri: string;
810
+ chainId: EvmChainId;
811
+ issuedAt?: string;
812
+ expiryAt?: string;
813
+ privacyPolicyUrl: string;
814
+ termsOfServiceUrl: string;
815
+ }) => string;
760
816
  /**
761
817
  * This will resolve the chainId number to the corresponding chain name.
762
818
  * @param chainId The chainId of the network
@@ -805,4 +861,4 @@ declare const shortenIban: (iban?: string) => string | undefined;
805
861
  * ```
806
862
  */
807
863
 
808
- export { AccountState, type Address, type AddressesQueryParams, type AddressesResponse, type AuthArgs, type AuthCodePayload, type AuthFlowOptions, type AuthorizationCodeCredentials, type Balances, type BearerProfile, type BearerTokenCredentials, type Beneficiary, type Chain, type ChainId, type ClassOptions, type ClientCredentials, type ClientCredentialsPayload, type Config, type CorporateProfileDetails, type CorporateProfileDetailsRequest, type Corporation, type CosmosChainId, type Counterpart, type CrossChainIdentifier, Currency, type CurrencyBalance, type CurrencyCode, type Director, type ENV, type Environment, type EvmChainId, type Fee, type IBAN, type IBANIdentifier, type IBANsResponse, type IbansQueryParams, IdDocumentKind, type Identifier, type Individual, type KYC, KYCOutcome, KYCState, type LinkAddress, type LinkedAddress, Method, MoneriumClient, type MoveIbanPayload, type NewOrder, type NewOrderByAccountId, type NewOrderByAddress, type NewOrderCommon, type OpenArgs, type Order, type OrderFilter, OrderKind, type OrderMetadata, type OrderNotificationQueryParams, OrderState, type OrdersResponse, type PKCERequest, type PKCERequestArgs, PaymentStandard, Permission, type PersonalProfileDetails, type PersonalProfileDetailsRequest, type ProductionChain, type Profile, type ProfilePermissions, ProfileState, ProfileType, type ProfilesQueryParams, type ProfilesResponse, type RefreshTokenPayload, type Representative, type RequestIbanPayload, type ResponseStatus, type SCANIdentifier, type SandboxChain, type SubmitProfileDetailsPayload, type SupportingDoc, type SupportingDocMetadata, type Ticker, type Token, type TokenSymbol, _default as constants, MoneriumClient as default, getChain, parseChain, placeOrderMessage, rfc3339, shortenIban };
864
+ export { AccountState, type Address, type AddressesQueryParams, type AddressesResponse, type AuthArgs, type AuthCodePayload, type AuthFlowOptions, type AuthFlowOptionsShared, type AuthFlowSIWEOptions, type AuthorizationCodeCredentials, type Balances, type BearerProfile, type BearerTokenCredentials, type Beneficiary, type Chain, type ChainId, type ClassOptions, type ClientCredentials, type ClientCredentialsPayload, type Config, type CorporateProfileDetails, type CorporateProfileDetailsRequest, type Corporation, type CosmosChainId, type Counterpart, type CrossChainIdentifier, Currency, type CurrencyBalance, type CurrencyCode, type Director, type ENV, type Environment, type EvmChainId, type Fee, type IBAN, type IBANIdentifier, type IBANsResponse, type IbansQueryParams, IdDocumentKind, type Identifier, type Individual, type KYC, KYCOutcome, KYCState, type LinkAddress, type LinkedAddress, Method, MoneriumClient, type MoveIbanPayload, type NewOrder, type NewOrderByAccountId, type NewOrderByAddress, type NewOrderCommon, type Order, type OrderFilter, OrderKind, type OrderMetadata, type OrderNotificationQueryParams, OrderState, type OrdersResponse, type PKCERSIWERequestArgs, type PKCERequest, type PKCERequestArgs, type PKCERequestShared, type PKCESIWERequest, PaymentStandard, Permission, type PersonalProfileDetails, type PersonalProfileDetailsRequest, type ProductionChain, type Profile, type ProfilePermissions, ProfileState, ProfileType, type ProfilesQueryParams, type ProfilesResponse, type RefreshTokenPayload, type Representative, type RequestIbanPayload, type ResponseStatus, type SCANIdentifier, type SandboxChain, type SubmitProfileDetailsPayload, type SupportingDoc, type SupportingDocMetadata, type Ticker, type Token, type TokenSymbol, _default as constants, MoneriumClient as default, getChain, parseChain, placeOrderMessage, rfc3339, shortenIban, siweMessage };
package/dist/index.js CHANGED
@@ -1,2 +1,15 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var Z=require('crypto-js/enc-base64url.js'),Y=require('crypto-js/sha256.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var Z__default=/*#__PURE__*/_interopDefault(Z);var Y__default=/*#__PURE__*/_interopDefault(Y);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 true;default:return false}},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 true;default:return false}},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!==undefined).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!==undefined?{signature:o}:{},...c!==undefined?{chain:c}:{}}:{};return C({client_id:r,redirect_uri:t,...i!==undefined?{scope:i}:{},...d!==undefined?{email:d}:{},...s!==undefined?{state:s}:{},...h!==undefined?{skip_create_account:h}:{},...v!==undefined?{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!==undefined&&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??false),this.#e=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#i={clientId:r,redirectUri:t};}else if(u&&e?.clientSecret){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")||undefined,a=new URLSearchParams(window.location.search).get("state")||undefined,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=false,this.bearerProfile=undefined,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=false,this.bearerProfile=undefined,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,true).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):undefined,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=true}){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=undefined;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#s=undefined,this.bearerProfile=undefined;}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;
2
- exports.AccountState=L;exports.Currency=O;exports.IdDocumentKind=V;exports.KYCOutcome=K;exports.KYCState=F;exports.Method=z;exports.MoneriumClient=w;exports.OrderKind=G;exports.OrderState=J;exports.PaymentStandard=Q;exports.Permission=j;exports.ProfileState=M;exports.ProfileType=q;exports.constants=f;exports.default=$e;exports.getChain=I;exports.parseChain=b;exports.placeOrderMessage=X;exports.rfc3339=x;exports.shortenIban=N;
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var U=require('crypto-js/enc-base64url.js'),z=require('crypto-js/sha256.js');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var U__default=/*#__PURE__*/_interopDefault(U);var z__default=/*#__PURE__*/_interopDefault(z);var y={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 h={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 I=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=e.length,t=0;for(;t<128;)n+=e.charAt(Math.floor(Math.random()*r)),t+=1;return n},q=n=>U__default.default.stringify(z__default.default(n)),A=()=>{let n=I(),e=q(n);return localStorage.setItem(h.STORAGE_CODE_VERIFIER,n||""),e},S=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,r]=n.split("?");r&&window.history.replaceState(null,"",e);},k=n=>n.code!=null,v=n=>n.refresh_token!=null,$=n=>n.client_secret!=null;var R=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 m=n=>{if(!n)return "";let e=Object.entries(n).filter(([r,t])=>t!==""&&t!==undefined&&t!==null).map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&");return e?"?"+e:""};var N=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var _=n=>Object.entries(n).filter(([r,t])=>t!=null).map(([r,t])=>`${r}-${t}`).join("-");var B=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(B||{}),F=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(F||{}),M=(r=>(r.corporate="corporate",r.personal="personal",r))(M||{}),j=(r=>(r.read="read",r.write="write",r))(j||{}),K=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(K||{}),W=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(W||{}),L=(t=>(t.approved="approved",t.rejected="rejected",t.unknown="unknown",t))(L||{}),Q=(t=>(t.requested="requested",t.approved="approved",t.pending="pending",t))(Q||{}),V=(t=>(t.iban="iban",t.scan="scan",t.chain="chain",t))(V||{}),G=(t=>(t.passport="passport",t.nationalIdentityCard="nationalIdentityCard",t.drivingLicense="drivingLicense",t))(G||{}),J=(r=>(r.redeem="redeem",r.issue="issue",r))(J||{}),H=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(H||{});var P=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())},X=n=>{switch(n){case "noble":case "noble-1":case "grand":case "grand-1":return true;default:return false}},Z=n=>{switch(n){case "ethereum":case "sepolia":case "polygon":case "amoy":case "gnosis":case "chiado":case "arbitrum":case "arbitrumsepolia":case "linea":case "lineasepolia":return true;default:return false}},x=n=>{if(typeof n=="number")return E(n);if(X(n))return n.split("-")[0];if(Z(n))return n;try{return E(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},u=(n,e)=>x(D(e,n)),Y=(n,e,r,t)=>{let i=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${r} on ${x(t)} at ${P(new Date)}`:i==="EUR"?`Send ${i} ${n} to ${T(r)} at ${P(new Date)}`:`Send ${i} ${n} to ${r} at ${P(new Date)}`},ee=({domain:n,address:e,appName:r,redirectUri:t,chainId:i,issuedAt:s=new Date().toISOString(),expiryAt:a=new Date(Date.now()+1e3*60*5).toISOString(),privacyPolicyUrl:o,termsOfServiceUrl:c})=>`${n} wants you to sign in with your Ethereum account:
2
+ ${e}
3
+
4
+ Allow ${r} to access my data on Monerium
5
+
6
+ URI: ${t}
7
+ Version: 1
8
+ Chain ID: ${i}
9
+ Nonce: ${I().slice(0,16)}
10
+ Issued At: ${s}
11
+ Expiration Time: ${a}
12
+ Resources:
13
+ - https://monerium.com/siwe
14
+ - ${o}
15
+ - ${c}`,f=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,r])=>r!==undefined).map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"):"",E=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}`)}},T=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 D=(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},C=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:x(D(r,n))}}return e};var {STORAGE_CODE_VERIFIER:w,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=h,l=typeof window>"u",b=class{#e;#s;bearerProfile;#i=new Map;isAuthorized=!!this.bearerProfile;#r=()=>{};#n;state;constructor(e){if(!e){this.#e=y.environments.sandbox;return}if(typeof e=="string")this.#e=y.environments[e];else if(this.#r=N(e.debug??false),this.#e=y.environments[e.environment||"sandbox"],!l&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#n={clientId:r,redirectUri:t};}else if(l&&e?.clientSecret){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.#n={clientId:r,clientSecret:t};}}async authorize(e){let r=A(),t=e?.address?{address:e?.address,signature:e?.signature,chain:e?.chain?u(this.#e.name,e?.chain):undefined}:{},i=f({client_id:this.#n?.clientId,redirect_uri:this.#n?.redirectUri,code_challenge:r,code_challenge_method:"S256",response_type:"code",state:e?.state,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc,email:e?.email,...t}),s=`${this.#e.api}/auth?${i}`;this.#r(`Auth flow URL: ${s}`),window.location.assign(s);}async siwe(e){let r=A(),t=f({client_id:this.#n?.clientId,redirect_uri:this.#n?.redirectUri,message:e.message,signature:e.signature,code_challenge:r,code_challenge_method:"S256",authentication_method:"siwe",state:e?.state}),i=`${this.#e.api}/auth?${t}`;this.#r(`Auth flow SIWE URL: ${i}`),window.location.assign(i);}async getAccess(e){let r=this.#n?.clientId;if(this.#n?.clientSecret){if(l)return await this.#c(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(!r)throw new Error("Missing ClientId");if(l)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||undefined,a=new URLSearchParams(window.location.search).get("state")||undefined,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.#d(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=false,this.bearerProfile=undefined,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=false,this.bearerProfile=undefined,new Error("Access token is invalid.")}}return this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let r;if(k(e))r={...e,grant_type:"authorization_code"};else if(v(e))r={...e,grant_type:"refresh_token"};else if($(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,true).then(t=>{if(this.bearerProfile=t,this.isAuthorized=!!t,this.#s=`Bearer ${t?.access_token}`,!l){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 l||(localStorage.removeItem(w),localStorage.removeItem(p),localStorage.removeItem(g),S()),new Error(t?.message)}),k(e)&&S(),this.bearerProfile}getProfile(e){return this.#t("get",`profiles/${e}`)}getProfiles(e){return this.#t("get",`profiles${m(e)}`)}getAddress(e){return this.#t("get",`addresses/${e}`)}getAddresses(e){e=C(this.#e.name,e);let r=e?f(e):undefined,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=u(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=m({profile:r,chain:t?u(this.#e.name,t):""});return this.#t("get",`ibans${i}`)}getOrders(e){return this.#t("get",`orders${m(e)}`)}getOrder(e){return this.#t("get",`orders/${e}`)}getTokens(){return this.#t("get","tokens")}linkAddress(e){return e=C(this.#e.name,e),this.#t("post","addresses",JSON.stringify(e))}placeOrder(e){let r={kind:"redeem",...C(this.#e.name,e),counterpart:{...e.counterpart,identifier:C(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:u(this.#e.name,t)}))}requestIban({address:e,chain:r,emailNotifications:t=true}){return this.#t("post","ibans",JSON.stringify({address:e,chain:u(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),R(`${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 R(`${this.#e.api}/${r}`,e.toUpperCase(),i?f(t):t,s)}#a=async(e,r,t,i)=>{let s=localStorage.getItem(w)||"";if(!s)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=i,localStorage.removeItem(w),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:s})};#c=async({clientId:e,clientSecret:r})=>await this.#o({client_id:e,client_secret:r});#d=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=m({access_token:this.bearerProfile?.access_token,profile:i,state:s}),o,c=_({profile:i,state:s});if(this.#i?.has(c))o=this.#i.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#i?.set(c,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=d=>{let O=JSON.parse(d.data);r&&r(O);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#i?.delete(a);},o.onerror=d=>{t&&t(d),console.error("WebSocket error:",d);},o}unsubscribeOrderNotifications(e){if(e){let r=_({profile:e?.profile,state:e?.state}),t=this.#i?.get(r);t&&(t.close(),this.#i?.delete(r));}else this.#i?.forEach(r=>{r?.close();}),this.#i?.clear(),this.#i=undefined;}async disconnect(){l||localStorage.removeItem(w),this.unsubscribeOrderNotifications(),this.#s=undefined,this.bearerProfile=undefined;}async revokeAccess(){l||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e};var Ne=b;exports.AccountState=Q;exports.Currency=B;exports.IdDocumentKind=G;exports.KYCOutcome=L;exports.KYCState=W;exports.Method=F;exports.MoneriumClient=b;exports.OrderKind=J;exports.OrderState=H;exports.PaymentStandard=V;exports.Permission=j;exports.ProfileState=K;exports.ProfileType=M;exports.constants=h;exports.default=Ne;exports.getChain=E;exports.parseChain=x;exports.placeOrderMessage=Y;exports.rfc3339=P;exports.shortenIban=T;exports.siweMessage=ee;
package/dist/index.mjs CHANGED
@@ -1,2 +1,15 @@
1
- import Z from'crypto-js/enc-base64url.js';import Y from'crypto-js/sha256.js';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 true;default:return false}},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 true;default:return false}},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!==undefined).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!==undefined?{signature:o}:{},...c!==undefined?{chain:c}:{}}:{};return C({client_id:r,redirect_uri:t,...i!==undefined?{scope:i}:{},...d!==undefined?{email:d}:{},...s!==undefined?{state:s}:{},...h!==undefined?{skip_create_account:h}:{},...v!==undefined?{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!==undefined&&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??false),this.#e=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#i={clientId:r,redirectUri:t};}else if(u&&e?.clientSecret){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")||undefined,a=new URLSearchParams(window.location.search).get("state")||undefined,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=false,this.bearerProfile=undefined,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=false,this.bearerProfile=undefined,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,true).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):undefined,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=true}){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=undefined;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#s=undefined,this.bearerProfile=undefined;}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;
2
- 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};
1
+ import U from'crypto-js/enc-base64url.js';import z from'crypto-js/sha256.js';var y={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 h={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 I=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=e.length,t=0;for(;t<128;)n+=e.charAt(Math.floor(Math.random()*r)),t+=1;return n},q=n=>U.stringify(z(n)),A=()=>{let n=I(),e=q(n);return localStorage.setItem(h.STORAGE_CODE_VERIFIER,n||""),e},S=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,r]=n.split("?");r&&window.history.replaceState(null,"",e);},k=n=>n.code!=null,v=n=>n.refresh_token!=null,$=n=>n.client_secret!=null;var R=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 m=n=>{if(!n)return "";let e=Object.entries(n).filter(([r,t])=>t!==""&&t!==undefined&&t!==null).map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&");return e?"?"+e:""};var N=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var _=n=>Object.entries(n).filter(([r,t])=>t!=null).map(([r,t])=>`${r}-${t}`).join("-");var B=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(B||{}),F=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(F||{}),M=(r=>(r.corporate="corporate",r.personal="personal",r))(M||{}),j=(r=>(r.read="read",r.write="write",r))(j||{}),K=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(K||{}),W=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(W||{}),L=(t=>(t.approved="approved",t.rejected="rejected",t.unknown="unknown",t))(L||{}),Q=(t=>(t.requested="requested",t.approved="approved",t.pending="pending",t))(Q||{}),V=(t=>(t.iban="iban",t.scan="scan",t.chain="chain",t))(V||{}),G=(t=>(t.passport="passport",t.nationalIdentityCard="nationalIdentityCard",t.drivingLicense="drivingLicense",t))(G||{}),J=(r=>(r.redeem="redeem",r.issue="issue",r))(J||{}),H=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(H||{});var P=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())},X=n=>{switch(n){case "noble":case "noble-1":case "grand":case "grand-1":return true;default:return false}},Z=n=>{switch(n){case "ethereum":case "sepolia":case "polygon":case "amoy":case "gnosis":case "chiado":case "arbitrum":case "arbitrumsepolia":case "linea":case "lineasepolia":return true;default:return false}},x=n=>{if(typeof n=="number")return E(n);if(X(n))return n.split("-")[0];if(Z(n))return n;try{return E(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},u=(n,e)=>x(D(e,n)),Y=(n,e,r,t)=>{let i=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${r} on ${x(t)} at ${P(new Date)}`:i==="EUR"?`Send ${i} ${n} to ${T(r)} at ${P(new Date)}`:`Send ${i} ${n} to ${r} at ${P(new Date)}`},ee=({domain:n,address:e,appName:r,redirectUri:t,chainId:i,issuedAt:s=new Date().toISOString(),expiryAt:a=new Date(Date.now()+1e3*60*5).toISOString(),privacyPolicyUrl:o,termsOfServiceUrl:c})=>`${n} wants you to sign in with your Ethereum account:
2
+ ${e}
3
+
4
+ Allow ${r} to access my data on Monerium
5
+
6
+ URI: ${t}
7
+ Version: 1
8
+ Chain ID: ${i}
9
+ Nonce: ${I().slice(0,16)}
10
+ Issued At: ${s}
11
+ Expiration Time: ${a}
12
+ Resources:
13
+ - https://monerium.com/siwe
14
+ - ${o}
15
+ - ${c}`,f=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,r])=>r!==undefined).map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"):"",E=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}`)}},T=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 D=(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},C=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:x(D(r,n))}}return e};var {STORAGE_CODE_VERIFIER:w,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=h,l=typeof window>"u",b=class{#e;#s;bearerProfile;#i=new Map;isAuthorized=!!this.bearerProfile;#r=()=>{};#n;state;constructor(e){if(!e){this.#e=y.environments.sandbox;return}if(typeof e=="string")this.#e=y.environments[e];else if(this.#r=N(e.debug??false),this.#e=y.environments[e.environment||"sandbox"],!l&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#n={clientId:r,redirectUri:t};}else if(l&&e?.clientSecret){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.#n={clientId:r,clientSecret:t};}}async authorize(e){let r=A(),t=e?.address?{address:e?.address,signature:e?.signature,chain:e?.chain?u(this.#e.name,e?.chain):undefined}:{},i=f({client_id:this.#n?.clientId,redirect_uri:this.#n?.redirectUri,code_challenge:r,code_challenge_method:"S256",response_type:"code",state:e?.state,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc,email:e?.email,...t}),s=`${this.#e.api}/auth?${i}`;this.#r(`Auth flow URL: ${s}`),window.location.assign(s);}async siwe(e){let r=A(),t=f({client_id:this.#n?.clientId,redirect_uri:this.#n?.redirectUri,message:e.message,signature:e.signature,code_challenge:r,code_challenge_method:"S256",authentication_method:"siwe",state:e?.state}),i=`${this.#e.api}/auth?${t}`;this.#r(`Auth flow SIWE URL: ${i}`),window.location.assign(i);}async getAccess(e){let r=this.#n?.clientId;if(this.#n?.clientSecret){if(l)return await this.#c(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(!r)throw new Error("Missing ClientId");if(l)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||undefined,a=new URLSearchParams(window.location.search).get("state")||undefined,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.#d(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=false,this.bearerProfile=undefined,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=false,this.bearerProfile=undefined,new Error("Access token is invalid.")}}return this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let r;if(k(e))r={...e,grant_type:"authorization_code"};else if(v(e))r={...e,grant_type:"refresh_token"};else if($(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,true).then(t=>{if(this.bearerProfile=t,this.isAuthorized=!!t,this.#s=`Bearer ${t?.access_token}`,!l){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 l||(localStorage.removeItem(w),localStorage.removeItem(p),localStorage.removeItem(g),S()),new Error(t?.message)}),k(e)&&S(),this.bearerProfile}getProfile(e){return this.#t("get",`profiles/${e}`)}getProfiles(e){return this.#t("get",`profiles${m(e)}`)}getAddress(e){return this.#t("get",`addresses/${e}`)}getAddresses(e){e=C(this.#e.name,e);let r=e?f(e):undefined,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=u(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=m({profile:r,chain:t?u(this.#e.name,t):""});return this.#t("get",`ibans${i}`)}getOrders(e){return this.#t("get",`orders${m(e)}`)}getOrder(e){return this.#t("get",`orders/${e}`)}getTokens(){return this.#t("get","tokens")}linkAddress(e){return e=C(this.#e.name,e),this.#t("post","addresses",JSON.stringify(e))}placeOrder(e){let r={kind:"redeem",...C(this.#e.name,e),counterpart:{...e.counterpart,identifier:C(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:u(this.#e.name,t)}))}requestIban({address:e,chain:r,emailNotifications:t=true}){return this.#t("post","ibans",JSON.stringify({address:e,chain:u(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),R(`${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 R(`${this.#e.api}/${r}`,e.toUpperCase(),i?f(t):t,s)}#a=async(e,r,t,i)=>{let s=localStorage.getItem(w)||"";if(!s)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=i,localStorage.removeItem(w),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:s})};#c=async({clientId:e,clientSecret:r})=>await this.#o({client_id:e,client_secret:r});#d=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=m({access_token:this.bearerProfile?.access_token,profile:i,state:s}),o,c=_({profile:i,state:s});if(this.#i?.has(c))o=this.#i.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#i?.set(c,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=d=>{let O=JSON.parse(d.data);r&&r(O);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#i?.delete(a);},o.onerror=d=>{t&&t(d),console.error("WebSocket error:",d);},o}unsubscribeOrderNotifications(e){if(e){let r=_({profile:e?.profile,state:e?.state}),t=this.#i?.get(r);t&&(t.close(),this.#i?.delete(r));}else this.#i?.forEach(r=>{r?.close();}),this.#i?.clear(),this.#i=undefined;}async disconnect(){l||localStorage.removeItem(w),this.unsubscribeOrderNotifications(),this.#s=undefined,this.bearerProfile=undefined;}async revokeAccess(){l||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e};var Ne=b;export{Q as AccountState,B as Currency,G as IdDocumentKind,L as KYCOutcome,W as KYCState,F as Method,b as MoneriumClient,J as OrderKind,H as OrderState,V as PaymentStandard,j as Permission,K as ProfileState,M as ProfileType,h as constants,Ne as default,E as getChain,x as parseChain,Y as placeOrderMessage,P as rfc3339,T as shortenIban,ee as siweMessage};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@monerium/sdk",
3
- "version": "3.2.1",
3
+ "version": "3.3.0",
4
4
  "description": "Essential tools to interact with the Monerium API, an electronic money issuer.",
5
5
  "repository": {
6
6
  "type": "git",