@monerium/sdk
Advanced tools
Comparing version 2.12.1 to 2.13.0
@@ -1,4 +0,568 @@ | ||
export { MoneriumClient } from './client'; | ||
export { default as constants } from './constants'; | ||
export * from './types'; | ||
export { placeOrderMessage, rfc3339, getChain, getNetwork } from './utils'; | ||
type Environment = { | ||
api: string; | ||
web: string; | ||
wss: string; | ||
}; | ||
type Config = { | ||
environments: { | ||
production: Environment; | ||
sandbox: Environment; | ||
}; | ||
}; | ||
type ENV = 'sandbox' | 'production'; | ||
type EthereumTestnet = 'sepolia'; | ||
type GnosisTestnet = 'chiado'; | ||
type PolygonTestnet = 'amoy'; | ||
type Chain = 'ethereum' | 'gnosis' | 'polygon'; | ||
type Networks = EthereumTestnet | GnosisTestnet | PolygonTestnet | 'mainnet'; | ||
type NetworkSemiStrict<C extends Chain> = C extends 'ethereum' ? EthereumTestnet | 'mainnet' : C extends 'gnosis' ? GnosisTestnet | 'mainnet' : C extends 'polygon' ? PolygonTestnet | 'mainnet' : never; | ||
type NetworkStrict<C extends Chain, E extends ENV> = E extends 'production' ? 'mainnet' : E extends 'sandbox' ? C extends 'ethereum' ? EthereumTestnet : C extends 'gnosis' ? GnosisTestnet : C extends 'polygon' ? PolygonTestnet : never : never; | ||
type Network<C extends Chain = Chain, E extends ENV = ENV> = C extends Chain ? E extends ENV ? NetworkStrict<C, E> & NetworkSemiStrict<C> : never : never; | ||
type ChainId = number | 1 | 11155111 | 100 | 137 | 10200 | 80002; | ||
declare enum Currency { | ||
eur = "eur", | ||
usd = "usd", | ||
gbp = "gbp", | ||
isk = "isk" | ||
} | ||
type TokenSymbol = 'EURe' | 'GBPe' | 'USDe' | 'ISKe'; | ||
type Ticker = 'EUR' | 'GBP' | 'USD' | 'ISK'; | ||
type AuthArgs = Omit<AuthCodeRequest, 'grant_type'> | Omit<RefreshTokenRequest, 'grant_type'> | Omit<ClientCredentialsRequest, 'grant_type'>; | ||
type OpenArgs = Omit<AuthCodeRequest, 'grant_type' | 'code' | 'code_verifier'> | Omit<RefreshTokenRequest, 'grant_type'> | Omit<ClientCredentialsRequest, 'grant_type'> | PKCERequestArgs; | ||
/** One of the options for the {@link AuthArgs}. | ||
* | ||
* [Auth endpoint in API documentation:](https://monerium.dev/api-docs#operation/auth). | ||
* */ | ||
interface AuthCodeRequest { | ||
grant_type: 'authorization_code'; | ||
client_id: string; | ||
code: string; | ||
code_verifier: string; | ||
redirect_uri: string; | ||
scope?: string; | ||
} | ||
/** One of the options for the {@link AuthArgs}. | ||
* | ||
* [Auth endpoint in API documentation:](https://monerium.dev/api-docs#operation/auth). | ||
* */ | ||
interface RefreshTokenRequest { | ||
grant_type: 'refresh_token'; | ||
client_id: string; | ||
refresh_token: string; | ||
scope?: string; | ||
} | ||
/** One of the options for the {@link AuthArgs}. | ||
* | ||
* [Auth endpoint in API documentation:](https://monerium.dev/api-docs#operation/auth). | ||
* */ | ||
interface ClientCredentialsRequest { | ||
grant_type: 'client_credentials'; | ||
client_id: string; | ||
client_secret: string; | ||
scope?: string; | ||
} | ||
interface BearerProfile { | ||
access_token: string; | ||
token_type: string; | ||
expires_in: number; | ||
refresh_token: string; | ||
profile: string; | ||
userId: string; | ||
} | ||
/** | ||
* @returns A {@link PKCERequest} object with properties omitted that are automatically computed in by the SDK. | ||
*/ | ||
type PKCERequestArgs = Omit<PKCERequest, 'code_challenge' | 'code_challenge_method' | 'response_type'>; | ||
type PKCERequest = { | ||
/** the authentication flow client id of the application */ | ||
client_id: string; | ||
/** the code challenge automatically generated by the SDK */ | ||
code_challenge: string; | ||
/** the code challenge method for the authentication flow , handled by the SDK */ | ||
code_challenge_method: 'S256'; | ||
/** the response type of the authentication flow, handled by the SDK */ | ||
response_type: 'code'; | ||
/** the state of the application */ | ||
state?: string; | ||
/** the redirect uri of the application */ | ||
redirect_uri: string; | ||
/** the scope of the application */ | ||
scope?: string; | ||
/** the address of the wallet to automatically link */ | ||
address?: string; | ||
/** the signature of the wallet to automatically link */ | ||
signature?: string; | ||
/** @deprecated - Use chainId */ | ||
network?: Network; | ||
/** @deprecated - Use chainId */ | ||
chain?: Chain; | ||
/** The network of the wallet to automatically link */ | ||
chainId?: ChainId; | ||
}; | ||
declare enum Method { | ||
password = "password", | ||
resource = "resource", | ||
jwt = "jwt", | ||
apiKey = "apiKey" | ||
} | ||
declare enum ProfileType { | ||
corporate = "corporate", | ||
personal = "personal" | ||
} | ||
declare enum Permission { | ||
read = "read", | ||
write = "write" | ||
} | ||
interface AuthProfile { | ||
id: string; | ||
type: ProfileType; | ||
name: string; | ||
perms: Permission[]; | ||
} | ||
interface AuthContext { | ||
userId: string; | ||
email: string; | ||
name: string; | ||
roles: 'admin'[]; | ||
auth: { | ||
method: Method; | ||
subject: string; | ||
verified: boolean; | ||
}; | ||
defaultProfile: string; | ||
profiles: AuthProfile[]; | ||
} | ||
declare enum KYCState { | ||
absent = "absent", | ||
submitted = "submitted", | ||
pending = "pending", | ||
confirmed = "confirmed" | ||
} | ||
declare enum KYCOutcome { | ||
approved = "approved", | ||
rejected = "rejected", | ||
unknown = "unknown" | ||
} | ||
declare enum AccountState { | ||
requested = "requested", | ||
approved = "approved", | ||
pending = "pending" | ||
} | ||
interface KYC { | ||
state: KYCState; | ||
outcome: KYCOutcome; | ||
} | ||
declare enum PaymentStandard { | ||
iban = "iban", | ||
scan = "scan", | ||
chain = "chain" | ||
} | ||
interface Identifier { | ||
standard: PaymentStandard; | ||
bic?: string; | ||
} | ||
interface Account { | ||
address: string; | ||
currency: Currency; | ||
standard: PaymentStandard; | ||
iban?: string; | ||
network?: Network; | ||
chain: Chain; | ||
id?: string; | ||
state?: AccountState; | ||
} | ||
interface Profile { | ||
id: string; | ||
name: string; | ||
email: string; | ||
kyc: KYC; | ||
kind: ProfileType; | ||
accounts: Account[]; | ||
} | ||
interface Balance { | ||
currency: Currency; | ||
amount: string; | ||
} | ||
interface Balances { | ||
id: string; | ||
address: string; | ||
chain: Chain; | ||
network: Network; | ||
balances: Balance[]; | ||
} | ||
declare enum OrderKind { | ||
redeem = "redeem", | ||
issue = "issue" | ||
} | ||
declare enum OrderState { | ||
placed = "placed", | ||
pending = "pending", | ||
processed = "processed", | ||
rejected = "rejected" | ||
} | ||
interface Fee { | ||
provider: 'satchel'; | ||
currency: Currency; | ||
amount: string; | ||
} | ||
interface IBAN extends Identifier { | ||
standard: PaymentStandard.iban; | ||
iban: string; | ||
} | ||
interface CrossChain extends Identifier { | ||
standard: PaymentStandard.chain; | ||
address: string; | ||
chainId: ChainId; | ||
/** @deprecated - Use chainId */ | ||
chain?: Chain; | ||
/** @deprecated - Use chainId */ | ||
network?: Network; | ||
} | ||
interface SCAN extends Identifier { | ||
standard: PaymentStandard.scan; | ||
sortCode: string; | ||
accountNumber: string; | ||
} | ||
interface Individual { | ||
firstName: string; | ||
lastName: string; | ||
country?: string; | ||
} | ||
interface Corporation { | ||
companyName: string; | ||
country: string; | ||
} | ||
interface Counterpart { | ||
identifier: IBAN | SCAN | CrossChain; | ||
details: Individual | Corporation; | ||
} | ||
interface OrderMetadata { | ||
approvedAt: string; | ||
processedAt: string; | ||
rejectedAt: string; | ||
state: OrderState; | ||
placedBy: string; | ||
placedAt: string; | ||
receivedAmount: string; | ||
sentAmount: string; | ||
} | ||
interface OrderFilter { | ||
address?: string; | ||
txHash?: string; | ||
profile?: string; | ||
memo?: string; | ||
accountId?: string; | ||
state?: OrderState; | ||
} | ||
interface Order { | ||
id: string; | ||
profile: string; | ||
accountId: string; | ||
address: string; | ||
kind: OrderKind; | ||
amount: string; | ||
currency: Currency; | ||
totalFee: string; | ||
fees: Fee[]; | ||
counterpart: Counterpart; | ||
memo: string; | ||
rejectedReason: string; | ||
supportingDocumentId: string; | ||
meta: OrderMetadata; | ||
} | ||
/** | ||
* Information about the EURe token on different networks. | ||
*/ | ||
interface Token { | ||
currency: Currency; | ||
ticker: Ticker; | ||
symbol: TokenSymbol; | ||
chain: Chain; | ||
network: Network; | ||
/** The address of the EURe contract on this network */ | ||
address: string; | ||
/** How many decimals this token supports */ | ||
decimals: number; | ||
} | ||
type NewOrder = NewOrderByAddress | NewOrderByAccountId; | ||
interface NewOrderCommon { | ||
amount: string; | ||
signature: string; | ||
currency?: Currency /** Not needed right now, only EUR */; | ||
counterpart: Counterpart; | ||
message: string; | ||
memo?: string; | ||
supportingDocumentId?: string; | ||
} | ||
interface NewOrderByAddress extends NewOrderCommon { | ||
address: string; | ||
/** @deprecated - Use 'chainId' */ | ||
chain?: Chain; | ||
/** @deprecated - Use 'chainId' */ | ||
network?: Network; | ||
chainId: ChainId; | ||
} | ||
interface NewOrderByAccountId extends NewOrderCommon { | ||
accountId: string; | ||
} | ||
interface SupportingDocMetadata { | ||
uploadedBy: string; | ||
createdAt: string; | ||
updatedAt: string; | ||
} | ||
interface SupportingDoc { | ||
id: string; | ||
name: string; | ||
type: string; | ||
size: number; | ||
hash: string; | ||
meta: SupportingDocMetadata; | ||
} | ||
interface CurrencyAccounts { | ||
/** @deprecated - Use 'chainId' */ | ||
network?: Network; | ||
/** @deprecated - Use 'chainId' */ | ||
chain?: Chain; | ||
chainId: ChainId; | ||
currency: Currency; | ||
} | ||
interface LinkAddress { | ||
address: string; | ||
message: string; | ||
signature: string; | ||
accounts: CurrencyAccounts[]; | ||
/** @deprecated - Use 'chainId' */ | ||
network?: Network; | ||
/** @deprecated - Use 'chainId' */ | ||
chain?: Chain; | ||
chainId?: ChainId; | ||
} | ||
interface OrderNotification { | ||
id: string; | ||
profile: string; | ||
accountId: string; | ||
address: string; | ||
kind: string; | ||
amount: string; | ||
currency: string; | ||
totalFee: string; | ||
fees: Fee[]; | ||
counterpart: Counterpart; | ||
memo: string; | ||
rejectedReason: string; | ||
supportingDocumentId: string; | ||
meta: OrderMetadata; | ||
} | ||
type MoneriumEvent = OrderState; | ||
type MoneriumEventListener = (notification: OrderNotification) => void; | ||
type ClassOptions = { | ||
environment?: ENV; | ||
} & BearerTokenCredentials; | ||
interface AuthFlowOptions { | ||
clientId?: string; | ||
redirectUrl?: string; | ||
address?: string; | ||
signature?: string; | ||
chainId?: ChainId; | ||
state?: string; | ||
} | ||
interface ClientCredentials { | ||
clientId: string; | ||
clientSecret: string; | ||
} | ||
interface AuthorizationCodeCredentials { | ||
clientId: string; | ||
redirectUrl: string; | ||
} | ||
type BearerTokenCredentials = ClientCredentials | AuthorizationCodeCredentials; | ||
declare class MoneriumClient { | ||
#private; | ||
/** | ||
* The PKCE code verifier | ||
* @deprecated, use localStorage, will be removed in v3 | ||
* @hidden | ||
* */ | ||
codeVerifier?: string; | ||
/** | ||
* The bearer profile will be available after authentication, it includes the `access_token` and `refresh_token` | ||
* */ | ||
bearerProfile?: BearerProfile; | ||
isAuthorized: boolean; | ||
/** | ||
* The state parameter is used to maintain state between the request and the callback. | ||
* */ | ||
state: string | undefined; | ||
/** | ||
* @defaultValue `sandbox` | ||
* @example | ||
* new MoneriumClient() // defaults to `sandbox` | ||
* | ||
* new MoneriumClient('production') | ||
* | ||
* new MoneriumClient({ | ||
* environment: 'sandbox', | ||
* clientId: 'your-client-id', | ||
* redirectUrl: 'your-redirect-url' | ||
* }) | ||
* */ | ||
constructor(envOrOptions?: ENV | ClassOptions); | ||
/** | ||
* Construct the url to the authorization code flow, | ||
* Code Verifier needed for the code challenge is stored in local storage | ||
* For automatic wallet link, add the following properties: `address`, `signature` & `chainId` | ||
* @returns string | ||
* {@link https://monerium.dev/api-docs#operation/auth} | ||
* @category Auth | ||
*/ | ||
authorize(client?: AuthFlowOptions): Promise<void>; | ||
/** | ||
* Get access to the API | ||
* @param {AuthorizationCodeCredentials | ClientCredentials} client - the client credentials | ||
* @returns boolean to indicate if access has been granted | ||
* @category Auth | ||
*/ | ||
getAccess(client?: AuthorizationCodeCredentials | ClientCredentials): Promise<boolean>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/auth-context} | ||
* @category Auth | ||
*/ | ||
getAuthContext(): Promise<AuthContext>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/profile} | ||
* @param {string} profileId - the id of the profile to fetch. | ||
* @category Profiles | ||
*/ | ||
getProfile(profileId: string): Promise<Profile>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/profile-balances} | ||
* @param {string=} profileId - the id of the profile to fetch balances. | ||
* @category Accounts | ||
*/ | ||
getBalances(profileId?: string): Promise<Balances[]>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/orders} | ||
* @category Orders | ||
*/ | ||
getOrders(filter?: OrderFilter): Promise<Order[]>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/order} | ||
* @category Orders | ||
*/ | ||
getOrder(orderId: string): Promise<Order>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/tokens} | ||
* @category Tokens | ||
*/ | ||
getTokens(): Promise<Token[]>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/profile-addresses} | ||
* @category Accounts | ||
*/ | ||
linkAddress(profileId: string, body: LinkAddress): Promise<unknown>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/post-orders} | ||
* @category Orders | ||
*/ | ||
placeOrder(order: NewOrder, profileId?: string): Promise<Order>; | ||
/** | ||
* {@link https://monerium.dev/api-docs#operation/supporting-document} | ||
* @category Orders | ||
*/ | ||
uploadSupportingDocument(document: File): Promise<SupportingDoc>; | ||
/** | ||
* Connects to the order notifications socket | ||
* @category Orders | ||
*/ | ||
connectOrderSocket(): Promise<void>; | ||
/** | ||
* Subscribes to the order notifications socket | ||
* @category Orders | ||
*/ | ||
subscribeToOrderNotifications: () => WebSocket; | ||
/** | ||
* Cleanups the socket and the subscriptions | ||
* @category Auth | ||
*/ | ||
disconnect(): Promise<void>; | ||
/** | ||
* Revokes access | ||
* @category Auth | ||
*/ | ||
revokeAccess(): Promise<void>; | ||
/** | ||
* Subscribe to MoneriumEvent to receive notifications using the Monerium API (WebSocket) | ||
* We are setting a subscription map because we need the user to have a token to start the WebSocket connection | ||
* {@link https://monerium.dev/api-docs#operation/profile-orders-notifications} | ||
* @param event The event to subscribe to | ||
* @param handler The handler to be called when the event is triggered | ||
* @category Orders | ||
*/ | ||
subscribeOrders(event: MoneriumEvent, handler: MoneriumEventListener): void; | ||
/** | ||
* Unsubscribe from MoneriumEvent and close the socket if there are no more subscriptions | ||
* @param event The event to unsubscribe from | ||
* @category Orders | ||
*/ | ||
unsubscribeOrders(event: MoneriumEvent): void; | ||
/** | ||
* @deprecated since v2.6.4, will be removed in 2.7.2+, use {@link getAccess} instead. | ||
* @hidden | ||
*/ | ||
auth: (args: AuthArgs) => Promise<BearerProfile>; | ||
/** | ||
* @deprecated since v2.7.1, will be removed in 2.7.2+, use {@link getAccess} instead. | ||
* @hidden | ||
*/ | ||
connect: (args: AuthArgs) => Promise<BearerProfile>; | ||
/** | ||
* @deprecated since v2.6.4, will be removed in 2.7.2+, use {@link authorize} instead. | ||
* @hidden | ||
*/ | ||
getAuthFlowURI: (args: PKCERequestArgs) => string; | ||
/** | ||
* @deprecated since v2.0.7, will be removed in 2.7.2+, use {@link getAuthFlowURI} instead. | ||
* @hidden | ||
*/ | ||
pkceRequest: (args: PKCERequestArgs) => string; | ||
/** | ||
* @hidden | ||
*/ | ||
getEnvironment: () => Environment; | ||
} | ||
declare const _default: { | ||
/** | ||
* The message used to link addresses. | ||
*/ | ||
LINK_MESSAGE: string; | ||
/** | ||
* The key used to store the code verifier in the local storage. | ||
*/ | ||
STORAGE_CODE_VERIFIER: string; | ||
/** | ||
* The key used to store the refresh token in the local storage. | ||
*/ | ||
STORAGE_REFRESH_TOKEN: string; | ||
}; | ||
declare const rfc3339: (d: Date) => string; | ||
/** | ||
* The message to be signed when placing an order. | ||
* | ||
* @returns string | ||
*/ | ||
declare const placeOrderMessage: (amount: string | number, receiver: string, chainId?: number, currency?: 'eur' | 'gbp' | 'usd' | 'isk') => string; | ||
/** | ||
* Get the corresponding Monerium SDK Chain from the current chain id | ||
* @returns The Chain | ||
*/ | ||
declare const getChain: (chainId: number) => Chain; | ||
/** | ||
* Get the corresponding Monerium SDK Network from the current chain id | ||
* @returns The Network | ||
* @deprecated network will be removed from Monerium API in the near future. | ||
*/ | ||
declare const getNetwork: (chainId: number) => Networks; | ||
export { type Account, AccountState, type AuthArgs, type AuthCodeRequest, type AuthContext, type AuthFlowOptions, type AuthProfile, type AuthorizationCodeCredentials, type Balance, type Balances, type BearerProfile, type BearerTokenCredentials, type Chain, type ChainId, type ClassOptions, type ClientCredentials, type ClientCredentialsRequest, type Config, type Corporation, type Counterpart, type CrossChain, Currency, type CurrencyAccounts, type ENV, type Environment, type EthereumTestnet, type Fee, type GnosisTestnet, type IBAN, type Identifier, type Individual, type KYC, KYCOutcome, KYCState, type LinkAddress, Method, MoneriumClient, type MoneriumEvent, type MoneriumEventListener, type Network, type NetworkSemiStrict, type NetworkStrict, type Networks, type NewOrder, type NewOrderByAccountId, type NewOrderByAddress, type NewOrderCommon, type OpenArgs, type Order, type OrderFilter, OrderKind, type OrderMetadata, type OrderNotification, OrderState, type PKCERequest, type PKCERequestArgs, PaymentStandard, Permission, type PolygonTestnet, type Profile, ProfileType, type RefreshTokenRequest, type SCAN, type SupportingDoc, type SupportingDocMetadata, type Ticker, type Token, type TokenSymbol, _default as constants, MoneriumClient as default, getChain, getNetwork, placeOrderMessage, rfc3339 }; |
@@ -1,1 +0,31 @@ | ||
"use strict";var K=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var g=(e,t,r)=>(K(e,t,"read from private field"),r?r.call(e):t.get(e)),O=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},E=(e,t,r,n)=>(K(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var k=(e,t,r)=>(K(e,t,"access private method"),r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var ue=(e=>(e.eur="eur",e))(ue||{}),he=(e=>(e.corporate="corporate",e.personal="personal",e))(he||{}),fe=(e=>(e.read="read",e.write="write",e))(fe||{}),de=(e=>(e.absent="absent",e.submitted="submitted",e.pending="pending",e.confirmed="confirmed",e))(de||{}),le=(e=>(e.approved="approved",e.rejected="rejected",e.unknown="unknown",e))(le||{}),pe=(e=>(e.requested="requested",e.approved="approved",e.pending="pending",e))(pe||{}),ve=(e=>(e.iban="iban",e.scan="scan",e.chain="chain",e))(ve||{}),ge=(e=>(e.redeem="redeem",e.issue="issue",e))(ge||{}),we=(e=>(e.placed="placed",e.pending="pending",e.processed="processed",e.rejected="rejected",e))(we||{});const ee=e=>{if(e.toString()==="Invalid Date")throw e;const t=n=>n<10?"0"+n:n,r=n=>{if(n===0)return"Z";const c=n>0?"-":"+";return n=Math.abs(n),c+t(Math.floor(n/60))+":"+t(n%60)};return e.getFullYear()+"-"+t(e.getMonth()+1)+"-"+t(e.getDate())+"T"+t(e.getHours())+":"+t(e.getMinutes())+":"+t(e.getSeconds())+r(e.getTimezoneOffset())},Ae=(e,t,r,n)=>{const c=`${(n==null?void 0:n.toUpperCase())||"EUR"}`;return r?`Send ${c} ${e} to ${t} on ${Z(r)} at ${ee(new Date)}`:`Send ${c} ${e} to ${t} at ${ee(new Date)}`},te=e=>{var t;return e&&((t=Object.entries(e))==null?void 0:t.length)>0?Object.entries(e).map(([r,n])=>`${encodeURIComponent(r)}=${encodeURIComponent(n)}`).join("&"):""},Z=e=>{switch(e){case 1:case 11155111:return"ethereum";case 100:case 10200:return"gnosis";case 137:case 80001:return"polygon";default:throw new Error(`Chain not supported: ${e}`)}},re=e=>{switch(e){case 1:case 100:case 137:return"mainnet";case 11155111:return"sepolia";case 10200:return"chiado";case 80001:return"mumbai";default:throw new Error(`Network not supported: ${e}`)}},Q=e=>{if(e!=null&&e.chainId){const{chainId:t,...r}=e;return{...r,chain:Z(t),network:re(t)}}return e},X={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"}}},Ee="I hereby declare that I am the address owner.",M="monerium.sdk.code_verifier",W="monerium.sdk.refresh_token",Ie={LINK_MESSAGE:Ee,STORAGE_CODE_VERIFIER:M,STORAGE_REFRESH_TOKEN:W};var q=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ye(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function $e(e){if(e.__esModule)return e;var t=e.default;if(typeof t=="function"){var r=function n(){return this instanceof n?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};r.prototype=t.prototype}else r={};return Object.defineProperty(r,"__esModule",{value:!0}),Object.keys(e).forEach(function(n){var c=Object.getOwnPropertyDescriptor(e,n);Object.defineProperty(r,n,c.get?c:{enumerable:!0,get:function(){return e[n]}})}),r}var me={exports:{}};function Re(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Y={exports:{}};const Oe={},Pe=Object.freeze(Object.defineProperty({__proto__:null,default:Oe},Symbol.toStringTag,{value:"Module"})),ze=$e(Pe);var oe;function _e(){return oe||(oe=1,function(e,t){(function(r,n){e.exports=n()})(q,function(){var r=r||function(n,c){var u;if(typeof window<"u"&&window.crypto&&(u=window.crypto),typeof self<"u"&&self.crypto&&(u=self.crypto),typeof globalThis<"u"&&globalThis.crypto&&(u=globalThis.crypto),!u&&typeof window<"u"&&window.msCrypto&&(u=window.msCrypto),!u&&typeof q<"u"&&q.crypto&&(u=q.crypto),!u&&typeof Re=="function")try{u=ze}catch{}var l=function(){if(u){if(typeof u.getRandomValues=="function")try{return u.getRandomValues(new Uint32Array(1))[0]}catch{}if(typeof u.randomBytes=="function")try{return u.randomBytes(4).readInt32LE()}catch{}}throw new Error("Native crypto module could not be used to get secure random number.")},C=Object.create||function(){function o(){}return function(s){var a;return o.prototype=s,a=new o,o.prototype=null,a}}(),v={},m=v.lib={},y=m.Base=function(){return{extend:function(o){var s=C(this);return o&&s.mixIn(o),(!s.hasOwnProperty("init")||this.init===s.init)&&(s.init=function(){s.$super.init.apply(this,arguments)}),s.init.prototype=s,s.$super=this,s},create:function(){var o=this.extend();return o.init.apply(o,arguments),o},init:function(){},mixIn:function(o){for(var s in o)o.hasOwnProperty(s)&&(this[s]=o[s]);o.hasOwnProperty("toString")&&(this.toString=o.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),w=m.WordArray=y.extend({init:function(o,s){o=this.words=o||[],s!=c?this.sigBytes=s:this.sigBytes=o.length*4},toString:function(o){return(o||f).stringify(this)},concat:function(o){var s=this.words,a=o.words,h=this.sigBytes,_=o.sigBytes;if(this.clamp(),h%4)for(var S=0;S<_;S++){var B=a[S>>>2]>>>24-S%4*8&255;s[h+S>>>2]|=B<<24-(h+S)%4*8}else for(var x=0;x<_;x+=4)s[h+x>>>2]=a[x>>>2];return this.sigBytes+=_,this},clamp:function(){var o=this.words,s=this.sigBytes;o[s>>>2]&=4294967295<<32-s%4*8,o.length=n.ceil(s/4)},clone:function(){var o=y.clone.call(this);return o.words=this.words.slice(0),o},random:function(o){for(var s=[],a=0;a<o;a+=4)s.push(l());return new w.init(s,o)}}),b=v.enc={},f=b.Hex={stringify:function(o){for(var s=o.words,a=o.sigBytes,h=[],_=0;_<a;_++){var S=s[_>>>2]>>>24-_%4*8&255;h.push((S>>>4).toString(16)),h.push((S&15).toString(16))}return h.join("")},parse:function(o){for(var s=o.length,a=[],h=0;h<s;h+=2)a[h>>>3]|=parseInt(o.substr(h,2),16)<<24-h%8*4;return new w.init(a,s/2)}},p=b.Latin1={stringify:function(o){for(var s=o.words,a=o.sigBytes,h=[],_=0;_<a;_++){var S=s[_>>>2]>>>24-_%4*8&255;h.push(String.fromCharCode(S))}return h.join("")},parse:function(o){for(var s=o.length,a=[],h=0;h<s;h++)a[h>>>2]|=(o.charCodeAt(h)&255)<<24-h%4*8;return new w.init(a,s)}},i=b.Utf8={stringify:function(o){try{return decodeURIComponent(escape(p.stringify(o)))}catch{throw new Error("Malformed UTF-8 data")}},parse:function(o){return p.parse(unescape(encodeURIComponent(o)))}},d=m.BufferedBlockAlgorithm=y.extend({reset:function(){this._data=new w.init,this._nDataBytes=0},_append:function(o){typeof o=="string"&&(o=i.parse(o)),this._data.concat(o),this._nDataBytes+=o.sigBytes},_process:function(o){var s,a=this._data,h=a.words,_=a.sigBytes,S=this.blockSize,B=S*4,x=_/B;o?x=n.ceil(x):x=n.max((x|0)-this._minBufferSize,0);var j=x*S,U=n.min(j*4,_);if(j){for(var D=0;D<j;D+=S)this._doProcessBlock(h,D);s=h.splice(0,j),a.sigBytes-=U}return new w.init(s,U)},clone:function(){var o=y.clone.call(this);return o._data=this._data.clone(),o},_minBufferSize:0});m.Hasher=d.extend({cfg:y.extend(),init:function(o){this.cfg=this.cfg.extend(o),this.reset()},reset:function(){d.reset.call(this),this._doReset()},update:function(o){return this._append(o),this._process(),this},finalize:function(o){o&&this._append(o);var s=this._doFinalize();return s},blockSize:16,_createHelper:function(o){return function(s,a){return new o.init(a).finalize(s)}},_createHmacHelper:function(o){return function(s,a){return new A.HMAC.init(o,a).finalize(s)}}});var A=v.algo={};return v}(Math);return r})}(Y)),Y.exports}(function(e,t){(function(r,n){e.exports=n(_e())})(q,function(r){return function(){var n=r,c=n.lib,u=c.WordArray,l=n.enc;l.Base64url={stringify:function(v,m){m===void 0&&(m=!0);var y=v.words,w=v.sigBytes,b=m?this._safe_map:this._map;v.clamp();for(var f=[],p=0;p<w;p+=3)for(var i=y[p>>>2]>>>24-p%4*8&255,d=y[p+1>>>2]>>>24-(p+1)%4*8&255,A=y[p+2>>>2]>>>24-(p+2)%4*8&255,o=i<<16|d<<8|A,s=0;s<4&&p+s*.75<w;s++)f.push(b.charAt(o>>>6*(3-s)&63));var a=b.charAt(64);if(a)for(;f.length%4;)f.push(a);return f.join("")},parse:function(v,m){m===void 0&&(m=!0);var y=v.length,w=m?this._safe_map:this._map,b=this._reverseMap;if(!b){b=this._reverseMap=[];for(var f=0;f<w.length;f++)b[w.charCodeAt(f)]=f}var p=w.charAt(64);if(p){var i=v.indexOf(p);i!==-1&&(y=i)}return C(v,y,b)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",_safe_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"};function C(v,m,y){for(var w=[],b=0,f=0;f<m;f++)if(f%4){var p=y[v.charCodeAt(f-1)]<<f%4*2,i=y[v.charCodeAt(f)]>>>6-f%4*2,d=p|i;w[b>>>2]|=d<<24-b%4*8,b++}return u.create(w,b)}}(),r.enc.Base64url})})(me);var Ue=me.exports;const He=ye(Ue);var be={exports:{}};(function(e,t){(function(r,n){e.exports=n(_e())})(q,function(r){return function(n){var c=r,u=c.lib,l=u.WordArray,C=u.Hasher,v=c.algo,m=[],y=[];(function(){function f(A){for(var o=n.sqrt(A),s=2;s<=o;s++)if(!(A%s))return!1;return!0}function p(A){return(A-(A|0))*4294967296|0}for(var i=2,d=0;d<64;)f(i)&&(d<8&&(m[d]=p(n.pow(i,1/2))),y[d]=p(n.pow(i,1/3)),d++),i++})();var w=[],b=v.SHA256=C.extend({_doReset:function(){this._hash=new l.init(m.slice(0))},_doProcessBlock:function(f,p){for(var i=this._hash.words,d=i[0],A=i[1],o=i[2],s=i[3],a=i[4],h=i[5],_=i[6],S=i[7],B=0;B<64;B++){if(B<16)w[B]=f[p+B]|0;else{var x=w[B-15],j=(x<<25|x>>>7)^(x<<14|x>>>18)^x>>>3,U=w[B-2],D=(U<<15|U>>>17)^(U<<13|U>>>19)^U>>>10;w[B]=j+w[B-7]+D+w[B-16]}var Se=a&h^~a&_,Ce=d&A^d&o^A&o,ke=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),Be=(a<<26|a>>>6)^(a<<21|a>>>11)^(a<<7|a>>>25),ne=S+Be+Se+y[B]+w[B],xe=ke+Ce;S=_,_=h,h=a,a=s+ne|0,s=o,o=A,A=d,d=ne+xe|0}i[0]=i[0]+d|0,i[1]=i[1]+A|0,i[2]=i[2]+o|0,i[3]=i[3]+s|0,i[4]=i[4]+a|0,i[5]=i[5]+h|0,i[6]=i[6]+_|0,i[7]=i[7]+S|0},_doFinalize:function(){var f=this._data,p=f.words,i=this._nDataBytes*8,d=f.sigBytes*8;return p[d>>>5]|=128<<24-d%32,p[(d+64>>>9<<4)+14]=n.floor(i/4294967296),p[(d+64>>>9<<4)+15]=i,f.sigBytes=p.length*4,this._process(),this._hash},clone:function(){var f=C.clone.call(this);return f._hash=this._hash.clone(),f}});c.SHA256=C._createHelper(b),c.HmacSHA256=C._createHmacHelper(b)}(Math),r.SHA256})})(be);var Te=be.exports;const Me=ye(Te),Le=(e,t)=>{const{client_id:r,redirect_uri:n,scope:c,state:u,chainId:l,chain:C,network:v,address:m,signature:y}=e,w=m?{address:m,...y!==void 0?{signature:y}:{},...l!==void 0||C!==void 0?{chain:l?Z(l):C}:{},...l!==void 0||v!==void 0?{network:l?re(l):v}:{}}:{};return te({client_id:r,redirect_uri:n,...c!==void 0?{scope:c}:{},...u!==void 0?{state:u}:{},code_challenge:t,code_challenge_method:"S256",response_type:"code",...w})},Ne=()=>{let e="";const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",r=t.length;let n=0;for(;n<128;)e+=t.charAt(Math.floor(Math.random()*r)),n+=1;return e},je=e=>He.stringify(Me(e)),se=(e,t)=>{const r=Ne(),n=je(r);return localStorage.setItem(M,r||""),`${e}/auth?${Le(t,n)}`},ie=()=>{const e=window.location.href;if(!e||!(e!=null&&e.includes("?")))return;const[t,r]=e.split("?");r&&window.history.replaceState(null,"",t)},ae=e=>e.code!=null,Fe=e=>e.refresh_token!=null,qe=e=>e.client_secret!=null,ce=async(e,t,r,n)=>{const c=await fetch(`${e}`,{method:t,headers:n,body:r});let u;const l=await c.text();try{u=JSON.parse(l)}catch{throw l}if(!c.ok)throw u;return u},T=typeof window>"u";var R,L,N,z,P,H,F,I,$,V,G,J;class De{constructor(t){O(this,H);O(this,I);O(this,R,void 0);O(this,L,void 0);O(this,N,void 0);O(this,z,void 0);O(this,P,void 0);O(this,V,void 0);O(this,G,void 0);O(this,J,void 0);if(E(this,z,new Map),this.isAuthorized=!!this.bearerProfile,E(this,V,async(r,n,c,u)=>{const l=localStorage.getItem(M)||"";if(!l)throw new Error("Code verifier not found");return this.codeVerifier=l,this.state=u,localStorage.removeItem(M),await k(this,H,F).call(this,{code:c,redirect_uri:n,client_id:r,code_verifier:l})}),E(this,G,async({clientId:r,clientSecret:n})=>await k(this,H,F).call(this,{client_id:r,client_secret:n})),E(this,J,async(r,n)=>await k(this,H,F).call(this,{refresh_token:n,client_id:r})),this.subscribeToOrderNotifications=()=>{var c,u;const r=`${g(this,R).wss}/profiles/${(c=this.bearerProfile)==null?void 0:c.profile}/orders?access_token=${(u=this.bearerProfile)==null?void 0:u.access_token}`,n=new WebSocket(r);return n.addEventListener("open",()=>{console.info(`Socket connected: ${r}`)}),n.addEventListener("error",l=>{throw console.error(l),new Error(`Socket error: ${r}`)}),n.addEventListener("message",l=>{var v;const C=JSON.parse(l.data);(v=g(this,z).get(C.meta.state))==null||v(C)}),n.addEventListener("close",()=>{console.info(`Socket connection closed: ${r}`)}),n},this.auth=async r=>await k(this,H,F).call(this,r),this.connect=async r=>await k(this,H,F).call(this,r),this.getAuthFlowURI=r=>{const n=se(g(this,R).api,r);return this.codeVerifier=localStorage.getItem(M),n},this.pkceRequest=r=>this.getAuthFlowURI(r),this.getEnvironment=()=>g(this,R),!t){E(this,R,X.environments.sandbox);return}if(typeof t=="string")E(this,R,X.environments[t]);else if(E(this,R,X.environments[t.environment||"sandbox"]),T){const{clientId:r,clientSecret:n}=t;E(this,P,{clientId:r,clientSecret:n})}else{const{clientId:r,redirectUrl:n}=t;E(this,P,{clientId:r,redirectUrl:n})}}async authorize(t){var u,l;const r=(t==null?void 0:t.clientId)||((u=g(this,P))==null?void 0:u.clientId),n=(t==null?void 0:t.redirectUrl)||((l=g(this,P))==null?void 0:l.redirectUrl);if(!r)throw new Error("Missing ClientId");if(!n)throw new Error("Missing RedirectUrl");const c=se(g(this,R).api,{client_id:r,redirect_uri:n,address:t==null?void 0:t.address,signature:t==null?void 0:t.signature,chainId:t==null?void 0:t.chainId,state:t==null?void 0:t.state});window.location.replace(c)}async getAccess(t){var v,m,y;const r=(t==null?void 0:t.clientId)||((v=g(this,P))==null?void 0:v.clientId);if((t==null?void 0:t.clientSecret)||((m=g(this,P))==null?void 0:m.clientSecret)){if(!T)throw new Error("Only use client credentials on server side");return await g(this,G).call(this,g(this,P)),!!this.bearerProfile}const c=(t==null?void 0:t.redirectUrl)||((y=g(this,P))==null?void 0:y.redirectUrl);if(!r)throw new Error("Missing ClientId");if(T)throw new Error("This only works client side");const u=new URLSearchParams(window.location.search).get("code")||void 0,l=new URLSearchParams(window.location.search).get("state")||void 0,C=localStorage.getItem(W)||void 0;return C?await g(this,J).call(this,r,C):u&&await g(this,V).call(this,r,c,u,l),!!this.bearerProfile}getAuthContext(){return k(this,I,$).call(this,"get","auth/context")}getProfile(t){return k(this,I,$).call(this,"get",`profiles/${t}`)}getBalances(t){return t?k(this,I,$).call(this,"get",`profiles/${t}/balances`):k(this,I,$).call(this,"get","balances")}getOrders(t){const r=te(t);return k(this,I,$).call(this,"get",`orders?${r}`)}getOrder(t){return k(this,I,$).call(this,"get",`orders/${t}`)}getTokens(){return k(this,I,$).call(this,"get","tokens")}linkAddress(t,r){return r=Q(r),r.accounts=r.accounts.map(n=>Q(n)),k(this,I,$).call(this,"post",`profiles/${t}/addresses`,JSON.stringify(r))}placeOrder(t,r){const n={kind:"redeem",currency:"eur",...Q(t),counterpart:{...t.counterpart,identifier:Q(t.counterpart.identifier)}};return r?k(this,I,$).call(this,"post",`profiles/${r}/orders`,JSON.stringify(n)):k(this,I,$).call(this,"post","orders",JSON.stringify(n))}uploadSupportingDocument(t){const r=new FormData;return r.append("file",t),ce(`${g(this,R).api}/files`,"post",r,{Authorization:g(this,L)||""})}async connectOrderSocket(){var t;(t=this.bearerProfile)!=null&&t.access_token&&g(this,z).size>0&&E(this,N,this.subscribeToOrderNotifications())}async disconnect(){var t;T||localStorage.removeItem(M),g(this,z).clear(),(t=g(this,N))==null||t.close(),E(this,L,void 0),this.bearerProfile=void 0}async revokeAccess(){T||localStorage.removeItem(W),this.disconnect()}subscribeOrders(t,r){g(this,z).set(t,r)}unsubscribeOrders(t){var r;g(this,z).delete(t),g(this,z).size===0&&((r=g(this,N))==null||r.close(),E(this,N,void 0))}}R=new WeakMap,L=new WeakMap,N=new WeakMap,z=new WeakMap,P=new WeakMap,H=new WeakSet,F=async function(t){let r;if(ae(t))r={...t,grant_type:"authorization_code"};else if(Fe(t))r={...t,grant_type:"refresh_token"};else if(qe(t))r={...t,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await k(this,I,$).call(this,"post","auth/token",r,!0).then(n=>{var c;this.bearerProfile=n,this.isAuthorized=!!n,E(this,L,`Bearer ${n==null?void 0:n.access_token}`),T||window.localStorage.setItem(W,((c=this.bearerProfile)==null?void 0:c.refresh_token)||"")}).catch(n=>{throw T||(localStorage.removeItem(M),localStorage.removeItem(W),ie()),new Error(n==null?void 0:n.message)}),ae(t)&&ie(),this.bearerProfile},I=new WeakSet,$=async function(t,r,n,c){return ce(`${g(this,R).api}/${r}`,t,c?te(n):n,{Authorization:g(this,L)||"","Content-Type":`application/${c?"x-www-form-urlencoded":"json"}`})},V=new WeakMap,G=new WeakMap,J=new WeakMap;exports.AccountState=pe;exports.Currency=ue;exports.KYCOutcome=le;exports.KYCState=de;exports.MoneriumClient=De;exports.OrderKind=ge;exports.OrderState=we;exports.PaymentStandard=ve;exports.Permission=fe;exports.ProfileType=he;exports.constants=Ie;exports.getChain=Z;exports.getNetwork=re;exports.placeOrderMessage=Ae;exports.rfc3339=ee; | ||
'use strict'; | ||
Object.defineProperty(exports, '__esModule', { value: true }); | ||
var z = require('crypto-js/enc-base64url'); | ||
var F = require('crypto-js/sha256'); | ||
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; } | ||
var z__default = /*#__PURE__*/_interopDefault(z); | ||
var F__default = /*#__PURE__*/_interopDefault(F); | ||
var h={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 d={LINK_MESSAGE:"I hereby declare that I am the address owner.",STORAGE_CODE_VERIFIER:"monerium.sdk.code_verifier",STORAGE_REFRESH_TOKEN:"monerium.sdk.refresh_token"};var R=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(R||{}),b=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(b||{}),O=(t=>(t.corporate="corporate",t.personal="personal",t))(O||{}),N=(t=>(t.read="read",t.write="write",t))(N||{}),P=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(P||{}),T=(r=>(r.approved="approved",r.rejected="rejected",r.unknown="unknown",r))(T||{}),v=(r=>(r.requested="requested",r.approved="approved",r.pending="pending",r))(v||{}),q=(r=>(r.iban="iban",r.scan="scan",r.chain="chain",r))(q||{}),B=(t=>(t.redeem="redeem",t.issue="issue",t))(B||{}),$=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))($||{});var C=n=>{if(n.toString()==="Invalid Date")throw n;let e=r=>r<10?"0"+r:r,t=r=>{if(r===0)return "Z";let i=r>0?"-":"+";return r=Math.abs(r),i+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())},U=(n,e,t,r)=>{let i=`${r?.toUpperCase()||"EUR"}`;return t?`Send ${i} ${n} to ${e} on ${g(t)} at ${C(new Date)}`:`Send ${i} ${n} to ${e} at ${C(new Date)}`},u=n=>n&&Object.entries(n)?.length>0?Object.entries(n).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",g=n=>{switch(n){case 1:case 11155111:return "ethereum";case 100:case 10200:return "gnosis";case 137:case 80002:return "polygon";default:throw new Error(`Chain not supported: ${n}`)}},M=n=>{switch(n){case 1:case 100:case 137:return "mainnet";case 11155111:return "sepolia";case 10200:return "chiado";case 80002:return "amoy";default:throw new Error(`Network not supported: ${n}`)}};var p=n=>{if(n?.chainId){let{chainId:e,...t}=n;return {...t,chain:g(e)}}return n};var D=(n,e)=>{let{client_id:t,redirect_uri:r,scope:i,state:s,chainId:o,chain:c,address:k,signature:E}=n,S=k?{address:k,...E!==void 0?{signature:E}:{},...o!==void 0||c!==void 0?{chain:o?g(o):c}:{}}:{};return u({client_id:t,redirect_uri:r,...i!==void 0?{scope:i}:{},...s!==void 0?{state:s}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...S})},V=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,r=0;for(;r<128;)n+=e.charAt(Math.floor(Math.random()*t)),r+=1;return n},K=n=>z__default.default.stringify(F__default.default(n)),x=(n,e)=>{let t=V(),r=K(t);return localStorage.setItem(d.STORAGE_CODE_VERIFIER,t||""),`${n}/auth?${D(e,r)}`},w=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,t]=n.split("?");t&&window.history.replaceState(null,"",e);},y=n=>n.code!=null,I=n=>n.refresh_token!=null,_=n=>n.client_secret!=null;var A=async(n,e,t,r)=>{let i=await fetch(`${n}`,{method:e,headers:r,body:t}),s,o=await i.text();try{s=JSON.parse(o);}catch{throw o}if(!i.ok)throw s;return s};var {STORAGE_CODE_VERIFIER:l,STORAGE_REFRESH_TOKEN:m}=d,a=typeof window>"u",f=class{#t;#s;codeVerifier;bearerProfile;#o;#n=new Map;isAuthorized=!!this.bearerProfile;#r;state;constructor(e){if(!e){this.#t=h.environments.sandbox;return}if(typeof e=="string")this.#t=h.environments[e];else if(this.#t=h.environments[e.environment||"sandbox"],a){let{clientId:t,clientSecret:r}=e;this.#r={clientId:t,clientSecret:r};}else {let{clientId:t,redirectUrl:r}=e;this.#r={clientId:t,redirectUrl:r};}}async authorize(e){let t=e?.clientId||this.#r?.clientId,r=e?.redirectUrl||this.#r?.redirectUrl;if(!t)throw new Error("Missing ClientId");if(!r)throw new Error("Missing RedirectUrl");let i=x(this.#t.api,{client_id:t,redirect_uri:r,address:e?.address,signature:e?.signature,chainId:e?.chainId,state:e?.state});window.location.assign(i);}async getAccess(e){let t=e?.clientId||this.#r?.clientId;if(e?.clientSecret||this.#r?.clientSecret){if(!a)throw new Error("Only use client credentials on server side");return await this.#c(this.#r),!!this.bearerProfile}let i=e?.redirectUrl||this.#r?.redirectUrl;if(!t)throw new Error("Missing ClientId");if(a)throw new Error("This only works client side");let s=new URLSearchParams(window.location.search).get("code")||void 0,o=new URLSearchParams(window.location.search).get("state")||void 0,c=localStorage.getItem(m)||void 0;return c?await this.#d(t,c):s&&await this.#a(t,i,s,o),!!this.bearerProfile}async#i(e){let t;if(y(e))t={...e,grant_type:"authorization_code"};else if(I(e))t={...e,grant_type:"refresh_token"};else if(_(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=>{this.bearerProfile=r,this.isAuthorized=!!r,this.#s=`Bearer ${r?.access_token}`,a||window.localStorage.setItem(m,this.bearerProfile?.refresh_token||"");}).catch(r=>{throw a||(localStorage.removeItem(l),localStorage.removeItem(m),w()),new Error(r?.message)}),y(e)&&w(),this.bearerProfile}getAuthContext(){return this.#e("get","auth/context")}getProfile(e){return this.#e("get",`profiles/${e}`)}getBalances(e){return e?this.#e("get",`profiles/${e}/balances`):this.#e("get","balances")}getOrders(e){let t=u(e);return this.#e("get",`orders?${t}`)}getOrder(e){return this.#e("get",`orders/${e}`)}getTokens(){return this.#e("get","tokens")}linkAddress(e,t){return t=p(t),t.accounts=t.accounts.map(r=>p(r)),this.#e("post",`profiles/${e}/addresses`,JSON.stringify(t))}placeOrder(e,t){let r={kind:"redeem",currency:"eur",...p(e),counterpart:{...e.counterpart,identifier:p(e.counterpart.identifier)}};return t?this.#e("post",`profiles/${t}/orders`,JSON.stringify(r)):this.#e("post","orders",JSON.stringify(r))}uploadSupportingDocument(e){let t=new FormData;return t.append("file",e),A(`${this.#t.api}/files`,"post",t,{Authorization:this.#s||""})}async#e(e,t,r,i){return A(`${this.#t.api}/${t}`,e,i?u(r):r,{Authorization:this.#s||"","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`})}#a=async(e,t,r,i)=>{let s=localStorage.getItem(l)||"";if(!s)throw new Error("Code verifier not found");return this.codeVerifier=s,this.state=i,localStorage.removeItem(l),await this.#i({code:r,redirect_uri:t,client_id:e,code_verifier:s})};#c=async({clientId:e,clientSecret:t})=>await this.#i({client_id:e,client_secret:t});#d=async(e,t)=>await this.#i({refresh_token:t,client_id:e});async connectOrderSocket(){this.bearerProfile?.access_token&&this.#n.size>0&&(this.#o=this.subscribeToOrderNotifications());}subscribeToOrderNotifications=()=>{let e=`${this.#t.wss}/profiles/${this.bearerProfile?.profile}/orders?access_token=${this.bearerProfile?.access_token}`,t=new WebSocket(e);return t.addEventListener("open",()=>{console.info(`Socket connected: ${e}`);}),t.addEventListener("error",r=>{throw console.error(r),new Error(`Socket error: ${e}`)}),t.addEventListener("message",r=>{let i=JSON.parse(r.data);this.#n.get(i.meta.state)?.(i);}),t.addEventListener("close",()=>{console.info(`Socket connection closed: ${e}`);}),t};async disconnect(){a||localStorage.removeItem(l),this.#n.clear(),this.#o?.close(),this.#s=void 0,this.bearerProfile=void 0;}async revokeAccess(){a||localStorage.removeItem(m),this.disconnect();}subscribeOrders(e,t){this.#n.set(e,t);}unsubscribeOrders(e){this.#n.delete(e),this.#n.size===0&&(this.#o?.close(),this.#o=void 0);}auth=async e=>await this.#i(e);connect=async e=>await this.#i(e);getAuthFlowURI=e=>{let t=x(this.#t.api,e);return this.codeVerifier=localStorage.getItem(l),t};pkceRequest=e=>this.getAuthFlowURI(e);getEnvironment=()=>this.#t};var me=f; | ||
exports.AccountState = v; | ||
exports.Currency = R; | ||
exports.KYCOutcome = T; | ||
exports.KYCState = P; | ||
exports.Method = b; | ||
exports.MoneriumClient = f; | ||
exports.OrderKind = B; | ||
exports.OrderState = $; | ||
exports.PaymentStandard = q; | ||
exports.Permission = N; | ||
exports.ProfileType = O; | ||
exports.constants = d; | ||
exports.default = me; | ||
exports.getChain = g; | ||
exports.getNetwork = M; | ||
exports.placeOrderMessage = U; | ||
exports.rfc3339 = C; |
{ | ||
"name": "@monerium/sdk", | ||
"version": "2.12.1", | ||
"description": "Everything you need to interact with the Monerium API - an electronic money issuer.", | ||
"license": "MIT", | ||
"version": "2.13.0", | ||
"description": "Essential tools to interact with the Monerium API, an electronic money issuer.", | ||
"repository": { | ||
"type": "git", | ||
"url": "git+https://github.com/monerium/js-sdk.git" | ||
"url": "git+https://github.com/monerium/js-monorepo.git", | ||
"directory": "packages/sdk" | ||
}, | ||
"bugs": { | ||
"url": "https://github.com/monerium/js-sdk/issues" | ||
"url": "https://github.com/monerium/js-monorepo/issues" | ||
}, | ||
"main": "./dist/index.js", | ||
"module": "./dist/index.mjs", | ||
"typings": "./dist/index.d.ts", | ||
"types": "./dist/index.d.ts", | ||
"exports": { | ||
@@ -24,19 +24,32 @@ ".": { | ||
"files": [ | ||
"dist" | ||
"dist/index.js", | ||
"dist/index.mjs", | ||
"dist/index.d.ts" | ||
], | ||
"dependencies": { | ||
"crypto-js": "^4.2.0" | ||
}, | ||
"devDependencies": { | ||
"@types/crypto-js": "^4.2.2", | ||
"jest-fetch-mock": "^3.0.3", | ||
"jest-localstorage-mock": "^2.4.26", | ||
"timezone-mock": "^1.3.6", | ||
"typedoc": "^0.25.13", | ||
"typedoc-plugin-markdown": "^4.0.3", | ||
"typescript": "latest" | ||
}, | ||
"engines": { | ||
"node": ">= 16.15" | ||
}, | ||
"dependencies": { | ||
"crypto-js": "^4.2.0" | ||
}, | ||
"scripts": { | ||
"docs": "yarn typedoc --options docs/typedoc.json && node docs/editStatic.js", | ||
"docs:watch": "nodemon --watch . --ignore static -e ts,css,md --exec 'typedoc --options docs/typedoc.json && node docs/editStatic.js'" | ||
}, | ||
"devDependencies": { | ||
"nodemon": "3.0.1", | ||
"typedoc": "0.23.23", | ||
"typedoc-theme-hierarchy": "^3.2.1" | ||
"dev": "tsup --watch --onSuccess 'pnpm type-map && pnpm run docs'", | ||
"build": "tsup", | ||
"docs": "typedoc", | ||
"docs:watch": "typedoc --watch", | ||
"type-map": "tsc --emitDeclarationOnly --declaration", | ||
"lint": "eslint . --fix", | ||
"pub:pre": "pnpm publish --no-git-checks --dry-run", | ||
"test": "jest", | ||
"test:watch": "jest --watch" | ||
} | ||
} | ||
} |
@@ -0,1 +1,4 @@ | ||
| [Monerium.com](https://monerium.com/) | [Monerium.app](https://monerium.app/) | [Monerium.dev](https://monerium.dev/) | | ||
| ------------------------------------- | ------------------------------------- | ------------------------------------- | | ||
# Monerium SDK Documentation | ||
@@ -8,2 +11,9 @@ | ||
## Useful resources | ||
- [Documentation](./docs/generated/README.md) | ||
- [API Documentation](https://monerium.dev/api-docs) | ||
- [Developer portal](https://monerium.dev/') | ||
- [NPM](https://www.npmjs.com/package/@monerium/sdk) | ||
## Table of Contents | ||
@@ -53,3 +63,3 @@ | ||
We recommend starting in the [Developer Portal](https://monerium.dev/docs/welcome). There you will learn more about `client_id`'s and ways of authenticating. | ||
We recommend starting in the [Developer Portal](https://monerium.dev/docs/welcome). There, you will learn more about `client_id`'s and ways of authenticating. | ||
@@ -92,3 +102,3 @@ #### Initialize and authenticate using Client Credentials | ||
First you have to navigate the user to the Monerium authentication flow. This can be done by generating a URL and redirecting the user to it. After the user has authenticated, Monerium will redirect back to your specified URI with a code. You can then finalize the authentication process by exchanging the code for access and refresh tokens. | ||
First, you have to navigate the user to the Monerium authentication flow. This can be done by generating a URL and redirecting the user to it. After the user has authenticated, Monerium will redirect back to your specified URI with a code. You can then finalize the authentication process by exchanging the code for access and refresh tokens. | ||
@@ -169,3 +179,5 @@ ```ts | ||
// Fetching all accounts for a specific profile | ||
const { id: profileId, accounts }: Profile = await monerium.getProfile(authCtx.profiles[0].id); | ||
const { id: profileId, accounts }: Profile = await monerium.getProfile( | ||
authCtx.profiles[0].id | ||
); | ||
@@ -206,3 +218,3 @@ // Fetching all balances for a specific profile | ||
It's important to understand, when interacting with a blockchain, the user needs to provide a signature in their wallet. | ||
It's important to understand when interacting with a blockchain, the user needs to provide a signature in their wallet. | ||
This signature is used to verify that the user is the owner of the wallet address. | ||
@@ -310,3 +322,4 @@ | ||
// Upload a supporting document | ||
const supportingDocumentId: SupportingDoc = await uploadSupportingDocument(document); | ||
const supportingDocumentId: SupportingDoc = | ||
await uploadSupportingDocument(document); | ||
``` | ||
@@ -359,41 +372,23 @@ | ||
We are using Yarn as a package manager. | ||
We are using PNPM as a package manager. | ||
```sh | ||
# Install dependencies | ||
nx run sdk:init | ||
#### Development mode | ||
# Run Vite to build a production release distributable | ||
nx run sdk:build | ||
# Run Vite in watch mode to detect changes to files during development | ||
nx run sdk:build --watch | ||
# Update the docs. This will run the build and update the docs in the static folder. | ||
# Open static/index.html in your browser to view the docs. Refresh the page to see changes. | ||
nx run sdk:docs:watch | ||
``` | ||
pnpm dev | ||
``` | ||
## Linking | ||
While in development mode, TypeScript declaration maps (`.d.ts.map`) are generated. TypeScript declaration maps are mainly used to quickly jump to type definitions in the context of a monorepo. | ||
For development, a package can be linked into another project. This is often useful to test out new features or when trying to debug an issue in a package that manifests itself in another project. run yarn link inside of the sdk project. | ||
#### Build | ||
```sh | ||
YARN_IGNORE_PATH=1 yarn link | ||
``` | ||
Use `yarn link "@monerium/sdk"` to link and test into your current project. | ||
```sh | ||
cd ../your-project | ||
yarn link "@monerium/sdk" | ||
pnpm build | ||
``` | ||
If you get an error that there is already a package called '@monerium/sdk' registered, but you can't find it and unlinking does nothing, remove it manually with `rm -rf ~/.config/yarn/link/@monerium` and try again. | ||
### Documentation | ||
Refer to [Typedocs](https://typedoc.org/) syntaxes to use for this [documentation](https://monerium.github.io/js-sdk/). | ||
Refer to [Typedocs](https://typedoc.org/) syntaxes to use for this [documentation](https://monerium.github.io/js-monorepo/). | ||
There is a Github action that will automatically run on the successful release of the SDK. It will generate a static output of the documentation and push it to the `gh-pages` branch. The documentation is then available at https://monerium.github.io/js-sdk/. | ||
There is a Github action that will automatically run on the successful release of the SDK. It will generate a static output of the documentation and push it to the `gh-pages` branch. The documentation is then available at https://monerium.github.io/js-monorepo/. | ||
@@ -411,7 +406,9 @@ #### Publishing | ||
[Support](https://monerium.app/help) | ||
[Telegram](https://t.me/+lGtM1gY9zWthNGE8) | ||
[Github Issues](https://github.com/monerium/js-sdk/issues) | ||
[Github Issues](https://github.com/monerium/js-monorepo/issues) | ||
## Release Notes | ||
https://github.com/monerium/js-sdk/releases | ||
https://github.com/monerium/js-monorepo/releases |
Sorry, the diff of this file is not supported yet
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Minified code
QualityThis package contains minified code. This may be harmless in some cases where minified code is included in packaged libraries, however packages on npm should not minify code.
Found 1 instance in 1 package
No License Found
License(Experimental) License information could not be found.
Found 1 instance in 1 package
48127
7
5
1
656
2
407
3