@monerium/sdk 3.3.3 → 3.4.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 +14 -8
- package/dist/index.d.ts +30 -5
- package/dist/index.js +4 -4
- package/dist/index.mjs +4 -4
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -74,14 +74,20 @@ yarn add @monerium/sdk
|
|
|
74
74
|
|
|
75
75
|
### Environments - Networks
|
|
76
76
|
|
|
77
|
-
| Environment | Chain |
|
|
78
|
-
| ----------- | -------- |
|
|
79
|
-
| sandbox | ethereum | sepolia
|
|
80
|
-
| | polygon | mumbai
|
|
81
|
-
| | gnosis | chiado
|
|
82
|
-
|
|
|
83
|
-
| |
|
|
84
|
-
| |
|
|
77
|
+
| Environment | Chain | Name |
|
|
78
|
+
| ----------- | -------- | -------- |
|
|
79
|
+
| sandbox | ethereum | sepolia |
|
|
80
|
+
| | polygon | mumbai |
|
|
81
|
+
| | gnosis | chiado |
|
|
82
|
+
| | linea | sepolia |
|
|
83
|
+
| | scroll | sepolia |
|
|
84
|
+
| | camino | columbus |
|
|
85
|
+
| production | ethereum | mainnet |
|
|
86
|
+
| | polygon | mainnet |
|
|
87
|
+
| | gnosis | mainnet |
|
|
88
|
+
| | linea | mainnet |
|
|
89
|
+
| | scroll | mainnet |
|
|
90
|
+
| | camino | mainnet |
|
|
85
91
|
|
|
86
92
|
## Usage Examples
|
|
87
93
|
|
package/dist/index.d.ts
CHANGED
|
@@ -11,10 +11,10 @@ type Config = {
|
|
|
11
11
|
};
|
|
12
12
|
};
|
|
13
13
|
type ENV = 'sandbox' | 'production';
|
|
14
|
-
type SandboxChain = 'sepolia' | 'chiado' | 'amoy' | 'arbitrumsepolia' | 'lineasepolia' | 'grand';
|
|
15
|
-
type ProductionChain = 'ethereum' | 'gnosis' | 'polygon' | 'arbitrum' | 'linea' | 'noble';
|
|
14
|
+
type SandboxChain = 'sepolia' | 'chiado' | 'amoy' | 'arbitrumsepolia' | 'lineasepolia' | 'scrollsepolia' | 'columbus' | 'grand';
|
|
15
|
+
type ProductionChain = 'ethereum' | 'gnosis' | 'polygon' | 'arbitrum' | 'linea' | 'scroll' | 'camino' | 'noble';
|
|
16
16
|
type Chain = string | ProductionChain | SandboxChain;
|
|
17
|
-
type EvmChainId = number | 1 | 11155111 | 100 | 10200 | 137 | 80002 | 42161 | 421614 | 59141 | 59144;
|
|
17
|
+
type EvmChainId = number | 1 | 11155111 | 100 | 10200 | 500 | 501 | 137 | 80002 | 42161 | 421614 | 59141 | 59144 | 534352 | 534351;
|
|
18
18
|
type ChainId = EvmChainId | CosmosChainId;
|
|
19
19
|
type CosmosChainId = 'noble-1' | 'grand-1' | 'florin-1';
|
|
20
20
|
declare enum Currency {
|
|
@@ -119,7 +119,8 @@ declare enum Method {
|
|
|
119
119
|
password = "password",
|
|
120
120
|
resource = "resource",
|
|
121
121
|
jwt = "jwt",
|
|
122
|
-
apiKey = "apiKey"
|
|
122
|
+
apiKey = "apiKey",
|
|
123
|
+
bearer = "bearer"
|
|
123
124
|
}
|
|
124
125
|
declare enum ProfileType {
|
|
125
126
|
corporate = "corporate",
|
|
@@ -179,6 +180,25 @@ interface Identifier {
|
|
|
179
180
|
standard: PaymentStandard;
|
|
180
181
|
bic?: string;
|
|
181
182
|
}
|
|
183
|
+
interface AuthContext {
|
|
184
|
+
userId: string;
|
|
185
|
+
email: string;
|
|
186
|
+
name: string;
|
|
187
|
+
roles: [] | null;
|
|
188
|
+
auth: {
|
|
189
|
+
method: Method;
|
|
190
|
+
subject: string;
|
|
191
|
+
verified: boolean;
|
|
192
|
+
invited?: boolean;
|
|
193
|
+
};
|
|
194
|
+
defaultProfile: string;
|
|
195
|
+
profiles: {
|
|
196
|
+
id: string;
|
|
197
|
+
kind: ProfileType | 'unknown';
|
|
198
|
+
name: string;
|
|
199
|
+
perms: Permission[];
|
|
200
|
+
}[];
|
|
201
|
+
}
|
|
182
202
|
interface ProfilesResponse {
|
|
183
203
|
profiles: Profile[];
|
|
184
204
|
}
|
|
@@ -598,6 +618,11 @@ declare class MoneriumClient {
|
|
|
598
618
|
* ```
|
|
599
619
|
*/
|
|
600
620
|
getAccess(refreshToken?: string): Promise<boolean>;
|
|
621
|
+
/**
|
|
622
|
+
* @group Authentication
|
|
623
|
+
* @see {@link https://monerium.dev/api-docs/v2#tag/auth/operation/auth-context | API Documentation}
|
|
624
|
+
*/
|
|
625
|
+
getAuthContext(): Promise<AuthContext>;
|
|
601
626
|
/**
|
|
602
627
|
* @group Profiles
|
|
603
628
|
* @param {string} profile - the id of the profile to fetch.
|
|
@@ -862,4 +887,4 @@ declare const shortenIban: (iban?: string) => string | undefined;
|
|
|
862
887
|
* ```
|
|
863
888
|
*/
|
|
864
889
|
|
|
865
|
-
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 };
|
|
890
|
+
export { AccountState, type Address, type AddressesQueryParams, type AddressesResponse, type AuthArgs, type AuthCodePayload, type AuthContext, 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,15 +1,15 @@
|
|
|
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
|
|
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 s=await fetch(`${n}`,{method:e,headers:t,body:r}),i,a=await s.text();try{if(i=JSON.parse(a),Object.keys(i).length===0&&i.constructor===Object)switch(s.status){case 201:case 202:return {status:s.status,statusText:s.statusText}}}catch{throw a}if(!s.ok)throw i;return i};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=(s=>(s.eur="eur",s.usd="usd",s.gbp="gbp",s.isk="isk",s))(B||{}),j=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i.bearer="bearer",i))(j||{}),F=(r=>(r.corporate="corporate",r.personal="personal",r))(F||{}),M=(r=>(r.read="read",r.write="write",r))(M||{}),K=(i=>(i.created="created",i.pending="pending",i.approved="approved",i.rejected="rejected",i.blocked="blocked",i))(K||{}),W=(s=>(s.absent="absent",s.submitted="submitted",s.pending="pending",s.confirmed="confirmed",s))(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=(s=>(s.placed="placed",s.pending="pending",s.processed="processed",s.rejected="rejected",s))(H||{});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 s=t>0?"-":"+";return t=Math.abs(t),s+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":case "scroll":case "scrollsepolia":case "camino":case "columbus":return true;default:return false}},P=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)=>P(D(e,n)),Y=(n,e,r,t)=>{let s=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${s} ${n} to ${r} on ${P(t)} at ${x(new Date)}`:s==="EUR"?`Send ${s} ${n} to ${T(r)} at ${x(new Date)}`:`Send ${s} ${n} to ${r} at ${x(new Date)}`},ee=({domain:n,address:e,appName:r,redirectUri:t,chainId:s,issuedAt:i=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
2
|
${e}
|
|
3
3
|
|
|
4
4
|
Allow ${r} to access my data on Monerium
|
|
5
5
|
|
|
6
6
|
URI: ${t}
|
|
7
7
|
Version: 1
|
|
8
|
-
Chain ID: ${
|
|
8
|
+
Chain ID: ${s}
|
|
9
9
|
Nonce: ${I().slice(0,16)}
|
|
10
|
-
Issued At: ${
|
|
10
|
+
Issued At: ${i}
|
|
11
11
|
Expiration Time: ${a}
|
|
12
12
|
Resources:
|
|
13
13
|
- https://monerium.com/siwe
|
|
14
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:P(D(r,n))}}return e};var {STORAGE_CODE_VERIFIER:
|
|
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";case 534352:return "scroll";case 534351:return "scrollsepolia";case 501:return "columbus";case 500:return "camino";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 "linea":return "lineasepolia";case "scroll":return "scrollsepolia";case "camino":return "columbus";case "noble":return "grand";default:return n}return n},C=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:P(D(r,n))}}return e};var {STORAGE_CODE_VERIFIER:b,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=h,l=typeof window>"u",w=class{#e;#i;bearerProfile;#s=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}:{},s=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}),i=`${this.#e.api}/auth?${s}`;this.#r(`Auth flow URL: ${i}`),window.location.assign(i);}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}),s=`${this.#e.api}/auth?${t}`;this.#r(`Auth flow SIWE URL: ${s}`),window.location.assign(s);}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 s=this.#n?.redirectUri;if(!r)throw new Error("Missing ClientId");if(l)throw new Error("This only works client side");let i=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(i)return this.#r("Using auth code from auth flow to authorize"),await this.#a(r,s,i,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.#i=`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.#i=`Bearer ${t?.access_token}`,!l){let i=new Date().getTime()+t?.expires_in*1e3;window.localStorage.setItem(p,t?.access_token||""),window.localStorage.setItem(g,i?.toString());}}).catch(t=>{throw l||(localStorage.removeItem(b),localStorage.removeItem(p),localStorage.removeItem(g),S()),new Error(t?.message)}),k(e)&&S(),this.bearerProfile}getAuthContext(){return this.#t("get","auth/context")}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 s=Array.isArray(t)?t.map(a=>`currency=${a}`).join("&"):t?`currency=${t}`:"",i=u(this.#e.name,r);return this.#t("get",`balances/${i}/${e}${s?`?${s}`:""}`)}getIban(e){return this.#t("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:r,chain:t}=e||{},s=m({profile:r,chain:t?u(this.#e.name,t):""});return this.#t("get",`ibans${s}`)}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.#i||""})}async#t(e,r,t,s){let i={Authorization:this.#i||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${s?"x-www-form-urlencoded":"json"}`};return R(`${this.#e.api}/${r}`,e.toUpperCase(),s?f(t):t,i)}#a=async(e,r,t,s)=>{let i=localStorage.getItem(b)||"";if(!i)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=s,localStorage.removeItem(b),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:i})};#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:s,state:i}=e||{},a=m({access_token:this.bearerProfile?.access_token,profile:s,state:i}),o,c=_({profile:s,state:i});if(this.#s?.has(c))o=this.#s.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#s?.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.#s?.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.#s?.get(r);t&&(t.close(),this.#s?.delete(r));}else this.#s?.forEach(r=>{r?.close();}),this.#s?.clear(),this.#s=undefined;}async disconnect(){l||localStorage.removeItem(b),this.unsubscribeOrderNotifications(),this.#i=undefined,this.bearerProfile=undefined;}async revokeAccess(){l||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e};var Ne=w;exports.AccountState=Q;exports.Currency=B;exports.IdDocumentKind=G;exports.KYCOutcome=L;exports.KYCState=W;exports.Method=j;exports.MoneriumClient=w;exports.OrderKind=J;exports.OrderState=H;exports.PaymentStandard=V;exports.Permission=M;exports.ProfileState=K;exports.ProfileType=F;exports.constants=h;exports.default=Ne;exports.getChain=E;exports.parseChain=P;exports.placeOrderMessage=Y;exports.rfc3339=x;exports.shortenIban=T;exports.siweMessage=ee;
|
package/dist/index.mjs
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
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
|
|
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 s=await fetch(`${n}`,{method:e,headers:t,body:r}),i,a=await s.text();try{if(i=JSON.parse(a),Object.keys(i).length===0&&i.constructor===Object)switch(s.status){case 201:case 202:return {status:s.status,statusText:s.statusText}}}catch{throw a}if(!s.ok)throw i;return i};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=(s=>(s.eur="eur",s.usd="usd",s.gbp="gbp",s.isk="isk",s))(B||{}),j=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i.bearer="bearer",i))(j||{}),F=(r=>(r.corporate="corporate",r.personal="personal",r))(F||{}),M=(r=>(r.read="read",r.write="write",r))(M||{}),K=(i=>(i.created="created",i.pending="pending",i.approved="approved",i.rejected="rejected",i.blocked="blocked",i))(K||{}),W=(s=>(s.absent="absent",s.submitted="submitted",s.pending="pending",s.confirmed="confirmed",s))(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=(s=>(s.placed="placed",s.pending="pending",s.processed="processed",s.rejected="rejected",s))(H||{});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 s=t>0?"-":"+";return t=Math.abs(t),s+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":case "scroll":case "scrollsepolia":case "camino":case "columbus":return true;default:return false}},P=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)=>P(D(e,n)),Y=(n,e,r,t)=>{let s=`${e?.toUpperCase()||"EUR"}`;return t?`Send ${s} ${n} to ${r} on ${P(t)} at ${x(new Date)}`:s==="EUR"?`Send ${s} ${n} to ${T(r)} at ${x(new Date)}`:`Send ${s} ${n} to ${r} at ${x(new Date)}`},ee=({domain:n,address:e,appName:r,redirectUri:t,chainId:s,issuedAt:i=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
2
|
${e}
|
|
3
3
|
|
|
4
4
|
Allow ${r} to access my data on Monerium
|
|
5
5
|
|
|
6
6
|
URI: ${t}
|
|
7
7
|
Version: 1
|
|
8
|
-
Chain ID: ${
|
|
8
|
+
Chain ID: ${s}
|
|
9
9
|
Nonce: ${I().slice(0,16)}
|
|
10
|
-
Issued At: ${
|
|
10
|
+
Issued At: ${i}
|
|
11
11
|
Expiration Time: ${a}
|
|
12
12
|
Resources:
|
|
13
13
|
- https://monerium.com/siwe
|
|
14
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:P(D(r,n))}}return e};var {STORAGE_CODE_VERIFIER:
|
|
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";case 534352:return "scroll";case 534351:return "scrollsepolia";case 501:return "columbus";case 500:return "camino";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 "linea":return "lineasepolia";case "scroll":return "scrollsepolia";case "camino":return "columbus";case "noble":return "grand";default:return n}return n},C=(n,e)=>{if(e?.chain){let{chain:r,...t}=e;return {...t,chain:P(D(r,n))}}return e};var {STORAGE_CODE_VERIFIER:b,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=h,l=typeof window>"u",w=class{#e;#i;bearerProfile;#s=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}:{},s=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}),i=`${this.#e.api}/auth?${s}`;this.#r(`Auth flow URL: ${i}`),window.location.assign(i);}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}),s=`${this.#e.api}/auth?${t}`;this.#r(`Auth flow SIWE URL: ${s}`),window.location.assign(s);}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 s=this.#n?.redirectUri;if(!r)throw new Error("Missing ClientId");if(l)throw new Error("This only works client side");let i=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(i)return this.#r("Using auth code from auth flow to authorize"),await this.#a(r,s,i,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.#i=`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.#i=`Bearer ${t?.access_token}`,!l){let i=new Date().getTime()+t?.expires_in*1e3;window.localStorage.setItem(p,t?.access_token||""),window.localStorage.setItem(g,i?.toString());}}).catch(t=>{throw l||(localStorage.removeItem(b),localStorage.removeItem(p),localStorage.removeItem(g),S()),new Error(t?.message)}),k(e)&&S(),this.bearerProfile}getAuthContext(){return this.#t("get","auth/context")}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 s=Array.isArray(t)?t.map(a=>`currency=${a}`).join("&"):t?`currency=${t}`:"",i=u(this.#e.name,r);return this.#t("get",`balances/${i}/${e}${s?`?${s}`:""}`)}getIban(e){return this.#t("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:r,chain:t}=e||{},s=m({profile:r,chain:t?u(this.#e.name,t):""});return this.#t("get",`ibans${s}`)}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.#i||""})}async#t(e,r,t,s){let i={Authorization:this.#i||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${s?"x-www-form-urlencoded":"json"}`};return R(`${this.#e.api}/${r}`,e.toUpperCase(),s?f(t):t,i)}#a=async(e,r,t,s)=>{let i=localStorage.getItem(b)||"";if(!i)throw new Error("Code verifier not found");return this.#r("Use code verifier to authorize"),this.state=s,localStorage.removeItem(b),await this.#o({code:t,redirect_uri:r,client_id:e,code_verifier:i})};#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:s,state:i}=e||{},a=m({access_token:this.bearerProfile?.access_token,profile:s,state:i}),o,c=_({profile:s,state:i});if(this.#s?.has(c))o=this.#s.get(c);else {let d=`${this.#e.wss}/orders${a}`;o=new WebSocket(d),this.#s?.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.#s?.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.#s?.get(r);t&&(t.close(),this.#s?.delete(r));}else this.#s?.forEach(r=>{r?.close();}),this.#s?.clear(),this.#s=undefined;}async disconnect(){l||localStorage.removeItem(b),this.unsubscribeOrderNotifications(),this.#i=undefined,this.bearerProfile=undefined;}async revokeAccess(){l||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#e};var Ne=w;export{Q as AccountState,B as Currency,G as IdDocumentKind,L as KYCOutcome,W as KYCState,j as Method,w as MoneriumClient,J as OrderKind,H as OrderState,V as PaymentStandard,M as Permission,K as ProfileState,F as ProfileType,h as constants,Ne as default,E as getChain,P as parseChain,Y as placeOrderMessage,x as rfc3339,T as shortenIban,ee as siweMessage};
|