@monerium/sdk 3.0.1 → 3.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +3 -0
- package/dist/index.d.ts +22 -8
- package/dist/index.js +23 -23
- package/dist/index.mjs +4 -4
- package/package.json +3 -2
package/README.md
CHANGED
|
@@ -107,6 +107,9 @@ await monerium.getProfiles();
|
|
|
107
107
|
|
|
108
108
|
// Access tokens are now available for use.
|
|
109
109
|
const { access_token, refresh_token } = monerium.bearerProfile as BearerProfile;
|
|
110
|
+
|
|
111
|
+
// Use refresh token to get a new access token
|
|
112
|
+
await monerium.getAccess(refresh_token);
|
|
110
113
|
```
|
|
111
114
|
|
|
112
115
|
API documentation:
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
type Environment = {
|
|
2
|
+
name: ENV;
|
|
2
3
|
api: string;
|
|
3
4
|
web: string;
|
|
4
5
|
wss: string;
|
|
@@ -10,8 +11,10 @@ type Config = {
|
|
|
10
11
|
};
|
|
11
12
|
};
|
|
12
13
|
type ENV = 'sandbox' | 'production';
|
|
13
|
-
type
|
|
14
|
-
type
|
|
14
|
+
type SandboxChain = 'sepolia' | 'chiado' | 'amoy' | 'arbitrumsepolia' | 'lineasepolia' | 'grand';
|
|
15
|
+
type ProductionChain = 'ethereum' | 'gnosis' | 'polygon' | 'arbitrum' | 'linea' | 'noble';
|
|
16
|
+
type Chain = string | ProductionChain | SandboxChain;
|
|
17
|
+
type EvmChainId = number | 1 | 11155111 | 100 | 10200 | 137 | 80002 | 42161 | 421614 | 59141 | 59144;
|
|
15
18
|
type ChainId = EvmChainId | CosmosChainId;
|
|
16
19
|
type CosmosChainId = 'noble-1' | 'grand-1' | 'florin-1';
|
|
17
20
|
declare enum Currency {
|
|
@@ -79,6 +82,8 @@ type PKCERequest = {
|
|
|
79
82
|
state?: string;
|
|
80
83
|
/** the redirect uri of the application */
|
|
81
84
|
redirect_uri: string;
|
|
85
|
+
/** the email of the user to prefill the login form */
|
|
86
|
+
email?: string;
|
|
82
87
|
/** the scope of the application */
|
|
83
88
|
scope?: string;
|
|
84
89
|
/** the address of the wallet to automatically link */
|
|
@@ -443,6 +448,8 @@ interface AuthFlowOptions {
|
|
|
443
448
|
clientId?: string;
|
|
444
449
|
/** the redirect URI defined by your application */
|
|
445
450
|
redirectUri?: string;
|
|
451
|
+
/** the email of the user to prefill the login form */
|
|
452
|
+
email?: string;
|
|
446
453
|
/** the address your customer should link in auth flow */
|
|
447
454
|
address?: string;
|
|
448
455
|
/** the signature of the address */
|
|
@@ -524,7 +531,7 @@ declare class MoneriumClient {
|
|
|
524
531
|
*
|
|
525
532
|
* @group Authentication
|
|
526
533
|
*
|
|
527
|
-
* @param {
|
|
534
|
+
* @param {string} refreshToken - provide the refresh token to get a new access token
|
|
528
535
|
*
|
|
529
536
|
* @returns boolean to indicate if access has been granted
|
|
530
537
|
*
|
|
@@ -539,6 +546,13 @@ declare class MoneriumClient {
|
|
|
539
546
|
* });
|
|
540
547
|
*
|
|
541
548
|
* await monerium.getAccess();
|
|
549
|
+
*
|
|
550
|
+
* const refreshToken = monerium.bearerProfile?.refresh_token;
|
|
551
|
+
*
|
|
552
|
+
* // TODO: store the refresh token securely
|
|
553
|
+
*
|
|
554
|
+
* // reconnect...
|
|
555
|
+
* await monerium.getAccess(refreshToken);
|
|
542
556
|
* ```
|
|
543
557
|
*/
|
|
544
558
|
getAccess(refreshToken?: string): Promise<boolean>;
|
|
@@ -721,7 +735,7 @@ declare const rfc3339: (d: Date) => string;
|
|
|
721
735
|
* @param chain The chainId of the network
|
|
722
736
|
* @returns chain name, 'ethereum', 'polygon', 'gnosis', etc.
|
|
723
737
|
*/
|
|
724
|
-
declare const parseChain: (chain: Chain | ChainId
|
|
738
|
+
declare const parseChain: (chain: Chain | ChainId) => Chain;
|
|
725
739
|
/**
|
|
726
740
|
* The message to be signed when placing an order.
|
|
727
741
|
* @param amount The amount to be sent
|
|
@@ -750,13 +764,13 @@ declare const placeOrderMessage: (amount: string | number, currency: Currency, r
|
|
|
750
764
|
* @example
|
|
751
765
|
* ```ts
|
|
752
766
|
* getChain(1) // 'ethereum'
|
|
753
|
-
* getChain(11155111) // '
|
|
767
|
+
* getChain(11155111) // 'sepolia'
|
|
754
768
|
*
|
|
755
769
|
* getChain(100) // 'gnosis'
|
|
756
|
-
* getChain(10200) // '
|
|
770
|
+
* getChain(10200) // 'chiado'
|
|
757
771
|
*
|
|
758
772
|
* getChain(137) // 'polygon'
|
|
759
|
-
* getChain(80002) // '
|
|
773
|
+
* getChain(80002) // 'amoy'
|
|
760
774
|
* ```
|
|
761
775
|
*/
|
|
762
776
|
declare const getChain: (chainId: number) => Chain;
|
|
@@ -791,4 +805,4 @@ declare const shortenIban: (iban?: string) => string | undefined;
|
|
|
791
805
|
* ```
|
|
792
806
|
*/
|
|
793
807
|
|
|
794
|
-
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 Profile, type ProfilePermissions, ProfileState, ProfileType, type ProfilesQueryParams, type ProfilesResponse, type RefreshTokenPayload, type Representative, type RequestIbanPayload, type ResponseStatus, type SCANIdentifier, type SubmitProfileDetailsPayload, type SupportingDoc, type SupportingDocMetadata, type Ticker, type Token, type TokenSymbol, _default as constants, MoneriumClient as default, getChain, parseChain, placeOrderMessage, rfc3339, shortenIban };
|
|
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 };
|
package/dist/index.js
CHANGED
|
@@ -2,33 +2,33 @@
|
|
|
2
2
|
|
|
3
3
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
4
4
|
|
|
5
|
-
var
|
|
6
|
-
var
|
|
5
|
+
var Z = require('crypto-js/enc-base64url.js');
|
|
6
|
+
var Y = require('crypto-js/sha256.js');
|
|
7
7
|
|
|
8
8
|
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
|
9
9
|
|
|
10
|
-
var
|
|
11
|
-
var
|
|
10
|
+
var Z__default = /*#__PURE__*/_interopDefault(Z);
|
|
11
|
+
var Y__default = /*#__PURE__*/_interopDefault(Y);
|
|
12
12
|
|
|
13
|
-
var P={environments:{production:{api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},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 E=(s=>(s.eur="eur",s.usd="usd",s.gbp="gbp",s.isk="isk",s))(E||{}),B=(s=>(s.password="password",s.resource="resource",s.jwt="jwt",s.apiKey="apiKey",s))(B||{}),D=(t=>(t.corporate="corporate",t.personal="personal",t))(D||{}),U=(t=>(t.read="read",t.write="write",t))(U||{}),z=(i=>(i.created="created",i.pending="pending",i.approved="approved",i.rejected="rejected",i.blocked="blocked",i))(z||{}),q=(s=>(s.absent="absent",s.submitted="submitted",s.pending="pending",s.confirmed="confirmed",s))(q||{}),j=(r=>(r.approved="approved",r.rejected="rejected",r.unknown="unknown",r))(j||{}),M=(r=>(r.requested="requested",r.approved="approved",r.pending="pending",r))(M||{}),F=(r=>(r.iban="iban",r.scan="scan",r.chain="chain",r))(F||{}),K=(r=>(r.passport="passport",r.nationalIdentityCard="nationalIdentityCard",r.drivingLicense="drivingLicense",r))(K||{}),L=(t=>(t.redeem="redeem",t.issue="issue",t))(L||{}),Q=(s=>(s.placed="placed",s.pending="pending",s.processed="processed",s.rejected="rejected",s))(Q||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=r=>r<10?"0"+r:r,t=r=>{if(r===0)return "Z";let s=r>0?"-":"+";return r=Math.abs(r),s+e(Math.floor(r/60))+":"+e(r%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+t(n.getTimezoneOffset())},V=n=>{switch(n){case"noble":case"noble-1":case"florin-1":case"grand-1":return !0;default:return !1}},G=n=>{switch(n){case"ethereum":case"polygon":case"gnosis":case"arbitrum":return !0;default:return !1}},c=n=>{if(typeof n=="number")return w(n);if(V(n))return "noble";if(G(n))return n;try{return w(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},J=(n,e,t,r)=>{let s=`${e?.toUpperCase()||"EUR"}`;return r?`Send ${s} ${n} to ${t} on ${c(r)} at ${x(new Date)}`:s==="EUR"?`Send ${s} ${n} to ${O(t)} at ${x(new Date)}`:`Send ${s} ${n} to ${t} at ${x(new Date)}`},m=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",w=n=>{switch(n){case 1:case 11155111:return "ethereum";case 100:case 10200:return "gnosis";case 137:case 80002:return "polygon";case 42161:case 421614:return "arbitrum";default:throw new Error(`Chain not supported: ${n}`)}},O=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var C=n=>{if(n?.chain){let{chain:e,...t}=n;return {...t,chain:c(e)}}return n};var X=(n,e)=>{let{client_id:t,redirect_uri:r,scope:s,state:i,address:d,signature:o,chain:l,skip_create_account:a,skip_kyc:h}=n,T=d?{address:d,...o!==void 0?{signature:o}:{},...l!==void 0?{chain:c(l)}:{}}:{};return m({client_id:t,redirect_uri:r,...s!==void 0?{scope:s}:{},...i!==void 0?{state:i}:{},...a!==void 0?{skip_create_account:a}:{},...h!==void 0?{skip_kyc:h}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...T})},Z=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,r=0;for(;r<128;)n+=e.charAt(Math.floor(Math.random()*t)),r+=1;return n},Y=n=>W__default.default.stringify(H__default.default(n)),I=(n,e)=>{let t=Z(),r=Y(t);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,t||""),`${n}/auth?${X(e,r)}`},k=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,t]=n.split("?");t&&window.history.replaceState(null,"",e);},R=n=>n.code!=null,v=n=>n.refresh_token!=null,N=n=>n.client_secret!=null;var _=async(n,e,t,r)=>{let s=await fetch(`${n}`,{method:e,headers:r,body:t}),i,d=await s.text();try{if(i=JSON.parse(d),Object.keys(i).length===0&&i.constructor===Object)switch(s.status){case 201:case 202:return {status:s.status,statusText:s.statusText}}}catch{throw d}if(!s.ok)throw i;return i};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([t,r])=>r!==""&&r!==void 0&&r!==null).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`).join("&");return e?"?"+e:""};var $=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var S=n=>Object.entries(n).filter(([t,r])=>r!=null).map(([t,r])=>`${t}-${r}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",b=class{#r;#i;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#t=()=>{};#s;state;constructor(e){if(!e){this.#r=P.environments.sandbox;return}if(typeof e=="string")this.#r=P.environments[e];else if(this.#t=$(e.debug??!1),this.#r=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:t,redirectUri:r}=e;this.#s={clientId:t,redirectUri:r};}else {this.#t("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:t,clientSecret:r}=e;this.#s={clientId:t,clientSecret:r};}}async authorize(e){let t=e?.clientId||this.#s?.clientId,r=e?.redirectUri||this.#s?.redirectUri;if(!t)throw new Error("Missing ClientId");let s=I(this.#r.api,{client_id:t,redirect_uri:r,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#t(`Authorization URL: ${s}`),window.location.assign(s);}async getAccess(e){let t=this.#s?.clientId;if(this.#s?.clientSecret){if(u)return await this.#d(this.#s),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let s=this.#s?.redirectUri;if(!t)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let i=new URLSearchParams(window.location.search).get("code")||void 0,d=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),l=window.localStorage.getItem(g);if(i)return this.#t("Using auth code from auth flow to authorize"),await this.#a(t,s,i,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(o&&l){let a=new Date;if(parseInt(l)<a.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,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 ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#t("Authorized"),!0}catch{throw this.#t("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let t;if(R(e))t={...e,grant_type:"authorization_code"};else if(v(e))t={...e,grant_type:"refresh_token"};else if(N(e))t={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#e("post","auth/token",t,!0).then(r=>{if(this.bearerProfile=r,this.isAuthorized=!!r,this.#i=`Bearer ${r?.access_token}`,!u){let i=new Date().getTime()+r?.expires_in*1e3;window.localStorage.setItem(p,r?.access_token||""),window.localStorage.setItem(g,i?.toString());}}).catch(r=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),k()),new Error(r?.message)}),R(e)&&k(),this.bearerProfile}getProfile(e){return this.#e("get",`profiles/${e}`)}getProfiles(e){return this.#e("get",`profiles${y(e)}`)}getAddress(e){return this.#e("get",`addresses/${e}`)}getAddresses(e){e=C(e);let t=e?m(e):void 0,r=t?`addresses?${t}`:"addresses";return this.#e("get",r)}getBalances(e,t,r){let s=Array.isArray(r)?r.map(i=>`currency=${i}`).join("&"):r?`currency=${r}`:"";return this.#e("get",`balances/${c(t)}/${e}${s?`?${s}`:""}`)}getIban(e){return this.#e("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:t,chain:r}=e||{},s=y({profile:t,chain:r?c(r):""});return this.#e("get",`ibans${s}`)}getOrders(e){return this.#e("get",`orders${y(e)}`)}getOrder(e){return this.#e("get",`orders/${e}`)}getTokens(){return this.#e("get","tokens")}linkAddress(e){return e=C(e),this.#e("post","addresses",JSON.stringify(e))}placeOrder(e){let t={kind:"redeem",...C(e),counterpart:{...e.counterpart,identifier:C(e.counterpart.identifier)}};return this.#e("post","orders",JSON.stringify(t))}moveIban(e,{address:t,chain:r}){return this.#e("patch",`ibans/${e}`,JSON.stringify({address:t,chain:c(r)}))}requestIban({address:e,chain:t,emailNotifications:r=!0}){return this.#e("post","ibans",JSON.stringify({address:e,chain:c(t),emailNotifications:r}))}submitProfileDetails(e,t){return this.#e("put",`profiles/${e}/details`,JSON.stringify(t))}uploadSupportingDocument(e){let t=new FormData;return t.append("file",e),_(`${this.#r.api}/files`,"post",t,{Authorization:this.#i||""})}async#e(e,t,r,s){let i={Authorization:this.#i||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${s?"x-www-form-urlencoded":"json"}`};return _(`${this.#r.api}/${t}`,e.toUpperCase(),s?m(r):r,i)}#a=async(e,t,r,s)=>{let i=localStorage.getItem(A)||"";if(!i)throw new Error("Code verifier not found");return this.#t("Use code verifier to authorize"),this.state=s,localStorage.removeItem(A),await this.#o({code:r,redirect_uri:t,client_id:e,code_verifier:i})};#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:r}={}){if(!this.bearerProfile?.access_token)return;let{profile:s,state:i}=e||{},d=y({access_token:this.bearerProfile?.access_token,profile:s,state:i}),o,l=S({profile:s,state:i});if(this.#n?.has(l))o=this.#n.get(l);else {let a=`${this.#r.wss}/orders${d}`;o=new WebSocket(a),this.#n?.set(l,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=a=>{let h=JSON.parse(a.data);t&&t(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(d);},o.onerror=a=>{r&&r(a),console.error("WebSocket error:",a);},o}unsubscribeOrderNotifications(e){if(e){let t=S({profile:e?.profile,state:e?.state}),r=this.#n?.get(t);r&&(r.close(),this.#n?.delete(t));}else this.#n?.forEach(t=>{t?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#i=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#r;getAuthFlowURI=e=>I(this.#r.api,e)};var Ee=b;
|
|
13
|
+
var P={environments:{production:{name:"production",api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},sandbox:{name:"sandbox",api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev",wss:"wss://api.monerium.dev"}}};var f={LINK_MESSAGE:"I hereby declare that I am the address owner.",STORAGE_CODE_VERIFIER:"monerium.sdk.code_verifier",STORAGE_ACCESS_TOKEN:"monerium.sdk.access_token",STORAGE_ACCESS_EXPIRY:"monerium.sdk.access_expiry"};var O=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(O||{}),z=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(z||{}),q=(r=>(r.corporate="corporate",r.personal="personal",r))(q||{}),j=(r=>(r.read="read",r.write="write",r))(j||{}),M=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(M||{}),F=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(F||{}),K=(t=>(t.approved="approved",t.rejected="rejected",t.unknown="unknown",t))(K||{}),L=(t=>(t.requested="requested",t.approved="approved",t.pending="pending",t))(L||{}),Q=(t=>(t.iban="iban",t.scan="scan",t.chain="chain",t))(Q||{}),V=(t=>(t.passport="passport",t.nationalIdentityCard="nationalIdentityCard",t.drivingLicense="drivingLicense",t))(V||{}),G=(r=>(r.redeem="redeem",r.issue="issue",r))(G||{}),J=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(J||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=t=>t<10?"0"+t:t,r=t=>{if(t===0)return "Z";let i=t>0?"-":"+";return t=Math.abs(t),i+e(Math.floor(t/60))+":"+e(t%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+r(n.getTimezoneOffset())},W=n=>{switch(n){case"noble":case"noble-1":case"grand":case"grand-1":return !0;default:return !1}},H=n=>{switch(n){case"ethereum":case"sepolia":case"polygon":case"amoy":case"gnosis":case"chiado":case"arbitrum":case"arbitrumsepolia":case"linea":case"lineasepolia":return !0;default:return !1}},b=n=>{if(typeof n=="number")return I(n);if(W(n))return n.split("-")[0];if(H(n))return n;try{return I(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},m=(n,e)=>b($(e,n)),X=(n,e,r,t)=>{let i=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${r} on ${b(t)} at ${x(new Date)}`:i==="EUR"?`Send ${i} ${n} to ${N(r)} at ${x(new Date)}`:`Send ${i} ${n} to ${r} at ${x(new Date)}`},C=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,r])=>r!==void 0).map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"):"",I=n=>{switch(n){case 1:return "ethereum";case 11155111:return "sepolia";case 100:return "gnosis";case 10200:return "chiado";case 137:return "polygon";case 80002:return "amoy";case 42161:return "arbitrum";case 421614:return "arbitrumsepolia";case 59144:return "linea";case 59141:return "lineasepolia";default:throw new Error(`Chain not supported: ${n}`)}},N=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var $=(n,e)=>{if(e==="sandbox")switch(n){case"ethereum":return "sepolia";case"polygon":return "amoy";case"gnosis":return "chiado";case"arbitrum":return "arbitrumsepolia";case"noble":return "grand";default:return n}return n},l=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:b($(r,n))}}return e};var ee=(n,e)=>{let{client_id:r,redirect_uri:t,scope:i,state:s,address:a,signature:o,chain:c,email:d,skip_create_account:h,skip_kyc:v}=n,U=a?{address:a,...o!==void 0?{signature:o}:{},...c!==void 0?{chain:c}:{}}:{};return C({client_id:r,redirect_uri:t,...i!==void 0?{scope:i}:{},...d!==void 0?{email:d}:{},...s!==void 0?{state:s}:{},...h!==void 0?{skip_create_account:h}:{},...v!==void 0?{skip_kyc:v}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...U})},te=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=e.length,t=0;for(;t<128;)n+=e.charAt(Math.floor(Math.random()*r)),t+=1;return n},re=n=>Z__default.default.stringify(Y__default.default(n)),k=(n,e)=>{let r=te(),t=re(r);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,r||""),`${n.api}/auth?${ee(l(n.name,e),t)}`},R=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,r]=n.split("?");r&&window.history.replaceState(null,"",e);},_=n=>n.code!=null,T=n=>n.refresh_token!=null,B=n=>n.client_secret!=null;var S=async(n,e,r,t)=>{let i=await fetch(`${n}`,{method:e,headers:t,body:r}),s,a=await i.text();try{if(s=JSON.parse(a),Object.keys(s).length===0&&s.constructor===Object)switch(i.status){case 201:case 202:return {status:i.status,statusText:i.statusText}}}catch{throw a}if(!i.ok)throw s;return s};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([r,t])=>t!==""&&t!==void 0&&t!==null).map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&");return e?"?"+e:""};var D=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var E=n=>Object.entries(n).filter(([r,t])=>t!=null).map(([r,t])=>`${r}-${t}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",w=class{#e;#s;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#r=()=>{};#i;state;constructor(e){if(!e){this.#e=P.environments.sandbox;return}if(typeof e=="string")this.#e=P.environments[e];else if(this.#r=D(e.debug??!1),this.#e=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#i={clientId:r,redirectUri:t};}else {this.#r("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:r,clientSecret:t}=e;this.#i={clientId:r,clientSecret:t};}}async authorize(e){let r=e?.clientId||this.#i?.clientId,t=e?.redirectUri||this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");let i=k(this.#e,{client_id:r,redirect_uri:t,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,email:e?.email,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#r(`Authorization URL: ${i}`),window.location.assign(i);}async getAccess(e){let r=this.#i?.clientId;if(this.#i?.clientSecret){if(u)return await this.#d(this.#i),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let i=this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||void 0,a=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),c=window.localStorage.getItem(g);if(s)return this.#r("Using auth code from auth flow to authorize"),await this.#a(r,i,s,a),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#r("Using refresh token to authorize"),await this.#c(r,e),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(o&&c){let d=new Date;if(parseInt(c)<d.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token has expired");this.#r("Access token should still be valid, checking if it is authorized...");try{return this.#s=`Bearer ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#r("Authorized"),!0}catch{throw this.#r("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let r;if(_(e))r={...e,grant_type:"authorization_code"};else if(T(e))r={...e,grant_type:"refresh_token"};else if(B(e))r={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#t("post","auth/token",r,!0).then(t=>{if(this.bearerProfile=t,this.isAuthorized=!!t,this.#s=`Bearer ${t?.access_token}`,!u){let s=new Date().getTime()+t?.expires_in*1e3;window.localStorage.setItem(p,t?.access_token||""),window.localStorage.setItem(g,s?.toString());}}).catch(t=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),R()),new Error(t?.message)}),_(e)&&R(),this.bearerProfile}getProfile(e){return this.#t("get",`profiles/${e}`)}getProfiles(e){return this.#t("get",`profiles${y(e)}`)}getAddress(e){return this.#t("get",`addresses/${e}`)}getAddresses(e){e=l(this.#e.name,e);let r=e?C(e):void 0,t=r?`addresses?${r}`:"addresses";return this.#t("get",t)}getBalances(e,r,t){let i=Array.isArray(t)?t.map(a=>`currency=${a}`).join("&"):t?`currency=${t}`:"",s=m(this.#e.name,r);return this.#t("get",`balances/${s}/${e}${i?`?${i}`:""}`)}getIban(e){return this.#t("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:r,chain:t}=e||{},i=y({profile:r,chain:t?m(this.#e.name,t):""});return this.#t("get",`ibans${i}`)}getOrders(e){return this.#t("get",`orders${y(e)}`)}getOrder(e){return this.#t("get",`orders/${e}`)}getTokens(){return this.#t("get","tokens")}linkAddress(e){return e=l(this.#e.name,e),this.#t("post","addresses",JSON.stringify(e))}placeOrder(e){let r={kind:"redeem",...l(this.#e.name,e),counterpart:{...e.counterpart,identifier:l(this.#e.name,e.counterpart.identifier)}};return this.#t("post","orders",JSON.stringify(r))}moveIban(e,{address:r,chain:t}){return this.#t("patch",`ibans/${e}`,JSON.stringify({address:r,chain:m(this.#e.name,t)}))}requestIban({address:e,chain:r,emailNotifications:t=!0}){return this.#t("post","ibans",JSON.stringify({address:e,chain:m(this.#e.name,r),emailNotifications:t}))}submitProfileDetails(e,r){return this.#t("put",`profiles/${e}/details`,JSON.stringify(r))}uploadSupportingDocument(e){let r=new FormData;return r.append("file",e),S(`${this.#e.api}/files`,"post",r,{Authorization:this.#s||""})}async#t(e,r,t,i){let s={Authorization:this.#s||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`};return S(`${this.#e.api}/${r}`,e.toUpperCase(),i?C(t):t,s)}#a=async(e,r,t,i)=>{let s=localStorage.getItem(A)||"";if(!s)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=i,localStorage.removeItem(A),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:r})=>await this.#o({client_id:e,client_secret:r});#c=async(e,r)=>await this.#o({refresh_token:r,client_id:e});subscribeOrderNotifications({filter:e,onMessage:r,onError:t}={}){if(!this.bearerProfile?.access_token)return;let{profile:i,state:s}=e||{},a=y({access_token:this.bearerProfile?.access_token,profile:i,state:s}),o,c=E({profile:i,state:s});if(this.#n?.has(c))o=this.#n.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#n?.set(c,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=d=>{let h=JSON.parse(d.data);r&&r(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(a);},o.onerror=d=>{t&&t(d),console.error("WebSocket error:",d);},o}unsubscribeOrderNotifications(e){if(e){let r=E({profile:e?.profile,state:e?.state}),t=this.#n?.get(r);t&&(t.close(),this.#n?.delete(r));}else this.#n?.forEach(r=>{r?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#s=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e;getAuthFlowURI=e=>k(this.#e,l(this.#e.name,e))};var $e=w;
|
|
14
14
|
|
|
15
|
-
exports.AccountState =
|
|
16
|
-
exports.Currency =
|
|
17
|
-
exports.IdDocumentKind =
|
|
18
|
-
exports.KYCOutcome =
|
|
19
|
-
exports.KYCState =
|
|
20
|
-
exports.Method =
|
|
21
|
-
exports.MoneriumClient =
|
|
22
|
-
exports.OrderKind =
|
|
23
|
-
exports.OrderState =
|
|
24
|
-
exports.PaymentStandard =
|
|
25
|
-
exports.Permission =
|
|
26
|
-
exports.ProfileState =
|
|
27
|
-
exports.ProfileType =
|
|
15
|
+
exports.AccountState = L;
|
|
16
|
+
exports.Currency = O;
|
|
17
|
+
exports.IdDocumentKind = V;
|
|
18
|
+
exports.KYCOutcome = K;
|
|
19
|
+
exports.KYCState = F;
|
|
20
|
+
exports.Method = z;
|
|
21
|
+
exports.MoneriumClient = w;
|
|
22
|
+
exports.OrderKind = G;
|
|
23
|
+
exports.OrderState = J;
|
|
24
|
+
exports.PaymentStandard = Q;
|
|
25
|
+
exports.Permission = j;
|
|
26
|
+
exports.ProfileState = M;
|
|
27
|
+
exports.ProfileType = q;
|
|
28
28
|
exports.constants = f;
|
|
29
|
-
exports.default =
|
|
30
|
-
exports.getChain =
|
|
31
|
-
exports.parseChain =
|
|
32
|
-
exports.placeOrderMessage =
|
|
29
|
+
exports.default = $e;
|
|
30
|
+
exports.getChain = I;
|
|
31
|
+
exports.parseChain = b;
|
|
32
|
+
exports.placeOrderMessage = X;
|
|
33
33
|
exports.rfc3339 = x;
|
|
34
|
-
exports.shortenIban =
|
|
34
|
+
exports.shortenIban = N;
|
package/dist/index.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import
|
|
2
|
-
import
|
|
1
|
+
import Z from 'crypto-js/enc-base64url.js';
|
|
2
|
+
import Y from 'crypto-js/sha256.js';
|
|
3
3
|
|
|
4
|
-
var P={environments:{production:{api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},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 E=(s=>(s.eur="eur",s.usd="usd",s.gbp="gbp",s.isk="isk",s))(E||{}),B=(s=>(s.password="password",s.resource="resource",s.jwt="jwt",s.apiKey="apiKey",s))(B||{}),D=(t=>(t.corporate="corporate",t.personal="personal",t))(D||{}),U=(t=>(t.read="read",t.write="write",t))(U||{}),z=(i=>(i.created="created",i.pending="pending",i.approved="approved",i.rejected="rejected",i.blocked="blocked",i))(z||{}),q=(s=>(s.absent="absent",s.submitted="submitted",s.pending="pending",s.confirmed="confirmed",s))(q||{}),j=(r=>(r.approved="approved",r.rejected="rejected",r.unknown="unknown",r))(j||{}),M=(r=>(r.requested="requested",r.approved="approved",r.pending="pending",r))(M||{}),F=(r=>(r.iban="iban",r.scan="scan",r.chain="chain",r))(F||{}),K=(r=>(r.passport="passport",r.nationalIdentityCard="nationalIdentityCard",r.drivingLicense="drivingLicense",r))(K||{}),L=(t=>(t.redeem="redeem",t.issue="issue",t))(L||{}),Q=(s=>(s.placed="placed",s.pending="pending",s.processed="processed",s.rejected="rejected",s))(Q||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=r=>r<10?"0"+r:r,t=r=>{if(r===0)return "Z";let s=r>0?"-":"+";return r=Math.abs(r),s+e(Math.floor(r/60))+":"+e(r%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+t(n.getTimezoneOffset())},V=n=>{switch(n){case"noble":case"noble-1":case"florin-1":case"grand-1":return !0;default:return !1}},G=n=>{switch(n){case"ethereum":case"polygon":case"gnosis":case"arbitrum":return !0;default:return !1}},c=n=>{if(typeof n=="number")return w(n);if(V(n))return "noble";if(G(n))return n;try{return w(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},J=(n,e,t,r)=>{let s=`${e?.toUpperCase()||"EUR"}`;return r?`Send ${s} ${n} to ${t} on ${c(r)} at ${x(new Date)}`:s==="EUR"?`Send ${s} ${n} to ${O(t)} at ${x(new Date)}`:`Send ${s} ${n} to ${t} at ${x(new Date)}`},m=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",w=n=>{switch(n){case 1:case 11155111:return "ethereum";case 100:case 10200:return "gnosis";case 137:case 80002:return "polygon";case 42161:case 421614:return "arbitrum";default:throw new Error(`Chain not supported: ${n}`)}},O=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var C=n=>{if(n?.chain){let{chain:e,...t}=n;return {...t,chain:c(e)}}return n};var X=(n,e)=>{let{client_id:t,redirect_uri:r,scope:s,state:i,address:d,signature:o,chain:l,skip_create_account:a,skip_kyc:h}=n,T=d?{address:d,...o!==void 0?{signature:o}:{},...l!==void 0?{chain:c(l)}:{}}:{};return m({client_id:t,redirect_uri:r,...s!==void 0?{scope:s}:{},...i!==void 0?{state:i}:{},...a!==void 0?{skip_create_account:a}:{},...h!==void 0?{skip_kyc:h}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...T})},Z=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,r=0;for(;r<128;)n+=e.charAt(Math.floor(Math.random()*t)),r+=1;return n},Y=n=>W.stringify(H(n)),I=(n,e)=>{let t=Z(),r=Y(t);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,t||""),`${n}/auth?${X(e,r)}`},k=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,t]=n.split("?");t&&window.history.replaceState(null,"",e);},R=n=>n.code!=null,v=n=>n.refresh_token!=null,N=n=>n.client_secret!=null;var _=async(n,e,t,r)=>{let s=await fetch(`${n}`,{method:e,headers:r,body:t}),i,d=await s.text();try{if(i=JSON.parse(d),Object.keys(i).length===0&&i.constructor===Object)switch(s.status){case 201:case 202:return {status:s.status,statusText:s.statusText}}}catch{throw d}if(!s.ok)throw i;return i};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([t,r])=>r!==""&&r!==void 0&&r!==null).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`).join("&");return e?"?"+e:""};var $=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var S=n=>Object.entries(n).filter(([t,r])=>r!=null).map(([t,r])=>`${t}-${r}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",b=class{#r;#i;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#t=()=>{};#s;state;constructor(e){if(!e){this.#r=P.environments.sandbox;return}if(typeof e=="string")this.#r=P.environments[e];else if(this.#t=$(e.debug??!1),this.#r=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:t,redirectUri:r}=e;this.#s={clientId:t,redirectUri:r};}else {this.#t("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:t,clientSecret:r}=e;this.#s={clientId:t,clientSecret:r};}}async authorize(e){let t=e?.clientId||this.#s?.clientId,r=e?.redirectUri||this.#s?.redirectUri;if(!t)throw new Error("Missing ClientId");let s=I(this.#r.api,{client_id:t,redirect_uri:r,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#t(`Authorization URL: ${s}`),window.location.assign(s);}async getAccess(e){let t=this.#s?.clientId;if(this.#s?.clientSecret){if(u)return await this.#d(this.#s),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let s=this.#s?.redirectUri;if(!t)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let i=new URLSearchParams(window.location.search).get("code")||void 0,d=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),l=window.localStorage.getItem(g);if(i)return this.#t("Using auth code from auth flow to authorize"),await this.#a(t,s,i,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(o&&l){let a=new Date;if(parseInt(l)<a.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,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 ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#t("Authorized"),!0}catch{throw this.#t("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let t;if(R(e))t={...e,grant_type:"authorization_code"};else if(v(e))t={...e,grant_type:"refresh_token"};else if(N(e))t={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#e("post","auth/token",t,!0).then(r=>{if(this.bearerProfile=r,this.isAuthorized=!!r,this.#i=`Bearer ${r?.access_token}`,!u){let i=new Date().getTime()+r?.expires_in*1e3;window.localStorage.setItem(p,r?.access_token||""),window.localStorage.setItem(g,i?.toString());}}).catch(r=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),k()),new Error(r?.message)}),R(e)&&k(),this.bearerProfile}getProfile(e){return this.#e("get",`profiles/${e}`)}getProfiles(e){return this.#e("get",`profiles${y(e)}`)}getAddress(e){return this.#e("get",`addresses/${e}`)}getAddresses(e){e=C(e);let t=e?m(e):void 0,r=t?`addresses?${t}`:"addresses";return this.#e("get",r)}getBalances(e,t,r){let s=Array.isArray(r)?r.map(i=>`currency=${i}`).join("&"):r?`currency=${r}`:"";return this.#e("get",`balances/${c(t)}/${e}${s?`?${s}`:""}`)}getIban(e){return this.#e("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:t,chain:r}=e||{},s=y({profile:t,chain:r?c(r):""});return this.#e("get",`ibans${s}`)}getOrders(e){return this.#e("get",`orders${y(e)}`)}getOrder(e){return this.#e("get",`orders/${e}`)}getTokens(){return this.#e("get","tokens")}linkAddress(e){return e=C(e),this.#e("post","addresses",JSON.stringify(e))}placeOrder(e){let t={kind:"redeem",...C(e),counterpart:{...e.counterpart,identifier:C(e.counterpart.identifier)}};return this.#e("post","orders",JSON.stringify(t))}moveIban(e,{address:t,chain:r}){return this.#e("patch",`ibans/${e}`,JSON.stringify({address:t,chain:c(r)}))}requestIban({address:e,chain:t,emailNotifications:r=!0}){return this.#e("post","ibans",JSON.stringify({address:e,chain:c(t),emailNotifications:r}))}submitProfileDetails(e,t){return this.#e("put",`profiles/${e}/details`,JSON.stringify(t))}uploadSupportingDocument(e){let t=new FormData;return t.append("file",e),_(`${this.#r.api}/files`,"post",t,{Authorization:this.#i||""})}async#e(e,t,r,s){let i={Authorization:this.#i||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${s?"x-www-form-urlencoded":"json"}`};return _(`${this.#r.api}/${t}`,e.toUpperCase(),s?m(r):r,i)}#a=async(e,t,r,s)=>{let i=localStorage.getItem(A)||"";if(!i)throw new Error("Code verifier not found");return this.#t("Use code verifier to authorize"),this.state=s,localStorage.removeItem(A),await this.#o({code:r,redirect_uri:t,client_id:e,code_verifier:i})};#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:r}={}){if(!this.bearerProfile?.access_token)return;let{profile:s,state:i}=e||{},d=y({access_token:this.bearerProfile?.access_token,profile:s,state:i}),o,l=S({profile:s,state:i});if(this.#n?.has(l))o=this.#n.get(l);else {let a=`${this.#r.wss}/orders${d}`;o=new WebSocket(a),this.#n?.set(l,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=a=>{let h=JSON.parse(a.data);t&&t(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(d);},o.onerror=a=>{r&&r(a),console.error("WebSocket error:",a);},o}unsubscribeOrderNotifications(e){if(e){let t=S({profile:e?.profile,state:e?.state}),r=this.#n?.get(t);r&&(r.close(),this.#n?.delete(t));}else this.#n?.forEach(t=>{t?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#i=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#r;getAuthFlowURI=e=>I(this.#r.api,e)};var Ee=b;
|
|
4
|
+
var P={environments:{production:{name:"production",api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},sandbox:{name:"sandbox",api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev",wss:"wss://api.monerium.dev"}}};var f={LINK_MESSAGE:"I hereby declare that I am the address owner.",STORAGE_CODE_VERIFIER:"monerium.sdk.code_verifier",STORAGE_ACCESS_TOKEN:"monerium.sdk.access_token",STORAGE_ACCESS_EXPIRY:"monerium.sdk.access_expiry"};var O=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(O||{}),z=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(z||{}),q=(r=>(r.corporate="corporate",r.personal="personal",r))(q||{}),j=(r=>(r.read="read",r.write="write",r))(j||{}),M=(s=>(s.created="created",s.pending="pending",s.approved="approved",s.rejected="rejected",s.blocked="blocked",s))(M||{}),F=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(F||{}),K=(t=>(t.approved="approved",t.rejected="rejected",t.unknown="unknown",t))(K||{}),L=(t=>(t.requested="requested",t.approved="approved",t.pending="pending",t))(L||{}),Q=(t=>(t.iban="iban",t.scan="scan",t.chain="chain",t))(Q||{}),V=(t=>(t.passport="passport",t.nationalIdentityCard="nationalIdentityCard",t.drivingLicense="drivingLicense",t))(V||{}),G=(r=>(r.redeem="redeem",r.issue="issue",r))(G||{}),J=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(J||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=t=>t<10?"0"+t:t,r=t=>{if(t===0)return "Z";let i=t>0?"-":"+";return t=Math.abs(t),i+e(Math.floor(t/60))+":"+e(t%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+r(n.getTimezoneOffset())},W=n=>{switch(n){case"noble":case"noble-1":case"grand":case"grand-1":return !0;default:return !1}},H=n=>{switch(n){case"ethereum":case"sepolia":case"polygon":case"amoy":case"gnosis":case"chiado":case"arbitrum":case"arbitrumsepolia":case"linea":case"lineasepolia":return !0;default:return !1}},b=n=>{if(typeof n=="number")return I(n);if(W(n))return n.split("-")[0];if(H(n))return n;try{return I(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},m=(n,e)=>b($(e,n)),X=(n,e,r,t)=>{let i=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${r} on ${b(t)} at ${x(new Date)}`:i==="EUR"?`Send ${i} ${n} to ${N(r)} at ${x(new Date)}`:`Send ${i} ${n} to ${r} at ${x(new Date)}`},C=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,r])=>r!==void 0).map(([e,r])=>`${encodeURIComponent(e)}=${encodeURIComponent(r)}`).join("&"):"",I=n=>{switch(n){case 1:return "ethereum";case 11155111:return "sepolia";case 100:return "gnosis";case 10200:return "chiado";case 137:return "polygon";case 80002:return "amoy";case 42161:return "arbitrum";case 421614:return "arbitrumsepolia";case 59144:return "linea";case 59141:return "lineasepolia";default:throw new Error(`Chain not supported: ${n}`)}},N=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var $=(n,e)=>{if(e==="sandbox")switch(n){case"ethereum":return "sepolia";case"polygon":return "amoy";case"gnosis":return "chiado";case"arbitrum":return "arbitrumsepolia";case"noble":return "grand";default:return n}return n},l=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:b($(r,n))}}return e};var ee=(n,e)=>{let{client_id:r,redirect_uri:t,scope:i,state:s,address:a,signature:o,chain:c,email:d,skip_create_account:h,skip_kyc:v}=n,U=a?{address:a,...o!==void 0?{signature:o}:{},...c!==void 0?{chain:c}:{}}:{};return C({client_id:r,redirect_uri:t,...i!==void 0?{scope:i}:{},...d!==void 0?{email:d}:{},...s!==void 0?{state:s}:{},...h!==void 0?{skip_create_account:h}:{},...v!==void 0?{skip_kyc:v}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...U})},te=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=e.length,t=0;for(;t<128;)n+=e.charAt(Math.floor(Math.random()*r)),t+=1;return n},re=n=>Z.stringify(Y(n)),k=(n,e)=>{let r=te(),t=re(r);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,r||""),`${n.api}/auth?${ee(l(n.name,e),t)}`},R=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,r]=n.split("?");r&&window.history.replaceState(null,"",e);},_=n=>n.code!=null,T=n=>n.refresh_token!=null,B=n=>n.client_secret!=null;var S=async(n,e,r,t)=>{let i=await fetch(`${n}`,{method:e,headers:t,body:r}),s,a=await i.text();try{if(s=JSON.parse(a),Object.keys(s).length===0&&s.constructor===Object)switch(i.status){case 201:case 202:return {status:i.status,statusText:i.statusText}}}catch{throw a}if(!i.ok)throw s;return s};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([r,t])=>t!==""&&t!==void 0&&t!==null).map(([r,t])=>`${encodeURIComponent(r)}=${encodeURIComponent(t)}`).join("&");return e?"?"+e:""};var D=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var E=n=>Object.entries(n).filter(([r,t])=>t!=null).map(([r,t])=>`${r}-${t}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",w=class{#e;#s;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#r=()=>{};#i;state;constructor(e){if(!e){this.#e=P.environments.sandbox;return}if(typeof e=="string")this.#e=P.environments[e];else if(this.#r=D(e.debug??!1),this.#e=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:r,redirectUri:t}=e;this.#i={clientId:r,redirectUri:t};}else {this.#r("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:r,clientSecret:t}=e;this.#i={clientId:r,clientSecret:t};}}async authorize(e){let r=e?.clientId||this.#i?.clientId,t=e?.redirectUri||this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");let i=k(this.#e,{client_id:r,redirect_uri:t,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,email:e?.email,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#r(`Authorization URL: ${i}`),window.location.assign(i);}async getAccess(e){let r=this.#i?.clientId;if(this.#i?.clientSecret){if(u)return await this.#d(this.#i),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let i=this.#i?.redirectUri;if(!r)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||void 0,a=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),c=window.localStorage.getItem(g);if(s)return this.#r("Using auth code from auth flow to authorize"),await this.#a(r,i,s,a),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#r("Using refresh token to authorize"),await this.#c(r,e),this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(o&&c){let d=new Date;if(parseInt(c)<d.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token has expired");this.#r("Access token should still be valid, checking if it is authorized...");try{return this.#s=`Bearer ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#r("Authorized"),!0}catch{throw this.#r("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#r(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let r;if(_(e))r={...e,grant_type:"authorization_code"};else if(T(e))r={...e,grant_type:"refresh_token"};else if(B(e))r={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#t("post","auth/token",r,!0).then(t=>{if(this.bearerProfile=t,this.isAuthorized=!!t,this.#s=`Bearer ${t?.access_token}`,!u){let s=new Date().getTime()+t?.expires_in*1e3;window.localStorage.setItem(p,t?.access_token||""),window.localStorage.setItem(g,s?.toString());}}).catch(t=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),R()),new Error(t?.message)}),_(e)&&R(),this.bearerProfile}getProfile(e){return this.#t("get",`profiles/${e}`)}getProfiles(e){return this.#t("get",`profiles${y(e)}`)}getAddress(e){return this.#t("get",`addresses/${e}`)}getAddresses(e){e=l(this.#e.name,e);let r=e?C(e):void 0,t=r?`addresses?${r}`:"addresses";return this.#t("get",t)}getBalances(e,r,t){let i=Array.isArray(t)?t.map(a=>`currency=${a}`).join("&"):t?`currency=${t}`:"",s=m(this.#e.name,r);return this.#t("get",`balances/${s}/${e}${i?`?${i}`:""}`)}getIban(e){return this.#t("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:r,chain:t}=e||{},i=y({profile:r,chain:t?m(this.#e.name,t):""});return this.#t("get",`ibans${i}`)}getOrders(e){return this.#t("get",`orders${y(e)}`)}getOrder(e){return this.#t("get",`orders/${e}`)}getTokens(){return this.#t("get","tokens")}linkAddress(e){return e=l(this.#e.name,e),this.#t("post","addresses",JSON.stringify(e))}placeOrder(e){let r={kind:"redeem",...l(this.#e.name,e),counterpart:{...e.counterpart,identifier:l(this.#e.name,e.counterpart.identifier)}};return this.#t("post","orders",JSON.stringify(r))}moveIban(e,{address:r,chain:t}){return this.#t("patch",`ibans/${e}`,JSON.stringify({address:r,chain:m(this.#e.name,t)}))}requestIban({address:e,chain:r,emailNotifications:t=!0}){return this.#t("post","ibans",JSON.stringify({address:e,chain:m(this.#e.name,r),emailNotifications:t}))}submitProfileDetails(e,r){return this.#t("put",`profiles/${e}/details`,JSON.stringify(r))}uploadSupportingDocument(e){let r=new FormData;return r.append("file",e),S(`${this.#e.api}/files`,"post",r,{Authorization:this.#s||""})}async#t(e,r,t,i){let s={Authorization:this.#s||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`};return S(`${this.#e.api}/${r}`,e.toUpperCase(),i?C(t):t,s)}#a=async(e,r,t,i)=>{let s=localStorage.getItem(A)||"";if(!s)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=i,localStorage.removeItem(A),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:r})=>await this.#o({client_id:e,client_secret:r});#c=async(e,r)=>await this.#o({refresh_token:r,client_id:e});subscribeOrderNotifications({filter:e,onMessage:r,onError:t}={}){if(!this.bearerProfile?.access_token)return;let{profile:i,state:s}=e||{},a=y({access_token:this.bearerProfile?.access_token,profile:i,state:s}),o,c=E({profile:i,state:s});if(this.#n?.has(c))o=this.#n.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#n?.set(c,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=d=>{let h=JSON.parse(d.data);r&&r(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(a);},o.onerror=d=>{t&&t(d),console.error("WebSocket error:",d);},o}unsubscribeOrderNotifications(e){if(e){let r=E({profile:e?.profile,state:e?.state}),t=this.#n?.get(r);t&&(t.close(),this.#n?.delete(r));}else this.#n?.forEach(r=>{r?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#s=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e;getAuthFlowURI=e=>k(this.#e,l(this.#e.name,e))};var $e=w;
|
|
5
5
|
|
|
6
|
-
export {
|
|
6
|
+
export { L as AccountState, O as Currency, V as IdDocumentKind, K as KYCOutcome, F as KYCState, z as Method, w as MoneriumClient, G as OrderKind, J as OrderState, Q as PaymentStandard, j as Permission, M as ProfileState, q as ProfileType, f as constants, $e as default, I as getChain, b as parseChain, X as placeOrderMessage, x as rfc3339, N as shortenIban };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@monerium/sdk",
|
|
3
|
-
"version": "3.0
|
|
3
|
+
"version": "3.2.0",
|
|
4
4
|
"description": "Essential tools to interact with the Monerium API, an electronic money issuer.",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -47,6 +47,7 @@
|
|
|
47
47
|
"lint": "eslint . --fix",
|
|
48
48
|
"pub:pre": "pnpm publish --no-git-checks --dry-run",
|
|
49
49
|
"test": "NODE_OPTIONS=--experimental-vm-modules jest",
|
|
50
|
-
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch"
|
|
50
|
+
"test:watch": "NODE_OPTIONS=--experimental-vm-modules jest --watch",
|
|
51
|
+
"clean": "rm -rf dist node_modules .turbo"
|
|
51
52
|
}
|
|
52
53
|
}
|