New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@monerium/sdk

Package Overview
Dependencies
Maintainers
0
Versions
75
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@monerium/sdk - npm Package Compare versions

Comparing version 2.15.0 to 3.0.0

575

dist/index.d.ts

@@ -13,11 +13,6 @@ type Environment = {

type ENV = 'sandbox' | 'production';
type EthereumTestnet = 'sepolia';
type GnosisTestnet = 'chiado';
type PolygonTestnet = 'amoy';
type Chain = 'ethereum' | 'gnosis' | 'polygon' | 'gnosismainnet';
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;
type Chain = 'ethereum' | 'gnosis' | 'polygon' | 'arbitrum' | 'noble';
type EvmChainId = number | 1 | 11155111 | 100 | 137 | 10200 | 80002 | 42161 | 421614;
type ChainId = EvmChainId | CosmosChainId;
type CosmosChainId = 'noble-1' | 'grand-1' | 'florin-1';
declare enum Currency {

@@ -31,4 +26,5 @@ eur = "eur",

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;
type CurrencyCode = 'eur' | 'gbp' | 'usd' | 'isk';
type AuthArgs = Omit<AuthCodePayload, 'grant_type'> | Omit<RefreshTokenPayload, 'grant_type'> | Omit<ClientCredentialsPayload, 'grant_type'>;
type OpenArgs = Omit<AuthCodePayload, 'grant_type' | 'code' | 'code_verifier'> | Omit<RefreshTokenPayload, 'grant_type'> | Omit<ClientCredentialsPayload, 'grant_type'> | PKCERequestArgs;
/** One of the options for the {@link AuthArgs}.

@@ -38,3 +34,3 @@ *

* */
interface AuthCodeRequest {
interface AuthCodePayload {
grant_type: 'authorization_code';

@@ -45,3 +41,2 @@ client_id: string;

redirect_uri: string;
scope?: string;
}

@@ -52,7 +47,6 @@ /** One of the options for the {@link AuthArgs}.

* */
interface RefreshTokenRequest {
interface RefreshTokenPayload {
grant_type: 'refresh_token';
client_id: string;
refresh_token: string;
scope?: string;
}

@@ -63,7 +57,6 @@ /** One of the options for the {@link AuthArgs}.

* */
interface ClientCredentialsRequest {
interface ClientCredentialsPayload {
grant_type: 'client_credentials';
client_id: string;
client_secret: string;
scope?: string;
}

@@ -103,2 +96,6 @@ interface BearerProfile {

chain?: Chain | ChainId;
/** You can skip the connect wallet and request IBAN steps in the Authorization Flow and use the Link Address and Request IBAN API endpoints after you have gotten the authorization */
skip_create_account?: boolean;
/** You can skip the KYC onboarding steps in the Authorization Flow and use the the details, additional data, and verifications API endpoints after you have gotten the authorization. */
skip_kyc?: boolean;
};

@@ -119,21 +116,14 @@ declare enum Method {

}
interface AuthProfile {
id: string;
type: ProfileType;
name: string;
perms: Permission[];
declare enum ProfileState {
/** The profile has been created but no details have been submitted.*/
created = "created",
/** The details have been submitted and are being processed. */
pending = "pending",
/** The profile is active and all Monerium services are supported.*/
approved = "approved",
/**The applicant details did not meet the compliance requirements of Monerium. Details can be fixed and re-submitted for processing.*/
rejected = "rejected",
/**Monerium is unable to offer the applicant services because of compliance reasons. Details cannot be re-submitted.*/
blocked = "blocked"
}
interface AuthContext {
userId: string;
email: string;
name: string;
roles: 'admin'[];
auth: {
method: Method;
subject: string;
verified: boolean;
};
defaultProfile: string;
profiles: AuthProfile[];
}
declare enum KYCState {

@@ -164,2 +154,11 @@ absent = "absent",

}
/**
* The type of ID document. Passports, National ID cards, and driving licenses are supported.
* The ID document must verify the person's name, birthday, and nationality
*/
declare enum IdDocumentKind {
passport = "passport",
nationalIdentityCard = "nationalIdentityCard",
drivingLicense = "drivingLicense"
}
interface Identifier {

@@ -169,21 +168,85 @@ standard: PaymentStandard;

}
interface Account {
address: string;
currency: Currency;
standard: PaymentStandard;
iban?: string;
network?: Network;
chain: Chain;
id?: string;
state?: AccountState;
interface ProfilePermissions {
id: string;
kind: ProfileType;
name: string;
perms: Permission[];
}
interface ProfilesResponse {
profiles: ProfilePermissions[];
}
interface Profile {
id: string;
name: string;
email: string;
kind: ProfileType;
state: ProfileState;
kyc: KYC;
kind: ProfileType;
accounts: Account[];
}
interface Balance {
interface ProfilesQueryParams {
/** profile state to filter by */
state?: ProfileState;
/** profile kind to filter by */
kind?: ProfileType;
}
interface PersonalProfileDetails {
idDocument: {
number: string;
kind: IdDocumentKind;
};
firstName: string;
lastName: string;
address: string;
postalCode: string;
city: string;
country: string;
countryState?: string;
nationality: string;
birthday: string;
}
interface PersonalProfileDetailsRequest {
personal: PersonalProfileDetails;
}
type Representative = PersonalProfileDetails;
type Beneficiary = Omit<PersonalProfileDetails, 'idDocument'> & {
/** Ownership in % that is between 25% and 100%. */
ownershipPercentage: number;
};
type Director = Omit<PersonalProfileDetails, 'idDocument'>;
interface CorporateProfileDetails {
name: string;
registrationNumber: string;
address: string;
postalCode: string;
city: string;
country: string;
countryState: string;
/** List of individuals representing the company and authorized to act on it's behalf. */
representatives: Representative[];
/** List of beneficial owner that owns 25% or more in a corporation. */
finalBeneficiaries: Beneficiary[];
/** List of Individual who has powers to legally bind the company (power of procuration). */
directors: Director[];
}
interface CorporateProfileDetailsRequest {
corporate: CorporateProfileDetails;
}
type SubmitProfileDetailsPayload = PersonalProfileDetailsRequest | CorporateProfileDetailsRequest;
interface AddressesQueryParams {
/** Filter the list by profile */
profile?: string;
/** Filter the list by chain */
chain?: Chain | ChainId;
}
interface Address {
/** The id of the profile the address belongs to. */
profile: string;
/** The address */
address: string;
/** Which chains is the address linked on. */
chains: Chain[];
}
interface AddressesResponse {
addresses: Address[];
}
interface CurrencyBalance {
currency: Currency;

@@ -196,4 +259,3 @@ amount: string;

chain: Chain;
network: Network;
balances: Balance[];
balances: CurrencyBalance[];
}

@@ -215,7 +277,7 @@ declare enum OrderKind {

}
interface IBAN extends Identifier {
interface IBANIdentifier extends Identifier {
standard: PaymentStandard.iban;
iban: string;
}
interface CrossChain extends Identifier {
interface CrossChainIdentifier extends Identifier {
standard: PaymentStandard.chain;

@@ -227,3 +289,3 @@ /** The receivers address */

}
interface SCAN extends Identifier {
interface SCANIdentifier extends Identifier {
standard: PaymentStandard.scan;

@@ -243,3 +305,3 @@ sortCode: string;

interface Counterpart {
identifier: IBAN | SCAN | CrossChain;
identifier: IBANIdentifier | SCANIdentifier | CrossChainIdentifier;
details: Individual | Corporation;

@@ -271,2 +333,3 @@ }

kind: OrderKind;
chain: Chain;
amount: string;

@@ -282,2 +345,5 @@ currency: Currency;

}
interface OrdersResponse {
orders: Order[];
}
/**

@@ -291,3 +357,2 @@ * Information about the EURe token on different networks.

chain: Chain;
network: Network;
/** The address of the EURe contract on this network */

@@ -329,19 +394,25 @@ address: string;

}
interface CurrencyAccounts {
/** The accounts network */
chain: Chain | ChainId;
currency: Currency;
}
interface LinkAddress {
/** Profile ID that owns the address. */
profile?: string;
/** The public key of the blockchain account. */
address: string;
message: string;
/**
* Fixed message to be signed with the private key corresponding to the given address.
*
* `I hereby declare that I am the address owner.`
*/
message?: string;
/**
* The signature hash of signing the `message` with the private key associated with the given address.
* For signing on-chain with ERC1271 contracts, use `0x`, visit the documentation for further details.
* https://monerium.dev/api-docs-v2#tag/addresses/operation/link-address
*/
signature: string;
accounts: CurrencyAccounts[];
chain?: Chain | ChainId;
chain: Chain | ChainId;
}
interface LinkedAddress {
id: string;
profile: string;
address: string;
message: string;
state: string;
meta: {

@@ -352,33 +423,55 @@ linkedBy: string;

}
interface OrderNotification {
id: string;
interface RequestIbanPayload {
/** the address to request the IBAN. */
address: string;
/** the chain to request the IBAN. */
chain: Chain | ChainId;
/** payment email notifications sent to customers, `true` by default. */
emailNotifications: boolean;
}
interface IbansQueryParams {
profile?: string;
chain?: Chain | ChainId;
}
interface IBAN {
iban: string;
bic: 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;
chain: Chain;
}
type MoneriumEvent = OrderState;
type MoneriumEventListener = (notification: OrderNotification) => void;
interface IBANsResponse {
ibans: IBAN[];
}
interface MoveIbanPayload {
/** the address to move iban to */
address: string;
/** the chain to move iban to */
chain: Chain | ChainId;
}
interface OrderNotificationQueryParams {
state?: OrderState;
profile?: string;
}
type ClassOptions = {
environment?: ENV;
debug?: boolean;
} & BearerTokenCredentials;
interface AuthFlowOptions {
/** the auth flow client ID for your application */
clientId?: string;
/** the redirect URI defined by your application */
redirectUri?: string;
/** @deprecated use redirectUri */
redirectUrl?: string;
/** the address your customer should link in auth flow */
address?: string;
/** the signature of the address */
signature?: string;
/** the chain of the address */
chain?: Chain | ChainId;
/** the state oauth parameter */
state?: string;
scope?: string;
/** skip account creation in auth flow */
skipCreateAccount?: boolean;
/** skip KYC in auth flow */
skipKyc?: boolean;
}

@@ -393,22 +486,36 @@ interface ClientCredentials {

}
/** @deprecated use redirectUri */
interface DeprecatedAuthorizationCodeCredentials {
clientId?: string;
/** @deprecated use redirectUri */
redirectUrl?: string;
}
type BearerTokenCredentials = ClientCredentials | AuthorizationCodeCredentials | DeprecatedAuthorizationCodeCredentials;
type BearerTokenCredentials = ClientCredentials | AuthorizationCodeCredentials;
type ResponseStatus = {
status: number;
statusText: string;
};
/**
* In the [Monerium UI](https://monerium.app/), create an application to get the `clientId` and register your `redirectUri`.
* ```ts
* import { MoneriumClient } from '@monerium/sdk';
*
* const monerium = new MoneriumClient() // defaults to `sandbox`
*
* // or
* new MoneriumClient('production')
*
* // or
* new MoneriumClient({
* environment: 'sandbox',
* clientId: 'your-client-id',
* redirectUri: 'http://your-redirect-url.com/monerium'
* });
*
*```
*/
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;
/**
* The client is authorized if the bearer profile is available
*/
isAuthorized: boolean;

@@ -421,12 +528,2 @@ /**

* @defaultValue `sandbox`
* @example
* new MoneriumClient() // defaults to `sandbox`
*
* new MoneriumClient('production')
*
* new MoneriumClient({
* environment: 'sandbox',
* clientId: 'your-client-id',
* redirectUri: 'your-redirect-url'
* })
* */

@@ -438,79 +535,160 @@ constructor(envOrOptions?: ENV | ClassOptions);

* For automatic wallet link, add the following properties: `address`, `signature` & `chain`
*
* @group Authentication
* @see {@link https://monerium.dev/api-docs-v2#tag/auth/operation/auth | API Documentation}
* @param {AuthFlowOptions} [params] - the auth flow params
* @returns string
* {@link https://monerium.dev/api-docs#operation/auth}
* @category Auth
*
*/
authorize(client?: AuthFlowOptions): Promise<void>;
authorize(params?: AuthFlowOptions): Promise<void>;
/**
* Get access to the API
* Will use the authorization code flow code to get access token
*
* @group Authentication
*
* @param {AuthorizationCodeCredentials | ClientCredentials} client - the client credentials
*
* @returns boolean to indicate if access has been granted
* @category Auth
*
* @example
* ```ts
* import { MoneriumClient } from '@monerium/sdk';
* // Initialize the client with credentials
* const monerium = new MoneriumClient({
* environment: 'sandbox',
* clientId: 'your_client_credentials_uuid', // replace with your client ID
* clientSecret: 'your_client_secret', // replace with your client secret
* });
*
* await monerium.getAccess();
* ```
*/
getAccess(client?: AuthorizationCodeCredentials | ClientCredentials | DeprecatedAuthorizationCodeCredentials): Promise<boolean>;
getAccess(refreshToken?: string): Promise<boolean>;
/**
* {@link https://monerium.dev/api-docs#operation/auth-context}
* @category Auth
* @group Profiles
* @param {string} profile - the id of the profile to fetch.
* @see {@link https://monerium.dev/api-docs-v2#tag/profiles/operation/profile | API Documentation}
*/
getAuthContext(): Promise<AuthContext>;
getProfile(profile: string): Promise<Profile>;
/**
* {@link https://monerium.dev/api-docs#operation/profile}
* @param {string} profileId - the id of the profile to fetch.
* @category Profiles
* @group Profiles
* @see {@link https://monerium.dev/api-docs-v2#tag/profiles/operation/profiles | API Documentation}
*/
getProfile(profileId: string): Promise<Profile>;
getProfiles(params?: ProfilesQueryParams): Promise<ProfilesResponse>;
/**
* {@link https://monerium.dev/api-docs#operation/profiles}
* @category Profiles
*
* Get details for a single address by using the address public key after the address has been successfully linked to Monerium.
*
* @group Addresses
* @param {string} address - The public key of the blockchain account.
*
* @see {@link https://monerium.dev/api-docs-v2#tag/addresses/operation/address | API Documentation}
*
* @example
* ```ts
* monerium.getAddress('0x1234567890abcdef1234567890abcdef12345678')
* ```
*/
getProfiles(): Promise<Profile[]>;
getAddress(address: string): Promise<Address>;
/**
* {@link https://monerium.dev/api-docs#operation/profile-balances}
* @param {string=} profileId - the id of the profile to fetch balances.
* @category Accounts
* @group Addresses
* @param {AddressesQueryParams} [params] - No required parameters.
* @see {@link https://monerium.dev/api-docs-v2#tag/addresses/operation/addresses | API Documentation}
*/
getBalances(profileId?: string): Promise<Balances[]>;
getAddresses(params?: AddressesQueryParams): Promise<AddressesResponse>;
/**
* {@link https://monerium.dev/api-docs#operation/orders}
* @category Orders
* @group Addresses
* @see {@link https://monerium.dev/api-docs/v2#tag/addresses/operation/balances| API Documentation}
*/
getOrders(filter?: OrderFilter): Promise<Order[]>;
getBalances(address: string, chain: Chain | ChainId, currencies?: Currency | Currency[]): Promise<Balances>;
/**
* {@link https://monerium.dev/api-docs#operation/order}
* @category Orders
* Fetch details about a single IBAN
*
* @group IBANs
* @param {string} iban - the IBAN to fetch.
* @see {@link https://monerium.dev/api-docs-v2#tag/ibans/operation/iban | API Documentation}
*/
getIban(iban: string): Promise<IBAN>;
/**
* Fetch all IBANs for the profile
* @group IBANs
* @see {@link https://monerium.dev/api-docs-v2#tag/ibans/operation/ibans | API Documentation}
*/
getIbans(queryParameters?: IbansQueryParams): Promise<IBANsResponse>;
/**
* @group Orders
* @see {@link https://monerium.dev/api-docs-v2#tag/orders | API Documentation}
*/
getOrders(filter?: OrderFilter): Promise<OrdersResponse>;
/**
* @group Orders
* @see {@link https://monerium.dev/api-docs-v2#tag/order | API Documentation}
*/
getOrder(orderId: string): Promise<Order>;
/**
* {@link https://monerium.dev/api-docs#operation/tokens}
* @category Tokens
* @group Tokens
* @see {@link https://monerium.dev/api-docs-v2#tag/tokens | API Documentation}
*/
getTokens(): Promise<Token[]>;
/**
* {@link https://monerium.dev/api-docs#operation/profile-addresses}
* @category Accounts
* Add a new address to the profile
* @group Addresses
* @see {@link https://monerium.dev/api-docs-v2#tag/addresses/operation/link-address | API Documentation}
*/
linkAddress(profileId: string, body: LinkAddress): Promise<LinkedAddress>;
linkAddress(payload: LinkAddress): Promise<LinkedAddress>;
/**
* {@link https://monerium.dev/api-docs#operation/post-orders}
* @category Orders
* @see {@link https://monerium.dev/api-docs-v2#tag/orders/operation/post-orders | API Documentation}
*
* @group Orders
*/
placeOrder(order: NewOrder): Promise<Order>;
/**
* {@link https://monerium.dev/api-docs#operation/supporting-document}
* @category Orders
* @group IBANs
* @param {string} iban - the IBAN to move.
* @param {MoveIbanPayload} payload - the payload to move the IBAN.
* @see {@link https://monerium.dev/api-docs-v2#tag/ibans/operation/move-iban | API Documentation}
*/
moveIban(iban: string, { address, chain }: MoveIbanPayload): Promise<ResponseStatus>;
/**
* @group IBANs
* @param {RequestIbanPayload} payload
* @see {@link https://monerium.dev/api-docs-v2#tag/ibans/operation/request-iban | API Documentation}
*/
requestIban({ address, chain, emailNotifications, }: RequestIbanPayload): Promise<ResponseStatus>;
/**
* @group Profiles
* @see {@link https://monerium.dev/api-docs-v2#tag/profiles/operation/profile-details | API Documentation}
*/
submitProfileDetails(profile: string, body: SubmitProfileDetailsPayload): Promise<ResponseStatus>;
/**
* @group Orders
* @see {@link https://monerium.dev/api-docs-v2#tag/orders/operation/supporting-document | API Documentation}
*/
uploadSupportingDocument(document: File): Promise<SupportingDoc>;
/**
* Connects to the order notifications socket
* @category Orders
*
* @group Orders
* @param {OrderNotificationQueryParams} [params]
* @see {@link https://monerium.dev/api-docs-v2#tag/orders/operation/orders-notifications | API Document - Websocket}
*/
connectOrderSocket(): Promise<void>;
subscribeOrderNotifications({ filter, onMessage, onError, }?: {
/** specify which type of orders to listen to */
filter?: OrderNotificationQueryParams;
onMessage?: (data: Order) => void;
onError?: (err: Event) => void;
}): WebSocket | undefined;
/**
* Subscribes to the order notifications socket
* @category Orders
* Closes the order notifications sockets
*
* @group Orders
* @param {OrderNotificationQueryParams} [params] - specify which socket to close or close all if not provided
* @see {@link https://monerium.dev/api-docs-v2#tag/orders/operation/orders-notifications | API Document - Websocket}
*/
subscribeToOrderNotifications: () => WebSocket;
unsubscribeOrderNotifications(params?: OrderNotificationQueryParams): void;
/**
* Cleanups the socket and the subscriptions
* @category Auth
* Cleanups the localstorage and websocket connections
*
* @group Authentication
*/

@@ -520,21 +698,8 @@ disconnect(): Promise<void>;

* Revokes access
* @category Auth
*
* @group Authentication
*/
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;
/**
*
* @hidden

@@ -544,2 +709,3 @@ */

/**
*
* @hidden

@@ -560,9 +726,26 @@ */

/**
* The key used to store the refresh token in the local storage.
* The key used to store the access token in the local storage.
*/
STORAGE_REFRESH_TOKEN: string;
STORAGE_ACCESS_TOKEN: string;
/**
* The unix timestamp used to calculate the expiration time of the access token.
*/
STORAGE_ACCESS_EXPIRY: string;
};
/**
*
* @param d Date to be formatted
* @returns RFC3339 date format.
* @example 2023-04-30T12:00:00+01:00
* @example 2023-04-30T02:08:15Z
*/
declare const rfc3339: (d: Date) => string;
/**
* This will resolve the chainId number to the corresponding chain name.
* @param chain The chainId of the network
* @returns chain name, 'ethereum', 'polygon', 'gnosis', etc.
*/
declare const parseChain: (chain: Chain | ChainId | number | string) => Chain;
/**
* The message to be signed when placing an order.

@@ -573,11 +756,65 @@ * @param amount The amount to be sent

* @param chain The chainId of the network if it's a cross-chain transaction
* @returns string
* @returns
* cross-chain:
* ```ts
* Send {CURRENCY} {AMOUNT} to {RECEIVER} on {CHAIN} at {DATE}`
* ```
*
* off-ramp:
* ```ts
* Send {CURRENCY} {AMOUNT} to {RECEIVER} at {DATE}
* ```
* @example `Send EUR 1 to 0x1234123412341234123412341234123412341234 on ethereum at 2023-04-30T12:00:00+01:00`
*
* @example `Send EUR 1 to IS1234123412341234 at 2023-04-30T12:00:00+01:00`
*/
declare const placeOrderMessage: (amount: string | number, currency: Currency, receiver: string, chain?: ChainId | Chain) => string;
/**
* Get the corresponding Monerium SDK Chain from the current chain id
* @returns The Chain
* This will resolve the chainId number to the corresponding chain name.
* @param chainId The chainId of the network
* @returns chain name
* @example
* ```ts
* getChain(1) // 'ethereum'
* getChain(11155111) // 'ethereum'
*
* getChain(100) // 'gnosis'
* getChain(10200) // 'gnosis'
*
* getChain(137) // 'polygon'
* getChain(80002) // 'polygon'
* ```
*/
declare const getChain: (chainId: number) => Chain;
declare const shortenIban: (iban?: string) => string | undefined;
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 DeprecatedAuthorizationCodeCredentials, type ENV, type Environment, type EthereumTestnet, type Fee, type GnosisTestnet, type IBAN, type Identifier, type Individual, type KYC, KYCOutcome, KYCState, type LinkAddress, type LinkedAddress, 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, placeOrderMessage, rfc3339 };
/**
* @packageDocumentation
* A library to interact with Monerium API.
*
*
* ## Installation
*
* ```bash
* pnpm add @monerium/sdk
* ```
*
* @example
* ```tsx
* import { MoneriumClient } from '@monerium/sdk';
*
* const monerium = new MoneriumClient({
* clientId: '...',
* redirectUri: '...',
* environment: 'sandbox',
* })
*
* // Will redirect the user to Monerium's authentication code flow.
* await monerium.getAccess();
*
* // Retrieve profiles the client has access to.
* await monerium.getProfiles();
* ```
*/
export { AccountState, type Address, type AddressesQueryParams, type AddressesResponse, type AuthArgs, type AuthCodePayload, type AuthFlowOptions, type AuthorizationCodeCredentials, type Balances, type BearerProfile, type BearerTokenCredentials, type Beneficiary, type Chain, type ChainId, type ClassOptions, type ClientCredentials, type ClientCredentialsPayload, type Config, type CorporateProfileDetails, type CorporateProfileDetailsRequest, type Corporation, type CosmosChainId, type Counterpart, type CrossChainIdentifier, Currency, type CurrencyBalance, type CurrencyCode, type Director, type ENV, type Environment, type EvmChainId, type Fee, type IBAN, type IBANIdentifier, type IBANsResponse, type IbansQueryParams, IdDocumentKind, type Identifier, type Individual, type KYC, KYCOutcome, KYCState, type LinkAddress, type LinkedAddress, Method, MoneriumClient, type MoveIbanPayload, type NewOrder, type NewOrderByAccountId, type NewOrderByAddress, type NewOrderCommon, type OpenArgs, type Order, type OrderFilter, OrderKind, type OrderMetadata, type OrderNotificationQueryParams, OrderState, type OrdersResponse, type PKCERequest, type PKCERequestArgs, PaymentStandard, Permission, type PersonalProfileDetails, type PersonalProfileDetailsRequest, type Profile, type ProfilePermissions, ProfileState, ProfileType, type ProfilesQueryParams, type ProfilesResponse, type RefreshTokenPayload, type Representative, type RequestIbanPayload, type ResponseStatus, type SCANIdentifier, type SubmitProfileDetailsPayload, type SupportingDoc, type SupportingDocMetadata, type Ticker, type Token, type TokenSymbol, _default as constants, MoneriumClient as default, getChain, parseChain, placeOrderMessage, rfc3339, shortenIban };

@@ -5,27 +5,31 @@ 'use strict';

var $ = require('crypto-js/enc-base64url.js');
var D = require('crypto-js/sha256.js');
var W = require('crypto-js/enc-base64url.js');
var H = require('crypto-js/sha256.js');
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
var $__default = /*#__PURE__*/_interopDefault($);
var D__default = /*#__PURE__*/_interopDefault(D);
var W__default = /*#__PURE__*/_interopDefault(W);
var H__default = /*#__PURE__*/_interopDefault(H);
var l={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 c={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 E=(i=>(i.eur="eur",i.usd="usd",i.gbp="gbp",i.isk="isk",i))(E||{}),b=(i=>(i.password="password",i.resource="resource",i.jwt="jwt",i.apiKey="apiKey",i))(b||{}),P=(t=>(t.corporate="corporate",t.personal="personal",t))(P||{}),O=(t=>(t.read="read",t.write="write",t))(O||{}),T=(i=>(i.absent="absent",i.submitted="submitted",i.pending="pending",i.confirmed="confirmed",i))(T||{}),v=(r=>(r.approved="approved",r.rejected="rejected",r.unknown="unknown",r))(v||{}),N=(r=>(r.requested="requested",r.approved="approved",r.pending="pending",r))(N||{}),q=(r=>(r.iban="iban",r.scan="scan",r.chain="chain",r))(q||{}),B=(t=>(t.redeem="redeem",t.issue="issue",t))(B||{}),U=(i=>(i.placed="placed",i.pending="pending",i.processed="processed",i.rejected="rejected",i))(U||{});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())},h=n=>typeof n=="number"?R(n):n,z=(n,e,t,r)=>{let i=`${e?.toUpperCase()||"EUR"}`;return r?`Send ${i} ${n} to ${t} on ${h(r)} at ${C(new Date)}`:`Send ${i} ${n} to ${t} at ${C(new Date)}`},u=n=>n&&Object.entries(n)?.length>0?Object.entries(n).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",R=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}`)}};var p=n=>{if(n?.chain){let{chain:e,...t}=n;return {...t,chain:h(e)}}return n};var M=(n,e)=>{let{client_id:t,redirect_uri:r,scope:i,state:s,address:o,signature:d,chain:k}=n,S=o?{address:o,...d!==void 0?{signature:d}:{},...k!==void 0?{chain:h(k)}:{}}:{};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})},F=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,r=0;for(;r<128;)n+=e.charAt(Math.floor(Math.random()*t)),r+=1;return n},L=n=>$__default.default.stringify(D__default.default(n)),x=(n,e)=>{let t=F(),r=L(t);return localStorage.setItem(c.STORAGE_CODE_VERIFIER,t||""),`${n}/auth?${M(e,r)}`},y=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,t]=n.split("?");t&&window.history.replaceState(null,"",e);},w=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:g,STORAGE_REFRESH_TOKEN:m}=c,a=typeof window>"u",f=class{#t;#i;codeVerifier;bearerProfile;#s;#n=new Map;isAuthorized=!!this.bearerProfile;#r;state;constructor(e){if(!e){this.#t=l.environments.sandbox;return}if(typeof e=="string")this.#t=l.environments[e];else if(this.#t=l.environments[e.environment||"sandbox"],a){let{clientId:t,clientSecret:r}=e;this.#r={clientId:t,clientSecret:r};}else {let{clientId:t,redirectUri:r}=e,{redirectUrl:i}=e;this.#r={clientId:t,redirectUri:r||i};}}async authorize(e){let t=e?.clientId||this.#r?.clientId,r=e?.redirectUri||e?.redirectUrl||this.#r?.redirectUri;if(!t)throw new Error("Missing ClientId");if(!r)throw new Error("Missing RedirectUri");let i=x(this.#t.api,{client_id:t,redirect_uri:r,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,scope:e?.scope});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.#d(this.#r),!!this.bearerProfile}let i=e?.redirectUri||e?.redirectUrl||this.#r?.redirectUri;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,d=localStorage.getItem(m)||void 0;return d?await this.#c(t,d):s&&await this.#a(t,i,s,o),!!this.bearerProfile}async#o(e){let t;if(w(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.#i=`Bearer ${r?.access_token}`,a||window.localStorage.setItem(m,this.bearerProfile?.refresh_token||"");}).catch(r=>{throw a||(localStorage.removeItem(g),localStorage.removeItem(m),y()),new Error(r?.message)}),w(e)&&y(),this.bearerProfile}getAuthContext(){return this.#e("get","auth/context")}getProfile(e){return this.#e("get",`profiles/${e}`)}getProfiles(){return this.#e("get","profiles")}getBalances(e){return e?this.#e("get",`profiles/${e}/balances`):this.#e("get","balances")}getOrders(e){let t=u(e),r=t?`orders?${t}`:"orders";return this.#e("get",r)}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){let t={kind:"redeem",...p(e),counterpart:{...e.counterpart,identifier:p(e.counterpart.identifier)}};return this.#e("post","orders",JSON.stringify(t))}uploadSupportingDocument(e){let t=new FormData;return t.append("file",e),A(`${this.#t.api}/files`,"post",t,{Authorization:this.#i||""})}async#e(e,t,r,i){return A(`${this.#t.api}/${t}`,e,i?u(r):r,{Authorization:this.#i||"","Content-Type":`application/${i?"x-www-form-urlencoded":"json"}`})}#a=async(e,t,r,i)=>{let s=localStorage.getItem(g)||"";if(!s)throw new Error("Code verifier not found");return this.codeVerifier=s,this.state=i,localStorage.removeItem(g),await this.#o({code:r,redirect_uri:t,client_id:e,code_verifier:s})};#d=async({clientId:e,clientSecret:t})=>await this.#o({client_id:e,client_secret:t});#c=async(e,t)=>await this.#o({refresh_token:t,client_id:e});async connectOrderSocket(){this.bearerProfile?.access_token&&this.#n.size>0&&(this.#s=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(g),this.#n.clear(),this.#s?.close(),this.#i=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.#s?.close(),this.#s=void 0);}getEnvironment=()=>this.#t;getAuthFlowURI=e=>{let t=x(this.#t.api,e);return this.codeVerifier=localStorage.getItem(g),t}};var le=f;
var P={environments:{production:{api:"https://api.monerium.app",web:"https://monerium.app",wss:"wss://api.monerium.app"},sandbox:{api:"https://api.monerium.dev",web:"https://sandbox.monerium.dev",wss:"wss://api.monerium.dev"}}};var f={LINK_MESSAGE:"I hereby declare that I am the address owner.",STORAGE_CODE_VERIFIER:"monerium.sdk.code_verifier",STORAGE_ACCESS_TOKEN:"monerium.sdk.access_token",STORAGE_ACCESS_EXPIRY:"monerium.sdk.access_expiry"};var E=(s=>(s.eur="eur",s.usd="usd",s.gbp="gbp",s.isk="isk",s))(E||{}),B=(s=>(s.password="password",s.resource="resource",s.jwt="jwt",s.apiKey="apiKey",s))(B||{}),D=(t=>(t.corporate="corporate",t.personal="personal",t))(D||{}),U=(t=>(t.read="read",t.write="write",t))(U||{}),z=(i=>(i.created="created",i.pending="pending",i.approved="approved",i.rejected="rejected",i.blocked="blocked",i))(z||{}),q=(s=>(s.absent="absent",s.submitted="submitted",s.pending="pending",s.confirmed="confirmed",s))(q||{}),j=(r=>(r.approved="approved",r.rejected="rejected",r.unknown="unknown",r))(j||{}),M=(r=>(r.requested="requested",r.approved="approved",r.pending="pending",r))(M||{}),F=(r=>(r.iban="iban",r.scan="scan",r.chain="chain",r))(F||{}),K=(r=>(r.passport="passport",r.nationalIdentityCard="nationalIdentityCard",r.drivingLicense="drivingLicense",r))(K||{}),L=(t=>(t.redeem="redeem",t.issue="issue",t))(L||{}),Q=(s=>(s.placed="placed",s.pending="pending",s.processed="processed",s.rejected="rejected",s))(Q||{});var x=n=>{if(n.toString()==="Invalid Date")throw n;let e=r=>r<10?"0"+r:r,t=r=>{if(r===0)return "Z";let s=r>0?"-":"+";return r=Math.abs(r),s+e(Math.floor(r/60))+":"+e(r%60)};return n.getFullYear()+"-"+e(n.getMonth()+1)+"-"+e(n.getDate())+"T"+e(n.getHours())+":"+e(n.getMinutes())+":"+e(n.getSeconds())+t(n.getTimezoneOffset())},V=n=>{switch(n){case"noble":case"noble-1":case"florin-1":case"grand-1":return !0;default:return !1}},G=n=>{switch(n){case"ethereum":case"polygon":case"gnosis":case"arbitrum":return !0;default:return !1}},c=n=>{if(typeof n=="number")return w(n);if(V(n))return "noble";if(G(n))return n;try{return w(parseInt(n))}catch{throw new Error(`Chain not supported: ${n}`)}},J=(n,e,t,r)=>{let s=`${e?.toUpperCase()||"EUR"}`;return r?`Send ${s} ${n} to ${t} on ${c(r)} at ${x(new Date)}`:s==="EUR"?`Send ${s} ${n} to ${O(t)} at ${x(new Date)}`:`Send ${s} ${n} to ${t} at ${x(new Date)}`},m=n=>n&&Object.entries(n)?.length>0?Object.entries(n).filter(([e,t])=>t!==void 0).map(([e,t])=>`${encodeURIComponent(e)}=${encodeURIComponent(t)}`).join("&"):"",w=n=>{switch(n){case 1:case 11155111:return "ethereum";case 100:case 10200:return "gnosis";case 137:case 80002:return "polygon";case 42161:case 421614:return "arbitrum";default:throw new Error(`Chain not supported: ${n}`)}},O=n=>{if(typeof n!="string"||!n?.length)return n;let e=n.replace(/\s/g,"");return n?.length>11?`${e.substring(0,4)}...${e.substring(e.length-4)}`:n};var C=n=>{if(n?.chain){let{chain:e,...t}=n;return {...t,chain:c(e)}}return n};var X=(n,e)=>{let{client_id:t,redirect_uri:r,scope:s,state:i,address:d,signature:o,chain:l,skip_create_account:a,skip_kyc:h}=n,T=d?{address:d,...o!==void 0?{signature:o}:{},...l!==void 0?{chain:c(l)}:{}}:{};return m({client_id:t,redirect_uri:r,...s!==void 0?{scope:s}:{},...i!==void 0?{state:i}:{},...a!==void 0?{skip_create_account:a}:{},...h!==void 0?{skip_kyc:h}:{},code_challenge:e,code_challenge_method:"S256",response_type:"code",...T})},Z=()=>{let n="",e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=e.length,r=0;for(;r<128;)n+=e.charAt(Math.floor(Math.random()*t)),r+=1;return n},Y=n=>W__default.default.stringify(H__default.default(n)),I=(n,e)=>{let t=Z(),r=Y(t);return localStorage.setItem(f.STORAGE_CODE_VERIFIER,t||""),`${n}/auth?${X(e,r)}`},k=()=>{let n=window.location.href;if(!n||!n?.includes("?"))return;let[e,t]=n.split("?");t&&window.history.replaceState(null,"",e);},R=n=>n.code!=null,v=n=>n.refresh_token!=null,N=n=>n.client_secret!=null;var _=async(n,e,t,r)=>{let s=await fetch(`${n}`,{method:e,headers:r,body:t}),i,d=await s.text();try{if(i=JSON.parse(d),Object.keys(i).length===0&&i.constructor===Object)switch(s.status){case 201:case 202:return {status:s.status,statusText:s.statusText}}}catch{throw d}if(!s.ok)throw i;return i};var y=n=>{if(!n)return "";let e=Object.entries(n).filter(([t,r])=>r!==""&&r!==void 0&&r!==null).map(([t,r])=>`${encodeURIComponent(t)}=${encodeURIComponent(r)}`).join("&");return e?"?"+e:""};var $=n=>n?e=>{console.log("%c [MONERIUM:DEBUG]:","color:orange;",e);}:()=>{};var S=n=>Object.entries(n).filter(([t,r])=>r!=null).map(([t,r])=>`${t}-${r}`).join("-");var {STORAGE_CODE_VERIFIER:A,STORAGE_ACCESS_TOKEN:p,STORAGE_ACCESS_EXPIRY:g}=f,u=typeof window>"u",b=class{#r;#i;bearerProfile;#n=new Map;isAuthorized=!!this.bearerProfile;#t=()=>{};#s;state;constructor(e){if(!e){this.#r=P.environments.sandbox;return}if(typeof e=="string")this.#r=P.environments[e];else if(this.#t=$(e.debug??!1),this.#r=P.environments[e.environment||"sandbox"],!u&&!e?.clientSecret){let{clientId:t,redirectUri:r}=e;this.#s={clientId:t,redirectUri:r};}else {this.#t("Client credentials detected"),console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");let{clientId:t,clientSecret:r}=e;this.#s={clientId:t,clientSecret:r};}}async authorize(e){let t=e?.clientId||this.#s?.clientId,r=e?.redirectUri||this.#s?.redirectUri;if(!t)throw new Error("Missing ClientId");let s=I(this.#r.api,{client_id:t,redirect_uri:r,address:e?.address,signature:e?.signature,chain:e?.chain,state:e?.state,skip_create_account:e?.skipCreateAccount,skip_kyc:e?.skipKyc});this.#t(`Authorization URL: ${s}`),window.location.assign(s);}async getAccess(e){let t=this.#s?.clientId;if(this.#s?.clientSecret){if(u)return await this.#d(this.#s),!!this?.bearerProfile;console.error("\x1B[31m%s\x1B[0m","Use client credentials only on the server where the secret is secure!");}let s=this.#s?.redirectUri;if(!t)throw new Error("Missing ClientId");if(u)throw new Error("This only works client side");let i=new URLSearchParams(window.location.search).get("code")||void 0,d=new URLSearchParams(window.location.search).get("state")||void 0,o=window.localStorage.getItem(p),l=window.localStorage.getItem(g);if(i)return this.#t("Using auth code from auth flow to authorize"),await this.#a(t,s,i,d),this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(e)return this.#t("Using refresh token to authorize"),await this.#c(t,e),this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile;if(o&&l){let a=new Date;if(parseInt(l)<a.getTime())throw window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token has expired");this.#t("Access token should still be valid, checking if it is authorized...");try{return this.#i=`Bearer ${o}`,this.isAuthorized=!0,await this.getTokens(),this.#t("Authorized"),!0}catch{throw this.#t("Access token is invalid."),window.localStorage.removeItem(p),window.localStorage.removeItem(g),this.isAuthorized=!1,this.bearerProfile=void 0,new Error("Access token is invalid.")}}return this.#t(this.bearerProfile?"Authorized":"Not authorized"),!!this.bearerProfile}async#o(e){let t;if(R(e))t={...e,grant_type:"authorization_code"};else if(v(e))t={...e,grant_type:"refresh_token"};else if(N(e))t={...e,grant_type:"client_credentials"};else throw new Error("Authorization grant type could not be detected.");return await this.#e("post","auth/token",t,!0).then(r=>{if(this.bearerProfile=r,this.isAuthorized=!!r,this.#i=`Bearer ${r?.access_token}`,!u){let i=new Date().getTime()+r?.expires_in*1e3;window.localStorage.setItem(p,r?.access_token||""),window.localStorage.setItem(g,i?.toString());}}).catch(r=>{throw u||(localStorage.removeItem(A),localStorage.removeItem(p),localStorage.removeItem(g),k()),new Error(r?.message)}),R(e)&&k(),this.bearerProfile}getProfile(e){return this.#e("get",`profiles/${e}`)}getProfiles(e){return this.#e("get",`profiles${y(e)}`)}getAddress(e){return this.#e("get",`addresses/${e}`)}getAddresses(e){e=C(e);let t=e?m(e):void 0,r=t?`addresses?${t}`:"addresses";return this.#e("get",r)}getBalances(e,t,r){let s=Array.isArray(r)?r.map(i=>`currency=${i}`).join("&"):r?`currency=${r}`:"";return this.#e("get",`balances/${c(t)}/${e}${s?`?${s}`:""}`)}getIban(e){return this.#e("get",`ibans/${encodeURI(e)}`)}getIbans(e){let{profile:t,chain:r}=e||{},s=y({profile:t,chain:r?c(r):""});return this.#e("get",`ibans${s}`)}getOrders(e){return this.#e("get",`orders${y(e)}`)}getOrder(e){return this.#e("get",`orders/${e}`)}getTokens(){return this.#e("get","tokens")}linkAddress(e){return e=C(e),this.#e("post","addresses",JSON.stringify(e))}placeOrder(e){let t={kind:"redeem",...C(e),counterpart:{...e.counterpart,identifier:C(e.counterpart.identifier)}};return this.#e("post","orders",JSON.stringify(t))}moveIban(e,{address:t,chain:r}){return this.#e("patch",`ibans/${e}`,JSON.stringify({address:t,chain:c(r)}))}requestIban({address:e,chain:t,emailNotifications:r=!0}){return this.#e("post","ibans",JSON.stringify({address:e,chain:c(t),emailNotifications:r}))}submitProfileDetails(e,t){return this.#e("put",`profiles/${e}/details`,JSON.stringify(t))}uploadSupportingDocument(e){let t=new FormData;return t.append("file",e),_(`${this.#r.api}/files`,"post",t,{Authorization:this.#i||""})}async#e(e,t,r,s){let i={Authorization:this.#i||"",Accept:"application/vnd.monerium.api-v2+json","Content-Type":`application/${s?"x-www-form-urlencoded":"json"}`};return _(`${this.#r.api}/${t}`,e.toUpperCase(),s?m(r):r,i)}#a=async(e,t,r,s)=>{let i=localStorage.getItem(A)||"";if(!i)throw new Error("Code verifier not found");return this.#t("Use code verifier to authorize"),this.state=s,localStorage.removeItem(A),await this.#o({code:r,redirect_uri:t,client_id:e,code_verifier:i})};#d=async({clientId:e,clientSecret:t})=>await this.#o({client_id:e,client_secret:t});#c=async(e,t)=>await this.#o({refresh_token:t,client_id:e});subscribeOrderNotifications({filter:e,onMessage:t,onError:r}={}){if(!this.bearerProfile?.access_token)return;let{profile:s,state:i}=e||{},d=y({access_token:this.bearerProfile?.access_token,profile:s,state:i}),o,l=S({profile:s,state:i});if(this.#n?.has(l))o=this.#n.get(l);else {let a=`${this.#r.wss}/orders${d}`;o=new WebSocket(a),this.#n?.set(l,o);}return o.onopen=()=>{console.log("Connected to WebSocket server");},o.onmessage=a=>{let h=JSON.parse(a.data);t&&t(h);},o.onclose=()=>{console.log("WebSocket connection closed"),this.#n?.delete(d);},o.onerror=a=>{r&&r(a),console.error("WebSocket error:",a);},o}unsubscribeOrderNotifications(e){if(e){let t=S({profile:e?.profile,state:e?.state}),r=this.#n?.get(t);r&&(r.close(),this.#n?.delete(t));}else this.#n?.forEach(t=>{t?.close();}),this.#n?.clear(),this.#n=void 0;}async disconnect(){u||localStorage.removeItem(A),this.unsubscribeOrderNotifications(),this.#i=void 0,this.bearerProfile=void 0;}async revokeAccess(){u||(localStorage.removeItem(p),localStorage.removeItem(g)),this.disconnect();}getEnvironment=()=>this.#r;getAuthFlowURI=e=>I(this.#r.api,e)};var Ee=b;
exports.AccountState = N;
exports.AccountState = M;
exports.Currency = E;
exports.KYCOutcome = v;
exports.KYCState = T;
exports.Method = b;
exports.MoneriumClient = f;
exports.OrderKind = B;
exports.OrderState = U;
exports.PaymentStandard = q;
exports.Permission = O;
exports.ProfileType = P;
exports.constants = c;
exports.default = le;
exports.getChain = R;
exports.placeOrderMessage = z;
exports.rfc3339 = C;
exports.IdDocumentKind = K;
exports.KYCOutcome = j;
exports.KYCState = q;
exports.Method = B;
exports.MoneriumClient = b;
exports.OrderKind = L;
exports.OrderState = Q;
exports.PaymentStandard = F;
exports.Permission = U;
exports.ProfileState = z;
exports.ProfileType = D;
exports.constants = f;
exports.default = Ee;
exports.getChain = w;
exports.parseChain = c;
exports.placeOrderMessage = J;
exports.rfc3339 = x;
exports.shortenIban = O;
{
"name": "@monerium/sdk",
"version": "2.15.0",
"version": "3.0.0",
"description": "Essential tools to interact with the Monerium API, an electronic money issuer.",

@@ -42,6 +42,5 @@ "repository": {

"scripts": {
"dev": "tsup --watch --onSuccess 'pnpm run docs'",
"dev": "tsup --watch",
"build": "tsup",
"docs": "typedoc",
"docs:watch": "typedoc --watch",
"typedoc": "typedoc",
"type-map": "tsc --emitDeclarationOnly --declaration",

@@ -48,0 +47,0 @@ "lint": "eslint . --fix",

@@ -8,4 +8,4 @@ | [Monerium.com](https://monerium.com/) | [Monerium.app](https://monerium.app/) | [Monerium.dev](https://monerium.dev/) |

<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/badge/Developer_portal-2c6ca7">
<img src="https://img.shields.io/badge/Developer_portal-2c6ca7" alt="Static Badge">
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/badge/Developer_portal-2c6ca7"></source>
<img src="https://img.shields.io/badge/Developer_portal-2c6ca7" alt="Static Badge"></img>
</picture>

@@ -15,17 +15,17 @@ </a>

<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/badge/API_documentation-2c6ca7">
<img src="https://img.shields.io/badge/API_documentation-2c6ca7" alt="Static Badge">
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/badge/API_documentation-2c6ca7"></source>
<img src="https://img.shields.io/badge/API_documentation-2c6ca7" alt="Static Badge"></img>
</picture>
</a>
</br>
<br></br>
<a href="https://www.npmjs.com/package/@monerium/sdk">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/npm/v/%40monerium%2Fsdk?colorA=2c6ca7&colorB=21262d">
<img src="https://img.shields.io/npm/v/%40monerium%2Fsdk?colorA=f6f8fa&colorB=f6f8fa" alt="Version">
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/npm/v/%40monerium%2Fsdk?colorA=2c6ca7&colorB=21262d"></source>
<img src="https://img.shields.io/npm/v/%40monerium%2Fsdk?colorA=f6f8fa&colorB=f6f8fa" alt="Version"></img>
</picture>
</a>
<a href="https://github.com/monerium/js-monorepo/issues>
<a href="https://github.com/monerium/js-monorepo/issues">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/github/issues/monerium/js-monorepo?colorA=2c6ca7&colorB=21262d">
<img src="https://img.shields.io/github/issues/monerium/js-monorepo?colorA=2c6ca7&colorB=21262d" alt="Version">
<source media="(prefers-color-scheme: dark)" srcset="https://img.shields.io/github/issues/monerium/js-monorepo?colorA=2c6ca7&colorB=21262d"></source>
<img src="https://img.shields.io/github/issues/monerium/js-monorepo?colorA=2c6ca7&colorB=21262d" alt="Version"></img>
</picture>

@@ -43,4 +43,4 @@ </a>

- [Documentation](./docs/generated/README.md)
- [Documentation - MoneriumClient](./docs/generated/classes/MoneriumClient.md)
- [Documentation](../../apps/developer/docs/packages/SDK/index.md)
- [Documentation - MoneriumClient](../../apps/developer/docs/packages/SDK/classes/MoneriumClient.md)

@@ -108,4 +108,4 @@ ## Table of Contents

// Retrieve authentication data after successful authentication.
await monerium.getAuthContext();
// Retrieve profiles the client has access to.
await monerium.getProfiles();

@@ -116,11 +116,5 @@ // Access tokens are now available for use.

Interfaces:
- [MoneriumClient](./docs/generated/classes/MoneriumClient.md)
- [BearerProfile](./docs/generated/interfaces/BearerProfile.md)
API documentation:
- [/auth/token](https://monerium.dev/api-docs#operation/auth-token)
- [/auth/context](https://monerium.dev/api-docs#operation/auth-context)

@@ -137,3 +131,3 @@ #### Initialize and authenticate using Authorization Code Flow with PKCE

export function App() {
const [authCtx, setAuthCtx] = useState<AuthContext | null>(null);
const [profiles, setProfiles] = useState<Profile[] | null>(null);
const [monerium, setMonerium] = useState<MoneriumClient>();

@@ -171,3 +165,4 @@ const [isAuthorized, setIsAuthorized] = useState<boolean>(false);

try {
setAuthCtx(await monerium.getAuthContext());
const { profiles } = await monerium.getProfiles();
setProfiles(profiles);
} catch (err) {

@@ -185,3 +180,3 @@ console.error('Error fetching data:', err);

<p>{authCtx?.name || authCtx?.email}</p>
<p>{profiles[0]?.name}</p>
</div>

@@ -192,7 +187,2 @@ );

Interfaces:
- [AuthCodeRequest](./docs/generated/interfaces/AuthCodeRequest.md)
- [BearerProfile](./docs/generated/interfaces/BearerProfile.md)
API documentation:

@@ -202,3 +192,2 @@

- [/auth/token](https://monerium.dev/api-docs#operation/auth-token)
- [/auth/context](https://monerium.dev/api-docs#operation/auth-context)

@@ -208,25 +197,18 @@ #### Get account information

```ts
// Get all profiles for the authenticated user.
const authCtx: AuthContext = await monerium.getAuthContext();
// Get all profiles
const { profiles }: Profile[] = await monerium.getProfiles();
// Fetching all accounts for a specific profile
const { id: profileId, accounts }: Profile = await monerium.getProfile(
authCtx.profiles[0].id
profiles[0].id
);
// Fetching all balances for a specific profile
const balances: Balances = await monerium.getBalances(profileId);
const balances: Balances = await monerium.getBalances();
```
Interfaces:
- [AuthContext](./docs/generated/interfaces/AuthContext.md)
- [Profile](./docs/generated/interfaces/Profile.md)
- [Balances](./docs/generated/interfaces/Balances.md)
API documentation:
- [/auth/context](https://monerium.dev/api-docs#operation/auth-context)
- [/profile](https://monerium.dev/api-docs#operation/profile)
- [/profile/{profiledId}/balances](https://monerium.dev/api-docs#operation/profile-balances)
- [/profile/&#123;profileId&#123;/balances](https://monerium.dev/api-docs#operation/profile-balances)

@@ -241,6 +223,2 @@ #### Get token information

Interfaces:
- [Token](./docs/generated/interfaces/Token.md)
API documentation:

@@ -270,20 +248,14 @@

// Link a new address to Monerium and create accounts for ethereum and gnosis.
await monerium.linkAddress(profileId, {
await monerium.linkAddress({
profile: 'your-profile-id',
address: '0xUserAddress72413Fa92980B889A1eCE84dD', // user wallet address
message: LINK_MESSAGE
signature,
accounts: [
{"currency":"eur","chain":"ethereum"},
{"currency":"eur","chain":"gnosis"}
],
chain: 'ethereum',
} as LinkAddress);
```
Interfaces:
- [LinkAddress](./docs/generated/interfaces/LinkAddress.md)
API documentation:
- [/profile/{profiledId}/addresses](https://monerium.dev/api-docs#operation/profile-addresses)
- [/profile/&#123;profileId&#123;/addresses](https://monerium.dev/api-docs#operation/profile-addresses)

@@ -341,7 +313,2 @@ #### Get and place orders

Interfaces:
- [Order](./docs/generated/interfaces/Order.md)
- [PaymentStandard](./docs/generated/enumerations/PaymentStandard.md)
API documentation:

@@ -362,6 +329,2 @@

Interfaces:
- [SupportingDoc](./docs/generated/interfaces/SupportingDoc.md)
API documentation:

@@ -376,24 +339,25 @@

const [orderState, setOrderState] = useState<OrderState>();
// Subscribe to order events
monerium.subscribeOrders(OrderState.pending, (notification) => {
setOrderState(notification.meta.state);
});
monerium.subscribeOrders(OrderState.placed, (notification) => {
setOrderState(notification.meta.state);
// Subscribe to all order events
monerium.subscribeOrderNotifications();
// Subscribe to specific order events
monerium.subscribeOrderNotifications({ 
filter: {
state: OrderState.pending,
profile: 'my-profile-id',
},
// optional callback functions
onMessage: (order) => console.log(order)
onError: (error) => console.error(error)
});
monerium.subscribeOrders(OrderState.rejected, (notification) => {
setOrderState(notification.meta.state);
setTimeout(() => {
setOrderState(undefined);
}, 5000);
// Unsubscribe from specific order events
monerium.unsubscribeOrderNotifications({ 
state: OrderState.pending,
profile: 'my-profile-id'
});
// Unsubscribe from all order events
monerium.unsubscribeOrderNotifications();
monerium.subscribeOrders(OrderState.processed, (notification) => {
setOrderState(notification.meta.state);
setTimeout(() => {
setOrderState(undefined);
}, 5000);
});
```

@@ -400,0 +364,0 @@

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc