From 7e4625a44fc61bd9bf76abe8f2b8ffcaf7e99df2 Mon Sep 17 00:00:00 2001 From: gguy Date: Mon, 11 Sep 2023 12:07:23 +0300 Subject: [PATCH 1/6] added bulk functions --- .DS_Store | Bin 0 -> 6148 bytes src mine/api-client.ts | 101 ++ src mine/api-token-provider.ts | 26 + src mine/fireblocks-sdk.ts | 1925 ++++++++++++++++++++++++++++++++ src mine/iauth-provider.ts | 5 + src mine/ncw-api-client.ts | 135 +++ src mine/ncw-sdk.ts | 155 +++ src mine/pii-client.ts | 83 ++ src mine/types.ts | 1763 +++++++++++++++++++++++++++++ src/fireblocks-sdk.ts | 102 ++ src/types.ts | 38 + 11 files changed, 4333 insertions(+) create mode 100644 .DS_Store create mode 100644 src mine/api-client.ts create mode 100644 src mine/api-token-provider.ts create mode 100644 src mine/fireblocks-sdk.ts create mode 100644 src mine/iauth-provider.ts create mode 100644 src mine/ncw-api-client.ts create mode 100644 src mine/ncw-sdk.ts create mode 100644 src mine/pii-client.ts create mode 100644 src mine/types.ts diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..c9ccc2316e73c438d28d7e45d631e140e0d9c4c2 GIT binary patch literal 6148 zcmeHK%}xR_5S{``2{GZI(PI;@B!c)GFB`-caE%_+AS*;SE?dHa90z@kgD}IB9lIX6wL?uFvEz5R#xyZwW%>&~unt zL=TFvsfadJxF?3N>1bCj&U2VrwCNzs$~cc(IeWYavpU+92?ya>T{O>9MC?pW1QBn bNXIzOVQP_PA-hRO { + const token = this.authProvider.signJwt(path); + const res = await this.axiosInstance.get(path, { + headers: {"Authorization": `Bearer ${token}`} + }); + return { + transactions: res.data, + pageDetails: { + prevPage: res.headers["prev-page"] ? res.headers["prev-page"].toString() : "", + nextPage: res.headers["next-page"] ? res.headers["next-page"].toString() : "", + } + }; + } + + public async issueGetRequest(path: string): Promise { + const token = this.authProvider.signJwt(path); + const res = await this.axiosInstance.get(path, { + headers: {"Authorization": `Bearer ${token}`} + }); + return res.data; + } + + public async issuePostRequest(path: string, body: any, requestOptions?: RequestOptions): Promise { + const token = this.authProvider.signJwt(path, body); + const headers: any = {"Authorization": `Bearer ${token}`}; + const idempotencyKey = requestOptions?.idempotencyKey; + if (idempotencyKey) { + headers["Idempotency-Key"] = idempotencyKey; + } + + const ncwWalletId = requestOptions?.ncw?.walletId; + if (ncwWalletId) { + headers["X-End-User-Wallet-Id"] = ncwWalletId; + } + + const response = await this.axiosInstance.post(path, body, {headers}); + return response.data; + } + + public async issuePutRequest(path: string, body: any): Promise { + const token = this.authProvider.signJwt(path, body); + const res = (await this.axiosInstance.put(path, body, { + headers: {"Authorization": `Bearer ${token}`} + })); + return res.data; + } + + public async issuePatchRequest(path: string, body: any): Promise { + const token = this.authProvider.signJwt(path, body); + const res = (await this.axiosInstance.patch(path, body, { + headers: {"Authorization": `Bearer ${token}`} + })); + return res.data; + } + + public async issueDeleteRequest(path: string): Promise { + const token = this.authProvider.signJwt(path); + const res = (await this.axiosInstance.delete(path, { + headers: {"Authorization": `Bearer ${token}`} + })); + return res.data; + } +} diff --git a/src mine/api-token-provider.ts b/src mine/api-token-provider.ts new file mode 100644 index 00000000..cfc11973 --- /dev/null +++ b/src mine/api-token-provider.ts @@ -0,0 +1,26 @@ +import { IAuthProvider } from "./iauth-provider"; +import * as jwt from "jsonwebtoken"; +import * as crypto from "crypto"; +import { v4 as uuid } from "uuid"; + +export class ApiTokenProvider implements IAuthProvider { + + constructor(private privateKey: string, private apiKey: string) { } + + signJwt(path: string, bodyJson?: any): string { + const token = jwt.sign({ + uri: path, + nonce: uuid(), + iat: Math.floor(Date.now() / 1000), + exp: Math.floor(Date.now() / 1000) + 55, + sub: this.apiKey, + bodyHash: crypto.createHash("sha256").update(JSON.stringify(bodyJson || "")).digest().toString("hex") + } as any, this.privateKey, { algorithm: "RS256"}); + + return token; + } + + getApiKey(): string { + return this.apiKey; + } +} diff --git a/src mine/fireblocks-sdk.ts b/src mine/fireblocks-sdk.ts new file mode 100644 index 00000000..64a38a56 --- /dev/null +++ b/src mine/fireblocks-sdk.ts @@ -0,0 +1,1925 @@ +import { ApiClient } from "./api-client"; +import { ApiTokenProvider } from "./api-token-provider"; +import { IAuthProvider } from "./iauth-provider"; +import queryString from "query-string"; +import { stringify } from "qs"; +import { + AllocateFundsRequest, + AssetResponse, + AssetTypeResponse, + CancelTransactionResponse, + ConvertExchangeAssetResponse, + CreateTransactionResponse, + DeallocateFundsRequest, + DepositAddressResponse, + EstimateFeeResponse, + EstimateTransactionFeeResponse, + ExchangeResponse, + ExternalWalletAsset, + FiatAccountResponse, + GasStationInfo, + GenerateAddressResponse, + InternalWalletAsset, + MaxSpendableAmountResponse, + MaxBip44IndexUsedResponse, + NetworkConnectionResponse, + OffExchangeEntityResponse, + OperationSuccessResponse, + PagedVaultAccountsRequestFilters, + PagedVaultAccountsResponse, + PublicKeyInfoArgs, + PublicKeyInfoForVaultAccountArgs, + RequestOptions, + ResendWebhooksResponse, + TransactionArguments, + TransactionFilter, + TransactionPageFilter, + TransactionPageResponse, + TransactionResponse, + User, + ValidateAddressResponse, + VaultAccountResponse, + VaultAssetResponse, + VaultBalancesFilter, + WalletContainerResponse, + SetFeePayerConfiguration, + FeePayerConfiguration, + CreateWeb3ConnectionPayload, + CreateWeb3ConnectionResponse, + Session, + NetworkConnectionRoutingPolicy, + NetworkIdRoutingPolicy, + NetworkIdResponse, + TimePeriod, + AuditsResponse, + NFTOwnershipFilter, + NFTOwnedAssetsFilter, + Token, + TokenWithBalance, + Web3PagedResponse, + CreateWalletConnectPayload, + Web3ConnectionType, + GetWeb3ConnectionsPayload, + PublicKeyResponse, + AllocateFundsResponse, + SettleOffExchangeAccountResponse, + AddCollateralTransactionRequest, + RemoveCollateralTransactionRequest, + GetSettlementTransactionsResponse, + SettlementRequest, + SettlementResponse, + GetNFTsFilter, + PeerType, + PublicKeyInformation, + DropTransactionResponse, + TokenLink, + TokenLinkPermissionEntry, + IssueTokenRequest, + NFTOwnershipStatus, + NFTOwnedCollectionsFilter, + CollectionOwnership, + TravelRuleOptions, + ValidateTravelRuleVaspInfo, + ValidateTravelRuleResult, + ValidateCreateTravelRuleTransaction, + ValidateFullTravelRuleResult, + TravelRuleVasp, + TravelRuleVaspFilter, + TravelRuleEncryptionOptions, + SmartTransfersTicketResponse, + SmartTransfersTicketCreatePayload, + SmartTransfersTicketsResponse, + SmartTransfersTicketsFilters, + SmartTransfersTicketTermPayload, + SmartTransfersTicketTermFundPayload, + SmartTransfersTicketTermResponse, + SmartTransfersUserGroupsResponse, + UsersGroup, + ContractUploadRequest, + ContractTemplateDto, + PendingTokenLinkDto, Web3ConnectionFeeLevel, + Task, Job, JobCreatedResponse +} from "./types"; +import { AxiosProxyConfig, AxiosResponse } from "axios"; +import { PIIEncryption } from "./pii-client"; +import { NcwApiClient } from "./ncw-api-client"; +import { NcwSdk } from "./ncw-sdk"; + +export * from "./types"; + +export interface SDKOptions { + /** HTTP request timeout */ + timeoutInMs?: number; + + /** Proxy configurations */ + proxy?: AxiosProxyConfig | false; + + /** Whether to remove platform from User-Agent header */ + anonymousPlatform?: boolean; + + /** Additional product identifier to be prepended to the User-Agent header */ + userAgent?: string; + + /** + * Providing custom axios options including a response interceptor (https://axios-http.com/docs/interceptors) + */ + customAxiosOptions?: { + interceptors?: { + response?: { + onFulfilled: (value: AxiosResponse) => AxiosResponse | Promise>; + onRejected: (error: any) => any; + }; + } + }; + + /** + * TravelRule Provider options to initialize PII Client for PII encryption + */ + travelRuleOptions?: TravelRuleOptions; +} + +export class FireblocksSDK { + private readonly authProvider: IAuthProvider; + private readonly apiBaseUrl: string; + private readonly apiClient: ApiClient; + private readonly apiNcw: NcwApiClient; + + private piiClient: PIIEncryption; + + /** + * Creates a new Fireblocks API Client + * @param privateKey A string representation of your private key + * @param apiKey Your api key. This is a uuid you received from Fireblocks + * @param apiBaseUrl The fireblocks server URL. Leave empty to use the default server + * @param authProvider + * @param sdkOptions + */ + constructor(privateKey: string, apiKey: string, apiBaseUrl: string = "https://api.fireblocks.io", authProvider: IAuthProvider = undefined, sdkOptions?: SDKOptions) { + this.authProvider = !!authProvider ? authProvider : new ApiTokenProvider(privateKey, apiKey); + + if (!!apiBaseUrl) { + this.apiBaseUrl = apiBaseUrl; + } + + this.apiClient = new ApiClient(this.authProvider, this.apiBaseUrl, sdkOptions); + + if (sdkOptions?.travelRuleOptions) { + this.piiClient = new PIIEncryption(sdkOptions.travelRuleOptions); + } + + this.apiNcw = new NcwApiClient(this.apiClient); + } + + /** + * NCW API Namespace + * + * @readonly + * @type {NcwSdk} + */ + public get NCW(): NcwSdk { + return this.apiNcw; + } + + /** + * Get the instance of ApiClient used by the FireblocksSDK + */ + public getApiClient(): ApiClient { + return this.apiClient; + } + + /** + * Gets all assets that are currently supported by Fireblocks + */ + public async getSupportedAssets(): Promise { + return await this.apiClient.issueGetRequest("/v1/supported_assets"); + } + /** + * Gets a list of vault accounts per page matching the given filter or path + * @param pagedVaultAccountsRequestFilters Filters for the first request + */ + public async getVaultAccountsWithPageInfo(pagedVaultAccountsRequestFilters: PagedVaultAccountsRequestFilters): Promise { + return await this.apiClient.issueGetRequest(`/v1/vault/accounts_paged?${queryString.stringify(pagedVaultAccountsRequestFilters)}`); + } + /** + * Gets a single vault account + * @param vaultAccountId The vault account ID + */ + public async getVaultAccountById(vaultAccountId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/vault/accounts/${vaultAccountId}`); + } + + /** + * Gets a single vault account asset + * @param vaultAccountId The vault account ID + * @param assetId The ID of the asset to get + */ + public async getVaultAccountAsset(vaultAccountId: string, assetId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}`); + } + + /** + * Gets a single vault account asset balance after forcing refresh from the blockchain + * @param vaultAccountId The vault account ID + * @param assetId The ID of the asset to get + * @param requestOptions + */ + public async refreshVaultAssetBalance(vaultAccountId: string, assetId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/balance`, "{}", requestOptions); + } + + /** + * Gets deposit addresses for an asset in a vault account + * @param vaultAccountId The vault account ID + * @param assetId The ID of the asset for which to get the deposit address + */ + public async getDepositAddresses(vaultAccountId: string, assetId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/addresses`); + } + + /** + * Gets utxo list for an asset in a vault account + * @param vaultAccountId The vault account ID + * @param assetId The ID of the asset for which to get the utxo list + */ + public async getUnspentInputs(vaultAccountId: string, assetId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/unspent_inputs`); + } + + /** + * Generates a new address for an asset in a vault account + * @param vaultAccountId The vault account ID + * @param assetId The ID of the asset for which to generate the deposit address + * @param description A description for the new address + * @param customerRefId A customer reference ID + * @param requestOptions + */ + public async generateNewAddress(vaultAccountId: string, assetId: string, description?: string, customerRefId?: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/addresses`, { + description, + customerRefId + }, requestOptions); + } + + /** + * Sets the description of an existing address + * @param vaultAccountId The vault account ID + * @param assetId The ID of the asset + * @param address The address for which to set the description + * @param tag The XRP tag, or EOS memo, for which to set the description + * @param description The description to set + */ + public async setAddressDescription(vaultAccountId: string, assetId: string, address: string, tag?: string, description?: string): Promise { + let addressId = address; + if (tag && tag.length > 0) { + addressId = `${address}:${tag}`; + } + + return await this.apiClient.issuePutRequest( + `/v1/vault/accounts/${vaultAccountId}/${assetId}/addresses/${addressId}`, + {description: description || ""}); + } + + /** + * Gets all network connections + * @returns NetworkConnectionResponse + */ + public async getNetworkConnections(): Promise { + return await this.apiClient.issueGetRequest("/v1/network_connections"); + } + + /** + * Creates a network connection + * @param localNetworkId The local netowrk profile's id + * @param remoteNetworkId The remote network profile's id + * @param routingPolicy The desired routing policy for the connection + * @returns NetworkConnectionResponse + */ + public async createNetworkConnection(localNetworkId: string, remoteNetworkId: string, routingPolicy?: NetworkConnectionRoutingPolicy): Promise { + const body = { localNetworkId, remoteNetworkId, routingPolicy }; + return await this.apiClient.issuePostRequest(`/v1/network_connections`, body); + } + + /** + * Gets a single network connection + * @param connectionId The network connection's id + * @returns NetworkConnectionResponse + */ + public async getNetworkConnectionById(connectionId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/network_connections/${connectionId}`); + } + + /** + * Removes a network connection + * @param connectionId The network connection's id + * @returns OperationSuccessResponse + */ + public async removeNetworkConnection(connectionId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/network_connections/${connectionId}`); + } + + /** + * Sets routing policy for a network connection + * @param connectionId The network connection's id + * @param routingPolicy The desired routing policy + */ + public async setNetworkConnectionRoutingPolicy(connectionId: string, routingPolicy: NetworkConnectionRoutingPolicy): Promise { + const body = { routingPolicy }; + return await this.apiClient.issuePatchRequest(`/v1/network_connections/${connectionId}/set_routing_policy`, body); + } + + /** + * Gets all discoverable network profiles + * @returns NetworkIdResponse + */ + public async getDiscoverableNetworkIds(): Promise { + return await this.apiClient.issueGetRequest(`/v1/network_ids`); + } + + /** + * Creates a new network profile + * @param name A name for the new network profile + * @param routingPolicy The desired routing policy for the network + * @returns NetworkConnectionResponse + */ + public async createNetworkId(name: string, routingPolicy?: NetworkIdRoutingPolicy): Promise { + const body = { name, routingPolicy }; + return await this.apiClient.issuePostRequest(`/v1/network_ids`, body); + } + + /** + * Gets a single network profile + * @param networkId The network profile's id + * @returns NetworkIdResponse + */ + public async getNetworkId(networkId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/network_ids/${networkId}`); + } + + /** + * Deletes a single network profile + * @param networkId The network profile's id + * @returns NetworkIdResponse + */ + public async deleteNetworkId(networkId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/network_ids/${networkId}`); + } + + /** + * Sets discoverability for network profile + * @param networkId The network profile's id + * @param isDiscoverable The desired discoverability to set + * @returns OperationSuccessResponse + */ + public async setNetworkIdDiscoverability(networkId: string, isDiscoverable: boolean): Promise { + const body = { isDiscoverable }; + return await this.apiClient.issuePatchRequest(`/v1/network_ids/${networkId}/set_discoverability`, body); + } + + /** + * Sets routing policy for network profile + * @param networkId The network profile's id + * @param routingPolicy The desired routing policy + * @returns OperationSuccessResponse + */ + public async setNetworkIdRoutingPolicy(networkId: string, routingPolicy: NetworkIdRoutingPolicy): Promise { + const body = { routingPolicy }; + return await this.apiClient.issuePatchRequest(`/v1/network_ids/${networkId}/set_routing_policy`, body); + } + + /** + * Sets network profile name + * @param networkId The network profile's id + * @param name The desired network profile's name + * @returns OperationSuccessResponse + */ + public async setNetworkIdName(networkId: string, name: string): Promise { + const body = { name }; + return await this.apiClient.issuePatchRequest(`/v1/network_ids/${networkId}/set_name`, body); + } + + /** + * Gets all exchange accounts for your tenant + */ + public async getExchangeAccounts(): Promise { + return await this.apiClient.issueGetRequest("/v1/exchange_accounts"); + } + + + /** + * Gets a single exchange account by ID + * @param exchangeAccountId The exchange account ID + */ + public async getExchangeAccountById(exchangeAccountId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/exchange_accounts/${exchangeAccountId}`); + } + + /** + * Gets a single asset within an Exchange Account + * @param exchangeAccountId The exchange account ID + * @param assetId The ID of the asset + */ + public async getExchangeAsset(exchangeAccountId: string, assetId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/exchange_accounts/${exchangeAccountId}/${assetId}`); + } + + /** + * Convert an asset at an Exchange Account + * @param exchangeAccountId The exchange account ID + * @param srcAsset The source asset to convert from + * @param destAsset The destination asset to convert to + * @param amount The amount to convert + */ + public async convertExchangeAsset(exchangeAccountId: string, srcAsset: string, destAsset: string, amount: number, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/exchange_accounts/${exchangeAccountId}/convert`, { + srcAsset, destAsset, amount + }, requestOptions); + } + + /** + * Transfer from a main exchange account to a subaccount + * @param exchangeAccountId The exchange ID in Fireblocks + * @param subaccountId The ID of the subaccount in the exchange + * @param assetId The asset to transfer + * @param amount The amount to transfer + * @param requestOptions + */ + public async transferToSubaccount(exchangeAccountId: string, subaccountId: string, assetId: string, amount: number, requestOptions?: RequestOptions): Promise { + const body = { + subaccountId, + amount + }; + + return await this.apiClient.issuePostRequest(`/v1/exchange_accounts/${exchangeAccountId}/${assetId}/transfer_to_subaccount`, body, requestOptions); + } + + /** + * Transfer from a subaccount to a main exchange account + * @param exchangeAccountId The exchange ID in Fireblocks + * @param subaccountId The ID of the subaccount in the exchange + * @param assetId The asset to transfer + * @param amount The amount to transfer + * @param requestOptions + */ + public async transferFromSubaccount(exchangeAccountId: string, subaccountId: string, assetId: string, amount: number, requestOptions?: RequestOptions): Promise { + const body = { + subaccountId, + amount + }; + + return await this.apiClient.issuePostRequest(`/v1/exchange_accounts/${exchangeAccountId}/${assetId}/transfer_from_subaccount`, body, requestOptions); + } + + /** + * Gets all fiat accounts for your tenant + */ + public async getFiatAccounts(): Promise { + return await this.apiClient.issueGetRequest("/v1/fiat_accounts"); + } + + /** + * Gets a single fiat account by ID + * @param accountId The fiat account ID + */ + public async getFiatAccountById(accountId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/fiat_accounts/${accountId}`); + } + + /** + * Redeem from a fiat account to a linked DDA + * @param accountId The fiat account ID in Fireblocks + * @param amount The amount to transfer + * @param requestOptions + */ + public async redeemToLinkedDDA(accountId: string, amount: number, requestOptions?: RequestOptions): Promise { + const body = { + amount + }; + + return await this.apiClient.issuePostRequest(`/v1/fiat_accounts/${accountId}/redeem_to_linked_dda`, body, requestOptions); + } + + /** + * Deposit to a fiat account from a linked DDA + * @param accountId The fiat account ID in Fireblocks + * @param amount The amount to transfer + * @param requestOptions + */ + public async depositFromLinkedDDA(accountId: string, amount: number, requestOptions?: RequestOptions): Promise { + const body = { + amount + }; + + return await this.apiClient.issuePostRequest(`/v1/fiat_accounts/${accountId}/deposit_from_linked_dda`, body, requestOptions); + } + + /** + * Gets a list of transactions matching the given filter + * @param filter.before Only gets transactions created before a given timestamp (in milliseconds) + * @param filter.after Only gets transactions created after a given timestamp (in milliseconds) + * @param filter.status Only gets transactions with the spcified status + * @param filter.limit Limit the amount of returned results. If not specified, a limit of 200 results will be used + * @param filter.orderBy Determines the order of the results + */ + public async getTransactions(filter: TransactionFilter): Promise { + return await this.apiClient.issueGetRequest(`/v1/transactions?${queryString.stringify(filter)}`); + } + + /** + * Gets a list of transactions per page matching the given filter or path + * @param pageFilter Get transactions matching pageFilter params + * @param nextOrPreviousPath Get transactions from each of pageDetails paths + */ + public async getTransactionsWithPageInfo(pageFilter?: TransactionPageFilter, nextOrPreviousPath?: string): Promise { + if (pageFilter) { + return await this.apiClient.issueGetRequestForTransactionPages(`/v1/transactions?${queryString.stringify(pageFilter)}`); + } else if (nextOrPreviousPath) { + const index = nextOrPreviousPath.indexOf("/v1/"); + const path = nextOrPreviousPath.substring(index, nextOrPreviousPath.length); + return await this.apiClient.issueGetRequestForTransactionPages(path); + } + + return { + transactions: [], pageDetails: { prevPage: "", nextPage: "" }, + }; + } + + /** + * Gets a transaction matching the external transaction id provided + * @param externalTxId + */ + public async getTransactionByExternalTxId(externalTxId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/transactions/external_tx_id/${externalTxId}`); + } + + /** + * Gets all internal wallets for your tenant + */ + public async getInternalWallets(): Promise[]> { + return await this.apiClient.issueGetRequest("/v1/internal_wallets"); + } + + /** + * Gets a single internal wallet + * @param walletId The internal wallet ID + */ + public async getInternalWallet(walletId: string): Promise> { + return await this.apiClient.issueGetRequest(`/v1/internal_wallets/${walletId}`); + } + + /** + * Gets a single internal wallet asset + * @param walletId The internal wallet ID + * @param assetId The asset ID + */ + public async getInternalWalletAsset(walletId: string, assetId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/internal_wallets/${walletId}/${assetId}`); + } + + /** + * Gets all external wallets for your tenant + */ + public async getExternalWallets(): Promise[]> { + return await this.apiClient.issueGetRequest("/v1/external_wallets"); + } + + /** + * Gets a single external wallet + * @param walletId The external wallet ID + */ + public async getExternalWallet(walletId: string): Promise> { + return await this.apiClient.issueGetRequest(`/v1/external_wallets/${walletId}`); + } + + /** + * Gets a single external wallet asset + * @param walletId The external wallet ID + * @param assetId The asset ID + */ + public async getExternalWalletAsset(walletId: string, assetId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/external_wallets/${walletId}/${assetId}`); + } + + /** + * Gets all contract wallets for your tenant + */ + public async getContractWallets(): Promise[]> { + return await this.apiClient.issueGetRequest("/v1/contracts"); + } + + /** + * Gets a single contract wallet + * @param walletId The contract wallet ID + */ + public async getContractWallet(walletId: string): Promise> { + return await this.apiClient.issueGetRequest(`/v1/contracts/${walletId}`); + } + + /** + * Gets a single contract wallet asset + * @param walletId The contract wallet ID + * @param assetId The asset ID + */ + public async getContractWalletAsset(walletId: string, assetId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/contracts/${walletId}/${assetId}`); + } + + /** + * Gets detailed information for a single transaction + * @param txId The transaction id to query + */ + public async getTransactionById(txId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/transactions/${txId}`); + } + + /** + * Cancels the selected transaction + * @param txId The transaction id to cancel + * @param requestOptions + */ + public async cancelTransactionById(txId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/transactions/${txId}/cancel`, {}, requestOptions); + } + + /** + * Creates a new vault account + * @param name A name for the new vault account + * @param hiddenOnUI If true, the created account and all related transactions will not be shown on Fireblocks console + * @param customerRefId A customer reference ID + * @param autoFuel + * @param requestOptions + * @param autoFuel + * @param requestOptions + */ + public async createVaultAccount(name: string, hiddenOnUI?: boolean, customerRefId?: string, autoFuel?: boolean, requestOptions?: RequestOptions): Promise { + const body = { + name, + customerRefId, + hiddenOnUI: hiddenOnUI || false, + autoFuel: autoFuel || false + }; + + return await this.apiClient.issuePostRequest("/v1/vault/accounts", body, requestOptions); + } + + /** + * Creates a new vault account + * @param count Number of new vault accounts requested + * @param requestOptions + */ + public async createVaultAccountBulk(count: number, requestOptions?: RequestOptions): Promise { + const body = { + count + }; + + return await this.apiClient.issuePostRequest("/v1/vault/accounts/bulk", body, requestOptions); + } + + /** + * Hides a vault account in Fireblocks console + * @param vaultAccountId The vault account ID + * @param requestOptions + */ + public async hideVaultAccount(vaultAccountId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/hide`, {}, requestOptions); + } + + /** + * Reveals a hidden vault account in Fireblocks console + * @param vaultAccountId The vault account ID + * @param requestOptions + */ + public async unhideVaultAccount(vaultAccountId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/unhide`, {}, requestOptions); + } + + /** + * Sets autoFuel to true/false for a vault account + * @param vaultAccountId The vault account ID + * @param autoFuel The new value for the autoFuel flag + * @param requestOptions + */ + public async setAutoFuel(vaultAccountId: string, autoFuel: boolean, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/set_auto_fuel`, {autoFuel}, requestOptions); + } + + /** + * Updates a vault account + * @param vaultAccountId + * @param name A new name for the vault account + */ + public async updateVaultAccount(vaultAccountId: string, name: string): Promise { + const body = { + name: name + }; + + return await this.apiClient.issuePutRequest(`/v1/vault/accounts/${vaultAccountId}`, body); + } + + /** + * Creates a new asset within an existing vault account + * @param vaultAccountId The vault account ID + * @param assetId The asset to add + * @param requestOptions + */ + public async createVaultAsset(vaultAccountId: string, assetId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}`, {}, requestOptions); + } + + /** + * Creates a new asset within a list of existing vault accounts + * @param assetId The asset to add + * @param vaultAccountIdFrom The first of the account ID range + * @param vaultAccountIdTo The last of the account ID range + * @param requestOptions + */ + public async createVaultAssetBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string, requestOptions?: RequestOptions): Promise { + const body = { + assetId, vaultAccountIdFrom, vaultAccountIdTo + }; + return await this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body, requestOptions); + } + + /** + * Retry to create a vault asset for a vault asset that failed + * @param vaultAccountId The vault account ID + * @param assetId The asset to add + * @param requestOptions + */ + public async activateVaultAsset(vaultAccountId: string, assetId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/activate`, {} , requestOptions); + } + + /** + * Creates a new external wallet + * @param name A name for the new external wallet + * @param customerRefId A customer reference ID + * @param requestOptions + */ + public async createExternalWallet(name: string, customerRefId?: string, requestOptions?: RequestOptions): Promise> { + const body = { + name, + customerRefId + }; + + return await this.apiClient.issuePostRequest("/v1/external_wallets", body, requestOptions); + } + + /** + * Creates a new internal wallet + * @param name A name for the new internal wallet + * @param customerRefId A customer reference ID + * @param requestOptions + */ + public async createInternalWallet(name: string, customerRefId?: string, requestOptions?: RequestOptions): Promise> { + const body = { + name, + customerRefId + }; + + return await this.apiClient.issuePostRequest("/v1/internal_wallets", body, requestOptions); + } + + /** + * Creates a new contract wallet + * @param name A name for the new contract wallet + */ + public async createContractWallet(name: string, requestOptions?: RequestOptions): Promise> { + const body = { + name, + }; + + return await this.apiClient.issuePostRequest("/v1/contracts", body, requestOptions); + } + + /** + * Creates a new asset within an exiting external wallet + * @param walletId The wallet id + * @param assetId The asset to add + * @param address The wallet address + * @param tag (for ripple only) The ripple account tag + * @param requestOptions + */ + public async createExternalWalletAsset(walletId: string, assetId: string, address: string, tag?: string, requestOptions?: RequestOptions): Promise { + const path = `/v1/external_wallets/${walletId}/${assetId}`; + + const body = { + address: address, + tag: tag + }; + return await this.apiClient.issuePostRequest(path, body, requestOptions); + } + + /** + * Creates a new asset within an exiting internal wallet + * @param walletId The wallet id + * @param assetId The asset to add + * @param address The wallet address + * @param tag (for ripple only) The ripple account tag + * @param requestOptions + */ + public async createInternalWalletAsset(walletId: string, assetId: string, address: string, tag?: string, requestOptions?: RequestOptions): Promise { + const path = `/v1/internal_wallets/${walletId}/${assetId}`; + + const body = { + address: address, + tag: tag + }; + return await this.apiClient.issuePostRequest(path, body, requestOptions); + } + + /** + * Creates a new asset within an exiting contract wallet + * @param walletId The wallet id + * @param assetId The asset to add + * @param address The wallet address + * @param tag (for ripple only) The ripple account tag + */ + public async createContractWalletAsset(walletId: string, assetId: string, address: string, tag?: string, requestOptions?: RequestOptions): Promise { + const path = `/v1/contracts/${walletId}/${assetId}`; + + const body = { + address: address, + tag: tag + }; + return await this.apiClient.issuePostRequest(path, body, requestOptions); + } + + /** + * Creates a new transaction with the specified options + */ + public async createTransaction(transactionArguments: TransactionArguments, requestOptions?: RequestOptions, travelRuleEncryptionOptions?: TravelRuleEncryptionOptions): Promise { + const opts = { ...requestOptions }; + + if (transactionArguments?.travelRuleMessage) { + transactionArguments = await this.piiClient.hybridEncode(transactionArguments, travelRuleEncryptionOptions); + } + + if (transactionArguments.source?.type === PeerType.END_USER_WALLET && !opts.ncw?.walletId) { + const { walletId } = transactionArguments.source; + opts.ncw = { ...opts.ncw, walletId }; + } + + return await this.apiClient.issuePostRequest("/v1/transactions", transactionArguments, opts); + } + + /** + * Estimates the fee for a transaction request + */ + public async estimateFeeForTransaction(transactionArguments: TransactionArguments, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest("/v1/transactions/estimate_fee", transactionArguments, requestOptions); + } + + /** + * Gets the estimated fees for an asset + */ + public async getFeeForAsset(asset: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/estimate_network_fee?assetId=${asset}`); + } + + /** + * Deletes a single internal wallet + * @param walletId The internal wallet ID + */ + public async deleteInternalWallet(walletId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/internal_wallets/${walletId}`); + } + + /** + * Deletes a single internal wallet asset + * @param walletId The internal wallet ID + * @param assetId The asset ID + */ + public async deleteInternalWalletAsset(walletId: string, assetId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/internal_wallets/${walletId}/${assetId}`); + } + + /** + * Deletes a single external wallet + * @param walletId The external wallet ID + */ + public async deleteExternalWallet(walletId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/external_wallets/${walletId}`); + } + + /** + * Deletes a single external wallet asset + * @param walletId The external wallet ID + * @param assetId The asset ID + */ + public async deleteExternalWalletAsset(walletId: string, assetId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/external_wallets/${walletId}/${assetId}`); + } + + /** + * Deletes a single contract wallet + * @param walletId The contract wallet ID + */ + public async deleteContractWallet(walletId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/contracts/${walletId}`); + } + + /** + * Deletes a single contract wallet asset + * @param walletId The contract wallet ID + * @param assetId The asset ID + */ + public async deleteContractWalletAsset(walletId: string, assetId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/contracts/${walletId}/${assetId}`); + } + + /** + * Sets a customer reference ID + * @param vaultAccountId The vault account ID + * @param customerRefId The customer reference ID to set + * @param requestOptions + */ + public async setCustomerRefIdForVaultAccount(vaultAccountId: string, customerRefId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/set_customer_ref_id`, {customerRefId}, requestOptions); + } + + /** + * Sets a customer reference ID + * @param walletId The ID of the internal wallet + * @param customerRefId The customer reference ID to set + * @param requestOptions + */ + public async setCustomerRefIdForInternalWallet(walletId: string, customerRefId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/internal_wallets/${walletId}/set_customer_ref_id`, {customerRefId}, requestOptions); + } + + /** + * Sets a customer reference ID + * @param walletId The ID of the external wallet + * @param customerRefId The customer reference ID to set + * @param requestOptions + */ + public async setCustomerRefIdForExternalWallet(walletId: string, customerRefId: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/external_wallets/${walletId}/set_customer_ref_id`, {customerRefId}, requestOptions); + } + + /** + * Sets a customer reference ID + * @param vaultAccountId The vault account ID + * @param assetId The ID of the asset + * @param address The address + * @param tag The XRP tag, or EOS memo + * @param customerRefId The customer reference ID to set + * @param requestOptions + */ + public async setCustomerRefIdForAddress(vaultAccountId: string, assetId: string, address: string, tag?: string, customerRefId?: string, requestOptions?: RequestOptions): Promise { + let addressId = address; + if (tag && tag.length > 0) { + addressId = `${address}:${tag}`; + } + + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/addresses/${addressId}/set_customer_ref_id`, {customerRefId}, requestOptions); + } + + /** + * Set the required number of confirmations for transaction + * @param txId + * @param requiredConfirmationsNumber + * @param requestOptions + */ + public async setConfirmationThresholdForTxId(txId: string, requiredConfirmationsNumber: number, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/transactions/${txId}/set_confirmation_threshold`, {numOfConfirmations: requiredConfirmationsNumber}, requestOptions); + } + + /** + * Set the required number of confirmations for transactions by tx hash + * @param txHash + * @param requiredConfirmationsNumber + * @param requestOptions + */ + public async setConfirmationThresholdForTxHash(txHash: string, requiredConfirmationsNumber: number, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/txHash/${txHash}/set_confirmation_threshold`, {numOfConfirmations: requiredConfirmationsNumber}, requestOptions); + } + + /** + * Get the public key information + * @param args + */ + public async getPublicKeyInfo(args: PublicKeyInfoArgs): Promise { + let url = `/v1/vault/public_key_info`; + if (args.algorithm) { + url += `?algorithm=${args.algorithm}`; + } + if (args.derivationPath) { + url += `&derivationPath=${JSON.stringify(args.derivationPath)}`; + } + if (args.compressed) { + url += `&compressed=${args.compressed}`; + } + return await this.apiClient.issueGetRequest(url); + } + + /** + * allocate funds from you default balance to a private ledger + * @param vaultAccountId + * @param asset + * @param vaultAccountId + * @param asset + * @param args + * @param requestOptions + */ + public async allocateFundsToPrivateLedger(vaultAccountId: string, asset: string, args: AllocateFundsRequest, requestOptions?: RequestOptions): Promise { + const url = `/v1/vault/accounts/${vaultAccountId}/${asset}/lock_allocation`; + return await this.apiClient.issuePostRequest(url, args, requestOptions); + } + + /** + * deallocate funds from a private ledger to your default balance + * @param vaultAccountId + * @param asset + * @param args + * @param requestOptions + */ + public async deallocateFundsFromPrivateLedger(vaultAccountId: string, asset: string, args: DeallocateFundsRequest, requestOptions?: RequestOptions): Promise { + const url = `/v1/vault/accounts/${vaultAccountId}/${asset}/release_allocation`; + return await this.apiClient.issuePostRequest(url, args, requestOptions); + } + + /** + * Get the public key information for a vault account + * @param args + */ + public async getPublicKeyInfoForVaultAccount(args: PublicKeyInfoForVaultAccountArgs): Promise { + let url = `/v1/vault/accounts/${args.vaultAccountId}/${args.assetId}/${args.change}/${args.addressIndex}/public_key_info`; + if (args.compressed) { + url += `?compressed=${args.compressed}`; + } + return await this.apiClient.issueGetRequest(url); + } + + /** + * Get configuration and status of the Gas Station account + */ + public async getGasStationInfo(assetId?: string): Promise { + let url = `/v1/gas_station`; + + if (assetId) { + url += `/${assetId}`; + } + + return await this.apiClient.issueGetRequest(url); + } + + /** + * Set configuration of the Gas Station account + */ + public async setGasStationConfiguration(gasThreshold: string, gasCap: string, maxGasPrice?: string, assetId?: string): Promise { + let url = `/v1/gas_station/configuration`; + + if (assetId) { + url += `/${assetId}`; + } + + const body = {gasThreshold, gasCap, maxGasPrice}; + + return await this.apiClient.issuePutRequest(url, body); + } + + /** + * Drop an ETH based transaction + */ + public async dropTransaction(txId: string, feeLevel?: string, requestedFee?: string, requestOptions?: RequestOptions): Promise { + const url = `/v1/transactions/${txId}/drop`; + + const body = {feeLevel, requestedFee}; + + return await this.apiClient.issuePostRequest(url, body, requestOptions); + } + + /** + * Get max spendable amount per asset and vault + */ + public async getMaxSpendableAmount(vaultAccountId: string, assetId: string, manualSigning?: Boolean): Promise { + let url = `/v1/vault/accounts/${vaultAccountId}/${assetId}/max_spendable_amount`; + + if (manualSigning) { + url += `?manualSigning=${manualSigning}`; + } + + return await this.apiClient.issueGetRequest(url); + } + + /** + * Get maximum BIP44 index used in deriving addresses or in change addresses + */ + public async getMaxBip44IndexUsed(vaultAccountId: string, assetId: string): Promise { + const url = `/v1/vault/accounts/${vaultAccountId}/${assetId}/max_bip44_index_used`; + + return await this.apiClient.issueGetRequest(url); + } + + /** + * Get all vault assets balance overview + */ + public async getVaultAssetsBalance(filter: VaultBalancesFilter): Promise { + const url = `/v1/vault/assets?${queryString.stringify(filter)}`; + + return await this.apiClient.issueGetRequest(url); + } + + /** + * Get vault balance overview per asset + */ + public async getVaultBalanceByAsset(assetId: string): Promise { + const url = `/v1/vault/assets/${assetId}`; + return await this.apiClient.issueGetRequest(url); + } + + /** + * Get address validation info + */ + public async validateAddress(assetId: string, address: string): Promise { + const url = `/v1/transactions/validate_address/${assetId}/${address}`; + return await this.apiClient.issueGetRequest(url); + } + + /** + * Unfreezes the selected transaction + * @param txId The transaction id to unfreeze + * @param requestOptions + */ + public async unfreezeTransactionById(txId: string, requestOptions?: RequestOptions): Promise { + return this.apiClient.issuePostRequest(`/v1/transactions/${txId}/unfreeze`, {}, requestOptions); + } + + /** + * Freezes the selected transaction + * @param txId The transaction id to freeze + * @param requestOptions + */ + public async freezeTransactionById(txId: string, requestOptions?: RequestOptions): Promise { + return this.apiClient.issuePostRequest(`/v1/transactions/${txId}/freeze`, {}, requestOptions); + } + + /** + * Resend failed webhooks + */ + public async resendWebhooks(requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest("/v1/webhooks/resend", {}, requestOptions); + } + + /** + * Resend transaction webhooks + * @param txId The transaction for which the message is sent + * @param resendCreated If true a webhook will be sent for the creation of the transaction + * @param resendStatusUpdated If true a webhook will be sent for the status of the transaction + * @param requestOptions + */ + public async resendTransactionWebhooksById(txId: string, resendCreated?: boolean, resendStatusUpdated?: boolean, requestOptions?: RequestOptions): Promise { + const body = { resendCreated, resendStatusUpdated }; + return await this.apiClient.issuePostRequest(`/v1/webhooks/resend/${txId}`, body, requestOptions); + } + + /** + * Gets all Users for your tenant + */ + public async getUsers(): Promise { + return await this.apiClient.issueGetRequest("/v1/users"); + } + + /** + * Gets all Users Groups for your tenant + */ + public async getUsersGroups(): Promise { + return await this.apiClient.issueGetRequest("/v1/users_groups"); + } + + /** + * Gets a Users Group by ID + * @param id The ID of the User + */ + public async getUsersGroup(id: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/users_groups/${id}`); + } + + /** + * Creates a new Users Group + * @param name The name of the Users Group + * @param memberIds The members of the Users Group + */ + public async createUserGroup(groupName: string, memberIds?: string[]): Promise { + const body = { groupName, memberIds }; + return await this.apiClient.issuePostRequest("/v1/users_groups", body); + } + + /** + * Updates a Users Group + * @param id The ID of the Users Group + * @param name The name of the Users Group + * @param memberIds The members of the Users Group + */ + public async updateUserGroup(id: string, groupName?: string, memberIds?: string[]): Promise { + const body = { groupName, memberIds }; + return await this.apiClient.issuePutRequest(`/v1/users_groups/${id}`, body); + } + + /** + * Deletes a Users Group + * @param id The ID of the Users Group + */ + public async deleteUserGroup(id: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/users_groups/${id}`); + } + + /** + * Get off exchange accounts + */ + public async getOffExchangeAccounts(): Promise { + return await this.apiClient.issueGetRequest(`/v1/off_exchange_accounts`); + } + + /** + * Get off exchange account by virtual account id + * @param id the ID of the off exchange + */ + public async getOffExchangeAccountById(id: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/off_exchange_accounts/${id}`); + } + + /** + * Settle off exchange account by virtual account id + * @param id the ID of the off exchange + * @param requestOptions + */ + public async settleOffExchangeAccountById(id: string, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/off_exchange_accounts/${id}/settle`, {}, requestOptions); + } + + /** + * Add collateral account, create deposit request + * @param depositRequest + * @param requestOptions + */ + public async addCollateral(depositRequest: AddCollateralTransactionRequest, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/off_exchange/add`, depositRequest, requestOptions); + } + + /** + * Remove collateral account, create withdraw request + * @param withdrawRequest + * @param requestOptions + */ + public async removeCollateral(withdrawRequest: RemoveCollateralTransactionRequest, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/off_exchange/remove`, withdrawRequest, requestOptions); + } + + /** + * + * @param requestOptions + */ + public async getSettlementTransactions(settlementRequest: SettlementRequest): Promise { + return await this.apiClient.issueGetRequest(`/v1/off_exchange/settlements/transactions?mainExchangeAccountId=${settlementRequest.mainExchangeAccountId}`); + } + + /** + * + * @param settlementRequest + * @param requestOptions + */ + public async settlement(settlementRequest: SettlementRequest, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/off_exchange/settlements/trader`, settlementRequest, requestOptions); + } + /** + * Set Fee Payer configuration + * @param feePayerConfiguration + * @param baseAsset + * @param requestOptions + */ + public async setFeePayerConfiguration(baseAsset: string, feePayerConfiguration: SetFeePayerConfiguration, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/fee_payer/${baseAsset}`, feePayerConfiguration, requestOptions); + } + + /** + * Get Fee Payer Configuration + * @param baseAsset + */ + public async getFeePayerConfiguration(baseAsset: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/fee_payer/${baseAsset}`); + } + + /** + * Delete Fee Payer Configuration + * @param baseAsset + */ + public async removeFeePayerConfiguration(baseAsset: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/fee_payer/${baseAsset}`); + } + + private getWeb3ConnectionPath(type: Web3ConnectionType): string { + const basePath = `/v1/connections`; + + switch (type) { + case(Web3ConnectionType.WALLET_CONNECT): { + return `${basePath}/wc`; + } + default: { + throw new Error(`Invalid Web3 connection type`); + } + } + } + + /** + * Get all signer connections of the current tenant + * @param {Object} payload The payload for getting the current tenant's sessions + * @param payload.pageCursor The cursor for the next page + * @param payload.pageSize The amount of results to return on the next page + * @param payload.sort The property to sort the results by + * @param payload.filter The filter object, containing properties as keys and the values to filter by as values + * @param payload.order Should the results be ordered in ascending order (false) or descending (true) + * + * @returns An object containing the data returned and the cursor for the next page + */ + public async getWeb3Connections({ + pageCursor, + pageSize, + sort, + filter, + order + }: GetWeb3ConnectionsPayload = {}): Promise> { + const params = new URLSearchParams({ + ...(pageCursor && { next: pageCursor }), + ...(pageSize && { pageSize: pageSize.toString() }), + ...(sort && { sort }), + ...(filter && { filter: stringify(filter, { delimiter: "," })}), + ...(order && { order }), + }); + + return await this.apiClient.issueGetRequest(`/v1/connections?${params.toString()}`); + } + + /** + * Initiate a new web3 connection + * @param type The type of the connection + * @param payload The payload for creating a new web3 connection + * @param requestOptions + * @param payload.vaultAccountId The vault account to link with the dapp + * @param payload.feeLevel The fee level for the connection + * @param payload.uri The WalletConnect URI, as provided by the dapp + * @param payload.chainIds Array of the approved chains for the connection + * + * @returns The created session's ID and it's metadata + * @example { + * vaultAccountId: 0 + * feeLevel: "MEDIUM" + * connectionType: "WalletConnect" + * uri: "wc:77752975-906f-48f5-b59f-047826ee947e@1?bridge=https%3A%2F%2F0.bridge.walletconnect.org&key=64be99adc6086b7a729b0ec8c7e1f174927ab92e84f5c6f9527050225344a637" + * chainIds: ["ETH", "ETH_TEST"] + * } + */ + public async createWeb3Connection(type: Web3ConnectionType.WALLET_CONNECT, payload: CreateWalletConnectPayload, requestOptions?: RequestOptions): Promise; + public async createWeb3Connection(type: Web3ConnectionType, payload: CreateWeb3ConnectionPayload, requestOptions?: RequestOptions): Promise { + const path = this.getWeb3ConnectionPath(type); + + return await this.apiClient.issuePostRequest(path, payload, requestOptions); + } + + /** + * Approve or Reject the initiated connection + * @param type The type of the connection + * @param sessionId The ID of the session + * @param approve Whether you approve the connection or not + */ + public async submitWeb3Connection(type: Web3ConnectionType.WALLET_CONNECT, sessionId: string, approve: boolean): Promise; + public async submitWeb3Connection(type: Web3ConnectionType, sessionId: string, approve: boolean): Promise { + const path = this.getWeb3ConnectionPath(type); + + return await this.apiClient.issuePutRequest(`${path}/${sessionId}`, {approve}); + } + + /** + * Remove an existing connection + * @param type The type of the connection + * @param sessionId The ID of the session + */ + public async removeWeb3Connection(type: Web3ConnectionType.WALLET_CONNECT, sessionId: string): Promise; + public async removeWeb3Connection(type: Web3ConnectionType, sessionId: string): Promise { + const path = this.getWeb3ConnectionPath(type); + + return await this.apiClient.issueDeleteRequest(`${path}/${sessionId}`); + } + + /** + * Gets all audits for selected time period + * @param timePeriod + */ + public async getAudits(timePeriod?: TimePeriod): Promise { + let url = `/v1/audits`; + if (timePeriod) { + url += `?timePeriod=${timePeriod}`; + } + return await this.apiClient.issueGetRequest(url); + } + + /** + * + * @param id + */ + public async getNFT(id: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/nfts/tokens/${id}`); + } + + /** + * + * @param filter.pageCursor + * @param filter.pageSize + * @param filter.ids + * @param filter.sort + * @param filter.order + */ + public async getNFTs(filter: GetNFTsFilter): Promise> { + const { pageCursor, pageSize, ids, sort, order } = filter; + const queryParams = { + pageCursor, + pageSize, + ids: this.getCommaSeparatedList(ids), + sort: this.getCommaSeparatedList(sort), + order, + }; + + return await this.apiClient.issueGetRequest(`/v1/nfts/tokens?${queryString.stringify(queryParams)}`); + } + + /** + * + * Gets a list of owned NFT tokens + * @param filter.vaultAccountIds List of vault account IDs + * @param filter.blockchainDescriptor The blockchain descriptor (based on legacy asset) + * @param filter.collectionIds List of collection IDs + * @param filter.ids List of token ids to fetch + * @param filter.pageCursor Page cursor + * @param filter.pageSize Page size + * @param filter.sort Sort by value + * @param filter.order Order value + * @param filter.status Status (LISTED, ARCHIVED) + * @param filter.search Search filter + * @param filter.ncwAccountIds List of Non-Custodial wallet account IDs + * @param filter.ncwId Non-Custodial wallet id + * @param filter.walletType Wallet type (VAULT_ACCOUNT, END_USER_WALLET) + */ + public async getOwnedNFTs(filter?: NFTOwnershipFilter): Promise> { + let url = "/v1/nfts/ownership/tokens"; + if (filter) { + const { blockchainDescriptor, vaultAccountIds, collectionIds, ids, pageCursor, pageSize, sort, order, status, search, ncwId, ncwAccountIds, walletType } = filter; + const requestFilter = { + vaultAccountIds: this.getCommaSeparatedList(vaultAccountIds), + blockchainDescriptor, + collectionIds: this.getCommaSeparatedList(collectionIds), + pageCursor, + pageSize, + ids: this.getCommaSeparatedList(ids), + sort: this.getCommaSeparatedList(sort), + order, + status, + search, + ncwId, + ncwAccountIds, + walletType, + }; + url += `?${queryString.stringify(requestFilter)}`; + } + return await this.apiClient.issueGetRequest(url); + } + + /** + * + * Get a list of owned NFT collections + * @param filter.search Search by value + * @param filter.status Status (LISTED, ARCHIVED) + * @param filter.ncwId Non-Custodial wallet id + * @param filter.walletType Wallet type (VAULT_ACCOUNT, END_USER_WALLET) + * @param filter.pageCursor Page cursor + * @param filter.pageSize Page size + * @param filter.sort Sort by value + * @param filter.order Order by value + */ + public async listOwnedCollections(filter?: NFTOwnedCollectionsFilter): Promise> { + let url = "/v1/nfts/ownership/collections"; + if (filter) { + const { search, status, ncwId, walletType, pageCursor, pageSize, sort, order } = filter; + + const requestFilter = { + search, + status, + ncwId, + walletType, + pageCursor, + pageSize, + sort: this.getCommaSeparatedList(sort), + order, + }; + url += `?${queryString.stringify(requestFilter)}`; + } + + return await this.apiClient.issueGetRequest(url); + } + + /** + * + * Get a list of owned tokens + * @param filter.search Search by value + * @param filter.status Status (LISTED, ARCHIVED) + * @param filter.ncwId Non-Custodial wallet id + * @param filter.walletType Wallet type (VAULT_ACCOUNT, END_USER_WALLET) + * @param filter.pageCursor Page cursor + * @param filter.pageSize Page size + * @param filter.sort Sort by value + * @param filter.order Order by value + */ + public async listOwnedAssets(filter?: NFTOwnedAssetsFilter): Promise> { + let url = "/v1/nfts/ownership/assets"; + if (filter) { + const { search, status, ncwId, walletType, pageCursor, pageSize, sort, order } = filter; + + const requestFilter = { + search, + status, + ncwId, + walletType, + pageCursor, + pageSize, + sort: this.getCommaSeparatedList(sort), + order, + }; + url += `?${queryString.stringify(requestFilter)}`; + } + + return await this.apiClient.issueGetRequest(url); + } + + /** + * + * @param id + */ + public async refreshNFTMetadata(id: string): Promise { + return await this.apiClient.issuePutRequest(`/v1/nfts/tokens/${id}`, undefined); + } + + /** + * + * Update NFT ownership status for specific token + * @param id NFT asset id + * @param status Status for update + */ + public async updateNFTOwnershipStatus(id: string, status: NFTOwnershipStatus): Promise { + return await this.apiClient.issuePutRequest(`/v1/nfts/ownership/tokens/${id}/status`, { status }); + } + + /** + * + * @param vaultAccountId + * @param blockchainDescriptor + */ + public async refreshNFTOwnershipByVault(vaultAccountId: string, blockchainDescriptor: string): Promise { + return await this.apiClient.issuePutRequest( + `/v1/nfts/ownership/tokens?vaultAccountId=${vaultAccountId}&blockchainDescriptor=${blockchainDescriptor}`, + undefined); + } + + /** + * Upload a new contract. This contract would be private and only your tenant can see it + * @param request + */ + public async uploadNewContract(request: ContractUploadRequest): Promise { + return await this.apiClient.issuePostRequest(`/v1/contract-registry/contracts`, request); + } + + /** + * Get all tokens linked to the tenant + * @param limit + * @param offset + */ + public async getLinkedTokens(limit: number = 100, offset: number = 0): Promise { + const requestFilter = { + limit, + offset + }; + const url = `/v1/tokenization/tokens?${queryString.stringify(requestFilter)}`; + return await this.apiClient.issueGetRequest(url); + } + + + /** + * Issue a new token and link it to the tenant + * @param request + */ + public async issueNewToken(request: IssueTokenRequest): Promise { + return await this.apiClient.issuePostRequest(`/v1/tokenization/tokens`, request); + } + + /** + * Get a token linked to the tenant by asset id + * @param assetId + */ + public async getLinkedToken(assetId: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/tokenization/tokens/${assetId}`); + } + + /** + * Link a token to the tenant + * @param assetId + */ + public async linkToken(assetId: string): Promise { + return await this.apiClient.issuePutRequest(`/v1/tokenization/tokens/${assetId}/link`, { }); + } + + /** + * remove a link to a token from the tenant + * @param assetId + */ + public async unlinkToken(assetId: string): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/tokenization/tokens/${assetId}`); + } + + /** + * Add permissions to a linked token + * @param assetId + * @param permissions + */ + public async addLinkedTokenPermissions(assetId: string, permissions: TokenLinkPermissionEntry[]): Promise { + return await this.apiClient.issuePutRequest(`/v1/tokenization/tokens/${assetId}/permissions`, { permissions }); + } + + /** + * Remove permissions from a linked token + * @param assetId + * @param permission + */ + public async removeLinkedTokenPermissions(assetId: string, permission: TokenLinkPermissionEntry): Promise { + return await this.apiClient.issueDeleteRequest(`/v1/tokenization/tokens/${assetId}/permissions?permission=${permission.permission}&vaultAccountId=${permission.vaultAccountId}`); + } + + /** + * Validate VASP details for travel rule compliance + * @param travelRuleMessageVaspInfo + */ + public async validateTravelRuleTransaction(travelRuleMessageVaspInfo: ValidateTravelRuleVaspInfo): Promise { + return await this.apiClient.issuePostRequest(`/v1/screening/travel_rule/transaction/validate`, travelRuleMessageVaspInfo); + } + + /** + * Validate Travel Rule transaction and PII data + * @param travelRuleMessage + */ + public async validateFullTravelRuleTransaction(travelRuleMessage: ValidateCreateTravelRuleTransaction): Promise { + return await this.apiClient.issuePostRequest(`/v1/screening/travel_rule/transaction/validate/full`, travelRuleMessage); + } + + /** + * Get VASP details for travel rule compliance + * @param did + */ + public async getTravelRuleVASPDetails(did: string): Promise { + return await this.apiClient.issueGetRequest(`/v1/screening/travel_rule/vasp/${did}`); + } + + /** + * Get VASP library for travel rule compliance + */ + public async getAllTravelRuleVASPs(filter?: TravelRuleVaspFilter): Promise { + let url = `/v1/screening/travel_rule/vasp`; + + if (filter) { + const { q, fields, page, per_page, order } = filter; + const queryParameters = { + q, + fields: this.getCommaSeparatedList(fields), + page, + per_page, + order, + }; + + url += `?${queryString.stringify(queryParameters)}`; + } + + return await this.apiClient.issueGetRequest(url); + } + + /** + * Update VASP for travel rule compliance + */ + public async updateVasp(vaspInfo: TravelRuleVasp): Promise { + return await this.apiClient.issuePutRequest(`/v1/screening/travel-rule/vasp/update`, vaspInfo); + } + + /** + * Creates Smart Transfers ticket + * @param data + * @param requestOptions + */ + public async createSmartTransferTicket(data: SmartTransfersTicketCreatePayload, requestOptions?: RequestOptions): Promise { + return await this.apiClient.issuePostRequest(`/v1/smart-transfers`, data, requestOptions); + } + + /** + * Get Smart Transfer tickets + * @param filters + */ + public getSmartTransferTickets(filters: SmartTransfersTicketsFilters): Promise { + return this.apiClient.issueGetRequest(`/v1/smart-transfers?${queryString.stringify(filters)}`); + } + + /** + * Get Smart Transfers ticket by id + * @param ticketId + */ + public getSmartTransferTicket(ticketId: string): Promise { + return this.apiClient.issueGetRequest(`/v1/smart-transfers/${ticketId}`); + } + + /** + * Set Smart Transfers ticket expires in + * @param ticketId + * @param expiresIn + */ + public setSmartTransferTicketExpiresIn(ticketId: string, expiresIn: number): Promise { + return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/expires-in`, {expiresIn}); + } + + /** + * Set Smart Transfer ticket external id + * @param ticketId + * @param externalRefId + */ + public setSmartTransferTicketExternalId(ticketId: string, externalRefId: string): Promise { + return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/external-id`, {externalRefId}); + } + + /** + * Submit Smart Transfers ticket + * @param ticketId + * @param expiresIn + */ + public submitSmartTransferTicket(ticketId: string, expiresIn: number): Promise { + return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/submit`, {expiresIn}); + } + + /** + * Fulfill Smart Transfers ticket + * @param ticketId + */ + public fulfillSmartTransferTicket(ticketId: string): Promise { + return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/fulfill`, {}); + } + + /** + * Cancel Smart Transfers ticket + * @param ticketId + */ + public cancelSmartTransferTicket(ticketId: string): Promise { + return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/cancel`, {}); + } + + /** + * Create Smart Transfers ticket term + * @param ticketId + * @param data + */ + public createSmartTransferTicketTerm(ticketId: string, data: SmartTransfersTicketTermPayload): Promise { + return this.apiClient.issuePostRequest(`/v1/smart-transfers/${ticketId}/terms`, data); + } + + /** + * Fet Smart Transfers ticket term + * @param ticketId + * @param termId + */ + public getSmartTransferTicketTerms(ticketId: string, termId: string): Promise { + return this.apiClient.issueGetRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}`); + } + + /** + * Update Smart Transfers ticket term + * @param ticketId + * @param termId + * @param data + */ + public updateSmartTransferTicketTerms(ticketId: string, termId: string, data: SmartTransfersTicketTermPayload): Promise { + return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}`, data); + } + + /** + * Fund Smart Transfers ticket term + * @param ticketId + * @param termId + * @param data + */ + public fundSmartTransferTicketTerm(ticketId: string, termId: string, data: SmartTransfersTicketTermFundPayload): Promise { + return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}/fund`, data); + } + + /** + * Manually fund Smart Transfers ticket term + * @param ticketId + * @param termId + * @param txHash + */ + public manuallyFundSmartTransferTicketTerms(ticketId: string, termId: string, txHash: string): Promise { + return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}/manually-fund`, { txHash }); + } + + /** + * Set Smart Transfers user group ids. User group ids are used for Smart Transfer notifications + * @param userGroupIds + */ + public setSmartTransferTicketUserGroups(userGroupIds: string[]): Promise { + return this.apiClient.issuePostRequest(`/v1/smart-transfers/settings/user-groups`, { userGroupIds }); + } + + /** + * Get Smart Transfers user group ids. User group ids are used for Smart Transfer notifications + */ + public getSmartTransferTicketUserGroups(): Promise { + return this.apiClient.issueGetRequest(`/v1/smart-transfers/settings/user-groups`); + } + + /** + * Delete Smart Transfers ticket term + * @param ticketId + * @param termId + */ + public deleteSmartTransferTicketTerms(ticketId: string, termId: string): Promise { + return this.apiClient.issueDeleteRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}`); + } + + private getCommaSeparatedList(items: Array): string | undefined { + return items ? items.join(",") : undefined; + } + + /** + * Get list of jobs for current tenant + * @param fromTime beggining of time range in MS since 1970 + * @param toTime ending of time range in MS since 1970 + */ + public getJobs(fromTime: number, toTime: number): Promise { + return this.apiClient.issueGetRequest(`/v1/batch/jobs?fromTime=${fromTime}&toTime=${toTime}`); + } + + /** + * Get job info by job ID + * @param jobId + */ + public getJob(jobId: string): Promise { + return this.apiClient.issueGetRequest(`/v1/batch/${jobId}`); + } + + /** + * Get tasks belonging to given job + * @param jobId + */ + public getTasks(jobId: string): Promise { + return this.apiClient.issueGetRequest(`/v1/batch/${jobId}/tasks`); + } + + /** + * Cancel a job by ID + * @param jobId + */ + public cancelJob(jobId: string): Promise { + return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/cancel`, {}); + } + + /** + * Pause a job by ID + * @param jobId + */ + public pauseJob(jobId: string): Promise { + return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/pause`, {}); + } + + /** + * Continue a job by ID + * @param jobId + */ + public continueJob(jobId: string): Promise { + return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/continue`, {}); + } + + /** + * Create multiple vault accounts in one bulk operation + * @param count number of vault accounts + */ + public createVaultAccountsBulk(count: number, assetId: string): Promise { + const body = { + count, + assetId + }; + return this.apiClient.issuePostRequest(`/v1/vault/accounts/bulk`, body); + } + + /** + * Create multiple vault wallets in one bulk operation + * @param count number of vault accounts + */ + public createVaultWalletsBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string): Promise { + const body = { + assetId, + vaultAccountIdFrom, + vaultAccountIdTo + }; + return this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body); + } +} diff --git a/src mine/iauth-provider.ts b/src mine/iauth-provider.ts new file mode 100644 index 00000000..afbfa7e2 --- /dev/null +++ b/src mine/iauth-provider.ts @@ -0,0 +1,5 @@ +export interface IAuthProvider { + signJwt(path: string, bodyJson?: any): string; + + getApiKey(): string; +} diff --git a/src mine/ncw-api-client.ts b/src mine/ncw-api-client.ts new file mode 100644 index 00000000..1026bd5d --- /dev/null +++ b/src mine/ncw-api-client.ts @@ -0,0 +1,135 @@ +import { ApiClient } from "./api-client"; +import { + AssetResponse, + Web3PagedResponse, + NCW, +} from "./types"; +import { NcwSdk } from "./ncw-sdk"; + +export class NcwApiClient implements NcwSdk { + private readonly NCW_BASE_PATH = "/v1/ncw/wallets"; + + constructor(private readonly apiClient: ApiClient) { } + + public async createWallet(): Promise<{ walletId: string; enabled: boolean; }> { + return await this.apiClient.issuePostRequest( + `${this.NCW_BASE_PATH}`, + {}); + } + + public async getWallet(walletId: string): Promise<{ walletId: string; enabled: boolean; }> { + return await this.apiClient.issueGetRequest( + `${this.NCW_BASE_PATH}/${walletId}`); + } + + public async enableWallet(walletId: string, enabled: boolean): Promise { + return await this.apiClient.issuePutRequest( + `${this.NCW_BASE_PATH}/${walletId}/enable`, + { enabled }); + } + + public async getWalletDevices(walletId: string): Promise { + return await this.apiClient.issueGetRequest( + `${this.NCW_BASE_PATH}/${walletId}/devices/`); + } + + public async enableWalletDevice(walletId: string, deviceId: string, enabled: boolean): Promise { + return await this.apiClient.issuePutRequest( + `${this.NCW_BASE_PATH}/${walletId}/devices/${deviceId}/enable`, + { enabled }); + } + + public async invokeWalletRpc(walletId: string, deviceId: string, payload: string): Promise<{ result: string; } | { error: { message: string; code?: number; }; }> { + return await this.apiClient.issuePostRequest( + `${this.NCW_BASE_PATH}/${walletId}/devices/${deviceId}/invoke`, + { payload }); + } + + public async createWalletAccount(walletId: string): Promise<{ + walletId: string; + accountId: number; + }> { + return await this.apiClient.issuePostRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts`, + {}); + } + + public async getWallets({ pageCursor, pageSize, sort, order }: NCW.GetWalletsPayload = {}): Promise> { + const params = new URLSearchParams({ + ...(pageCursor && { pageCursor }), + ...(pageSize && { pageSize: pageSize.toString() }), + ...(sort && { sort }), + ...(order && { order }), + }); + + return await this.apiClient.issueGetRequest(`${this.NCW_BASE_PATH}?${params.toString()}`); + } + + public async getWalletAccounts(walletId: string, { pageCursor, pageSize, sort, order }: NCW.GetWalletsPayload = {}): Promise> { + const params = new URLSearchParams({ + ...(pageCursor && { pageCursor }), + ...(pageSize && { pageSize: pageSize.toString() }), + ...(sort && { sort }), + ...(order && { order }), + }); + + return await this.apiClient.issueGetRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts?${params.toString()}`); + } + + public async getWalletAccount(walletId: string, accountId: number): Promise<{ + walletId: string; + accountId: number; + }> { + return await this.apiClient.issueGetRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}`); + } + + public async getWalletAssets(walletId: string, accountId: number, { pageCursor, pageSize, sort, order }: NCW.GetWalletAssetsPayload = {}): Promise> { + const params = new URLSearchParams({ + ...(pageCursor && { pageCursor }), + ...(pageSize && { pageSize: pageSize.toString() }), + ...(sort && { sort }), + ...(order && { order }), + }); + + return await this.apiClient.issueGetRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets?${params.toString()}`); + } + + public async getWalletAsset(walletId: string, accountId: number, assetId: string): Promise { + return await this.apiClient.issueGetRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}`); + } + + public async activateWalletAsset(walletId: string, accountId: number, assetId: string): Promise { + return await this.apiClient.issuePostRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}`, {}); + } + + public async getWalletAssetAddresses(walletId: string, accountId: number, assetId: string, { pageCursor, pageSize, sort, order }: NCW.GetWalletAddressesPayload = {}): Promise> { + const params = new URLSearchParams({ + ...(pageCursor && { pageCursor }), + ...(pageSize && { pageSize: pageSize.toString() }), + ...(sort && { sort }), + ...(order && { order }), + }); + + return await this.apiClient.issueGetRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}/addresses?${params.toString()}`); + } + + public async getWalletAssetBalance(walletId: string, accountId: number, assetId: string): Promise { + return await this.apiClient.issueGetRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}/balance`); + } + + public async refreshWalletAssetBalance(walletId: string, accountId: number, assetId: string): Promise { + return await this.apiClient.issuePutRequest( + `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}/balance`, + {}); + } +} \ No newline at end of file diff --git a/src mine/ncw-sdk.ts b/src mine/ncw-sdk.ts new file mode 100644 index 00000000..25f68318 --- /dev/null +++ b/src mine/ncw-sdk.ts @@ -0,0 +1,155 @@ +import { + AssetResponse, Web3PagedResponse, NCW, +} from "./types"; + +export interface NcwSdk { + /** + * Create a new NCW wallet + */ + createWallet(): Promise<{ walletId: string; enabled: boolean; }>; + + /** + * Get a NCW wallet + * + * @param {string} walletId + */ + getWallet(walletId: string): Promise<{ walletId: string; enabled: boolean; }>; + + /** + * Enable a NCW wallet + * + * @param {string} walletId + * @param {boolean} enabled + */ + enableWallet(walletId: string, enabled: boolean): Promise; + + + /** + * Get NCW wallet devices + * + * @param {string} walletId + * @return {*} {Promise} + */ + getWalletDevices(walletId: string): Promise; + + /** + * Set NCW wallet device's enabled state + * + * @param {string} walletId + * @param {string} deviceId + * @param {boolean} enabled + * @return {*} {Promise} + */ + enableWalletDevice(walletId: string, deviceId: string, enabled: boolean): Promise; + + /** + * Invoke NCW wallet RPC call + * + * @param {string} walletId + * @param {string} deviceId + * @param {string} payload + * @return {*} {(Promise<{ result: string } | { error: { message: string, code?: number } }>)} + */ + invokeWalletRpc(walletId: string, deviceId: string, payload: string): Promise<{ result: string; } | { error: { message: string; code?: number; }; }>; + + /** + * Create a new NCW wallet account + * + * @param {string} walletId + */ + createWalletAccount(walletId: string): Promise<{ + walletId: string; + accountId: number; + }>; + + /** + * Get NCW wallets + * + * @param {GetWalletsPayload} { pageCursor, pageSize, sort, order } + * @return {*} {Promise>} + */ + getWallets({ pageCursor, pageSize, sort, order }: NCW.GetWalletsPayload): Promise>; + + /** + * Get NCW accounts + * + * @param {string} walletId + * @param {GetWalletsPayload} [{ pageCursor, pageSize, sort, order }] + */ + getWalletAccounts(walletId: string, { pageCursor, pageSize, sort, order }?: NCW.GetWalletsPayload): Promise>; + + /** + * Get a NCW account + * + * @param {string} walletId + * @param {number} accountId + */ + getWalletAccount(walletId: string, accountId: number): Promise<{ + walletId: string; + accountId: number; + }>; + + /** + * Get NCW assets + * + * @param {string} walletId + * @param {number} accountId + * @param {GetWalletAssetsPayload} [{ pageCursor, pageSize, sort, order }] + * @return {*} {Promise>} + */ + getWalletAssets(walletId: string, accountId: number, { pageCursor, pageSize, sort, order }?: NCW.GetWalletAssetsPayload): Promise>; + + /** + * Get a NCW asset + * + * @param {string} walletId + * @param {number} accountId + * @param {string} assetId + * @return {*} {Promise} + */ + getWalletAsset(walletId: string, accountId: number, assetId: string): Promise; + + /** + * Activate a NCW asset + * + * @param {string} walletId + * @param {number} accountId + * @param {string} assetId + * @return {*} {Promise} + */ + activateWalletAsset(walletId: string, accountId: number, assetId: string): Promise; + + /** + * Get a NCW asset addresses + * + * @param {string} walletId + * @param {number} accountId + * @param {string} assetId + * @param {GetWalletAddressesPayload} { pageCursor, pageSize, sort, order } + * @return {*} {Promise>} + */ + getWalletAssetAddresses(walletId: string, accountId: number, assetId: string, { pageCursor, pageSize, sort, order }?: NCW.GetWalletAddressesPayload): Promise>; + + /** + * Get a NCW asset balance + * + * @param {string} walletId + * @param {number} accountId + * @param {string} assetId + * @return {*} {Promise} + */ + getWalletAssetBalance(walletId: string, accountId: number, assetId: string): Promise; + + /** + * refresh a NCW asset balance + * + * @param {string} walletId + * @param {number} accountId + * @param {string} assetId + * @return {*} {Promise} + */ + refreshWalletAssetBalance(walletId: string, accountId: number, assetId: string): Promise; +} \ No newline at end of file diff --git a/src mine/pii-client.ts b/src mine/pii-client.ts new file mode 100644 index 00000000..3d82dbe7 --- /dev/null +++ b/src mine/pii-client.ts @@ -0,0 +1,83 @@ +import PIIsdk, { PIIEncryptionMethod } from "@notabene/pii-sdk"; +import { TransactionArguments, TravelRule, TravelRuleEncryptionOptions, TravelRuleOptions } from "./types"; +import * as util from "util"; + +const requiredFields = [ + "baseURLPII", + "audiencePII", + "clientId", + "clientSecret", + "authURL", + "jsonDidKey", +]; + +export class PIIEncryption { + public toolset: PIIsdk; + + constructor(private readonly config: TravelRuleOptions) { + this.config = config; + const missingFields = requiredFields.filter( + (field) => !(field in this.config) + ); + + if (missingFields.length > 0) { + throw new Error( + `Missing PII configuration fields: ${missingFields.join(", ")}` + ); + } + + this.toolset = new PIIsdk({ + piiURL: config.baseURLPII, + audience: config.audiencePII, + clientId: config.clientId, + clientSecret: config.clientSecret, + authURL: config.authURL, + }); + } + + async hybridEncode(transaction: TransactionArguments, travelRuleEncryptionOptions?: TravelRuleEncryptionOptions) { + const { travelRuleMessage } = transaction; + const pii = travelRuleMessage.pii || { + originator: travelRuleMessage.originator, + beneficiary: travelRuleMessage.beneficiary, + }; + const { jsonDidKey } = this.config; + const counterpartyDIDKey = travelRuleEncryptionOptions?.beneficiaryPIIDidKey; + + let piiIvms; + + try { + piiIvms = await this.toolset.generatePIIField({ + pii, + originatorVASPdid: travelRuleMessage.originatorVASPdid, + beneficiaryVASPdid: travelRuleMessage.beneficiaryVASPdid, + counterpartyDIDKey, + keypair: JSON.parse(jsonDidKey), + senderDIDKey: JSON.parse(jsonDidKey).did, + encryptionMethod: travelRuleEncryptionOptions?.sendToProvider + ? PIIEncryptionMethod.HYBRID + : PIIEncryptionMethod.END_2_END, + }); + } catch (error) { + const errorMessage = error.message || error.toString(); + const errorDetails = JSON.stringify(error); + throw new Error(`Failed to generate PII fields error: ${errorMessage}. Details: ${errorDetails}`); + } + + transaction.travelRuleMessage = this.travelRuleMessageHandler(travelRuleMessage, piiIvms); + + return transaction; + } + + private travelRuleMessageHandler(travelRuleMessage: TravelRule, piiIvms: any): TravelRule { + travelRuleMessage.beneficiary = piiIvms.beneficiary; + travelRuleMessage.originator = piiIvms.originator; + + travelRuleMessage.beneficiary = { + originatorPersons: piiIvms.beneficiary.beneficiaryPersons, + accountNumber: piiIvms.beneficiary.accountNumber, + }; + + return travelRuleMessage; + } +} \ No newline at end of file diff --git a/src mine/types.ts b/src mine/types.ts new file mode 100644 index 00000000..829b91a8 --- /dev/null +++ b/src mine/types.ts @@ -0,0 +1,1763 @@ +import { AxiosResponseHeaders } from "axios"; + +export interface Web3PagedResponse { + data: T[]; + paging?: Paging; +} + +export type APIResponseHeaders = AxiosResponseHeaders & {"x-request-id"?: string}; + +export interface VaultAccountResponse { + id: string; + name: string; + hiddenOnUI?: boolean; + assets?: AssetResponse[]; + customerRefId?: string; + autoFuel?: boolean; +} + +export enum VirtualAffiliation { + OFF_EXCHANGE = "OFF_EXCHANGE", + DEFAULT = "DEFAULT" +} + +export interface BalanceRewardInfo { + pendingRewards: string; +} + +export interface AssetResponse { + id: string; + total: string; + /** + * @deprecated Replaced by "total" + */ + balance?: string; + lockedAmount?: string; + available?: string; + pending?: string; + selfStakedCPU?: string; + selfStakedNetwork?: string; + pendingRefundCPU?: string; + pendingRefundNetwork?: string; + totalStakedCPU?: string; + totalStakedNetwork?: string; + rewardInfo?: BalanceRewardInfo; + blockHeight?: string; + blockHash?: string; + allocatedBalances?: { + allocationId: string; + thirdPartyAccountId?: string; + affiliation?: VirtualAffiliation; + virtualType?: VirtualType; + total: string; + available: string; + pending?: string; + frozen?: string; + locked?: string; + }[]; +} + +export interface UnfreezeTransactionResponse { + success: boolean; +} + +export interface VaultAssetResponse { + id: string; + address: string; + legacyAddress: string; + enterpriseAddress?: string; + tag: string; + eosAccountName?: string; + status?: VaultAssetActivationStatus; + activationTxId?: string; +} + +export enum VaultAssetActivationStatus { + PENDING_ACTIVATION = "PENDING_ACTIVATION", + ACTIVATION_FAILED = "ACTIVATION_FAILED", + READY = "READY" +} + +export interface WalletContainerResponse { + id: string; + name: string; + assets: WalletAssetType[]; + customerRefId?: string; +} + +export interface ExternalWalletAsset { + id: string; + status: string; + address?: string; + tag?: string; + activationTime?: string; +} + +export interface InternalWalletAsset extends ExternalWalletAsset { + balance: string; +} + +export interface CreateTransactionResponse { + id: string; + status: string; + systemMessages?: ISystemMessageInfo[]; +} + +export interface EstimateFeeResponse { + low: EstimatedFee; + medium: EstimatedFee; + high: EstimatedFee; +} + +export interface EstimateTransactionFeeResponse { + low: EstimatedTransactionFee; + medium: EstimatedTransactionFee; + high: EstimatedTransactionFee; +} + +export interface EstimatedFee { + networkFee?: string; + gasPrice?: string; + feePerByte?: string; + baseFee?: string; + priorityFee?: string; +} + +export interface EstimatedTransactionFee { + networkFee?: string; + gasPrice?: string; + gasLimit?: string; + feePerByte?: string; + baseFee?: string; + priorityFee?: string; +} + +export interface TransferPeerPath { + type?: PeerType; + id?: string; + walletId?: string; + virtualId?: string; + virtualType?: VirtualType; + address?: string; +} + +export interface DestinationTransferPeerPath { + type: PeerType; + id?: string; + walletId?: string; + virtualId?: string; + virtualType?: VirtualType; + oneTimeAddress?: IOneTimeAddress; +} + +export interface IOneTimeAddress { + address: string; + tag?: string; +} + +export interface DepositAddressResponse { + assetId?: string; + address: string; + tag?: string; + description?: string; + type?: string; + customerRefId?: string; + addressFormat?: string; + legacyAddress?: string; + enterpriseAddress?: string; +} + +export interface GenerateAddressResponse { + address: string; + tag?: string; + legacyAddress?: string; + enterpriseAddress?: string; +} + +export enum SigningAlgorithm { + MPC_ECDSA_SECP256K1 = "MPC_ECDSA_SECP256K1", + MPC_ECDSA_SECP256R1 = "MPC_ECDSA_SECP256R1", + MPC_EDDSA_ED25519 = "MPC_EDDSA_ED25519" +} + +export interface RawMessageData { + messages: RawMessage[]; + algorithm?: SigningAlgorithm; +} + +export interface RawMessage { + content: string; + bip44addressIndex?: number; + bip44change?: number; + derivationPath?: number[]; +} + +export interface TransactionDestination { + amount: string | number; + destination: DestinationTransferPeerPath; +} + +export interface TransactionArgumentsFeePayerInfo { + feePayerAccountId: string; +} + +export interface TransactionArguments { + assetId?: string; + source?: TransferPeerPath; + destination?: DestinationTransferPeerPath; + amount?: number | string; + operation?: TransactionOperation; + fee?: number | string; + feeLevel?: FeeLevel; + failOnLowFee?: boolean; + maxFee?: string; + priorityFee?: number | string; + gasPrice?: number | string; + gasLimit?: number | string; + note?: string; + cpuStaking?: number; + networkStaking?: number; + autoStaking?: boolean; + customerRefId?: string; + extraParameters?: object; + destinations?: TransactionDestination[]; + replaceTxByHash?: string; + externalTxId?: string; + treatAsGrossAmount?: boolean; + forceSweep?: boolean; + feePayerInfo?: TransactionArgumentsFeePayerInfo; + travelRuleMessage?: TravelRule; +} + +export type OwnershipProof = { + type: string; + proof: string; +}; + +export enum TravelRuleAddressTypeCode { + HOME = "HOME", + BIZZ = "BIZZ", + GEOG = "GEOG" +} + +type TravelRulePersonAddress = { + addressType?: TravelRuleAddressTypeCode; + department?: string; + subDepartment?: string; + streetName?: string; + buildingNumber?: string; + buildingName?: string; + floor?: string; + postBox?: string; + room?: string; + postCode?: string; + townName?: string; + townLocationName?: string; + districtName?: string; + countrySubDivision?: string; + addressLine?: string[]; + country?: string; +}; + +export interface ValidateTravelRuleVaspInfo { + transactionAsset: string; + destination: string; + transactionAmount: string; + originatorVASPdid: string; + originatorEqualsBeneficiary: boolean; + beneficiaryVASPdid?: string; + beneficiaryVASPname?: string; + beneficiaryName?: string; + beneficiaryAccountNumber?: string; + beneficiaryAddress?: TravelRulePersonAddress; + beneficiaryProof?: OwnershipProof; + travelRuleBehavior?: boolean; +} + +export interface ValidateCreateTravelRuleTransaction { + transactionAsset: string; + transactionAmount: string; + originatorDid?: string; + beneficiaryDid?: string; + originatorVASPdid: string; + beneficiaryVASPdid?: string; + beneficiaryVASPname?: string; + transactionBlockchainInfo?: { + origin?: string; + destination?: string; + txHash?: string; + }; + originator?: TROriginator; + beneficiary?: TROriginator; + pii?: PII; + pii_url?: string; + protocol?: string; + notificationEmail?: string; + originatorProof?: OwnershipProof; + beneficiaryProof?: OwnershipProof; + skipBeneficiaryDataValidation?: boolean; +} + +export interface TravelRule { + originatorRef?: string; + beneficiaryRef?: string; + originatorVASPdid: string; + travelRuleBehavior?: boolean; + beneficiaryVASPdid: string; + beneficiaryVASPname?: string; + originator: TROriginator; + beneficiary: TRBeneficiary; + pii?: PII; + jsonDidKey?: string; +} + +export interface TROriginator { + originatorPersons?: TROriginatorPerson[]; + accountNumber?: string[]; +} + +export interface TROriginatorPerson { + naturalPerson?: TRNaturalPerson; + legalPerson?: TRNaturalPerson; +} + +export interface TRNaturalPerson { + name: TRName[]; + geographicAddress?: TRGeographicAddress[]; + nationalIdentification?: TRNationalIdentification; + dateAndPlaceOfBirth?: TRDateAndPlaceOfBirth; +} + +export interface TRName { + nameIdentifier?: TRNameIdentifier[]; +} + +export interface TRNameIdentifier { + primaryIdentifier?: string; + secondaryIdentifier?: string; +} + +export interface TRGeographicAddress { + streetName?: string; + townName?: string; + country?: string; + buildingNumber?: string; + postCode?: string; + addressType?: string; + department?: string; + subDepartment?: string; + buildingName?: string; + floor?: string; + postBox?: string; + room?: string; + townLocationName?: string; + districtName?: string; + countrySubDivision?: string; + addressLine?: string; +} + +export interface TRNationalIdentification { + nationalIdentifier?: string; + nationalIdentifierType?: string; + registrationAuthority?: string; + countryOfIssue?: string; +} + +export interface TRDateAndPlaceOfBirth { + dateOfBirth?: string; + placeOfBirth?: string; +} + +export interface TRBeneficiary { + beneficiaryPersons?: TRBeneficiaryPerson[]; + originatorPersons?: TROriginatorPerson[]; + accountNumber?: string[]; +} + +export interface TRBeneficiaryPerson { + naturalPerson?: TRNaturalPerson; +} + +interface PII { + originator?: TROriginator; + beneficiary?: TRBeneficiary; +} + +export interface TravelRuleOptions { + clientId: string; + clientSecret: string; + authURL?: string; + audience?: string; + audiencePII?: string; + baseURL?: string; + baseURLPII?: string; + jsonDidKey?: string; +} + +export interface TravelRuleEncryptionOptions { + beneficiaryPIIDidKey?: string; + sendToProvider?: boolean; +} + +export interface TravelRuleVasp { + did: string; + name: string; + verificationStatus: string; + addressLine1: string; + addressLine2: string; + city: string; + country: string; + emailDomains: string; + website: string; + logo: string; + legalStructure: string; + legalName: string; + yearFounded: string; + incorporationCountry: string; + isRegulated: string; + otherNames: string; + identificationType: string; + identificationCountry: string; + businessNumber: string; + regulatoryAuthorities: string; + jurisdictions: string; + street: string; + number: string; + unit: string; + postCode: string; + state: string; + certificates: string; + description: string; + travelRule_OPENVASP: string; + travelRule_SYGNA: string; + travelRule_TRISA: string; + travelRule_TRLIGHT: string; + travelRule_EMAIL: string; + travelRule_TRP: string; + travelRule_SHYFT: string; + travelRule_USTRAVELRULEWG: string; + createdAt: string; + createdBy: string; + updatedAt: string; + updatedBy: string; + lastSentDate: string; + lastReceivedDate: string; + documents: string; + hasAdmin: boolean; + isNotifiable: boolean; + issuers: { + name: { + issuerDid: string; + }; + nonce: { + issuerDid: string; + }; + }; + regulatoryStatus: string; + supervisoryAuthority: string; + registrationLicenseId: string; + statusStartDate: string; + statusExpirationDate: string; + lastChecked: string; + additionalInformation: string; + subsidiaryOf: string; + chainalysis_clusterName: string; + pii_didkey: string; + onboardingStatus: string; + compliancePhase: number; + vaspnetId: string; + node: string; + node_didkey: string; + parentGateway: string; + isActiveSender: boolean; + isActiveReceiver: boolean; + subsidiaries: string[]; +} + +export interface ValidateFullTravelRuleResult { + isValid: boolean; + type: string; + beneficiaryAddressType: string; + addressSource: string; + beneficiaryVASPname: string; + beneficiaryVASPdid: string; + errors: string[]; + warnings: string[]; +} + +export interface ValidateTravelRuleResult { + isValid: boolean; + type: string; + beneficiaryAddressType: string; + addressSource: string; + beneficiaryVASPdid: string; + warnings: string[]; +} + +export interface TravelRuleVaspFilter { + q?: string; + fields?: string[]; + page?: number; + per_page?: number; + order?: string; +} + +export enum Web3ConnectionFeeLevel { + HIGH = "HIGH", + MEDIUM = "MEDIUM", +} + +export enum FeeLevel { + HIGH = "HIGH", + MEDIUM = "MEDIUM", + LOW = "LOW" +} + +export interface ExchangeResponse { + id: string; + type: string; + name: string; + assets: AssetResponse[]; + isSubaccount: boolean; + status: string; +} + +export interface ConvertExchangeAssetResponse { + status: boolean; +} + +export interface FiatAccountResponse { + id: string; + type: string; + name: string; + address?: string; + assets: AssetResponse[]; +} + +export interface TransactionPageResponse { + transactions: TransactionResponse[]; + pageDetails: PageDetails; +} + +export interface PageDetails { + prevPage: string; + nextPage: string; +} + +export interface RewardInfo { + srcRewards?: string; + destRewards?: string; +} + +export interface FeePayerInfo { + feePayerAccountId?: string; +} + +export interface TransactionResponse { + id: string; + assetId: string; + source: TransferPeerPathResponse; + destination: TransferPeerPathResponse; + amount: number; + /** + * @deprecated Replaced by "networkFee" + */ + fee?: number; + networkFee: number; + amountUSD: number; + netAmount: number; + createdAt: number; + lastUpdated: number; + status: TransactionStatus; + txHash: string; + numOfConfirmations?: number; + subStatus?: string; + signedBy: string[]; + createdBy: string; + rejectedBy: string; + destinationAddress: string; + sourceAddress?: string; + destinationAddressDescription?: string; + destinationTag: string; + addressType: string; + note: string; + exchangeTxId: string; + requestedAmount: number; + serviceFee?: number; + feeCurrency: string; + amlScreeningResult?: AmlScreeningResult; + customerRefId?: string; + amountInfo?: AmountInfo; + feeInfo?: FeeInfo; + signedMessages?: SignedMessageResponse[]; + extraParameters?: any; + externalTxId?: string; + destinations?: TransactionResponseDestination[]; + blockInfo?: BlockInfo; + authorizationInfo?: AuthorizationInfo; + index?: number; + rewardInfo?: RewardInfo; + feePayerInfo?: FeePayerInfo; +} + +export interface AmountInfo { + amount?: string; + requestedAmount?: string; + netAmount?: string; + amountUSD?: string; +} + +export interface FeeInfo { + networkFee?: string; + serviceFee?: string; + gasPrice?: string; +} + +export interface TransactionResponseDestination { + amount?: string; + amountUSD?: string; + amlScreeningResult?: AmlScreeningResult; + destination?: TransferPeerPathResponse; + authorizationInfo?: AuthorizationInfo; +} + +export interface AmlScreeningResult { + provider?: string; + payload: any; + screeningStatus: string; + bypassReason: string; + timestamp: number; +} + +export interface TransferPeerPathResponse { + id: string; + type: PeerType; + name?: string; + subType?: string; + virtualType?: VirtualType; + virtualId?: string; + walletId?: string; +} + +export interface AuthorizationInfo { + allowOperatorAsAuthorizer: boolean; + logic: "OR" | "AND"; + groups: { + users: UserGroup; + th: number + }[]; +} + +export interface UserGroup { + [id: string]: string; +} + +export interface BlockInfo { + blockHeight?: string; + blockHash?: string; +} + +export interface SignedMessageResponse { + content: string; + algorithm: string; + derivationPath: number[]; + signature: { + fullSig: string; + r?: string; + s?: string; + v?: number; + }; + publicKey: string; +} + +export interface CancelTransactionResponse { + success: boolean; +} + +export interface OperationSuccessResponse { + success: boolean; +} + +export interface NetworkConnectionResponse { + id: string; + status: string; + remoteNetworkId: NetworkId; + localNetworkId: NetworkId; + routingPolicy?: NetworkConnectionRoutingPolicy; +} + +export interface NetworkIdResponse { + id: string; + name: string; + isDiscoverable: boolean; + routingPolicy?: NetworkIdRoutingPolicy; +} + +interface NetworkId { + id: string; + name: string; +} + +export interface CustomCryptoRoutingDest { + scheme: NetworkScheme.CUSTOM; + dstType: NetworkDestType.EXCHANGE_ACCOUNT | NetworkDestType.VAULT_ACCOUNT; + dstId: string; +} + +export interface CustomFiatRoutingDest { + scheme: NetworkScheme.CUSTOM; + dstType: NetworkDestType.FIAT_ACCOUNT; + dstId: string; +} + +export interface DefaultNetworkRoutingDest { + scheme: NetworkScheme.DEFAULT; +} + +export interface NoneNetworkRoutingDest { + scheme: NetworkScheme.NONE; +} + +export type NetworkConnectionCryptoRoutingDest = CustomCryptoRoutingDest | DefaultNetworkRoutingDest | NoneNetworkRoutingDest; +export type NetworkConnectionFiatRoutingDest = CustomFiatRoutingDest | DefaultNetworkRoutingDest | NoneNetworkRoutingDest; +export type NetworkIdCryptoRoutingDest = CustomCryptoRoutingDest | NoneNetworkRoutingDest; +export type NetworkIdFiatRoutingDest = CustomFiatRoutingDest | NoneNetworkRoutingDest; + +export interface NetworkConnectionRoutingPolicy { + crypto?: NetworkConnectionCryptoRoutingDest; + sen?: NetworkConnectionFiatRoutingDest; + signet?: NetworkConnectionFiatRoutingDest; + sen_test?: NetworkConnectionFiatRoutingDest; + signet_test?: NetworkConnectionFiatRoutingDest; +} + +export interface NetworkIdRoutingPolicy { + crypto?: NetworkIdCryptoRoutingDest; + sen?: NetworkIdFiatRoutingDest; + signet?: NetworkIdFiatRoutingDest; + sen_test?: NetworkIdFiatRoutingDest; + signet_test?: NetworkIdFiatRoutingDest; +} + +export enum NetworkScheme { + DEFAULT = "DEFAULT", + CUSTOM = "CUSTOM", + NONE = "NONE", +} + +export enum NetworkDestType { + VAULT_ACCOUNT = "VAULT", + EXCHANGE_ACCOUNT = "EXCHANGE", + FIAT_ACCOUNT = "FIAT_ACCOUNT", +} + +export interface TransactionFilter { + before?: number; + after?: number; + status?: TransactionStatus; + orderBy?: TransactionOrder; + limit?: number; + txHash?: string; + assets?: string; + sourceType?: PeerType; + destType?: PeerType; + sourceId?: string; + destId?: string; +} + +export interface NFTOwnershipFilter { + blockchainDescriptor?: string; + vaultAccountIds?: string[]; + collectionIds?: string[]; + ids?: string[]; + pageCursor?: string; + pageSize?: number; + sort?: GetOwnedNFTsSortValues[]; + order?: OrderValues; + status?: NFTOwnershipStatus; + search?: string; + ncwId?: string; + ncwAccountIds?: string[]; + walletType?: NFTOwnershipWalletType; +} + +export interface NFTOwnedCollectionsFilter { + search?: string; + status?: NFTOwnershipStatus; + ncwId?: string; + walletType?: NFTOwnershipWalletType; + pageCursor?: string; + pageSize?: number; + sort?: GetOwnedCollectionsSortValues[]; + order?: OrderValues; +} + +export interface NFTOwnedAssetsFilter { + search?: string; + status?: NFTOwnershipStatus; + ncwId?: string; + walletType?: NFTOwnershipWalletType; + pageCursor?: string; + pageSize?: number; + sort?: GetOwnedAssetsSortValues[]; + order?: OrderValues; +} + +export interface GetNFTsFilter { + ids: string[]; + pageCursor?: string; + pageSize?: number; + sort?: GetNFTsSortValues[]; + order?: OrderValues; +} + +class MediaEntity { + url: string; + contentType: string; +} + +interface NFTCollection { + id: string; + name: string; + symbol: string; +} + +export interface Paging { + next: string; +} + +export interface Token { + id: string; + tokenId: string; + standard: string; + blockchainDescriptor: string; + description: string; + name: string; + media: MediaEntity[]; + metadataURI?: string; + cachedMetadataURI?: string; + collection?: NFTCollection; +} + +export interface BaseTokenWithBalance extends Token { + balance: string; + ownershipStartTime: number; + ownershipLastUpdateTime: number; +} + +export type TokenWithBalance = (WorkspaceWalletIdentifier | NonCustodialWalletIdentifier) & BaseTokenWithBalance; + +export interface CollectionOwnership extends NFTCollection { + standard?: string; + blockchainDescriptor: string; + contractAddress?: string; +} + +export interface TransactionPageFilter { + before?: number; + after?: number; + status?: TransactionStatus; + limit?: number; + txHash?: string; + assets?: string; + sourceType?: PeerType; + destType?: PeerType; + sourceId?: string; + destId?: string; +} + +export enum TransactionOrder { + CREATED_AT = "createdAt", + LAST_UPDATED = "lastUpdated" +} + +export enum TransactionStatus { + SUBMITTED = "SUBMITTED", + QUEUED = "QUEUED", + PENDING_SIGNATURE = "PENDING_SIGNATURE", + PENDING_AUTHORIZATION = "PENDING_AUTHORIZATION", + PENDING_3RD_PARTY_MANUAL_APPROVAL = "PENDING_3RD_PARTY_MANUAL_APPROVAL", + PENDING_3RD_PARTY = "PENDING_3RD_PARTY", + /** + * @deprecated + */ + PENDING = "PENDING", + BROADCASTING = "BROADCASTING", + CONFIRMING = "CONFIRMING", + /** + * @deprecated Replaced by "COMPLETED" + */ + CONFIRMED = "CONFIRMED", + COMPLETED = "COMPLETED", + PENDING_AML_SCREENING = "PENDING_AML_SCREENING", + PARTIALLY_COMPLETED = "PARTIALLY_COMPLETED", + CANCELLING = "CANCELLING", + CANCELLED = "CANCELLED", + REJECTED = "REJECTED", + FAILED = "FAILED", + TIMEOUT = "TIMEOUT", + BLOCKED = "BLOCKED" +} + +export enum PeerType { + VAULT_ACCOUNT = "VAULT_ACCOUNT", + EXCHANGE_ACCOUNT = "EXCHANGE_ACCOUNT", + INTERNAL_WALLET = "INTERNAL_WALLET", + EXTERNAL_WALLET = "EXTERNAL_WALLET", + UNKNOWN = "UNKNOWN", + NETWORK_CONNECTION = "NETWORK_CONNECTION", + FIAT_ACCOUNT = "FIAT_ACCOUNT", + COMPOUND = "COMPOUND", + ONE_TIME_ADDRESS = "ONE_TIME_ADDRESS", + OEC_PARTNER = "OEC_PARTNER", + END_USER_WALLET = "END_USER_WALLET", +} + +export enum VirtualType { + OFF_EXCHANGE = "OFF_EXCHANGE", + DEFAULT = "DEFAULT", + OEC_FEE_BANK = "OEC_FEE_BANK" +} + +export enum TransactionOperation { + TRANSFER = "TRANSFER", + MINT = "MINT", + BURN = "BURN", + SUPPLY_TO_COMPOUND = "SUPPLY_TO_COMPOUND", + REDEEM_FROM_COMPOUND = "REDEEM_FROM_COMPOUND", + RAW = "RAW", + CONTRACT_CALL = "CONTRACT_CALL", + TYPED_MESSAGE = "TYPED_MESSAGE", +} + +export enum Web3ConnectionType { + WALLET_CONNECT = "WalletConnect" +} + +export enum Web3ConnectionMethod { + MOBILE = "MOBILE", + DESKTOP = "DESKTOP", + API = "API" +} + +export interface AllocateFundsRequest { + allocationId: string; + amount: string; + treatAsGrossAmount?: boolean; +} + +export interface DeallocateFundsRequest { + allocationId: string; + amount: string; +} + +export interface AllocateFundsResponse { + id: string; + status: string; +} + +export interface CreateTransferTicketArgs { + externalTicketId: string; + description?: string; + terms: { + networkConnectionId: string; + outgoing: boolean; + asset: string; + amount: string; + note: string; + }[]; +} + +export enum TransferTicketStatus { + OPEN = "OPEN", + PARTIALLY_FULFILLED = "PARTIALLY_FULFILLED", + FULFILLED = "FULFILLED", + FAILED = "FAILED", + CANCELED = "CANCELED" +} + +export enum TransferTicketTermStatus { + OPEN = "OPEN", + FULFILLED = "FULFILLED" +} + +export interface TransferTicketResponse { + ticketId: string; + externalTicketId: string; + description: string; + status: TransferTicketStatus; + terms: TermResponse[]; +} + +export interface TermResponse { + termId: string; + networkConnectionId: string; + outgoing: boolean; + asset: string; + amount: string; + txIds: string[]; + status: TransferTicketTermStatus; + note: string; +} + +export interface ExecuteTermArgs { + source: { + type: string; + id: string; + }; + fee?: number; + gasPrice?: number; +} + +export interface CreateTransferTicketResponse { + ticketId: string; +} + +export interface PublicKeyInfoArgs { + algorithm?: string; + derivationPath?: number[]; + compressed?: boolean; +} + +export interface PublicKeyInfoForVaultAccountArgs { + assetId: string; + vaultAccountId: number; + change: number; + addressIndex: number; + compressed?: boolean; +} + +export interface GasStationInfo { + balance: { [asset: string]: string }; + configuration: { + gasThreshold: string; + gasCap: string; + maxGasPrice: string; + }; +} + +export interface PublicKeyResponse { + status: number; + algorithm: string; + derivationPath: number[]; + publicKey: string; +} + +export interface PublicKeyInformation { + algorithm: string; + derivationPath: number[]; + publicKey: String; +} + +export interface DropTransactionResponse { + success: boolean; + transactions?: string[]; +} + +export interface MaxSpendableAmountResponse { + maxSpendableAmount: string; +} + +export interface MaxBip44IndexUsedResponse { + maxBip44AddressIndexUsed?: number; + maxBip44ChangeAddressIndexUsed?: number; +} + +export interface VaultAccountsFilter { + namePrefix?: string; + nameSuffix?: string; + minAmountThreshold?: number; + assetId?: string; +} + +export interface PagedVaultAccountsRequestFilters { + namePrefix?: string; + nameSuffix?: string; + minAmountThreshold?: number; + assetId?: string; + orderBy?: "ASC" | "DESC"; + limit?: number; // for default and max limit values please see: https://docs.fireblocks.com/api/swagger-ui/#/ + before?: string; + after?: string; +} + +export interface PagedVaultAccountsResponse { + accounts: VaultAccountResponse[]; + paging?: { + before?: string; + after?: string; + }; + previousUrl?: string; + nextUrl?: string; +} + +export interface VaultBalancesFilter { + accountNamePrefix?: string; + accountNameSuffix?: string; +} + +export interface RequestOptions { + idempotencyKey?: string; + ncw?: { + walletId?: string; + }; +} + +export interface ValidateAddressResponse { + isValid: boolean; + isActive: boolean; + requiresTag: boolean; +} + +export interface AssetTypeResponse { + id: string; + name: string; + type: string; + contractAddress: string; + nativeAsset: string; + decimals?: number; +} + +export interface User { + id: string; + firstName: string; + lastName: string; + email: string; + enabled: boolean; + role: string; +} + +export interface UsersGroup { + id: string; + name: string; + membersIds: string[]; + status: string; +} + +export interface ResendWebhooksResponse { + webhooksCount: number; +} + +export interface OffExchangeEntityResponse { + id: string; + vaultAccountId: string; + thirdPartyAccountId: string; + balance?: { + [assetId: string]: { + total?: string; + locked?: string; + pending?: string; + frozen?: string; + }; + }; +} + +export interface SettleOffExchangeAccountResponse { + message: string; + code: SettleResponseCode; +} + +export enum SettleResponseCode { + NONE = 0, + NOTHING_TO_SETTLE = 1 +} + +export interface GetSettlementTransactionsResponse { + toExchange: ToExchangeTransaction[]; + toCollateral: ToCollateralTransaction[]; +} + +export interface ToExchangeTransaction { + assetId: string; + amount: string; + dstAddress: string; + dstTag: string; +} + +export interface ToCollateralTransaction { + assetId: string; + amount: string; + fee?: string; + srcAddress?: string; + srcTag?: string; +} + +export interface AddCollateralTransactionRequest { + transactionRequest: TransactionArguments; + isSrcCollateral?: boolean; +} + +export interface RemoveCollateralTransactionRequest { + transactionRequest: TransactionArguments; + isDstCollateral?: boolean; +} + +export interface SettlementRequest { + mainExchangeAccountId: string; +} + +enum InitiatorType { + EXCHANGE = "EXCHANGE", + TRADER = "TRADER" +} + +export interface InitiatedTransactions { + toExchange: SettlementTransactionResponse[]; + toCollateral: SettlementTransactionResponse[]; +} + +export interface SettlementTransactionResponse { + txId: string; + status: TransactionStatus; +} + +export enum ExchangeReply { + REJECTED = "REJECTED", + NOT_NEEDED = "NOT_NEEDED", + FAILED = "FAILED" +} + +export interface SettlementResponse { + id: string; + initiator: InitiatorType; + exchangeReply?: ExchangeReply; + fireblocksInitiatedTransactions?: InitiatedTransactions; + exchangeRequestedTransactions?: GetSettlementTransactionsResponse; +} + +export interface SetFeePayerConfiguration { + feePayerAccountId: string; +} + +export interface FeePayerConfiguration { + feePayerAccountId: string; +} + +export interface BaseWeb3ConnectionPayload { + feeLevel: Web3ConnectionFeeLevel; +} +export interface WorkspaceWalletIdentifier { + vaultAccountId: number; +} + +export interface NonCustodialWalletIdentifier { + ncwId: string; + ncwAccountId: number; +} + +export interface WalletConnectConnectionPayload { + uri: string; + chainIds?: string[]; +} + +export type CreateWeb3ConnectionPayload = (WorkspaceWalletIdentifier | NonCustodialWalletIdentifier) & BaseWeb3ConnectionPayload; + +export type CreateWalletConnectPayload = CreateWeb3ConnectionPayload & WalletConnectConnectionPayload; + +export interface GetWeb3ConnectionsPayload { + pageCursor?: string; + pageSize?: number; + sort?: string; + filter?: { [filterProp: string]: string }; + order?: "ASC" | "DESC"; +} + +export interface CreateWeb3ConnectionResponse { + id: string; + sessionMetadata: SessionMetadata; +} + +export interface SessionMetadata { + appUrl: string; + appIcon?: string; + appName?: string; + appDescription?: string; +} + +export interface Session { + id: string; + vaultAccountId?: number; + ncwId?: string; + ncwAccountId?: number; + chainIds: string[]; + feeLevel: Web3ConnectionFeeLevel; + creationDate: string; + connectionType: Web3ConnectionType; + connectionMethod: Web3ConnectionMethod; + sessionMetadata: SessionMetadata; +} + +export enum TimePeriod { + DAY = "DAY", + WEEK = "WEEK" +} + +export interface Audit { + data?: any; + vendorId?: string; + tenantId?: string; + severity?: string; + createdAt?: string; + subject?: string; + event?: string; + user?: string; + email?: string; + txId?: string; + amount?: string; + transactionId?: string; + walletType?: string; + walletName?: string; + confirmationThreshold?: string; + sourceType?: string; + sourceName?: string; + sourceId?: string; + destination?: string; + destAddress?: string; + newNote?: string; + remoteType?: string; + destName?: string; + remoteId?: string; + note?: string; + signedBy?: string; + approvedBy?: string; + setBy?: string; + cancelType?: string; + fee?: string; + rule?: string; + screeningStatus?: string; + verdict?: string; + bypassReason?: string; + status?: string; + subStatus?: string; + ruleJsonStr?: string; + rejectedReason?: string; + failReason?: string; + oldRole?: string; + role?: string; + subjectUser?: string; + ip?: string; + accountName?: string; + tag?: string; + address?: string; + accountType?: string; + counterpartyName?: string; + initiatedBy?: string; + asset?: string; + newIpAddress?: string; + approverList?: string; + removedUserName?: string; + removedUserEmail?: string; + action?: string; + description?: string; + userAgent?: string; + authorizationInfo?: string; + reEnrolledUser?: string; + oldThreshold?: string; + newThreshold?: string; + oldAmount?: string; + newAmount?: string; + draftPolicyJson?: string; +} + +export interface AuditsResponse { + data: Audit[]; + total: number; +} + +export interface ISystemMessageInfo { + type: string; + message: string; +} + +export enum GetNFTsSortValues { + "collectionName" = "collection.name", + "name" = "name", + "blockchainDescriptor" = "blockchainDescriptor", +} + +export enum GetOwnedNFTsSortValues { + "ownershipLastUpdateTime" = "ownershipLastUpdateTime", + "name" = "name", + "collectionName" = "collection.name", + "blockchainDescriptor" = "blockchainDescriptor", +} + +export enum GetOwnedCollectionsSortValues { + "name" = "name", +} + +export enum GetOwnedAssetsSortValues { + "name" = "name", +} + +export enum OrderValues { + "ASC" = "ASC", + "DESC" = "DESC", +} + +export enum NFTOwnershipStatus { + "LISTED" = "LISTED", + "ARCHIVED" = "ARCHIVED", +} + +export enum NFTOwnershipWalletType { + "VAULT_ACCOUNT" = "VAULT_ACCOUNT", + "END_USER_WALLET" = "END_USER_WALLET", +} + +export interface ContractUploadRequest { + name: string; + description: string; + longDescription: string; + bytecode: string; + sourcecode: string; + compilerOutputMetadata?: object; + docs?: ContractDoc; + abi?: AbiFunction[]; + attributes?: Record; + vendorId?: string; +} +interface AbiFunction { + name?: string; + stateMutability?: string; + type: "function" | "constructor" | string; + inputs: Parameter[]; + outputs?: Parameter[]; + description?: string; + returns?: Record; +} + +interface Parameter { + name: string; + description?: string; + internalType: string; + type: string; + components?: Parameter[]; +} +interface ContractDoc { + details?: string; + events?: string; + kind: "dev" | "user" | string; + methods: Record; + version: string | number; +} + +interface FunctionDoc { + details?: string; + params?: Record; + returns?: Record; +} +interface VendorDto { + id: string; + name: string; + attributes: Record; +} + +export interface ContractTemplateDto { + isPublic: boolean; + vendor?: VendorDto; + id: string; + name: string; + description: string; + bytecode: string; + sourcecode?: string; + owner?: string; + compilerOutputMetadata?: object; + abi: AbiFunction[]; + docs?: ContractDoc; + attributes?: Record; +} +export enum TokenLinkPermission { + MINT = "MINT", + BURN = "BURN", +} + +export interface TokenLinkPermissionEntry { + permission: TokenLinkPermission; + vaultAccountId: string; +} + +export interface LinkedTokenMetadata { + assetId: string; + name?: string; + totalSupply?: string; + holdersCount?: number; + type?: string; + contractAddress?: string; + issuerAddress?: string; + testnet?: boolean; + blockchain?: string; +} +export interface TokenLink { + id: string; + assetId: string; + assetMetadata?: LinkedTokenMetadata; + permissions: TokenLinkPermissionEntry[]; +} +export interface PendingTokenLinkDto { + id: number; + txId?: string; + name?: string; + symbol?: string; + vaultAccountId?: string; + blockchainId?: string; +} + + +export interface IssueTokenRequest { + symbol: string; + name: string; + blockchainId: string; + vaultAccountId: string; + createParams: CreateTokenParams; +} + +export interface JobCreatedResponse { + jobId: string; +} + +export enum Status { + NONE = "NONE", + CREATED = "CREATED", + INPROGRESS = "INPROGRESS", + DONE = "DONE", + ERROR = "ERROR", + CANCELED = "CANCELED", + PAUSED = "PAUSED" +} + +export class Job { + id: string; + tenantId: string; + type: string; + userId: string; + created: number; + updated?: number; + state: Status; + data: string; +} + +export class Task { + id: string; + jobId: string; + type: string; + tenantId: string; + created: number; + updated?: number; + state: Status; + data?: string; + result?: string; +} + +type CreateTokenParams = EVMTokenCreateParamsDto | StellarRippleCreateParamsDto; +interface StellarRippleCreateParamsDto { + issuerAddress?: string; +} + +interface ParameterWithValue { + internalType: string; + name: string; + type: string; + description?: string; + value: any; +} + +interface EVMTokenCreateParamsDto { + contractId: string; + constructorParams?: Array; +} + +export enum SmartTransfersTicketDirection { + EXCHANGE = "EXCHANGE", + SEND = "SEND", + RECEIVE = "RECEIVE", + INTERMEDIATE = "INTERMEDIATE", +} + +export enum SmartTransfersTicketStatus { + DRAFT = "DRAFT", + PENDING_APPROVAL = "PENDING_APPROVAL", + OPEN = "OPEN", + IN_SETTLEMENT = "IN_SETTLEMENT", + FULFILLED = "FULFILLED", + EXPIRED = "EXPIRED", + CANCELED = "CANCELED", +} + +export enum SmartTransferTicketTermStatus { + CREATED = "CREATED", + FUNDING = "FUNDING", + FUNDING_FAILED = "FUNDING_FAILED", + FUNDED = "FUNDED", + REJECTED = "REJECTED", +} + +export interface SmartTransfersTicketTermPayload { + asset: string; + amount: string; + fromNetworkId: string; + toNetworkId: string; +} +export interface SmartTransfersTicketCreatePayload { + createdByNetworkId: string; + type: string; + expiresIn?: number; + terms?: SmartTransfersTicketTermPayload[]; + externalRefId?: string; + note?: string; + submit?: boolean; +} + +export interface SmartTransfersTicketTerm { + id: string; + asset: string; + amount: string; + fromNetworkId: string; + fromNetworkIdName?: string; + toNetworkId: string; + toNetworkIdName?: string; + txHash?: string; + fbTxId?: string; + transactionStatus: TransactionStatus; + status: SmartTransferTicketTermStatus; + createdAt: Date; + updatedAt: Date; +} + +export interface SmartTransfersTicket { + id: string; + type: string; + direction?: SmartTransfersTicketDirection; + canceledByMe?: boolean; + createdByMe?: boolean; + status: SmartTransfersTicketStatus; + terms: SmartTransfersTicketTerm[]; + expiresIn?: number; + expiresAt?: Date; + submittedAt?: Date; + createdAt: Date; + updatedAt: Date; + externalRefId?: string; + note?: string; + createdByNetworkId: string; + createdByNetworkIdName: string; +} + +export interface SmartTransfersTicketTermResponse { + data: SmartTransfersTicketTerm; +} + +export interface SmartTransfersTicketResponse { + data: SmartTransfersTicket; +} + +export interface SmartTransfersTicketsResponse { + message?: string; + after?: string; + data: SmartTransfersTicket[]; +} + +export interface SmartTransfersTicketsFilters { + q?: string; + statuses?: SmartTransfersTicketStatus[]; + networkId?: string; + externalRefId?: string; + after?: string; + limit?: number; + createdByMe?: boolean; + expiresAfter?: Date; + expiresBefore?: Date; + type?: string; +} + +export interface SmartTransfersUserGroupsResponse { + data: SmartTransfersUserGroups; +} + +export interface SmartTransfersUserGroups { + userGroupIds: string[]; +} + +export interface SmartTransfersTicketTermFundPayload { + asset: string; + amount: string; + networkConnectionId: string; + srcId: string; + srcType: string; + fee?: string; + feeLevel?: FeeLevel; +} + +export namespace NCW { + export const WalletIdHeader = "X-End-User-Wallet-Id"; + + export interface WalletInfo { + walletId: string; + enabled: boolean; + } + + export interface GetWalletsPayload { + pageCursor?: string; + pageSize?: number; + sort?: string; + order?: "ASC" | "DESC"; + } + + export interface GetWalletAccountsPayload { + pageCursor?: string; + pageSize?: number; + sort?: string; + order?: "ASC" | "DESC"; + } + + export interface GetWalletAssetsPayload { + pageCursor?: string; + pageSize?: number; + sort?: string; + order?: "ASC" | "DESC"; + } + + export interface GetWalletAddressesPayload { + pageCursor?: string; + pageSize?: number; + sort?: string; + order?: "ASC" | "DESC"; + } + + export interface WalletAssetResponse { + id: string; + symbol: string; + name: string; + decimals: number; + networkProtocol: string; + testnet: boolean; + hasFee: boolean; + type: string; + baseAsset: string; + ethNetwork?: number; + ethContractAddress?: string; + issuerAddress?: string; + blockchainSymbol?: string; + deprecated?: boolean; + coinType: number; + blockchain: string; + blockchainDisplayName?: string; + blockchainId?: string; + } + export interface WalletAssetAddress { + accountName: string; + accountId: string; + asset: string; + address: string; + addressType: string; + addressDescription?: string; + tag?: string; + addressIndex?: number; + legacyAddress?: string; + } + + export interface Device { + deviceId: string; + enabled: boolean; + } +} diff --git a/src/fireblocks-sdk.ts b/src/fireblocks-sdk.ts index 716d6f97..64a38a56 100644 --- a/src/fireblocks-sdk.ts +++ b/src/fireblocks-sdk.ts @@ -98,6 +98,7 @@ import { ContractUploadRequest, ContractTemplateDto, PendingTokenLinkDto, Web3ConnectionFeeLevel, + Task, Job, JobCreatedResponse } from "./types"; import { AxiosProxyConfig, AxiosResponse } from "axios"; import { PIIEncryption } from "./pii-client"; @@ -660,6 +661,19 @@ export class FireblocksSDK { return await this.apiClient.issuePostRequest("/v1/vault/accounts", body, requestOptions); } + /** + * Creates a new vault account + * @param count Number of new vault accounts requested + * @param requestOptions + */ + public async createVaultAccountBulk(count: number, requestOptions?: RequestOptions): Promise { + const body = { + count + }; + + return await this.apiClient.issuePostRequest("/v1/vault/accounts/bulk", body, requestOptions); + } + /** * Hides a vault account in Fireblocks console * @param vaultAccountId The vault account ID @@ -711,6 +725,20 @@ export class FireblocksSDK { return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}`, {}, requestOptions); } + /** + * Creates a new asset within a list of existing vault accounts + * @param assetId The asset to add + * @param vaultAccountIdFrom The first of the account ID range + * @param vaultAccountIdTo The last of the account ID range + * @param requestOptions + */ + public async createVaultAssetBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string, requestOptions?: RequestOptions): Promise { + const body = { + assetId, vaultAccountIdFrom, vaultAccountIdTo + }; + return await this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body, requestOptions); + } + /** * Retry to create a vault asset for a vault asset that failed * @param vaultAccountId The vault account ID @@ -1820,4 +1848,78 @@ export class FireblocksSDK { private getCommaSeparatedList(items: Array): string | undefined { return items ? items.join(",") : undefined; } + + /** + * Get list of jobs for current tenant + * @param fromTime beggining of time range in MS since 1970 + * @param toTime ending of time range in MS since 1970 + */ + public getJobs(fromTime: number, toTime: number): Promise { + return this.apiClient.issueGetRequest(`/v1/batch/jobs?fromTime=${fromTime}&toTime=${toTime}`); + } + + /** + * Get job info by job ID + * @param jobId + */ + public getJob(jobId: string): Promise { + return this.apiClient.issueGetRequest(`/v1/batch/${jobId}`); + } + + /** + * Get tasks belonging to given job + * @param jobId + */ + public getTasks(jobId: string): Promise { + return this.apiClient.issueGetRequest(`/v1/batch/${jobId}/tasks`); + } + + /** + * Cancel a job by ID + * @param jobId + */ + public cancelJob(jobId: string): Promise { + return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/cancel`, {}); + } + + /** + * Pause a job by ID + * @param jobId + */ + public pauseJob(jobId: string): Promise { + return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/pause`, {}); + } + + /** + * Continue a job by ID + * @param jobId + */ + public continueJob(jobId: string): Promise { + return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/continue`, {}); + } + + /** + * Create multiple vault accounts in one bulk operation + * @param count number of vault accounts + */ + public createVaultAccountsBulk(count: number, assetId: string): Promise { + const body = { + count, + assetId + }; + return this.apiClient.issuePostRequest(`/v1/vault/accounts/bulk`, body); + } + + /** + * Create multiple vault wallets in one bulk operation + * @param count number of vault accounts + */ + public createVaultWalletsBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string): Promise { + const body = { + assetId, + vaultAccountIdFrom, + vaultAccountIdTo + }; + return this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body); + } } diff --git a/src/types.ts b/src/types.ts index 267259d3..829b91a8 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1511,6 +1511,44 @@ export interface IssueTokenRequest { vaultAccountId: string; createParams: CreateTokenParams; } + +export interface JobCreatedResponse { + jobId: string; +} + +export enum Status { + NONE = "NONE", + CREATED = "CREATED", + INPROGRESS = "INPROGRESS", + DONE = "DONE", + ERROR = "ERROR", + CANCELED = "CANCELED", + PAUSED = "PAUSED" +} + +export class Job { + id: string; + tenantId: string; + type: string; + userId: string; + created: number; + updated?: number; + state: Status; + data: string; +} + +export class Task { + id: string; + jobId: string; + type: string; + tenantId: string; + created: number; + updated?: number; + state: Status; + data?: string; + result?: string; +} + type CreateTokenParams = EVMTokenCreateParamsDto | StellarRippleCreateParamsDto; interface StellarRippleCreateParamsDto { issuerAddress?: string; From 0b55439291310f17a430cb1bc85d4bf40a3a6380 Mon Sep 17 00:00:00 2001 From: gguy Date: Mon, 11 Sep 2023 12:09:27 +0300 Subject: [PATCH 2/6] removed redundant files --- src mine/api-client.ts | 101 -- src mine/api-token-provider.ts | 26 - src mine/fireblocks-sdk.ts | 1925 -------------------------------- src mine/iauth-provider.ts | 5 - src mine/ncw-api-client.ts | 135 --- src mine/ncw-sdk.ts | 155 --- src mine/pii-client.ts | 83 -- src mine/types.ts | 1763 ----------------------------- 8 files changed, 4193 deletions(-) delete mode 100644 src mine/api-client.ts delete mode 100644 src mine/api-token-provider.ts delete mode 100644 src mine/fireblocks-sdk.ts delete mode 100644 src mine/iauth-provider.ts delete mode 100644 src mine/ncw-api-client.ts delete mode 100644 src mine/ncw-sdk.ts delete mode 100644 src mine/pii-client.ts delete mode 100644 src mine/types.ts diff --git a/src mine/api-client.ts b/src mine/api-client.ts deleted file mode 100644 index cfd8915d..00000000 --- a/src mine/api-client.ts +++ /dev/null @@ -1,101 +0,0 @@ -import os from "os"; -import platform from "platform"; -import { IAuthProvider } from "./iauth-provider"; -import { RequestOptions, TransactionPageResponse } from "./types"; -import { SDKOptions } from "./fireblocks-sdk"; -import axios, { AxiosInstance } from "axios"; -import { version as SDK_VERSION } from "../package.json"; - -export class ApiClient { - private axiosInstance: AxiosInstance; - - constructor(private authProvider: IAuthProvider, private apiBaseUrl: string, private options?: SDKOptions) { - this.axiosInstance = axios.create({ - baseURL: this.apiBaseUrl, - proxy: this.options?.proxy, - timeout: this.options?.timeoutInMs, - headers: { - "X-API-Key": this.authProvider.getApiKey(), - "User-Agent": this.getUserAgent() - } - }); - - if (options?.customAxiosOptions?.interceptors?.response) { - this.axiosInstance.interceptors.response.use(options.customAxiosOptions.interceptors.response.onFulfilled, options.customAxiosOptions.interceptors.response.onRejected); - } - } - - private getUserAgent(): string { - let userAgent = `fireblocks-sdk-js/${SDK_VERSION}`; - if (!this.options?.anonymousPlatform) { - userAgent += ` (${os.type()} ${os.release()}; ${platform.name} ${platform.version}; ${os.arch()})`; - } - if (this.options?.userAgent) { - userAgent = `${this.options.userAgent} ${userAgent}`; - } - return userAgent; - } - - public async issueGetRequestForTransactionPages(path: string): Promise { - const token = this.authProvider.signJwt(path); - const res = await this.axiosInstance.get(path, { - headers: {"Authorization": `Bearer ${token}`} - }); - return { - transactions: res.data, - pageDetails: { - prevPage: res.headers["prev-page"] ? res.headers["prev-page"].toString() : "", - nextPage: res.headers["next-page"] ? res.headers["next-page"].toString() : "", - } - }; - } - - public async issueGetRequest(path: string): Promise { - const token = this.authProvider.signJwt(path); - const res = await this.axiosInstance.get(path, { - headers: {"Authorization": `Bearer ${token}`} - }); - return res.data; - } - - public async issuePostRequest(path: string, body: any, requestOptions?: RequestOptions): Promise { - const token = this.authProvider.signJwt(path, body); - const headers: any = {"Authorization": `Bearer ${token}`}; - const idempotencyKey = requestOptions?.idempotencyKey; - if (idempotencyKey) { - headers["Idempotency-Key"] = idempotencyKey; - } - - const ncwWalletId = requestOptions?.ncw?.walletId; - if (ncwWalletId) { - headers["X-End-User-Wallet-Id"] = ncwWalletId; - } - - const response = await this.axiosInstance.post(path, body, {headers}); - return response.data; - } - - public async issuePutRequest(path: string, body: any): Promise { - const token = this.authProvider.signJwt(path, body); - const res = (await this.axiosInstance.put(path, body, { - headers: {"Authorization": `Bearer ${token}`} - })); - return res.data; - } - - public async issuePatchRequest(path: string, body: any): Promise { - const token = this.authProvider.signJwt(path, body); - const res = (await this.axiosInstance.patch(path, body, { - headers: {"Authorization": `Bearer ${token}`} - })); - return res.data; - } - - public async issueDeleteRequest(path: string): Promise { - const token = this.authProvider.signJwt(path); - const res = (await this.axiosInstance.delete(path, { - headers: {"Authorization": `Bearer ${token}`} - })); - return res.data; - } -} diff --git a/src mine/api-token-provider.ts b/src mine/api-token-provider.ts deleted file mode 100644 index cfc11973..00000000 --- a/src mine/api-token-provider.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { IAuthProvider } from "./iauth-provider"; -import * as jwt from "jsonwebtoken"; -import * as crypto from "crypto"; -import { v4 as uuid } from "uuid"; - -export class ApiTokenProvider implements IAuthProvider { - - constructor(private privateKey: string, private apiKey: string) { } - - signJwt(path: string, bodyJson?: any): string { - const token = jwt.sign({ - uri: path, - nonce: uuid(), - iat: Math.floor(Date.now() / 1000), - exp: Math.floor(Date.now() / 1000) + 55, - sub: this.apiKey, - bodyHash: crypto.createHash("sha256").update(JSON.stringify(bodyJson || "")).digest().toString("hex") - } as any, this.privateKey, { algorithm: "RS256"}); - - return token; - } - - getApiKey(): string { - return this.apiKey; - } -} diff --git a/src mine/fireblocks-sdk.ts b/src mine/fireblocks-sdk.ts deleted file mode 100644 index 64a38a56..00000000 --- a/src mine/fireblocks-sdk.ts +++ /dev/null @@ -1,1925 +0,0 @@ -import { ApiClient } from "./api-client"; -import { ApiTokenProvider } from "./api-token-provider"; -import { IAuthProvider } from "./iauth-provider"; -import queryString from "query-string"; -import { stringify } from "qs"; -import { - AllocateFundsRequest, - AssetResponse, - AssetTypeResponse, - CancelTransactionResponse, - ConvertExchangeAssetResponse, - CreateTransactionResponse, - DeallocateFundsRequest, - DepositAddressResponse, - EstimateFeeResponse, - EstimateTransactionFeeResponse, - ExchangeResponse, - ExternalWalletAsset, - FiatAccountResponse, - GasStationInfo, - GenerateAddressResponse, - InternalWalletAsset, - MaxSpendableAmountResponse, - MaxBip44IndexUsedResponse, - NetworkConnectionResponse, - OffExchangeEntityResponse, - OperationSuccessResponse, - PagedVaultAccountsRequestFilters, - PagedVaultAccountsResponse, - PublicKeyInfoArgs, - PublicKeyInfoForVaultAccountArgs, - RequestOptions, - ResendWebhooksResponse, - TransactionArguments, - TransactionFilter, - TransactionPageFilter, - TransactionPageResponse, - TransactionResponse, - User, - ValidateAddressResponse, - VaultAccountResponse, - VaultAssetResponse, - VaultBalancesFilter, - WalletContainerResponse, - SetFeePayerConfiguration, - FeePayerConfiguration, - CreateWeb3ConnectionPayload, - CreateWeb3ConnectionResponse, - Session, - NetworkConnectionRoutingPolicy, - NetworkIdRoutingPolicy, - NetworkIdResponse, - TimePeriod, - AuditsResponse, - NFTOwnershipFilter, - NFTOwnedAssetsFilter, - Token, - TokenWithBalance, - Web3PagedResponse, - CreateWalletConnectPayload, - Web3ConnectionType, - GetWeb3ConnectionsPayload, - PublicKeyResponse, - AllocateFundsResponse, - SettleOffExchangeAccountResponse, - AddCollateralTransactionRequest, - RemoveCollateralTransactionRequest, - GetSettlementTransactionsResponse, - SettlementRequest, - SettlementResponse, - GetNFTsFilter, - PeerType, - PublicKeyInformation, - DropTransactionResponse, - TokenLink, - TokenLinkPermissionEntry, - IssueTokenRequest, - NFTOwnershipStatus, - NFTOwnedCollectionsFilter, - CollectionOwnership, - TravelRuleOptions, - ValidateTravelRuleVaspInfo, - ValidateTravelRuleResult, - ValidateCreateTravelRuleTransaction, - ValidateFullTravelRuleResult, - TravelRuleVasp, - TravelRuleVaspFilter, - TravelRuleEncryptionOptions, - SmartTransfersTicketResponse, - SmartTransfersTicketCreatePayload, - SmartTransfersTicketsResponse, - SmartTransfersTicketsFilters, - SmartTransfersTicketTermPayload, - SmartTransfersTicketTermFundPayload, - SmartTransfersTicketTermResponse, - SmartTransfersUserGroupsResponse, - UsersGroup, - ContractUploadRequest, - ContractTemplateDto, - PendingTokenLinkDto, Web3ConnectionFeeLevel, - Task, Job, JobCreatedResponse -} from "./types"; -import { AxiosProxyConfig, AxiosResponse } from "axios"; -import { PIIEncryption } from "./pii-client"; -import { NcwApiClient } from "./ncw-api-client"; -import { NcwSdk } from "./ncw-sdk"; - -export * from "./types"; - -export interface SDKOptions { - /** HTTP request timeout */ - timeoutInMs?: number; - - /** Proxy configurations */ - proxy?: AxiosProxyConfig | false; - - /** Whether to remove platform from User-Agent header */ - anonymousPlatform?: boolean; - - /** Additional product identifier to be prepended to the User-Agent header */ - userAgent?: string; - - /** - * Providing custom axios options including a response interceptor (https://axios-http.com/docs/interceptors) - */ - customAxiosOptions?: { - interceptors?: { - response?: { - onFulfilled: (value: AxiosResponse) => AxiosResponse | Promise>; - onRejected: (error: any) => any; - }; - } - }; - - /** - * TravelRule Provider options to initialize PII Client for PII encryption - */ - travelRuleOptions?: TravelRuleOptions; -} - -export class FireblocksSDK { - private readonly authProvider: IAuthProvider; - private readonly apiBaseUrl: string; - private readonly apiClient: ApiClient; - private readonly apiNcw: NcwApiClient; - - private piiClient: PIIEncryption; - - /** - * Creates a new Fireblocks API Client - * @param privateKey A string representation of your private key - * @param apiKey Your api key. This is a uuid you received from Fireblocks - * @param apiBaseUrl The fireblocks server URL. Leave empty to use the default server - * @param authProvider - * @param sdkOptions - */ - constructor(privateKey: string, apiKey: string, apiBaseUrl: string = "https://api.fireblocks.io", authProvider: IAuthProvider = undefined, sdkOptions?: SDKOptions) { - this.authProvider = !!authProvider ? authProvider : new ApiTokenProvider(privateKey, apiKey); - - if (!!apiBaseUrl) { - this.apiBaseUrl = apiBaseUrl; - } - - this.apiClient = new ApiClient(this.authProvider, this.apiBaseUrl, sdkOptions); - - if (sdkOptions?.travelRuleOptions) { - this.piiClient = new PIIEncryption(sdkOptions.travelRuleOptions); - } - - this.apiNcw = new NcwApiClient(this.apiClient); - } - - /** - * NCW API Namespace - * - * @readonly - * @type {NcwSdk} - */ - public get NCW(): NcwSdk { - return this.apiNcw; - } - - /** - * Get the instance of ApiClient used by the FireblocksSDK - */ - public getApiClient(): ApiClient { - return this.apiClient; - } - - /** - * Gets all assets that are currently supported by Fireblocks - */ - public async getSupportedAssets(): Promise { - return await this.apiClient.issueGetRequest("/v1/supported_assets"); - } - /** - * Gets a list of vault accounts per page matching the given filter or path - * @param pagedVaultAccountsRequestFilters Filters for the first request - */ - public async getVaultAccountsWithPageInfo(pagedVaultAccountsRequestFilters: PagedVaultAccountsRequestFilters): Promise { - return await this.apiClient.issueGetRequest(`/v1/vault/accounts_paged?${queryString.stringify(pagedVaultAccountsRequestFilters)}`); - } - /** - * Gets a single vault account - * @param vaultAccountId The vault account ID - */ - public async getVaultAccountById(vaultAccountId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/vault/accounts/${vaultAccountId}`); - } - - /** - * Gets a single vault account asset - * @param vaultAccountId The vault account ID - * @param assetId The ID of the asset to get - */ - public async getVaultAccountAsset(vaultAccountId: string, assetId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}`); - } - - /** - * Gets a single vault account asset balance after forcing refresh from the blockchain - * @param vaultAccountId The vault account ID - * @param assetId The ID of the asset to get - * @param requestOptions - */ - public async refreshVaultAssetBalance(vaultAccountId: string, assetId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/balance`, "{}", requestOptions); - } - - /** - * Gets deposit addresses for an asset in a vault account - * @param vaultAccountId The vault account ID - * @param assetId The ID of the asset for which to get the deposit address - */ - public async getDepositAddresses(vaultAccountId: string, assetId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/addresses`); - } - - /** - * Gets utxo list for an asset in a vault account - * @param vaultAccountId The vault account ID - * @param assetId The ID of the asset for which to get the utxo list - */ - public async getUnspentInputs(vaultAccountId: string, assetId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/unspent_inputs`); - } - - /** - * Generates a new address for an asset in a vault account - * @param vaultAccountId The vault account ID - * @param assetId The ID of the asset for which to generate the deposit address - * @param description A description for the new address - * @param customerRefId A customer reference ID - * @param requestOptions - */ - public async generateNewAddress(vaultAccountId: string, assetId: string, description?: string, customerRefId?: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/addresses`, { - description, - customerRefId - }, requestOptions); - } - - /** - * Sets the description of an existing address - * @param vaultAccountId The vault account ID - * @param assetId The ID of the asset - * @param address The address for which to set the description - * @param tag The XRP tag, or EOS memo, for which to set the description - * @param description The description to set - */ - public async setAddressDescription(vaultAccountId: string, assetId: string, address: string, tag?: string, description?: string): Promise { - let addressId = address; - if (tag && tag.length > 0) { - addressId = `${address}:${tag}`; - } - - return await this.apiClient.issuePutRequest( - `/v1/vault/accounts/${vaultAccountId}/${assetId}/addresses/${addressId}`, - {description: description || ""}); - } - - /** - * Gets all network connections - * @returns NetworkConnectionResponse - */ - public async getNetworkConnections(): Promise { - return await this.apiClient.issueGetRequest("/v1/network_connections"); - } - - /** - * Creates a network connection - * @param localNetworkId The local netowrk profile's id - * @param remoteNetworkId The remote network profile's id - * @param routingPolicy The desired routing policy for the connection - * @returns NetworkConnectionResponse - */ - public async createNetworkConnection(localNetworkId: string, remoteNetworkId: string, routingPolicy?: NetworkConnectionRoutingPolicy): Promise { - const body = { localNetworkId, remoteNetworkId, routingPolicy }; - return await this.apiClient.issuePostRequest(`/v1/network_connections`, body); - } - - /** - * Gets a single network connection - * @param connectionId The network connection's id - * @returns NetworkConnectionResponse - */ - public async getNetworkConnectionById(connectionId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/network_connections/${connectionId}`); - } - - /** - * Removes a network connection - * @param connectionId The network connection's id - * @returns OperationSuccessResponse - */ - public async removeNetworkConnection(connectionId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/network_connections/${connectionId}`); - } - - /** - * Sets routing policy for a network connection - * @param connectionId The network connection's id - * @param routingPolicy The desired routing policy - */ - public async setNetworkConnectionRoutingPolicy(connectionId: string, routingPolicy: NetworkConnectionRoutingPolicy): Promise { - const body = { routingPolicy }; - return await this.apiClient.issuePatchRequest(`/v1/network_connections/${connectionId}/set_routing_policy`, body); - } - - /** - * Gets all discoverable network profiles - * @returns NetworkIdResponse - */ - public async getDiscoverableNetworkIds(): Promise { - return await this.apiClient.issueGetRequest(`/v1/network_ids`); - } - - /** - * Creates a new network profile - * @param name A name for the new network profile - * @param routingPolicy The desired routing policy for the network - * @returns NetworkConnectionResponse - */ - public async createNetworkId(name: string, routingPolicy?: NetworkIdRoutingPolicy): Promise { - const body = { name, routingPolicy }; - return await this.apiClient.issuePostRequest(`/v1/network_ids`, body); - } - - /** - * Gets a single network profile - * @param networkId The network profile's id - * @returns NetworkIdResponse - */ - public async getNetworkId(networkId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/network_ids/${networkId}`); - } - - /** - * Deletes a single network profile - * @param networkId The network profile's id - * @returns NetworkIdResponse - */ - public async deleteNetworkId(networkId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/network_ids/${networkId}`); - } - - /** - * Sets discoverability for network profile - * @param networkId The network profile's id - * @param isDiscoverable The desired discoverability to set - * @returns OperationSuccessResponse - */ - public async setNetworkIdDiscoverability(networkId: string, isDiscoverable: boolean): Promise { - const body = { isDiscoverable }; - return await this.apiClient.issuePatchRequest(`/v1/network_ids/${networkId}/set_discoverability`, body); - } - - /** - * Sets routing policy for network profile - * @param networkId The network profile's id - * @param routingPolicy The desired routing policy - * @returns OperationSuccessResponse - */ - public async setNetworkIdRoutingPolicy(networkId: string, routingPolicy: NetworkIdRoutingPolicy): Promise { - const body = { routingPolicy }; - return await this.apiClient.issuePatchRequest(`/v1/network_ids/${networkId}/set_routing_policy`, body); - } - - /** - * Sets network profile name - * @param networkId The network profile's id - * @param name The desired network profile's name - * @returns OperationSuccessResponse - */ - public async setNetworkIdName(networkId: string, name: string): Promise { - const body = { name }; - return await this.apiClient.issuePatchRequest(`/v1/network_ids/${networkId}/set_name`, body); - } - - /** - * Gets all exchange accounts for your tenant - */ - public async getExchangeAccounts(): Promise { - return await this.apiClient.issueGetRequest("/v1/exchange_accounts"); - } - - - /** - * Gets a single exchange account by ID - * @param exchangeAccountId The exchange account ID - */ - public async getExchangeAccountById(exchangeAccountId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/exchange_accounts/${exchangeAccountId}`); - } - - /** - * Gets a single asset within an Exchange Account - * @param exchangeAccountId The exchange account ID - * @param assetId The ID of the asset - */ - public async getExchangeAsset(exchangeAccountId: string, assetId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/exchange_accounts/${exchangeAccountId}/${assetId}`); - } - - /** - * Convert an asset at an Exchange Account - * @param exchangeAccountId The exchange account ID - * @param srcAsset The source asset to convert from - * @param destAsset The destination asset to convert to - * @param amount The amount to convert - */ - public async convertExchangeAsset(exchangeAccountId: string, srcAsset: string, destAsset: string, amount: number, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/exchange_accounts/${exchangeAccountId}/convert`, { - srcAsset, destAsset, amount - }, requestOptions); - } - - /** - * Transfer from a main exchange account to a subaccount - * @param exchangeAccountId The exchange ID in Fireblocks - * @param subaccountId The ID of the subaccount in the exchange - * @param assetId The asset to transfer - * @param amount The amount to transfer - * @param requestOptions - */ - public async transferToSubaccount(exchangeAccountId: string, subaccountId: string, assetId: string, amount: number, requestOptions?: RequestOptions): Promise { - const body = { - subaccountId, - amount - }; - - return await this.apiClient.issuePostRequest(`/v1/exchange_accounts/${exchangeAccountId}/${assetId}/transfer_to_subaccount`, body, requestOptions); - } - - /** - * Transfer from a subaccount to a main exchange account - * @param exchangeAccountId The exchange ID in Fireblocks - * @param subaccountId The ID of the subaccount in the exchange - * @param assetId The asset to transfer - * @param amount The amount to transfer - * @param requestOptions - */ - public async transferFromSubaccount(exchangeAccountId: string, subaccountId: string, assetId: string, amount: number, requestOptions?: RequestOptions): Promise { - const body = { - subaccountId, - amount - }; - - return await this.apiClient.issuePostRequest(`/v1/exchange_accounts/${exchangeAccountId}/${assetId}/transfer_from_subaccount`, body, requestOptions); - } - - /** - * Gets all fiat accounts for your tenant - */ - public async getFiatAccounts(): Promise { - return await this.apiClient.issueGetRequest("/v1/fiat_accounts"); - } - - /** - * Gets a single fiat account by ID - * @param accountId The fiat account ID - */ - public async getFiatAccountById(accountId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/fiat_accounts/${accountId}`); - } - - /** - * Redeem from a fiat account to a linked DDA - * @param accountId The fiat account ID in Fireblocks - * @param amount The amount to transfer - * @param requestOptions - */ - public async redeemToLinkedDDA(accountId: string, amount: number, requestOptions?: RequestOptions): Promise { - const body = { - amount - }; - - return await this.apiClient.issuePostRequest(`/v1/fiat_accounts/${accountId}/redeem_to_linked_dda`, body, requestOptions); - } - - /** - * Deposit to a fiat account from a linked DDA - * @param accountId The fiat account ID in Fireblocks - * @param amount The amount to transfer - * @param requestOptions - */ - public async depositFromLinkedDDA(accountId: string, amount: number, requestOptions?: RequestOptions): Promise { - const body = { - amount - }; - - return await this.apiClient.issuePostRequest(`/v1/fiat_accounts/${accountId}/deposit_from_linked_dda`, body, requestOptions); - } - - /** - * Gets a list of transactions matching the given filter - * @param filter.before Only gets transactions created before a given timestamp (in milliseconds) - * @param filter.after Only gets transactions created after a given timestamp (in milliseconds) - * @param filter.status Only gets transactions with the spcified status - * @param filter.limit Limit the amount of returned results. If not specified, a limit of 200 results will be used - * @param filter.orderBy Determines the order of the results - */ - public async getTransactions(filter: TransactionFilter): Promise { - return await this.apiClient.issueGetRequest(`/v1/transactions?${queryString.stringify(filter)}`); - } - - /** - * Gets a list of transactions per page matching the given filter or path - * @param pageFilter Get transactions matching pageFilter params - * @param nextOrPreviousPath Get transactions from each of pageDetails paths - */ - public async getTransactionsWithPageInfo(pageFilter?: TransactionPageFilter, nextOrPreviousPath?: string): Promise { - if (pageFilter) { - return await this.apiClient.issueGetRequestForTransactionPages(`/v1/transactions?${queryString.stringify(pageFilter)}`); - } else if (nextOrPreviousPath) { - const index = nextOrPreviousPath.indexOf("/v1/"); - const path = nextOrPreviousPath.substring(index, nextOrPreviousPath.length); - return await this.apiClient.issueGetRequestForTransactionPages(path); - } - - return { - transactions: [], pageDetails: { prevPage: "", nextPage: "" }, - }; - } - - /** - * Gets a transaction matching the external transaction id provided - * @param externalTxId - */ - public async getTransactionByExternalTxId(externalTxId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/transactions/external_tx_id/${externalTxId}`); - } - - /** - * Gets all internal wallets for your tenant - */ - public async getInternalWallets(): Promise[]> { - return await this.apiClient.issueGetRequest("/v1/internal_wallets"); - } - - /** - * Gets a single internal wallet - * @param walletId The internal wallet ID - */ - public async getInternalWallet(walletId: string): Promise> { - return await this.apiClient.issueGetRequest(`/v1/internal_wallets/${walletId}`); - } - - /** - * Gets a single internal wallet asset - * @param walletId The internal wallet ID - * @param assetId The asset ID - */ - public async getInternalWalletAsset(walletId: string, assetId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/internal_wallets/${walletId}/${assetId}`); - } - - /** - * Gets all external wallets for your tenant - */ - public async getExternalWallets(): Promise[]> { - return await this.apiClient.issueGetRequest("/v1/external_wallets"); - } - - /** - * Gets a single external wallet - * @param walletId The external wallet ID - */ - public async getExternalWallet(walletId: string): Promise> { - return await this.apiClient.issueGetRequest(`/v1/external_wallets/${walletId}`); - } - - /** - * Gets a single external wallet asset - * @param walletId The external wallet ID - * @param assetId The asset ID - */ - public async getExternalWalletAsset(walletId: string, assetId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/external_wallets/${walletId}/${assetId}`); - } - - /** - * Gets all contract wallets for your tenant - */ - public async getContractWallets(): Promise[]> { - return await this.apiClient.issueGetRequest("/v1/contracts"); - } - - /** - * Gets a single contract wallet - * @param walletId The contract wallet ID - */ - public async getContractWallet(walletId: string): Promise> { - return await this.apiClient.issueGetRequest(`/v1/contracts/${walletId}`); - } - - /** - * Gets a single contract wallet asset - * @param walletId The contract wallet ID - * @param assetId The asset ID - */ - public async getContractWalletAsset(walletId: string, assetId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/contracts/${walletId}/${assetId}`); - } - - /** - * Gets detailed information for a single transaction - * @param txId The transaction id to query - */ - public async getTransactionById(txId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/transactions/${txId}`); - } - - /** - * Cancels the selected transaction - * @param txId The transaction id to cancel - * @param requestOptions - */ - public async cancelTransactionById(txId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/transactions/${txId}/cancel`, {}, requestOptions); - } - - /** - * Creates a new vault account - * @param name A name for the new vault account - * @param hiddenOnUI If true, the created account and all related transactions will not be shown on Fireblocks console - * @param customerRefId A customer reference ID - * @param autoFuel - * @param requestOptions - * @param autoFuel - * @param requestOptions - */ - public async createVaultAccount(name: string, hiddenOnUI?: boolean, customerRefId?: string, autoFuel?: boolean, requestOptions?: RequestOptions): Promise { - const body = { - name, - customerRefId, - hiddenOnUI: hiddenOnUI || false, - autoFuel: autoFuel || false - }; - - return await this.apiClient.issuePostRequest("/v1/vault/accounts", body, requestOptions); - } - - /** - * Creates a new vault account - * @param count Number of new vault accounts requested - * @param requestOptions - */ - public async createVaultAccountBulk(count: number, requestOptions?: RequestOptions): Promise { - const body = { - count - }; - - return await this.apiClient.issuePostRequest("/v1/vault/accounts/bulk", body, requestOptions); - } - - /** - * Hides a vault account in Fireblocks console - * @param vaultAccountId The vault account ID - * @param requestOptions - */ - public async hideVaultAccount(vaultAccountId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/hide`, {}, requestOptions); - } - - /** - * Reveals a hidden vault account in Fireblocks console - * @param vaultAccountId The vault account ID - * @param requestOptions - */ - public async unhideVaultAccount(vaultAccountId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/unhide`, {}, requestOptions); - } - - /** - * Sets autoFuel to true/false for a vault account - * @param vaultAccountId The vault account ID - * @param autoFuel The new value for the autoFuel flag - * @param requestOptions - */ - public async setAutoFuel(vaultAccountId: string, autoFuel: boolean, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/set_auto_fuel`, {autoFuel}, requestOptions); - } - - /** - * Updates a vault account - * @param vaultAccountId - * @param name A new name for the vault account - */ - public async updateVaultAccount(vaultAccountId: string, name: string): Promise { - const body = { - name: name - }; - - return await this.apiClient.issuePutRequest(`/v1/vault/accounts/${vaultAccountId}`, body); - } - - /** - * Creates a new asset within an existing vault account - * @param vaultAccountId The vault account ID - * @param assetId The asset to add - * @param requestOptions - */ - public async createVaultAsset(vaultAccountId: string, assetId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}`, {}, requestOptions); - } - - /** - * Creates a new asset within a list of existing vault accounts - * @param assetId The asset to add - * @param vaultAccountIdFrom The first of the account ID range - * @param vaultAccountIdTo The last of the account ID range - * @param requestOptions - */ - public async createVaultAssetBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string, requestOptions?: RequestOptions): Promise { - const body = { - assetId, vaultAccountIdFrom, vaultAccountIdTo - }; - return await this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body, requestOptions); - } - - /** - * Retry to create a vault asset for a vault asset that failed - * @param vaultAccountId The vault account ID - * @param assetId The asset to add - * @param requestOptions - */ - public async activateVaultAsset(vaultAccountId: string, assetId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/activate`, {} , requestOptions); - } - - /** - * Creates a new external wallet - * @param name A name for the new external wallet - * @param customerRefId A customer reference ID - * @param requestOptions - */ - public async createExternalWallet(name: string, customerRefId?: string, requestOptions?: RequestOptions): Promise> { - const body = { - name, - customerRefId - }; - - return await this.apiClient.issuePostRequest("/v1/external_wallets", body, requestOptions); - } - - /** - * Creates a new internal wallet - * @param name A name for the new internal wallet - * @param customerRefId A customer reference ID - * @param requestOptions - */ - public async createInternalWallet(name: string, customerRefId?: string, requestOptions?: RequestOptions): Promise> { - const body = { - name, - customerRefId - }; - - return await this.apiClient.issuePostRequest("/v1/internal_wallets", body, requestOptions); - } - - /** - * Creates a new contract wallet - * @param name A name for the new contract wallet - */ - public async createContractWallet(name: string, requestOptions?: RequestOptions): Promise> { - const body = { - name, - }; - - return await this.apiClient.issuePostRequest("/v1/contracts", body, requestOptions); - } - - /** - * Creates a new asset within an exiting external wallet - * @param walletId The wallet id - * @param assetId The asset to add - * @param address The wallet address - * @param tag (for ripple only) The ripple account tag - * @param requestOptions - */ - public async createExternalWalletAsset(walletId: string, assetId: string, address: string, tag?: string, requestOptions?: RequestOptions): Promise { - const path = `/v1/external_wallets/${walletId}/${assetId}`; - - const body = { - address: address, - tag: tag - }; - return await this.apiClient.issuePostRequest(path, body, requestOptions); - } - - /** - * Creates a new asset within an exiting internal wallet - * @param walletId The wallet id - * @param assetId The asset to add - * @param address The wallet address - * @param tag (for ripple only) The ripple account tag - * @param requestOptions - */ - public async createInternalWalletAsset(walletId: string, assetId: string, address: string, tag?: string, requestOptions?: RequestOptions): Promise { - const path = `/v1/internal_wallets/${walletId}/${assetId}`; - - const body = { - address: address, - tag: tag - }; - return await this.apiClient.issuePostRequest(path, body, requestOptions); - } - - /** - * Creates a new asset within an exiting contract wallet - * @param walletId The wallet id - * @param assetId The asset to add - * @param address The wallet address - * @param tag (for ripple only) The ripple account tag - */ - public async createContractWalletAsset(walletId: string, assetId: string, address: string, tag?: string, requestOptions?: RequestOptions): Promise { - const path = `/v1/contracts/${walletId}/${assetId}`; - - const body = { - address: address, - tag: tag - }; - return await this.apiClient.issuePostRequest(path, body, requestOptions); - } - - /** - * Creates a new transaction with the specified options - */ - public async createTransaction(transactionArguments: TransactionArguments, requestOptions?: RequestOptions, travelRuleEncryptionOptions?: TravelRuleEncryptionOptions): Promise { - const opts = { ...requestOptions }; - - if (transactionArguments?.travelRuleMessage) { - transactionArguments = await this.piiClient.hybridEncode(transactionArguments, travelRuleEncryptionOptions); - } - - if (transactionArguments.source?.type === PeerType.END_USER_WALLET && !opts.ncw?.walletId) { - const { walletId } = transactionArguments.source; - opts.ncw = { ...opts.ncw, walletId }; - } - - return await this.apiClient.issuePostRequest("/v1/transactions", transactionArguments, opts); - } - - /** - * Estimates the fee for a transaction request - */ - public async estimateFeeForTransaction(transactionArguments: TransactionArguments, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest("/v1/transactions/estimate_fee", transactionArguments, requestOptions); - } - - /** - * Gets the estimated fees for an asset - */ - public async getFeeForAsset(asset: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/estimate_network_fee?assetId=${asset}`); - } - - /** - * Deletes a single internal wallet - * @param walletId The internal wallet ID - */ - public async deleteInternalWallet(walletId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/internal_wallets/${walletId}`); - } - - /** - * Deletes a single internal wallet asset - * @param walletId The internal wallet ID - * @param assetId The asset ID - */ - public async deleteInternalWalletAsset(walletId: string, assetId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/internal_wallets/${walletId}/${assetId}`); - } - - /** - * Deletes a single external wallet - * @param walletId The external wallet ID - */ - public async deleteExternalWallet(walletId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/external_wallets/${walletId}`); - } - - /** - * Deletes a single external wallet asset - * @param walletId The external wallet ID - * @param assetId The asset ID - */ - public async deleteExternalWalletAsset(walletId: string, assetId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/external_wallets/${walletId}/${assetId}`); - } - - /** - * Deletes a single contract wallet - * @param walletId The contract wallet ID - */ - public async deleteContractWallet(walletId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/contracts/${walletId}`); - } - - /** - * Deletes a single contract wallet asset - * @param walletId The contract wallet ID - * @param assetId The asset ID - */ - public async deleteContractWalletAsset(walletId: string, assetId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/contracts/${walletId}/${assetId}`); - } - - /** - * Sets a customer reference ID - * @param vaultAccountId The vault account ID - * @param customerRefId The customer reference ID to set - * @param requestOptions - */ - public async setCustomerRefIdForVaultAccount(vaultAccountId: string, customerRefId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/set_customer_ref_id`, {customerRefId}, requestOptions); - } - - /** - * Sets a customer reference ID - * @param walletId The ID of the internal wallet - * @param customerRefId The customer reference ID to set - * @param requestOptions - */ - public async setCustomerRefIdForInternalWallet(walletId: string, customerRefId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/internal_wallets/${walletId}/set_customer_ref_id`, {customerRefId}, requestOptions); - } - - /** - * Sets a customer reference ID - * @param walletId The ID of the external wallet - * @param customerRefId The customer reference ID to set - * @param requestOptions - */ - public async setCustomerRefIdForExternalWallet(walletId: string, customerRefId: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/external_wallets/${walletId}/set_customer_ref_id`, {customerRefId}, requestOptions); - } - - /** - * Sets a customer reference ID - * @param vaultAccountId The vault account ID - * @param assetId The ID of the asset - * @param address The address - * @param tag The XRP tag, or EOS memo - * @param customerRefId The customer reference ID to set - * @param requestOptions - */ - public async setCustomerRefIdForAddress(vaultAccountId: string, assetId: string, address: string, tag?: string, customerRefId?: string, requestOptions?: RequestOptions): Promise { - let addressId = address; - if (tag && tag.length > 0) { - addressId = `${address}:${tag}`; - } - - return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}/addresses/${addressId}/set_customer_ref_id`, {customerRefId}, requestOptions); - } - - /** - * Set the required number of confirmations for transaction - * @param txId - * @param requiredConfirmationsNumber - * @param requestOptions - */ - public async setConfirmationThresholdForTxId(txId: string, requiredConfirmationsNumber: number, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/transactions/${txId}/set_confirmation_threshold`, {numOfConfirmations: requiredConfirmationsNumber}, requestOptions); - } - - /** - * Set the required number of confirmations for transactions by tx hash - * @param txHash - * @param requiredConfirmationsNumber - * @param requestOptions - */ - public async setConfirmationThresholdForTxHash(txHash: string, requiredConfirmationsNumber: number, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/txHash/${txHash}/set_confirmation_threshold`, {numOfConfirmations: requiredConfirmationsNumber}, requestOptions); - } - - /** - * Get the public key information - * @param args - */ - public async getPublicKeyInfo(args: PublicKeyInfoArgs): Promise { - let url = `/v1/vault/public_key_info`; - if (args.algorithm) { - url += `?algorithm=${args.algorithm}`; - } - if (args.derivationPath) { - url += `&derivationPath=${JSON.stringify(args.derivationPath)}`; - } - if (args.compressed) { - url += `&compressed=${args.compressed}`; - } - return await this.apiClient.issueGetRequest(url); - } - - /** - * allocate funds from you default balance to a private ledger - * @param vaultAccountId - * @param asset - * @param vaultAccountId - * @param asset - * @param args - * @param requestOptions - */ - public async allocateFundsToPrivateLedger(vaultAccountId: string, asset: string, args: AllocateFundsRequest, requestOptions?: RequestOptions): Promise { - const url = `/v1/vault/accounts/${vaultAccountId}/${asset}/lock_allocation`; - return await this.apiClient.issuePostRequest(url, args, requestOptions); - } - - /** - * deallocate funds from a private ledger to your default balance - * @param vaultAccountId - * @param asset - * @param args - * @param requestOptions - */ - public async deallocateFundsFromPrivateLedger(vaultAccountId: string, asset: string, args: DeallocateFundsRequest, requestOptions?: RequestOptions): Promise { - const url = `/v1/vault/accounts/${vaultAccountId}/${asset}/release_allocation`; - return await this.apiClient.issuePostRequest(url, args, requestOptions); - } - - /** - * Get the public key information for a vault account - * @param args - */ - public async getPublicKeyInfoForVaultAccount(args: PublicKeyInfoForVaultAccountArgs): Promise { - let url = `/v1/vault/accounts/${args.vaultAccountId}/${args.assetId}/${args.change}/${args.addressIndex}/public_key_info`; - if (args.compressed) { - url += `?compressed=${args.compressed}`; - } - return await this.apiClient.issueGetRequest(url); - } - - /** - * Get configuration and status of the Gas Station account - */ - public async getGasStationInfo(assetId?: string): Promise { - let url = `/v1/gas_station`; - - if (assetId) { - url += `/${assetId}`; - } - - return await this.apiClient.issueGetRequest(url); - } - - /** - * Set configuration of the Gas Station account - */ - public async setGasStationConfiguration(gasThreshold: string, gasCap: string, maxGasPrice?: string, assetId?: string): Promise { - let url = `/v1/gas_station/configuration`; - - if (assetId) { - url += `/${assetId}`; - } - - const body = {gasThreshold, gasCap, maxGasPrice}; - - return await this.apiClient.issuePutRequest(url, body); - } - - /** - * Drop an ETH based transaction - */ - public async dropTransaction(txId: string, feeLevel?: string, requestedFee?: string, requestOptions?: RequestOptions): Promise { - const url = `/v1/transactions/${txId}/drop`; - - const body = {feeLevel, requestedFee}; - - return await this.apiClient.issuePostRequest(url, body, requestOptions); - } - - /** - * Get max spendable amount per asset and vault - */ - public async getMaxSpendableAmount(vaultAccountId: string, assetId: string, manualSigning?: Boolean): Promise { - let url = `/v1/vault/accounts/${vaultAccountId}/${assetId}/max_spendable_amount`; - - if (manualSigning) { - url += `?manualSigning=${manualSigning}`; - } - - return await this.apiClient.issueGetRequest(url); - } - - /** - * Get maximum BIP44 index used in deriving addresses or in change addresses - */ - public async getMaxBip44IndexUsed(vaultAccountId: string, assetId: string): Promise { - const url = `/v1/vault/accounts/${vaultAccountId}/${assetId}/max_bip44_index_used`; - - return await this.apiClient.issueGetRequest(url); - } - - /** - * Get all vault assets balance overview - */ - public async getVaultAssetsBalance(filter: VaultBalancesFilter): Promise { - const url = `/v1/vault/assets?${queryString.stringify(filter)}`; - - return await this.apiClient.issueGetRequest(url); - } - - /** - * Get vault balance overview per asset - */ - public async getVaultBalanceByAsset(assetId: string): Promise { - const url = `/v1/vault/assets/${assetId}`; - return await this.apiClient.issueGetRequest(url); - } - - /** - * Get address validation info - */ - public async validateAddress(assetId: string, address: string): Promise { - const url = `/v1/transactions/validate_address/${assetId}/${address}`; - return await this.apiClient.issueGetRequest(url); - } - - /** - * Unfreezes the selected transaction - * @param txId The transaction id to unfreeze - * @param requestOptions - */ - public async unfreezeTransactionById(txId: string, requestOptions?: RequestOptions): Promise { - return this.apiClient.issuePostRequest(`/v1/transactions/${txId}/unfreeze`, {}, requestOptions); - } - - /** - * Freezes the selected transaction - * @param txId The transaction id to freeze - * @param requestOptions - */ - public async freezeTransactionById(txId: string, requestOptions?: RequestOptions): Promise { - return this.apiClient.issuePostRequest(`/v1/transactions/${txId}/freeze`, {}, requestOptions); - } - - /** - * Resend failed webhooks - */ - public async resendWebhooks(requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest("/v1/webhooks/resend", {}, requestOptions); - } - - /** - * Resend transaction webhooks - * @param txId The transaction for which the message is sent - * @param resendCreated If true a webhook will be sent for the creation of the transaction - * @param resendStatusUpdated If true a webhook will be sent for the status of the transaction - * @param requestOptions - */ - public async resendTransactionWebhooksById(txId: string, resendCreated?: boolean, resendStatusUpdated?: boolean, requestOptions?: RequestOptions): Promise { - const body = { resendCreated, resendStatusUpdated }; - return await this.apiClient.issuePostRequest(`/v1/webhooks/resend/${txId}`, body, requestOptions); - } - - /** - * Gets all Users for your tenant - */ - public async getUsers(): Promise { - return await this.apiClient.issueGetRequest("/v1/users"); - } - - /** - * Gets all Users Groups for your tenant - */ - public async getUsersGroups(): Promise { - return await this.apiClient.issueGetRequest("/v1/users_groups"); - } - - /** - * Gets a Users Group by ID - * @param id The ID of the User - */ - public async getUsersGroup(id: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/users_groups/${id}`); - } - - /** - * Creates a new Users Group - * @param name The name of the Users Group - * @param memberIds The members of the Users Group - */ - public async createUserGroup(groupName: string, memberIds?: string[]): Promise { - const body = { groupName, memberIds }; - return await this.apiClient.issuePostRequest("/v1/users_groups", body); - } - - /** - * Updates a Users Group - * @param id The ID of the Users Group - * @param name The name of the Users Group - * @param memberIds The members of the Users Group - */ - public async updateUserGroup(id: string, groupName?: string, memberIds?: string[]): Promise { - const body = { groupName, memberIds }; - return await this.apiClient.issuePutRequest(`/v1/users_groups/${id}`, body); - } - - /** - * Deletes a Users Group - * @param id The ID of the Users Group - */ - public async deleteUserGroup(id: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/users_groups/${id}`); - } - - /** - * Get off exchange accounts - */ - public async getOffExchangeAccounts(): Promise { - return await this.apiClient.issueGetRequest(`/v1/off_exchange_accounts`); - } - - /** - * Get off exchange account by virtual account id - * @param id the ID of the off exchange - */ - public async getOffExchangeAccountById(id: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/off_exchange_accounts/${id}`); - } - - /** - * Settle off exchange account by virtual account id - * @param id the ID of the off exchange - * @param requestOptions - */ - public async settleOffExchangeAccountById(id: string, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/off_exchange_accounts/${id}/settle`, {}, requestOptions); - } - - /** - * Add collateral account, create deposit request - * @param depositRequest - * @param requestOptions - */ - public async addCollateral(depositRequest: AddCollateralTransactionRequest, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/off_exchange/add`, depositRequest, requestOptions); - } - - /** - * Remove collateral account, create withdraw request - * @param withdrawRequest - * @param requestOptions - */ - public async removeCollateral(withdrawRequest: RemoveCollateralTransactionRequest, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/off_exchange/remove`, withdrawRequest, requestOptions); - } - - /** - * - * @param requestOptions - */ - public async getSettlementTransactions(settlementRequest: SettlementRequest): Promise { - return await this.apiClient.issueGetRequest(`/v1/off_exchange/settlements/transactions?mainExchangeAccountId=${settlementRequest.mainExchangeAccountId}`); - } - - /** - * - * @param settlementRequest - * @param requestOptions - */ - public async settlement(settlementRequest: SettlementRequest, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/off_exchange/settlements/trader`, settlementRequest, requestOptions); - } - /** - * Set Fee Payer configuration - * @param feePayerConfiguration - * @param baseAsset - * @param requestOptions - */ - public async setFeePayerConfiguration(baseAsset: string, feePayerConfiguration: SetFeePayerConfiguration, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/fee_payer/${baseAsset}`, feePayerConfiguration, requestOptions); - } - - /** - * Get Fee Payer Configuration - * @param baseAsset - */ - public async getFeePayerConfiguration(baseAsset: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/fee_payer/${baseAsset}`); - } - - /** - * Delete Fee Payer Configuration - * @param baseAsset - */ - public async removeFeePayerConfiguration(baseAsset: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/fee_payer/${baseAsset}`); - } - - private getWeb3ConnectionPath(type: Web3ConnectionType): string { - const basePath = `/v1/connections`; - - switch (type) { - case(Web3ConnectionType.WALLET_CONNECT): { - return `${basePath}/wc`; - } - default: { - throw new Error(`Invalid Web3 connection type`); - } - } - } - - /** - * Get all signer connections of the current tenant - * @param {Object} payload The payload for getting the current tenant's sessions - * @param payload.pageCursor The cursor for the next page - * @param payload.pageSize The amount of results to return on the next page - * @param payload.sort The property to sort the results by - * @param payload.filter The filter object, containing properties as keys and the values to filter by as values - * @param payload.order Should the results be ordered in ascending order (false) or descending (true) - * - * @returns An object containing the data returned and the cursor for the next page - */ - public async getWeb3Connections({ - pageCursor, - pageSize, - sort, - filter, - order - }: GetWeb3ConnectionsPayload = {}): Promise> { - const params = new URLSearchParams({ - ...(pageCursor && { next: pageCursor }), - ...(pageSize && { pageSize: pageSize.toString() }), - ...(sort && { sort }), - ...(filter && { filter: stringify(filter, { delimiter: "," })}), - ...(order && { order }), - }); - - return await this.apiClient.issueGetRequest(`/v1/connections?${params.toString()}`); - } - - /** - * Initiate a new web3 connection - * @param type The type of the connection - * @param payload The payload for creating a new web3 connection - * @param requestOptions - * @param payload.vaultAccountId The vault account to link with the dapp - * @param payload.feeLevel The fee level for the connection - * @param payload.uri The WalletConnect URI, as provided by the dapp - * @param payload.chainIds Array of the approved chains for the connection - * - * @returns The created session's ID and it's metadata - * @example { - * vaultAccountId: 0 - * feeLevel: "MEDIUM" - * connectionType: "WalletConnect" - * uri: "wc:77752975-906f-48f5-b59f-047826ee947e@1?bridge=https%3A%2F%2F0.bridge.walletconnect.org&key=64be99adc6086b7a729b0ec8c7e1f174927ab92e84f5c6f9527050225344a637" - * chainIds: ["ETH", "ETH_TEST"] - * } - */ - public async createWeb3Connection(type: Web3ConnectionType.WALLET_CONNECT, payload: CreateWalletConnectPayload, requestOptions?: RequestOptions): Promise; - public async createWeb3Connection(type: Web3ConnectionType, payload: CreateWeb3ConnectionPayload, requestOptions?: RequestOptions): Promise { - const path = this.getWeb3ConnectionPath(type); - - return await this.apiClient.issuePostRequest(path, payload, requestOptions); - } - - /** - * Approve or Reject the initiated connection - * @param type The type of the connection - * @param sessionId The ID of the session - * @param approve Whether you approve the connection or not - */ - public async submitWeb3Connection(type: Web3ConnectionType.WALLET_CONNECT, sessionId: string, approve: boolean): Promise; - public async submitWeb3Connection(type: Web3ConnectionType, sessionId: string, approve: boolean): Promise { - const path = this.getWeb3ConnectionPath(type); - - return await this.apiClient.issuePutRequest(`${path}/${sessionId}`, {approve}); - } - - /** - * Remove an existing connection - * @param type The type of the connection - * @param sessionId The ID of the session - */ - public async removeWeb3Connection(type: Web3ConnectionType.WALLET_CONNECT, sessionId: string): Promise; - public async removeWeb3Connection(type: Web3ConnectionType, sessionId: string): Promise { - const path = this.getWeb3ConnectionPath(type); - - return await this.apiClient.issueDeleteRequest(`${path}/${sessionId}`); - } - - /** - * Gets all audits for selected time period - * @param timePeriod - */ - public async getAudits(timePeriod?: TimePeriod): Promise { - let url = `/v1/audits`; - if (timePeriod) { - url += `?timePeriod=${timePeriod}`; - } - return await this.apiClient.issueGetRequest(url); - } - - /** - * - * @param id - */ - public async getNFT(id: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/nfts/tokens/${id}`); - } - - /** - * - * @param filter.pageCursor - * @param filter.pageSize - * @param filter.ids - * @param filter.sort - * @param filter.order - */ - public async getNFTs(filter: GetNFTsFilter): Promise> { - const { pageCursor, pageSize, ids, sort, order } = filter; - const queryParams = { - pageCursor, - pageSize, - ids: this.getCommaSeparatedList(ids), - sort: this.getCommaSeparatedList(sort), - order, - }; - - return await this.apiClient.issueGetRequest(`/v1/nfts/tokens?${queryString.stringify(queryParams)}`); - } - - /** - * - * Gets a list of owned NFT tokens - * @param filter.vaultAccountIds List of vault account IDs - * @param filter.blockchainDescriptor The blockchain descriptor (based on legacy asset) - * @param filter.collectionIds List of collection IDs - * @param filter.ids List of token ids to fetch - * @param filter.pageCursor Page cursor - * @param filter.pageSize Page size - * @param filter.sort Sort by value - * @param filter.order Order value - * @param filter.status Status (LISTED, ARCHIVED) - * @param filter.search Search filter - * @param filter.ncwAccountIds List of Non-Custodial wallet account IDs - * @param filter.ncwId Non-Custodial wallet id - * @param filter.walletType Wallet type (VAULT_ACCOUNT, END_USER_WALLET) - */ - public async getOwnedNFTs(filter?: NFTOwnershipFilter): Promise> { - let url = "/v1/nfts/ownership/tokens"; - if (filter) { - const { blockchainDescriptor, vaultAccountIds, collectionIds, ids, pageCursor, pageSize, sort, order, status, search, ncwId, ncwAccountIds, walletType } = filter; - const requestFilter = { - vaultAccountIds: this.getCommaSeparatedList(vaultAccountIds), - blockchainDescriptor, - collectionIds: this.getCommaSeparatedList(collectionIds), - pageCursor, - pageSize, - ids: this.getCommaSeparatedList(ids), - sort: this.getCommaSeparatedList(sort), - order, - status, - search, - ncwId, - ncwAccountIds, - walletType, - }; - url += `?${queryString.stringify(requestFilter)}`; - } - return await this.apiClient.issueGetRequest(url); - } - - /** - * - * Get a list of owned NFT collections - * @param filter.search Search by value - * @param filter.status Status (LISTED, ARCHIVED) - * @param filter.ncwId Non-Custodial wallet id - * @param filter.walletType Wallet type (VAULT_ACCOUNT, END_USER_WALLET) - * @param filter.pageCursor Page cursor - * @param filter.pageSize Page size - * @param filter.sort Sort by value - * @param filter.order Order by value - */ - public async listOwnedCollections(filter?: NFTOwnedCollectionsFilter): Promise> { - let url = "/v1/nfts/ownership/collections"; - if (filter) { - const { search, status, ncwId, walletType, pageCursor, pageSize, sort, order } = filter; - - const requestFilter = { - search, - status, - ncwId, - walletType, - pageCursor, - pageSize, - sort: this.getCommaSeparatedList(sort), - order, - }; - url += `?${queryString.stringify(requestFilter)}`; - } - - return await this.apiClient.issueGetRequest(url); - } - - /** - * - * Get a list of owned tokens - * @param filter.search Search by value - * @param filter.status Status (LISTED, ARCHIVED) - * @param filter.ncwId Non-Custodial wallet id - * @param filter.walletType Wallet type (VAULT_ACCOUNT, END_USER_WALLET) - * @param filter.pageCursor Page cursor - * @param filter.pageSize Page size - * @param filter.sort Sort by value - * @param filter.order Order by value - */ - public async listOwnedAssets(filter?: NFTOwnedAssetsFilter): Promise> { - let url = "/v1/nfts/ownership/assets"; - if (filter) { - const { search, status, ncwId, walletType, pageCursor, pageSize, sort, order } = filter; - - const requestFilter = { - search, - status, - ncwId, - walletType, - pageCursor, - pageSize, - sort: this.getCommaSeparatedList(sort), - order, - }; - url += `?${queryString.stringify(requestFilter)}`; - } - - return await this.apiClient.issueGetRequest(url); - } - - /** - * - * @param id - */ - public async refreshNFTMetadata(id: string): Promise { - return await this.apiClient.issuePutRequest(`/v1/nfts/tokens/${id}`, undefined); - } - - /** - * - * Update NFT ownership status for specific token - * @param id NFT asset id - * @param status Status for update - */ - public async updateNFTOwnershipStatus(id: string, status: NFTOwnershipStatus): Promise { - return await this.apiClient.issuePutRequest(`/v1/nfts/ownership/tokens/${id}/status`, { status }); - } - - /** - * - * @param vaultAccountId - * @param blockchainDescriptor - */ - public async refreshNFTOwnershipByVault(vaultAccountId: string, blockchainDescriptor: string): Promise { - return await this.apiClient.issuePutRequest( - `/v1/nfts/ownership/tokens?vaultAccountId=${vaultAccountId}&blockchainDescriptor=${blockchainDescriptor}`, - undefined); - } - - /** - * Upload a new contract. This contract would be private and only your tenant can see it - * @param request - */ - public async uploadNewContract(request: ContractUploadRequest): Promise { - return await this.apiClient.issuePostRequest(`/v1/contract-registry/contracts`, request); - } - - /** - * Get all tokens linked to the tenant - * @param limit - * @param offset - */ - public async getLinkedTokens(limit: number = 100, offset: number = 0): Promise { - const requestFilter = { - limit, - offset - }; - const url = `/v1/tokenization/tokens?${queryString.stringify(requestFilter)}`; - return await this.apiClient.issueGetRequest(url); - } - - - /** - * Issue a new token and link it to the tenant - * @param request - */ - public async issueNewToken(request: IssueTokenRequest): Promise { - return await this.apiClient.issuePostRequest(`/v1/tokenization/tokens`, request); - } - - /** - * Get a token linked to the tenant by asset id - * @param assetId - */ - public async getLinkedToken(assetId: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/tokenization/tokens/${assetId}`); - } - - /** - * Link a token to the tenant - * @param assetId - */ - public async linkToken(assetId: string): Promise { - return await this.apiClient.issuePutRequest(`/v1/tokenization/tokens/${assetId}/link`, { }); - } - - /** - * remove a link to a token from the tenant - * @param assetId - */ - public async unlinkToken(assetId: string): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/tokenization/tokens/${assetId}`); - } - - /** - * Add permissions to a linked token - * @param assetId - * @param permissions - */ - public async addLinkedTokenPermissions(assetId: string, permissions: TokenLinkPermissionEntry[]): Promise { - return await this.apiClient.issuePutRequest(`/v1/tokenization/tokens/${assetId}/permissions`, { permissions }); - } - - /** - * Remove permissions from a linked token - * @param assetId - * @param permission - */ - public async removeLinkedTokenPermissions(assetId: string, permission: TokenLinkPermissionEntry): Promise { - return await this.apiClient.issueDeleteRequest(`/v1/tokenization/tokens/${assetId}/permissions?permission=${permission.permission}&vaultAccountId=${permission.vaultAccountId}`); - } - - /** - * Validate VASP details for travel rule compliance - * @param travelRuleMessageVaspInfo - */ - public async validateTravelRuleTransaction(travelRuleMessageVaspInfo: ValidateTravelRuleVaspInfo): Promise { - return await this.apiClient.issuePostRequest(`/v1/screening/travel_rule/transaction/validate`, travelRuleMessageVaspInfo); - } - - /** - * Validate Travel Rule transaction and PII data - * @param travelRuleMessage - */ - public async validateFullTravelRuleTransaction(travelRuleMessage: ValidateCreateTravelRuleTransaction): Promise { - return await this.apiClient.issuePostRequest(`/v1/screening/travel_rule/transaction/validate/full`, travelRuleMessage); - } - - /** - * Get VASP details for travel rule compliance - * @param did - */ - public async getTravelRuleVASPDetails(did: string): Promise { - return await this.apiClient.issueGetRequest(`/v1/screening/travel_rule/vasp/${did}`); - } - - /** - * Get VASP library for travel rule compliance - */ - public async getAllTravelRuleVASPs(filter?: TravelRuleVaspFilter): Promise { - let url = `/v1/screening/travel_rule/vasp`; - - if (filter) { - const { q, fields, page, per_page, order } = filter; - const queryParameters = { - q, - fields: this.getCommaSeparatedList(fields), - page, - per_page, - order, - }; - - url += `?${queryString.stringify(queryParameters)}`; - } - - return await this.apiClient.issueGetRequest(url); - } - - /** - * Update VASP for travel rule compliance - */ - public async updateVasp(vaspInfo: TravelRuleVasp): Promise { - return await this.apiClient.issuePutRequest(`/v1/screening/travel-rule/vasp/update`, vaspInfo); - } - - /** - * Creates Smart Transfers ticket - * @param data - * @param requestOptions - */ - public async createSmartTransferTicket(data: SmartTransfersTicketCreatePayload, requestOptions?: RequestOptions): Promise { - return await this.apiClient.issuePostRequest(`/v1/smart-transfers`, data, requestOptions); - } - - /** - * Get Smart Transfer tickets - * @param filters - */ - public getSmartTransferTickets(filters: SmartTransfersTicketsFilters): Promise { - return this.apiClient.issueGetRequest(`/v1/smart-transfers?${queryString.stringify(filters)}`); - } - - /** - * Get Smart Transfers ticket by id - * @param ticketId - */ - public getSmartTransferTicket(ticketId: string): Promise { - return this.apiClient.issueGetRequest(`/v1/smart-transfers/${ticketId}`); - } - - /** - * Set Smart Transfers ticket expires in - * @param ticketId - * @param expiresIn - */ - public setSmartTransferTicketExpiresIn(ticketId: string, expiresIn: number): Promise { - return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/expires-in`, {expiresIn}); - } - - /** - * Set Smart Transfer ticket external id - * @param ticketId - * @param externalRefId - */ - public setSmartTransferTicketExternalId(ticketId: string, externalRefId: string): Promise { - return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/external-id`, {externalRefId}); - } - - /** - * Submit Smart Transfers ticket - * @param ticketId - * @param expiresIn - */ - public submitSmartTransferTicket(ticketId: string, expiresIn: number): Promise { - return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/submit`, {expiresIn}); - } - - /** - * Fulfill Smart Transfers ticket - * @param ticketId - */ - public fulfillSmartTransferTicket(ticketId: string): Promise { - return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/fulfill`, {}); - } - - /** - * Cancel Smart Transfers ticket - * @param ticketId - */ - public cancelSmartTransferTicket(ticketId: string): Promise { - return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/cancel`, {}); - } - - /** - * Create Smart Transfers ticket term - * @param ticketId - * @param data - */ - public createSmartTransferTicketTerm(ticketId: string, data: SmartTransfersTicketTermPayload): Promise { - return this.apiClient.issuePostRequest(`/v1/smart-transfers/${ticketId}/terms`, data); - } - - /** - * Fet Smart Transfers ticket term - * @param ticketId - * @param termId - */ - public getSmartTransferTicketTerms(ticketId: string, termId: string): Promise { - return this.apiClient.issueGetRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}`); - } - - /** - * Update Smart Transfers ticket term - * @param ticketId - * @param termId - * @param data - */ - public updateSmartTransferTicketTerms(ticketId: string, termId: string, data: SmartTransfersTicketTermPayload): Promise { - return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}`, data); - } - - /** - * Fund Smart Transfers ticket term - * @param ticketId - * @param termId - * @param data - */ - public fundSmartTransferTicketTerm(ticketId: string, termId: string, data: SmartTransfersTicketTermFundPayload): Promise { - return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}/fund`, data); - } - - /** - * Manually fund Smart Transfers ticket term - * @param ticketId - * @param termId - * @param txHash - */ - public manuallyFundSmartTransferTicketTerms(ticketId: string, termId: string, txHash: string): Promise { - return this.apiClient.issuePutRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}/manually-fund`, { txHash }); - } - - /** - * Set Smart Transfers user group ids. User group ids are used for Smart Transfer notifications - * @param userGroupIds - */ - public setSmartTransferTicketUserGroups(userGroupIds: string[]): Promise { - return this.apiClient.issuePostRequest(`/v1/smart-transfers/settings/user-groups`, { userGroupIds }); - } - - /** - * Get Smart Transfers user group ids. User group ids are used for Smart Transfer notifications - */ - public getSmartTransferTicketUserGroups(): Promise { - return this.apiClient.issueGetRequest(`/v1/smart-transfers/settings/user-groups`); - } - - /** - * Delete Smart Transfers ticket term - * @param ticketId - * @param termId - */ - public deleteSmartTransferTicketTerms(ticketId: string, termId: string): Promise { - return this.apiClient.issueDeleteRequest(`/v1/smart-transfers/${ticketId}/terms/${termId}`); - } - - private getCommaSeparatedList(items: Array): string | undefined { - return items ? items.join(",") : undefined; - } - - /** - * Get list of jobs for current tenant - * @param fromTime beggining of time range in MS since 1970 - * @param toTime ending of time range in MS since 1970 - */ - public getJobs(fromTime: number, toTime: number): Promise { - return this.apiClient.issueGetRequest(`/v1/batch/jobs?fromTime=${fromTime}&toTime=${toTime}`); - } - - /** - * Get job info by job ID - * @param jobId - */ - public getJob(jobId: string): Promise { - return this.apiClient.issueGetRequest(`/v1/batch/${jobId}`); - } - - /** - * Get tasks belonging to given job - * @param jobId - */ - public getTasks(jobId: string): Promise { - return this.apiClient.issueGetRequest(`/v1/batch/${jobId}/tasks`); - } - - /** - * Cancel a job by ID - * @param jobId - */ - public cancelJob(jobId: string): Promise { - return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/cancel`, {}); - } - - /** - * Pause a job by ID - * @param jobId - */ - public pauseJob(jobId: string): Promise { - return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/pause`, {}); - } - - /** - * Continue a job by ID - * @param jobId - */ - public continueJob(jobId: string): Promise { - return this.apiClient.issuePostRequest(`/v1/batch/${jobId}/continue`, {}); - } - - /** - * Create multiple vault accounts in one bulk operation - * @param count number of vault accounts - */ - public createVaultAccountsBulk(count: number, assetId: string): Promise { - const body = { - count, - assetId - }; - return this.apiClient.issuePostRequest(`/v1/vault/accounts/bulk`, body); - } - - /** - * Create multiple vault wallets in one bulk operation - * @param count number of vault accounts - */ - public createVaultWalletsBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string): Promise { - const body = { - assetId, - vaultAccountIdFrom, - vaultAccountIdTo - }; - return this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body); - } -} diff --git a/src mine/iauth-provider.ts b/src mine/iauth-provider.ts deleted file mode 100644 index afbfa7e2..00000000 --- a/src mine/iauth-provider.ts +++ /dev/null @@ -1,5 +0,0 @@ -export interface IAuthProvider { - signJwt(path: string, bodyJson?: any): string; - - getApiKey(): string; -} diff --git a/src mine/ncw-api-client.ts b/src mine/ncw-api-client.ts deleted file mode 100644 index 1026bd5d..00000000 --- a/src mine/ncw-api-client.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { ApiClient } from "./api-client"; -import { - AssetResponse, - Web3PagedResponse, - NCW, -} from "./types"; -import { NcwSdk } from "./ncw-sdk"; - -export class NcwApiClient implements NcwSdk { - private readonly NCW_BASE_PATH = "/v1/ncw/wallets"; - - constructor(private readonly apiClient: ApiClient) { } - - public async createWallet(): Promise<{ walletId: string; enabled: boolean; }> { - return await this.apiClient.issuePostRequest( - `${this.NCW_BASE_PATH}`, - {}); - } - - public async getWallet(walletId: string): Promise<{ walletId: string; enabled: boolean; }> { - return await this.apiClient.issueGetRequest( - `${this.NCW_BASE_PATH}/${walletId}`); - } - - public async enableWallet(walletId: string, enabled: boolean): Promise { - return await this.apiClient.issuePutRequest( - `${this.NCW_BASE_PATH}/${walletId}/enable`, - { enabled }); - } - - public async getWalletDevices(walletId: string): Promise { - return await this.apiClient.issueGetRequest( - `${this.NCW_BASE_PATH}/${walletId}/devices/`); - } - - public async enableWalletDevice(walletId: string, deviceId: string, enabled: boolean): Promise { - return await this.apiClient.issuePutRequest( - `${this.NCW_BASE_PATH}/${walletId}/devices/${deviceId}/enable`, - { enabled }); - } - - public async invokeWalletRpc(walletId: string, deviceId: string, payload: string): Promise<{ result: string; } | { error: { message: string; code?: number; }; }> { - return await this.apiClient.issuePostRequest( - `${this.NCW_BASE_PATH}/${walletId}/devices/${deviceId}/invoke`, - { payload }); - } - - public async createWalletAccount(walletId: string): Promise<{ - walletId: string; - accountId: number; - }> { - return await this.apiClient.issuePostRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts`, - {}); - } - - public async getWallets({ pageCursor, pageSize, sort, order }: NCW.GetWalletsPayload = {}): Promise> { - const params = new URLSearchParams({ - ...(pageCursor && { pageCursor }), - ...(pageSize && { pageSize: pageSize.toString() }), - ...(sort && { sort }), - ...(order && { order }), - }); - - return await this.apiClient.issueGetRequest(`${this.NCW_BASE_PATH}?${params.toString()}`); - } - - public async getWalletAccounts(walletId: string, { pageCursor, pageSize, sort, order }: NCW.GetWalletsPayload = {}): Promise> { - const params = new URLSearchParams({ - ...(pageCursor && { pageCursor }), - ...(pageSize && { pageSize: pageSize.toString() }), - ...(sort && { sort }), - ...(order && { order }), - }); - - return await this.apiClient.issueGetRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts?${params.toString()}`); - } - - public async getWalletAccount(walletId: string, accountId: number): Promise<{ - walletId: string; - accountId: number; - }> { - return await this.apiClient.issueGetRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}`); - } - - public async getWalletAssets(walletId: string, accountId: number, { pageCursor, pageSize, sort, order }: NCW.GetWalletAssetsPayload = {}): Promise> { - const params = new URLSearchParams({ - ...(pageCursor && { pageCursor }), - ...(pageSize && { pageSize: pageSize.toString() }), - ...(sort && { sort }), - ...(order && { order }), - }); - - return await this.apiClient.issueGetRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets?${params.toString()}`); - } - - public async getWalletAsset(walletId: string, accountId: number, assetId: string): Promise { - return await this.apiClient.issueGetRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}`); - } - - public async activateWalletAsset(walletId: string, accountId: number, assetId: string): Promise { - return await this.apiClient.issuePostRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}`, {}); - } - - public async getWalletAssetAddresses(walletId: string, accountId: number, assetId: string, { pageCursor, pageSize, sort, order }: NCW.GetWalletAddressesPayload = {}): Promise> { - const params = new URLSearchParams({ - ...(pageCursor && { pageCursor }), - ...(pageSize && { pageSize: pageSize.toString() }), - ...(sort && { sort }), - ...(order && { order }), - }); - - return await this.apiClient.issueGetRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}/addresses?${params.toString()}`); - } - - public async getWalletAssetBalance(walletId: string, accountId: number, assetId: string): Promise { - return await this.apiClient.issueGetRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}/balance`); - } - - public async refreshWalletAssetBalance(walletId: string, accountId: number, assetId: string): Promise { - return await this.apiClient.issuePutRequest( - `${this.NCW_BASE_PATH}/${walletId}/accounts/${accountId}/assets/${assetId}/balance`, - {}); - } -} \ No newline at end of file diff --git a/src mine/ncw-sdk.ts b/src mine/ncw-sdk.ts deleted file mode 100644 index 25f68318..00000000 --- a/src mine/ncw-sdk.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { - AssetResponse, Web3PagedResponse, NCW, -} from "./types"; - -export interface NcwSdk { - /** - * Create a new NCW wallet - */ - createWallet(): Promise<{ walletId: string; enabled: boolean; }>; - - /** - * Get a NCW wallet - * - * @param {string} walletId - */ - getWallet(walletId: string): Promise<{ walletId: string; enabled: boolean; }>; - - /** - * Enable a NCW wallet - * - * @param {string} walletId - * @param {boolean} enabled - */ - enableWallet(walletId: string, enabled: boolean): Promise; - - - /** - * Get NCW wallet devices - * - * @param {string} walletId - * @return {*} {Promise} - */ - getWalletDevices(walletId: string): Promise; - - /** - * Set NCW wallet device's enabled state - * - * @param {string} walletId - * @param {string} deviceId - * @param {boolean} enabled - * @return {*} {Promise} - */ - enableWalletDevice(walletId: string, deviceId: string, enabled: boolean): Promise; - - /** - * Invoke NCW wallet RPC call - * - * @param {string} walletId - * @param {string} deviceId - * @param {string} payload - * @return {*} {(Promise<{ result: string } | { error: { message: string, code?: number } }>)} - */ - invokeWalletRpc(walletId: string, deviceId: string, payload: string): Promise<{ result: string; } | { error: { message: string; code?: number; }; }>; - - /** - * Create a new NCW wallet account - * - * @param {string} walletId - */ - createWalletAccount(walletId: string): Promise<{ - walletId: string; - accountId: number; - }>; - - /** - * Get NCW wallets - * - * @param {GetWalletsPayload} { pageCursor, pageSize, sort, order } - * @return {*} {Promise>} - */ - getWallets({ pageCursor, pageSize, sort, order }: NCW.GetWalletsPayload): Promise>; - - /** - * Get NCW accounts - * - * @param {string} walletId - * @param {GetWalletsPayload} [{ pageCursor, pageSize, sort, order }] - */ - getWalletAccounts(walletId: string, { pageCursor, pageSize, sort, order }?: NCW.GetWalletsPayload): Promise>; - - /** - * Get a NCW account - * - * @param {string} walletId - * @param {number} accountId - */ - getWalletAccount(walletId: string, accountId: number): Promise<{ - walletId: string; - accountId: number; - }>; - - /** - * Get NCW assets - * - * @param {string} walletId - * @param {number} accountId - * @param {GetWalletAssetsPayload} [{ pageCursor, pageSize, sort, order }] - * @return {*} {Promise>} - */ - getWalletAssets(walletId: string, accountId: number, { pageCursor, pageSize, sort, order }?: NCW.GetWalletAssetsPayload): Promise>; - - /** - * Get a NCW asset - * - * @param {string} walletId - * @param {number} accountId - * @param {string} assetId - * @return {*} {Promise} - */ - getWalletAsset(walletId: string, accountId: number, assetId: string): Promise; - - /** - * Activate a NCW asset - * - * @param {string} walletId - * @param {number} accountId - * @param {string} assetId - * @return {*} {Promise} - */ - activateWalletAsset(walletId: string, accountId: number, assetId: string): Promise; - - /** - * Get a NCW asset addresses - * - * @param {string} walletId - * @param {number} accountId - * @param {string} assetId - * @param {GetWalletAddressesPayload} { pageCursor, pageSize, sort, order } - * @return {*} {Promise>} - */ - getWalletAssetAddresses(walletId: string, accountId: number, assetId: string, { pageCursor, pageSize, sort, order }?: NCW.GetWalletAddressesPayload): Promise>; - - /** - * Get a NCW asset balance - * - * @param {string} walletId - * @param {number} accountId - * @param {string} assetId - * @return {*} {Promise} - */ - getWalletAssetBalance(walletId: string, accountId: number, assetId: string): Promise; - - /** - * refresh a NCW asset balance - * - * @param {string} walletId - * @param {number} accountId - * @param {string} assetId - * @return {*} {Promise} - */ - refreshWalletAssetBalance(walletId: string, accountId: number, assetId: string): Promise; -} \ No newline at end of file diff --git a/src mine/pii-client.ts b/src mine/pii-client.ts deleted file mode 100644 index 3d82dbe7..00000000 --- a/src mine/pii-client.ts +++ /dev/null @@ -1,83 +0,0 @@ -import PIIsdk, { PIIEncryptionMethod } from "@notabene/pii-sdk"; -import { TransactionArguments, TravelRule, TravelRuleEncryptionOptions, TravelRuleOptions } from "./types"; -import * as util from "util"; - -const requiredFields = [ - "baseURLPII", - "audiencePII", - "clientId", - "clientSecret", - "authURL", - "jsonDidKey", -]; - -export class PIIEncryption { - public toolset: PIIsdk; - - constructor(private readonly config: TravelRuleOptions) { - this.config = config; - const missingFields = requiredFields.filter( - (field) => !(field in this.config) - ); - - if (missingFields.length > 0) { - throw new Error( - `Missing PII configuration fields: ${missingFields.join(", ")}` - ); - } - - this.toolset = new PIIsdk({ - piiURL: config.baseURLPII, - audience: config.audiencePII, - clientId: config.clientId, - clientSecret: config.clientSecret, - authURL: config.authURL, - }); - } - - async hybridEncode(transaction: TransactionArguments, travelRuleEncryptionOptions?: TravelRuleEncryptionOptions) { - const { travelRuleMessage } = transaction; - const pii = travelRuleMessage.pii || { - originator: travelRuleMessage.originator, - beneficiary: travelRuleMessage.beneficiary, - }; - const { jsonDidKey } = this.config; - const counterpartyDIDKey = travelRuleEncryptionOptions?.beneficiaryPIIDidKey; - - let piiIvms; - - try { - piiIvms = await this.toolset.generatePIIField({ - pii, - originatorVASPdid: travelRuleMessage.originatorVASPdid, - beneficiaryVASPdid: travelRuleMessage.beneficiaryVASPdid, - counterpartyDIDKey, - keypair: JSON.parse(jsonDidKey), - senderDIDKey: JSON.parse(jsonDidKey).did, - encryptionMethod: travelRuleEncryptionOptions?.sendToProvider - ? PIIEncryptionMethod.HYBRID - : PIIEncryptionMethod.END_2_END, - }); - } catch (error) { - const errorMessage = error.message || error.toString(); - const errorDetails = JSON.stringify(error); - throw new Error(`Failed to generate PII fields error: ${errorMessage}. Details: ${errorDetails}`); - } - - transaction.travelRuleMessage = this.travelRuleMessageHandler(travelRuleMessage, piiIvms); - - return transaction; - } - - private travelRuleMessageHandler(travelRuleMessage: TravelRule, piiIvms: any): TravelRule { - travelRuleMessage.beneficiary = piiIvms.beneficiary; - travelRuleMessage.originator = piiIvms.originator; - - travelRuleMessage.beneficiary = { - originatorPersons: piiIvms.beneficiary.beneficiaryPersons, - accountNumber: piiIvms.beneficiary.accountNumber, - }; - - return travelRuleMessage; - } -} \ No newline at end of file diff --git a/src mine/types.ts b/src mine/types.ts deleted file mode 100644 index 829b91a8..00000000 --- a/src mine/types.ts +++ /dev/null @@ -1,1763 +0,0 @@ -import { AxiosResponseHeaders } from "axios"; - -export interface Web3PagedResponse { - data: T[]; - paging?: Paging; -} - -export type APIResponseHeaders = AxiosResponseHeaders & {"x-request-id"?: string}; - -export interface VaultAccountResponse { - id: string; - name: string; - hiddenOnUI?: boolean; - assets?: AssetResponse[]; - customerRefId?: string; - autoFuel?: boolean; -} - -export enum VirtualAffiliation { - OFF_EXCHANGE = "OFF_EXCHANGE", - DEFAULT = "DEFAULT" -} - -export interface BalanceRewardInfo { - pendingRewards: string; -} - -export interface AssetResponse { - id: string; - total: string; - /** - * @deprecated Replaced by "total" - */ - balance?: string; - lockedAmount?: string; - available?: string; - pending?: string; - selfStakedCPU?: string; - selfStakedNetwork?: string; - pendingRefundCPU?: string; - pendingRefundNetwork?: string; - totalStakedCPU?: string; - totalStakedNetwork?: string; - rewardInfo?: BalanceRewardInfo; - blockHeight?: string; - blockHash?: string; - allocatedBalances?: { - allocationId: string; - thirdPartyAccountId?: string; - affiliation?: VirtualAffiliation; - virtualType?: VirtualType; - total: string; - available: string; - pending?: string; - frozen?: string; - locked?: string; - }[]; -} - -export interface UnfreezeTransactionResponse { - success: boolean; -} - -export interface VaultAssetResponse { - id: string; - address: string; - legacyAddress: string; - enterpriseAddress?: string; - tag: string; - eosAccountName?: string; - status?: VaultAssetActivationStatus; - activationTxId?: string; -} - -export enum VaultAssetActivationStatus { - PENDING_ACTIVATION = "PENDING_ACTIVATION", - ACTIVATION_FAILED = "ACTIVATION_FAILED", - READY = "READY" -} - -export interface WalletContainerResponse { - id: string; - name: string; - assets: WalletAssetType[]; - customerRefId?: string; -} - -export interface ExternalWalletAsset { - id: string; - status: string; - address?: string; - tag?: string; - activationTime?: string; -} - -export interface InternalWalletAsset extends ExternalWalletAsset { - balance: string; -} - -export interface CreateTransactionResponse { - id: string; - status: string; - systemMessages?: ISystemMessageInfo[]; -} - -export interface EstimateFeeResponse { - low: EstimatedFee; - medium: EstimatedFee; - high: EstimatedFee; -} - -export interface EstimateTransactionFeeResponse { - low: EstimatedTransactionFee; - medium: EstimatedTransactionFee; - high: EstimatedTransactionFee; -} - -export interface EstimatedFee { - networkFee?: string; - gasPrice?: string; - feePerByte?: string; - baseFee?: string; - priorityFee?: string; -} - -export interface EstimatedTransactionFee { - networkFee?: string; - gasPrice?: string; - gasLimit?: string; - feePerByte?: string; - baseFee?: string; - priorityFee?: string; -} - -export interface TransferPeerPath { - type?: PeerType; - id?: string; - walletId?: string; - virtualId?: string; - virtualType?: VirtualType; - address?: string; -} - -export interface DestinationTransferPeerPath { - type: PeerType; - id?: string; - walletId?: string; - virtualId?: string; - virtualType?: VirtualType; - oneTimeAddress?: IOneTimeAddress; -} - -export interface IOneTimeAddress { - address: string; - tag?: string; -} - -export interface DepositAddressResponse { - assetId?: string; - address: string; - tag?: string; - description?: string; - type?: string; - customerRefId?: string; - addressFormat?: string; - legacyAddress?: string; - enterpriseAddress?: string; -} - -export interface GenerateAddressResponse { - address: string; - tag?: string; - legacyAddress?: string; - enterpriseAddress?: string; -} - -export enum SigningAlgorithm { - MPC_ECDSA_SECP256K1 = "MPC_ECDSA_SECP256K1", - MPC_ECDSA_SECP256R1 = "MPC_ECDSA_SECP256R1", - MPC_EDDSA_ED25519 = "MPC_EDDSA_ED25519" -} - -export interface RawMessageData { - messages: RawMessage[]; - algorithm?: SigningAlgorithm; -} - -export interface RawMessage { - content: string; - bip44addressIndex?: number; - bip44change?: number; - derivationPath?: number[]; -} - -export interface TransactionDestination { - amount: string | number; - destination: DestinationTransferPeerPath; -} - -export interface TransactionArgumentsFeePayerInfo { - feePayerAccountId: string; -} - -export interface TransactionArguments { - assetId?: string; - source?: TransferPeerPath; - destination?: DestinationTransferPeerPath; - amount?: number | string; - operation?: TransactionOperation; - fee?: number | string; - feeLevel?: FeeLevel; - failOnLowFee?: boolean; - maxFee?: string; - priorityFee?: number | string; - gasPrice?: number | string; - gasLimit?: number | string; - note?: string; - cpuStaking?: number; - networkStaking?: number; - autoStaking?: boolean; - customerRefId?: string; - extraParameters?: object; - destinations?: TransactionDestination[]; - replaceTxByHash?: string; - externalTxId?: string; - treatAsGrossAmount?: boolean; - forceSweep?: boolean; - feePayerInfo?: TransactionArgumentsFeePayerInfo; - travelRuleMessage?: TravelRule; -} - -export type OwnershipProof = { - type: string; - proof: string; -}; - -export enum TravelRuleAddressTypeCode { - HOME = "HOME", - BIZZ = "BIZZ", - GEOG = "GEOG" -} - -type TravelRulePersonAddress = { - addressType?: TravelRuleAddressTypeCode; - department?: string; - subDepartment?: string; - streetName?: string; - buildingNumber?: string; - buildingName?: string; - floor?: string; - postBox?: string; - room?: string; - postCode?: string; - townName?: string; - townLocationName?: string; - districtName?: string; - countrySubDivision?: string; - addressLine?: string[]; - country?: string; -}; - -export interface ValidateTravelRuleVaspInfo { - transactionAsset: string; - destination: string; - transactionAmount: string; - originatorVASPdid: string; - originatorEqualsBeneficiary: boolean; - beneficiaryVASPdid?: string; - beneficiaryVASPname?: string; - beneficiaryName?: string; - beneficiaryAccountNumber?: string; - beneficiaryAddress?: TravelRulePersonAddress; - beneficiaryProof?: OwnershipProof; - travelRuleBehavior?: boolean; -} - -export interface ValidateCreateTravelRuleTransaction { - transactionAsset: string; - transactionAmount: string; - originatorDid?: string; - beneficiaryDid?: string; - originatorVASPdid: string; - beneficiaryVASPdid?: string; - beneficiaryVASPname?: string; - transactionBlockchainInfo?: { - origin?: string; - destination?: string; - txHash?: string; - }; - originator?: TROriginator; - beneficiary?: TROriginator; - pii?: PII; - pii_url?: string; - protocol?: string; - notificationEmail?: string; - originatorProof?: OwnershipProof; - beneficiaryProof?: OwnershipProof; - skipBeneficiaryDataValidation?: boolean; -} - -export interface TravelRule { - originatorRef?: string; - beneficiaryRef?: string; - originatorVASPdid: string; - travelRuleBehavior?: boolean; - beneficiaryVASPdid: string; - beneficiaryVASPname?: string; - originator: TROriginator; - beneficiary: TRBeneficiary; - pii?: PII; - jsonDidKey?: string; -} - -export interface TROriginator { - originatorPersons?: TROriginatorPerson[]; - accountNumber?: string[]; -} - -export interface TROriginatorPerson { - naturalPerson?: TRNaturalPerson; - legalPerson?: TRNaturalPerson; -} - -export interface TRNaturalPerson { - name: TRName[]; - geographicAddress?: TRGeographicAddress[]; - nationalIdentification?: TRNationalIdentification; - dateAndPlaceOfBirth?: TRDateAndPlaceOfBirth; -} - -export interface TRName { - nameIdentifier?: TRNameIdentifier[]; -} - -export interface TRNameIdentifier { - primaryIdentifier?: string; - secondaryIdentifier?: string; -} - -export interface TRGeographicAddress { - streetName?: string; - townName?: string; - country?: string; - buildingNumber?: string; - postCode?: string; - addressType?: string; - department?: string; - subDepartment?: string; - buildingName?: string; - floor?: string; - postBox?: string; - room?: string; - townLocationName?: string; - districtName?: string; - countrySubDivision?: string; - addressLine?: string; -} - -export interface TRNationalIdentification { - nationalIdentifier?: string; - nationalIdentifierType?: string; - registrationAuthority?: string; - countryOfIssue?: string; -} - -export interface TRDateAndPlaceOfBirth { - dateOfBirth?: string; - placeOfBirth?: string; -} - -export interface TRBeneficiary { - beneficiaryPersons?: TRBeneficiaryPerson[]; - originatorPersons?: TROriginatorPerson[]; - accountNumber?: string[]; -} - -export interface TRBeneficiaryPerson { - naturalPerson?: TRNaturalPerson; -} - -interface PII { - originator?: TROriginator; - beneficiary?: TRBeneficiary; -} - -export interface TravelRuleOptions { - clientId: string; - clientSecret: string; - authURL?: string; - audience?: string; - audiencePII?: string; - baseURL?: string; - baseURLPII?: string; - jsonDidKey?: string; -} - -export interface TravelRuleEncryptionOptions { - beneficiaryPIIDidKey?: string; - sendToProvider?: boolean; -} - -export interface TravelRuleVasp { - did: string; - name: string; - verificationStatus: string; - addressLine1: string; - addressLine2: string; - city: string; - country: string; - emailDomains: string; - website: string; - logo: string; - legalStructure: string; - legalName: string; - yearFounded: string; - incorporationCountry: string; - isRegulated: string; - otherNames: string; - identificationType: string; - identificationCountry: string; - businessNumber: string; - regulatoryAuthorities: string; - jurisdictions: string; - street: string; - number: string; - unit: string; - postCode: string; - state: string; - certificates: string; - description: string; - travelRule_OPENVASP: string; - travelRule_SYGNA: string; - travelRule_TRISA: string; - travelRule_TRLIGHT: string; - travelRule_EMAIL: string; - travelRule_TRP: string; - travelRule_SHYFT: string; - travelRule_USTRAVELRULEWG: string; - createdAt: string; - createdBy: string; - updatedAt: string; - updatedBy: string; - lastSentDate: string; - lastReceivedDate: string; - documents: string; - hasAdmin: boolean; - isNotifiable: boolean; - issuers: { - name: { - issuerDid: string; - }; - nonce: { - issuerDid: string; - }; - }; - regulatoryStatus: string; - supervisoryAuthority: string; - registrationLicenseId: string; - statusStartDate: string; - statusExpirationDate: string; - lastChecked: string; - additionalInformation: string; - subsidiaryOf: string; - chainalysis_clusterName: string; - pii_didkey: string; - onboardingStatus: string; - compliancePhase: number; - vaspnetId: string; - node: string; - node_didkey: string; - parentGateway: string; - isActiveSender: boolean; - isActiveReceiver: boolean; - subsidiaries: string[]; -} - -export interface ValidateFullTravelRuleResult { - isValid: boolean; - type: string; - beneficiaryAddressType: string; - addressSource: string; - beneficiaryVASPname: string; - beneficiaryVASPdid: string; - errors: string[]; - warnings: string[]; -} - -export interface ValidateTravelRuleResult { - isValid: boolean; - type: string; - beneficiaryAddressType: string; - addressSource: string; - beneficiaryVASPdid: string; - warnings: string[]; -} - -export interface TravelRuleVaspFilter { - q?: string; - fields?: string[]; - page?: number; - per_page?: number; - order?: string; -} - -export enum Web3ConnectionFeeLevel { - HIGH = "HIGH", - MEDIUM = "MEDIUM", -} - -export enum FeeLevel { - HIGH = "HIGH", - MEDIUM = "MEDIUM", - LOW = "LOW" -} - -export interface ExchangeResponse { - id: string; - type: string; - name: string; - assets: AssetResponse[]; - isSubaccount: boolean; - status: string; -} - -export interface ConvertExchangeAssetResponse { - status: boolean; -} - -export interface FiatAccountResponse { - id: string; - type: string; - name: string; - address?: string; - assets: AssetResponse[]; -} - -export interface TransactionPageResponse { - transactions: TransactionResponse[]; - pageDetails: PageDetails; -} - -export interface PageDetails { - prevPage: string; - nextPage: string; -} - -export interface RewardInfo { - srcRewards?: string; - destRewards?: string; -} - -export interface FeePayerInfo { - feePayerAccountId?: string; -} - -export interface TransactionResponse { - id: string; - assetId: string; - source: TransferPeerPathResponse; - destination: TransferPeerPathResponse; - amount: number; - /** - * @deprecated Replaced by "networkFee" - */ - fee?: number; - networkFee: number; - amountUSD: number; - netAmount: number; - createdAt: number; - lastUpdated: number; - status: TransactionStatus; - txHash: string; - numOfConfirmations?: number; - subStatus?: string; - signedBy: string[]; - createdBy: string; - rejectedBy: string; - destinationAddress: string; - sourceAddress?: string; - destinationAddressDescription?: string; - destinationTag: string; - addressType: string; - note: string; - exchangeTxId: string; - requestedAmount: number; - serviceFee?: number; - feeCurrency: string; - amlScreeningResult?: AmlScreeningResult; - customerRefId?: string; - amountInfo?: AmountInfo; - feeInfo?: FeeInfo; - signedMessages?: SignedMessageResponse[]; - extraParameters?: any; - externalTxId?: string; - destinations?: TransactionResponseDestination[]; - blockInfo?: BlockInfo; - authorizationInfo?: AuthorizationInfo; - index?: number; - rewardInfo?: RewardInfo; - feePayerInfo?: FeePayerInfo; -} - -export interface AmountInfo { - amount?: string; - requestedAmount?: string; - netAmount?: string; - amountUSD?: string; -} - -export interface FeeInfo { - networkFee?: string; - serviceFee?: string; - gasPrice?: string; -} - -export interface TransactionResponseDestination { - amount?: string; - amountUSD?: string; - amlScreeningResult?: AmlScreeningResult; - destination?: TransferPeerPathResponse; - authorizationInfo?: AuthorizationInfo; -} - -export interface AmlScreeningResult { - provider?: string; - payload: any; - screeningStatus: string; - bypassReason: string; - timestamp: number; -} - -export interface TransferPeerPathResponse { - id: string; - type: PeerType; - name?: string; - subType?: string; - virtualType?: VirtualType; - virtualId?: string; - walletId?: string; -} - -export interface AuthorizationInfo { - allowOperatorAsAuthorizer: boolean; - logic: "OR" | "AND"; - groups: { - users: UserGroup; - th: number - }[]; -} - -export interface UserGroup { - [id: string]: string; -} - -export interface BlockInfo { - blockHeight?: string; - blockHash?: string; -} - -export interface SignedMessageResponse { - content: string; - algorithm: string; - derivationPath: number[]; - signature: { - fullSig: string; - r?: string; - s?: string; - v?: number; - }; - publicKey: string; -} - -export interface CancelTransactionResponse { - success: boolean; -} - -export interface OperationSuccessResponse { - success: boolean; -} - -export interface NetworkConnectionResponse { - id: string; - status: string; - remoteNetworkId: NetworkId; - localNetworkId: NetworkId; - routingPolicy?: NetworkConnectionRoutingPolicy; -} - -export interface NetworkIdResponse { - id: string; - name: string; - isDiscoverable: boolean; - routingPolicy?: NetworkIdRoutingPolicy; -} - -interface NetworkId { - id: string; - name: string; -} - -export interface CustomCryptoRoutingDest { - scheme: NetworkScheme.CUSTOM; - dstType: NetworkDestType.EXCHANGE_ACCOUNT | NetworkDestType.VAULT_ACCOUNT; - dstId: string; -} - -export interface CustomFiatRoutingDest { - scheme: NetworkScheme.CUSTOM; - dstType: NetworkDestType.FIAT_ACCOUNT; - dstId: string; -} - -export interface DefaultNetworkRoutingDest { - scheme: NetworkScheme.DEFAULT; -} - -export interface NoneNetworkRoutingDest { - scheme: NetworkScheme.NONE; -} - -export type NetworkConnectionCryptoRoutingDest = CustomCryptoRoutingDest | DefaultNetworkRoutingDest | NoneNetworkRoutingDest; -export type NetworkConnectionFiatRoutingDest = CustomFiatRoutingDest | DefaultNetworkRoutingDest | NoneNetworkRoutingDest; -export type NetworkIdCryptoRoutingDest = CustomCryptoRoutingDest | NoneNetworkRoutingDest; -export type NetworkIdFiatRoutingDest = CustomFiatRoutingDest | NoneNetworkRoutingDest; - -export interface NetworkConnectionRoutingPolicy { - crypto?: NetworkConnectionCryptoRoutingDest; - sen?: NetworkConnectionFiatRoutingDest; - signet?: NetworkConnectionFiatRoutingDest; - sen_test?: NetworkConnectionFiatRoutingDest; - signet_test?: NetworkConnectionFiatRoutingDest; -} - -export interface NetworkIdRoutingPolicy { - crypto?: NetworkIdCryptoRoutingDest; - sen?: NetworkIdFiatRoutingDest; - signet?: NetworkIdFiatRoutingDest; - sen_test?: NetworkIdFiatRoutingDest; - signet_test?: NetworkIdFiatRoutingDest; -} - -export enum NetworkScheme { - DEFAULT = "DEFAULT", - CUSTOM = "CUSTOM", - NONE = "NONE", -} - -export enum NetworkDestType { - VAULT_ACCOUNT = "VAULT", - EXCHANGE_ACCOUNT = "EXCHANGE", - FIAT_ACCOUNT = "FIAT_ACCOUNT", -} - -export interface TransactionFilter { - before?: number; - after?: number; - status?: TransactionStatus; - orderBy?: TransactionOrder; - limit?: number; - txHash?: string; - assets?: string; - sourceType?: PeerType; - destType?: PeerType; - sourceId?: string; - destId?: string; -} - -export interface NFTOwnershipFilter { - blockchainDescriptor?: string; - vaultAccountIds?: string[]; - collectionIds?: string[]; - ids?: string[]; - pageCursor?: string; - pageSize?: number; - sort?: GetOwnedNFTsSortValues[]; - order?: OrderValues; - status?: NFTOwnershipStatus; - search?: string; - ncwId?: string; - ncwAccountIds?: string[]; - walletType?: NFTOwnershipWalletType; -} - -export interface NFTOwnedCollectionsFilter { - search?: string; - status?: NFTOwnershipStatus; - ncwId?: string; - walletType?: NFTOwnershipWalletType; - pageCursor?: string; - pageSize?: number; - sort?: GetOwnedCollectionsSortValues[]; - order?: OrderValues; -} - -export interface NFTOwnedAssetsFilter { - search?: string; - status?: NFTOwnershipStatus; - ncwId?: string; - walletType?: NFTOwnershipWalletType; - pageCursor?: string; - pageSize?: number; - sort?: GetOwnedAssetsSortValues[]; - order?: OrderValues; -} - -export interface GetNFTsFilter { - ids: string[]; - pageCursor?: string; - pageSize?: number; - sort?: GetNFTsSortValues[]; - order?: OrderValues; -} - -class MediaEntity { - url: string; - contentType: string; -} - -interface NFTCollection { - id: string; - name: string; - symbol: string; -} - -export interface Paging { - next: string; -} - -export interface Token { - id: string; - tokenId: string; - standard: string; - blockchainDescriptor: string; - description: string; - name: string; - media: MediaEntity[]; - metadataURI?: string; - cachedMetadataURI?: string; - collection?: NFTCollection; -} - -export interface BaseTokenWithBalance extends Token { - balance: string; - ownershipStartTime: number; - ownershipLastUpdateTime: number; -} - -export type TokenWithBalance = (WorkspaceWalletIdentifier | NonCustodialWalletIdentifier) & BaseTokenWithBalance; - -export interface CollectionOwnership extends NFTCollection { - standard?: string; - blockchainDescriptor: string; - contractAddress?: string; -} - -export interface TransactionPageFilter { - before?: number; - after?: number; - status?: TransactionStatus; - limit?: number; - txHash?: string; - assets?: string; - sourceType?: PeerType; - destType?: PeerType; - sourceId?: string; - destId?: string; -} - -export enum TransactionOrder { - CREATED_AT = "createdAt", - LAST_UPDATED = "lastUpdated" -} - -export enum TransactionStatus { - SUBMITTED = "SUBMITTED", - QUEUED = "QUEUED", - PENDING_SIGNATURE = "PENDING_SIGNATURE", - PENDING_AUTHORIZATION = "PENDING_AUTHORIZATION", - PENDING_3RD_PARTY_MANUAL_APPROVAL = "PENDING_3RD_PARTY_MANUAL_APPROVAL", - PENDING_3RD_PARTY = "PENDING_3RD_PARTY", - /** - * @deprecated - */ - PENDING = "PENDING", - BROADCASTING = "BROADCASTING", - CONFIRMING = "CONFIRMING", - /** - * @deprecated Replaced by "COMPLETED" - */ - CONFIRMED = "CONFIRMED", - COMPLETED = "COMPLETED", - PENDING_AML_SCREENING = "PENDING_AML_SCREENING", - PARTIALLY_COMPLETED = "PARTIALLY_COMPLETED", - CANCELLING = "CANCELLING", - CANCELLED = "CANCELLED", - REJECTED = "REJECTED", - FAILED = "FAILED", - TIMEOUT = "TIMEOUT", - BLOCKED = "BLOCKED" -} - -export enum PeerType { - VAULT_ACCOUNT = "VAULT_ACCOUNT", - EXCHANGE_ACCOUNT = "EXCHANGE_ACCOUNT", - INTERNAL_WALLET = "INTERNAL_WALLET", - EXTERNAL_WALLET = "EXTERNAL_WALLET", - UNKNOWN = "UNKNOWN", - NETWORK_CONNECTION = "NETWORK_CONNECTION", - FIAT_ACCOUNT = "FIAT_ACCOUNT", - COMPOUND = "COMPOUND", - ONE_TIME_ADDRESS = "ONE_TIME_ADDRESS", - OEC_PARTNER = "OEC_PARTNER", - END_USER_WALLET = "END_USER_WALLET", -} - -export enum VirtualType { - OFF_EXCHANGE = "OFF_EXCHANGE", - DEFAULT = "DEFAULT", - OEC_FEE_BANK = "OEC_FEE_BANK" -} - -export enum TransactionOperation { - TRANSFER = "TRANSFER", - MINT = "MINT", - BURN = "BURN", - SUPPLY_TO_COMPOUND = "SUPPLY_TO_COMPOUND", - REDEEM_FROM_COMPOUND = "REDEEM_FROM_COMPOUND", - RAW = "RAW", - CONTRACT_CALL = "CONTRACT_CALL", - TYPED_MESSAGE = "TYPED_MESSAGE", -} - -export enum Web3ConnectionType { - WALLET_CONNECT = "WalletConnect" -} - -export enum Web3ConnectionMethod { - MOBILE = "MOBILE", - DESKTOP = "DESKTOP", - API = "API" -} - -export interface AllocateFundsRequest { - allocationId: string; - amount: string; - treatAsGrossAmount?: boolean; -} - -export interface DeallocateFundsRequest { - allocationId: string; - amount: string; -} - -export interface AllocateFundsResponse { - id: string; - status: string; -} - -export interface CreateTransferTicketArgs { - externalTicketId: string; - description?: string; - terms: { - networkConnectionId: string; - outgoing: boolean; - asset: string; - amount: string; - note: string; - }[]; -} - -export enum TransferTicketStatus { - OPEN = "OPEN", - PARTIALLY_FULFILLED = "PARTIALLY_FULFILLED", - FULFILLED = "FULFILLED", - FAILED = "FAILED", - CANCELED = "CANCELED" -} - -export enum TransferTicketTermStatus { - OPEN = "OPEN", - FULFILLED = "FULFILLED" -} - -export interface TransferTicketResponse { - ticketId: string; - externalTicketId: string; - description: string; - status: TransferTicketStatus; - terms: TermResponse[]; -} - -export interface TermResponse { - termId: string; - networkConnectionId: string; - outgoing: boolean; - asset: string; - amount: string; - txIds: string[]; - status: TransferTicketTermStatus; - note: string; -} - -export interface ExecuteTermArgs { - source: { - type: string; - id: string; - }; - fee?: number; - gasPrice?: number; -} - -export interface CreateTransferTicketResponse { - ticketId: string; -} - -export interface PublicKeyInfoArgs { - algorithm?: string; - derivationPath?: number[]; - compressed?: boolean; -} - -export interface PublicKeyInfoForVaultAccountArgs { - assetId: string; - vaultAccountId: number; - change: number; - addressIndex: number; - compressed?: boolean; -} - -export interface GasStationInfo { - balance: { [asset: string]: string }; - configuration: { - gasThreshold: string; - gasCap: string; - maxGasPrice: string; - }; -} - -export interface PublicKeyResponse { - status: number; - algorithm: string; - derivationPath: number[]; - publicKey: string; -} - -export interface PublicKeyInformation { - algorithm: string; - derivationPath: number[]; - publicKey: String; -} - -export interface DropTransactionResponse { - success: boolean; - transactions?: string[]; -} - -export interface MaxSpendableAmountResponse { - maxSpendableAmount: string; -} - -export interface MaxBip44IndexUsedResponse { - maxBip44AddressIndexUsed?: number; - maxBip44ChangeAddressIndexUsed?: number; -} - -export interface VaultAccountsFilter { - namePrefix?: string; - nameSuffix?: string; - minAmountThreshold?: number; - assetId?: string; -} - -export interface PagedVaultAccountsRequestFilters { - namePrefix?: string; - nameSuffix?: string; - minAmountThreshold?: number; - assetId?: string; - orderBy?: "ASC" | "DESC"; - limit?: number; // for default and max limit values please see: https://docs.fireblocks.com/api/swagger-ui/#/ - before?: string; - after?: string; -} - -export interface PagedVaultAccountsResponse { - accounts: VaultAccountResponse[]; - paging?: { - before?: string; - after?: string; - }; - previousUrl?: string; - nextUrl?: string; -} - -export interface VaultBalancesFilter { - accountNamePrefix?: string; - accountNameSuffix?: string; -} - -export interface RequestOptions { - idempotencyKey?: string; - ncw?: { - walletId?: string; - }; -} - -export interface ValidateAddressResponse { - isValid: boolean; - isActive: boolean; - requiresTag: boolean; -} - -export interface AssetTypeResponse { - id: string; - name: string; - type: string; - contractAddress: string; - nativeAsset: string; - decimals?: number; -} - -export interface User { - id: string; - firstName: string; - lastName: string; - email: string; - enabled: boolean; - role: string; -} - -export interface UsersGroup { - id: string; - name: string; - membersIds: string[]; - status: string; -} - -export interface ResendWebhooksResponse { - webhooksCount: number; -} - -export interface OffExchangeEntityResponse { - id: string; - vaultAccountId: string; - thirdPartyAccountId: string; - balance?: { - [assetId: string]: { - total?: string; - locked?: string; - pending?: string; - frozen?: string; - }; - }; -} - -export interface SettleOffExchangeAccountResponse { - message: string; - code: SettleResponseCode; -} - -export enum SettleResponseCode { - NONE = 0, - NOTHING_TO_SETTLE = 1 -} - -export interface GetSettlementTransactionsResponse { - toExchange: ToExchangeTransaction[]; - toCollateral: ToCollateralTransaction[]; -} - -export interface ToExchangeTransaction { - assetId: string; - amount: string; - dstAddress: string; - dstTag: string; -} - -export interface ToCollateralTransaction { - assetId: string; - amount: string; - fee?: string; - srcAddress?: string; - srcTag?: string; -} - -export interface AddCollateralTransactionRequest { - transactionRequest: TransactionArguments; - isSrcCollateral?: boolean; -} - -export interface RemoveCollateralTransactionRequest { - transactionRequest: TransactionArguments; - isDstCollateral?: boolean; -} - -export interface SettlementRequest { - mainExchangeAccountId: string; -} - -enum InitiatorType { - EXCHANGE = "EXCHANGE", - TRADER = "TRADER" -} - -export interface InitiatedTransactions { - toExchange: SettlementTransactionResponse[]; - toCollateral: SettlementTransactionResponse[]; -} - -export interface SettlementTransactionResponse { - txId: string; - status: TransactionStatus; -} - -export enum ExchangeReply { - REJECTED = "REJECTED", - NOT_NEEDED = "NOT_NEEDED", - FAILED = "FAILED" -} - -export interface SettlementResponse { - id: string; - initiator: InitiatorType; - exchangeReply?: ExchangeReply; - fireblocksInitiatedTransactions?: InitiatedTransactions; - exchangeRequestedTransactions?: GetSettlementTransactionsResponse; -} - -export interface SetFeePayerConfiguration { - feePayerAccountId: string; -} - -export interface FeePayerConfiguration { - feePayerAccountId: string; -} - -export interface BaseWeb3ConnectionPayload { - feeLevel: Web3ConnectionFeeLevel; -} -export interface WorkspaceWalletIdentifier { - vaultAccountId: number; -} - -export interface NonCustodialWalletIdentifier { - ncwId: string; - ncwAccountId: number; -} - -export interface WalletConnectConnectionPayload { - uri: string; - chainIds?: string[]; -} - -export type CreateWeb3ConnectionPayload = (WorkspaceWalletIdentifier | NonCustodialWalletIdentifier) & BaseWeb3ConnectionPayload; - -export type CreateWalletConnectPayload = CreateWeb3ConnectionPayload & WalletConnectConnectionPayload; - -export interface GetWeb3ConnectionsPayload { - pageCursor?: string; - pageSize?: number; - sort?: string; - filter?: { [filterProp: string]: string }; - order?: "ASC" | "DESC"; -} - -export interface CreateWeb3ConnectionResponse { - id: string; - sessionMetadata: SessionMetadata; -} - -export interface SessionMetadata { - appUrl: string; - appIcon?: string; - appName?: string; - appDescription?: string; -} - -export interface Session { - id: string; - vaultAccountId?: number; - ncwId?: string; - ncwAccountId?: number; - chainIds: string[]; - feeLevel: Web3ConnectionFeeLevel; - creationDate: string; - connectionType: Web3ConnectionType; - connectionMethod: Web3ConnectionMethod; - sessionMetadata: SessionMetadata; -} - -export enum TimePeriod { - DAY = "DAY", - WEEK = "WEEK" -} - -export interface Audit { - data?: any; - vendorId?: string; - tenantId?: string; - severity?: string; - createdAt?: string; - subject?: string; - event?: string; - user?: string; - email?: string; - txId?: string; - amount?: string; - transactionId?: string; - walletType?: string; - walletName?: string; - confirmationThreshold?: string; - sourceType?: string; - sourceName?: string; - sourceId?: string; - destination?: string; - destAddress?: string; - newNote?: string; - remoteType?: string; - destName?: string; - remoteId?: string; - note?: string; - signedBy?: string; - approvedBy?: string; - setBy?: string; - cancelType?: string; - fee?: string; - rule?: string; - screeningStatus?: string; - verdict?: string; - bypassReason?: string; - status?: string; - subStatus?: string; - ruleJsonStr?: string; - rejectedReason?: string; - failReason?: string; - oldRole?: string; - role?: string; - subjectUser?: string; - ip?: string; - accountName?: string; - tag?: string; - address?: string; - accountType?: string; - counterpartyName?: string; - initiatedBy?: string; - asset?: string; - newIpAddress?: string; - approverList?: string; - removedUserName?: string; - removedUserEmail?: string; - action?: string; - description?: string; - userAgent?: string; - authorizationInfo?: string; - reEnrolledUser?: string; - oldThreshold?: string; - newThreshold?: string; - oldAmount?: string; - newAmount?: string; - draftPolicyJson?: string; -} - -export interface AuditsResponse { - data: Audit[]; - total: number; -} - -export interface ISystemMessageInfo { - type: string; - message: string; -} - -export enum GetNFTsSortValues { - "collectionName" = "collection.name", - "name" = "name", - "blockchainDescriptor" = "blockchainDescriptor", -} - -export enum GetOwnedNFTsSortValues { - "ownershipLastUpdateTime" = "ownershipLastUpdateTime", - "name" = "name", - "collectionName" = "collection.name", - "blockchainDescriptor" = "blockchainDescriptor", -} - -export enum GetOwnedCollectionsSortValues { - "name" = "name", -} - -export enum GetOwnedAssetsSortValues { - "name" = "name", -} - -export enum OrderValues { - "ASC" = "ASC", - "DESC" = "DESC", -} - -export enum NFTOwnershipStatus { - "LISTED" = "LISTED", - "ARCHIVED" = "ARCHIVED", -} - -export enum NFTOwnershipWalletType { - "VAULT_ACCOUNT" = "VAULT_ACCOUNT", - "END_USER_WALLET" = "END_USER_WALLET", -} - -export interface ContractUploadRequest { - name: string; - description: string; - longDescription: string; - bytecode: string; - sourcecode: string; - compilerOutputMetadata?: object; - docs?: ContractDoc; - abi?: AbiFunction[]; - attributes?: Record; - vendorId?: string; -} -interface AbiFunction { - name?: string; - stateMutability?: string; - type: "function" | "constructor" | string; - inputs: Parameter[]; - outputs?: Parameter[]; - description?: string; - returns?: Record; -} - -interface Parameter { - name: string; - description?: string; - internalType: string; - type: string; - components?: Parameter[]; -} -interface ContractDoc { - details?: string; - events?: string; - kind: "dev" | "user" | string; - methods: Record; - version: string | number; -} - -interface FunctionDoc { - details?: string; - params?: Record; - returns?: Record; -} -interface VendorDto { - id: string; - name: string; - attributes: Record; -} - -export interface ContractTemplateDto { - isPublic: boolean; - vendor?: VendorDto; - id: string; - name: string; - description: string; - bytecode: string; - sourcecode?: string; - owner?: string; - compilerOutputMetadata?: object; - abi: AbiFunction[]; - docs?: ContractDoc; - attributes?: Record; -} -export enum TokenLinkPermission { - MINT = "MINT", - BURN = "BURN", -} - -export interface TokenLinkPermissionEntry { - permission: TokenLinkPermission; - vaultAccountId: string; -} - -export interface LinkedTokenMetadata { - assetId: string; - name?: string; - totalSupply?: string; - holdersCount?: number; - type?: string; - contractAddress?: string; - issuerAddress?: string; - testnet?: boolean; - blockchain?: string; -} -export interface TokenLink { - id: string; - assetId: string; - assetMetadata?: LinkedTokenMetadata; - permissions: TokenLinkPermissionEntry[]; -} -export interface PendingTokenLinkDto { - id: number; - txId?: string; - name?: string; - symbol?: string; - vaultAccountId?: string; - blockchainId?: string; -} - - -export interface IssueTokenRequest { - symbol: string; - name: string; - blockchainId: string; - vaultAccountId: string; - createParams: CreateTokenParams; -} - -export interface JobCreatedResponse { - jobId: string; -} - -export enum Status { - NONE = "NONE", - CREATED = "CREATED", - INPROGRESS = "INPROGRESS", - DONE = "DONE", - ERROR = "ERROR", - CANCELED = "CANCELED", - PAUSED = "PAUSED" -} - -export class Job { - id: string; - tenantId: string; - type: string; - userId: string; - created: number; - updated?: number; - state: Status; - data: string; -} - -export class Task { - id: string; - jobId: string; - type: string; - tenantId: string; - created: number; - updated?: number; - state: Status; - data?: string; - result?: string; -} - -type CreateTokenParams = EVMTokenCreateParamsDto | StellarRippleCreateParamsDto; -interface StellarRippleCreateParamsDto { - issuerAddress?: string; -} - -interface ParameterWithValue { - internalType: string; - name: string; - type: string; - description?: string; - value: any; -} - -interface EVMTokenCreateParamsDto { - contractId: string; - constructorParams?: Array; -} - -export enum SmartTransfersTicketDirection { - EXCHANGE = "EXCHANGE", - SEND = "SEND", - RECEIVE = "RECEIVE", - INTERMEDIATE = "INTERMEDIATE", -} - -export enum SmartTransfersTicketStatus { - DRAFT = "DRAFT", - PENDING_APPROVAL = "PENDING_APPROVAL", - OPEN = "OPEN", - IN_SETTLEMENT = "IN_SETTLEMENT", - FULFILLED = "FULFILLED", - EXPIRED = "EXPIRED", - CANCELED = "CANCELED", -} - -export enum SmartTransferTicketTermStatus { - CREATED = "CREATED", - FUNDING = "FUNDING", - FUNDING_FAILED = "FUNDING_FAILED", - FUNDED = "FUNDED", - REJECTED = "REJECTED", -} - -export interface SmartTransfersTicketTermPayload { - asset: string; - amount: string; - fromNetworkId: string; - toNetworkId: string; -} -export interface SmartTransfersTicketCreatePayload { - createdByNetworkId: string; - type: string; - expiresIn?: number; - terms?: SmartTransfersTicketTermPayload[]; - externalRefId?: string; - note?: string; - submit?: boolean; -} - -export interface SmartTransfersTicketTerm { - id: string; - asset: string; - amount: string; - fromNetworkId: string; - fromNetworkIdName?: string; - toNetworkId: string; - toNetworkIdName?: string; - txHash?: string; - fbTxId?: string; - transactionStatus: TransactionStatus; - status: SmartTransferTicketTermStatus; - createdAt: Date; - updatedAt: Date; -} - -export interface SmartTransfersTicket { - id: string; - type: string; - direction?: SmartTransfersTicketDirection; - canceledByMe?: boolean; - createdByMe?: boolean; - status: SmartTransfersTicketStatus; - terms: SmartTransfersTicketTerm[]; - expiresIn?: number; - expiresAt?: Date; - submittedAt?: Date; - createdAt: Date; - updatedAt: Date; - externalRefId?: string; - note?: string; - createdByNetworkId: string; - createdByNetworkIdName: string; -} - -export interface SmartTransfersTicketTermResponse { - data: SmartTransfersTicketTerm; -} - -export interface SmartTransfersTicketResponse { - data: SmartTransfersTicket; -} - -export interface SmartTransfersTicketsResponse { - message?: string; - after?: string; - data: SmartTransfersTicket[]; -} - -export interface SmartTransfersTicketsFilters { - q?: string; - statuses?: SmartTransfersTicketStatus[]; - networkId?: string; - externalRefId?: string; - after?: string; - limit?: number; - createdByMe?: boolean; - expiresAfter?: Date; - expiresBefore?: Date; - type?: string; -} - -export interface SmartTransfersUserGroupsResponse { - data: SmartTransfersUserGroups; -} - -export interface SmartTransfersUserGroups { - userGroupIds: string[]; -} - -export interface SmartTransfersTicketTermFundPayload { - asset: string; - amount: string; - networkConnectionId: string; - srcId: string; - srcType: string; - fee?: string; - feeLevel?: FeeLevel; -} - -export namespace NCW { - export const WalletIdHeader = "X-End-User-Wallet-Id"; - - export interface WalletInfo { - walletId: string; - enabled: boolean; - } - - export interface GetWalletsPayload { - pageCursor?: string; - pageSize?: number; - sort?: string; - order?: "ASC" | "DESC"; - } - - export interface GetWalletAccountsPayload { - pageCursor?: string; - pageSize?: number; - sort?: string; - order?: "ASC" | "DESC"; - } - - export interface GetWalletAssetsPayload { - pageCursor?: string; - pageSize?: number; - sort?: string; - order?: "ASC" | "DESC"; - } - - export interface GetWalletAddressesPayload { - pageCursor?: string; - pageSize?: number; - sort?: string; - order?: "ASC" | "DESC"; - } - - export interface WalletAssetResponse { - id: string; - symbol: string; - name: string; - decimals: number; - networkProtocol: string; - testnet: boolean; - hasFee: boolean; - type: string; - baseAsset: string; - ethNetwork?: number; - ethContractAddress?: string; - issuerAddress?: string; - blockchainSymbol?: string; - deprecated?: boolean; - coinType: number; - blockchain: string; - blockchainDisplayName?: string; - blockchainId?: string; - } - export interface WalletAssetAddress { - accountName: string; - accountId: string; - asset: string; - address: string; - addressType: string; - addressDescription?: string; - tag?: string; - addressIndex?: number; - legacyAddress?: string; - } - - export interface Device { - deviceId: string; - enabled: boolean; - } -} From 6880ee9b00cd4233bebfa37fa2d6dabd58fbbd07 Mon Sep 17 00:00:00 2001 From: gguy Date: Tue, 31 Oct 2023 10:22:32 +0200 Subject: [PATCH 3/6] fixed comments reviews --- src/fireblocks-sdk.ts | 65 ++++++++++++++----------------------------- src/types.ts | 13 ++++----- 2 files changed, 27 insertions(+), 51 deletions(-) diff --git a/src/fireblocks-sdk.ts b/src/fireblocks-sdk.ts index 64a38a56..c736a201 100644 --- a/src/fireblocks-sdk.ts +++ b/src/fireblocks-sdk.ts @@ -98,7 +98,7 @@ import { ContractUploadRequest, ContractTemplateDto, PendingTokenLinkDto, Web3ConnectionFeeLevel, - Task, Job, JobCreatedResponse + BatchTask, BatchJob, JobCreatedResponse } from "./types"; import { AxiosProxyConfig, AxiosResponse } from "axios"; import { PIIEncryption } from "./pii-client"; @@ -661,19 +661,6 @@ export class FireblocksSDK { return await this.apiClient.issuePostRequest("/v1/vault/accounts", body, requestOptions); } - /** - * Creates a new vault account - * @param count Number of new vault accounts requested - * @param requestOptions - */ - public async createVaultAccountBulk(count: number, requestOptions?: RequestOptions): Promise { - const body = { - count - }; - - return await this.apiClient.issuePostRequest("/v1/vault/accounts/bulk", body, requestOptions); - } - /** * Hides a vault account in Fireblocks console * @param vaultAccountId The vault account ID @@ -707,12 +694,12 @@ export class FireblocksSDK { * @param vaultAccountId * @param name A new name for the vault account */ - public async updateVaultAccount(vaultAccountId: string, name: string): Promise { + public async updateVaultAccount(vaultAccountId: string, name: string, requestOptions?: RequestOptions): Promise { const body = { name: name }; - return await this.apiClient.issuePutRequest(`/v1/vault/accounts/${vaultAccountId}`, body); + return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}`, body, requestOptions); } /** @@ -725,20 +712,6 @@ export class FireblocksSDK { return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}`, {}, requestOptions); } - /** - * Creates a new asset within a list of existing vault accounts - * @param assetId The asset to add - * @param vaultAccountIdFrom The first of the account ID range - * @param vaultAccountIdTo The last of the account ID range - * @param requestOptions - */ - public async createVaultAssetBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string, requestOptions?: RequestOptions): Promise { - const body = { - assetId, vaultAccountIdFrom, vaultAccountIdTo - }; - return await this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body, requestOptions); - } - /** * Retry to create a vault asset for a vault asset that failed * @param vaultAccountId The vault account ID @@ -1851,10 +1824,10 @@ export class FireblocksSDK { /** * Get list of jobs for current tenant - * @param fromTime beggining of time range in MS since 1970 - * @param toTime ending of time range in MS since 1970 + * @param fromTime beggining of time range in Unix Epoch + * @param toTime ending of time range in Unix Epoch */ - public getJobs(fromTime: number, toTime: number): Promise { + public getJobsForTenant(fromTime: number, toTime: number): Promise { return this.apiClient.issueGetRequest(`/v1/batch/jobs?fromTime=${fromTime}&toTime=${toTime}`); } @@ -1862,7 +1835,7 @@ export class FireblocksSDK { * Get job info by job ID * @param jobId */ - public getJob(jobId: string): Promise { + public getJobById(jobId: string): Promise { return this.apiClient.issueGetRequest(`/v1/batch/${jobId}`); } @@ -1870,7 +1843,7 @@ export class FireblocksSDK { * Get tasks belonging to given job * @param jobId */ - public getTasks(jobId: string): Promise { + public getTasksByJobId(jobId: string): Promise { return this.apiClient.issueGetRequest(`/v1/batch/${jobId}/tasks`); } @@ -1901,25 +1874,29 @@ export class FireblocksSDK { /** * Create multiple vault accounts in one bulk operation * @param count number of vault accounts + * @param assetId optional asset id to create in each new account + * @param requestOptions */ - public createVaultAccountsBulk(count: number, assetId: string): Promise { + public createVaultAccountsBulk(count: number, assetId: string, requestOptions?: RequestOptions): Promise { const body = { count, assetId }; - return this.apiClient.issuePostRequest(`/v1/vault/accounts/bulk`, body); + return this.apiClient.issuePostRequest(`/v1/vault/accounts/bulk`, body, requestOptions); } /** - * Create multiple vault wallets in one bulk operation - * @param count number of vault accounts + * Creates a new asset within a list of existing vault accounts + * @param assetId The asset to add + * @param vaultAccountIdFrom The first of the account ID range + * @param vaultAccountIdTo The last of the account ID range + * @param requestOptions */ - public createVaultWalletsBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string): Promise { + public async createVaultAssetsBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string, requestOptions?: RequestOptions): Promise { const body = { - assetId, - vaultAccountIdFrom, - vaultAccountIdTo + assetId, vaultAccountIdFrom, vaultAccountIdTo }; - return this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body); + return await this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body, requestOptions); } + } diff --git a/src/types.ts b/src/types.ts index 829b91a8..3bdaca80 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1516,35 +1516,34 @@ export interface JobCreatedResponse { jobId: string; } -export enum Status { - NONE = "NONE", +export enum BatchStatus { CREATED = "CREATED", - INPROGRESS = "INPROGRESS", + IN_PROGRESS = "INPROGRESS", DONE = "DONE", ERROR = "ERROR", CANCELED = "CANCELED", PAUSED = "PAUSED" } -export class Job { +export class BatchJob { id: string; tenantId: string; type: string; userId: string; created: number; updated?: number; - state: Status; + state: BatchJob; data: string; } -export class Task { +export class BatchTask { id: string; jobId: string; type: string; tenantId: string; created: number; updated?: number; - state: Status; + state: BatchStatus; data?: string; result?: string; } From 4ec37a7c89adfd85cf55cdc54cf521b852e5f9c6 Mon Sep 17 00:00:00 2001 From: gguy Date: Wed, 1 Nov 2023 10:49:10 +0200 Subject: [PATCH 4/6] no need for async --- src/fireblocks-sdk.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/fireblocks-sdk.ts b/src/fireblocks-sdk.ts index c736a201..8d0c5ce6 100644 --- a/src/fireblocks-sdk.ts +++ b/src/fireblocks-sdk.ts @@ -1892,11 +1892,10 @@ export class FireblocksSDK { * @param vaultAccountIdTo The last of the account ID range * @param requestOptions */ - public async createVaultAssetsBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string, requestOptions?: RequestOptions): Promise { + public createVaultAssetsBulk(assetId: string, vaultAccountIdFrom: string, vaultAccountIdTo: string, requestOptions?: RequestOptions): Promise { const body = { assetId, vaultAccountIdFrom, vaultAccountIdTo }; - return await this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body, requestOptions); + return this.apiClient.issuePostRequest(`/v1/vault/assets/bulk`, body, requestOptions); } - } From 2ef682936d5ef2166c5af31c72101752ff3f1a58 Mon Sep 17 00:00:00 2001 From: gguy Date: Wed, 1 Nov 2023 10:53:48 +0200 Subject: [PATCH 5/6] fixed merge error --- src/fireblocks-sdk.ts | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/fireblocks-sdk.ts b/src/fireblocks-sdk.ts index 84fb609d..1288f6c5 100644 --- a/src/fireblocks-sdk.ts +++ b/src/fireblocks-sdk.ts @@ -101,8 +101,7 @@ import { UsersGroup, LeanContractTemplateDto, ContractTemplateDto, - PendingTokenLinkDto, Web3ConnectionFeeLevel, - BatchTask, BatchJob, JobCreatedResponse + BatchTask, BatchJob, JobCreatedResponse, ContractUploadRequest, ContractDeployResponse, ContractDeployRequest, From 20a48ec17ed2b1fb2c7b730a59fd2516140e4262 Mon Sep 17 00:00:00 2001 From: gguy Date: Thu, 2 Nov 2023 09:56:43 +0200 Subject: [PATCH 6/6] removed duplicates --- src/types.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/types.ts b/src/types.ts index 0bb2d877..6cf9e8ae 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1618,8 +1618,6 @@ export interface PendingTokenLinkDto { blockchainId?: string; } -type CreateTokenParams = EVMTokenCreateParamsDto | StellarRippleCreateParamsDto; - export interface IssueTokenRequest { symbol: string; name: string;