Giter Site home page Giter Site logo

fireblocks / fireblocks-sdk-js Goto Github PK

View Code? Open in Web Editor NEW
69.0 23.0 63.0 1001 KB

Typescript & Javascript SDK for developers using Fireblocks API

Home Page: https://docs.fireblocks.com/api/swagger-ui/

License: MIT License

TypeScript 100.00%
sdk nodejs typescript javascript fireblocks blockchain crypto

fireblocks-sdk-js's Introduction

The Official Javascript & Typescript SDK for Fireblocks API

npm version

The current version of the SDK has changed the minimum supported Node.js version from v12 to v16.

Versions older than v16 are no longer maintained by the Node.js community and are considered EOL.

About

This repository contains the official Javascript & Typescript SDK for Fireblocks API. For the complete API reference, go to API reference.

v4 Migration

Please read the following guide for migration.

Usage

Before You Begin

Make sure you have the credentials for Fireblocks API Services. Otherwise, please contact Fireblocks support for further instructions on how to obtain your API credentials.

Requirements

Installation

npm install fireblocks-sdk --save

or

yarn add fireblocks-sdk

Importing Fireblocks SDK

JavaScript:

const FireblocksSDK = require("fireblocks-sdk").FireblocksSDK;
const fireblocks = new FireblocksSDK(privateKey, apiKey);

TypeScript:

import { FireblocksSDK } from "fireblocks-sdk";
const fireblocks = new FireblocksSDK(privateKey, apiKey);

You can also pass additional options:

const baseUrl = "https://api.fireblocks.io";
const authProvider: IAuthProvider = { /* Custom implementation */ };
const fireblocks = new FireblocksSDK(privateKey, apiKey, baseUrl, authProvider, options);

The options argument has the following structure:

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;

    /** TravelRule Provider options to initialize PII Client for PII encryption */
    travelRuleOptions?: TravelRuleOptions;
}

Axios Interceptor

You can provide the sdk options with an axios response interceptor:

new FireblocksSDK(privateKey, userId, serverAddress, undefined, {
    customAxiosOptions: {
        interceptors: {
            response: {
                onFulfilled: (response) => {
                    console.log(`Request ID: ${response.headers["x-request-id"]}`);
                    return response;
                },
                onRejected: (error) => {
                    console.log(`Request ID: ${error.response.headers["x-request-id"]}`);
                    throw error;
                }
            }
        }
    }
});

Error Handling

The SDK throws AxiosError upon http errors for API requests.

You can read more about axios error handling here.

You can get more data on the Fireblocks error using the following fields:

  • error.response.data.code: The Fireblocks error code, should be provided on support tickets
  • error.response.data.message: Explanation of the Fireblocks error
  • error.response.headers['x-request-id']: The request ID correlated to the API request, should be provided on support tickets / Github issues

fireblocks-sdk-js's People

Contributors

amimagid avatar amirlevygit avatar amiryadid-fb avatar amper-fb avatar asudimac avatar aviba avatar barakfireblocks avatar dependabot[bot] avatar dpetrovic-fb avatar gadiguy avatar idanya avatar itamar17 avatar kennethtxytqw avatar lazars14-f avatar mayashechter1 avatar or109 avatar orenyomtov avatar osaban-fireblocks avatar pbereng avatar rade-fireblocks avatar sashalinder avatar shirgerasi10 avatar snirs avatar tomervil avatar vsiskin avatar yarinvak avatar yinon-hever avatar yoavbz avatar yuval-fireblocks avatar zoharsf avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fireblocks-sdk-js's Issues

[Feature Request] Test Cases

Is your feature request related to a problem? Please describe.
It's not related to a problem.

Please provide test cases for the SDK, it will help people understand what type of data they use in the different functions. This is will especially be helpful with the createTransaction function that has so many data types.

Describe the solution you'd like
Add test cases for each major function in this SDK.

Additional context
Add any other context or screenshots about the feature request here.

[Bug] getTransactionsWithPageInfo does not throw with incorrect credentials and empty filter

Describe the bug
When calling getTransactionsWithPageInfo() without any of the optionnal parameters and incorrect credentials (for example privateKey set to "-----BEGIN PRIVATE KEY-----"), no error is thrown and the response is an empty list.

To Reproduce
Steps to reproduce the behavior:

  1. const fireblocks = new FireblocksSDK("-----BEGIN PRIVATE KEY-----", "test");
  2. const tx = fireblocks.getTransactionsWithPageInfo()
  3. result is { transactions: [], pageDetails: { prevPage: '', nextPage: '' } }

Reproduced on Sandbox account credentials so url set to https://sandbox-api.fireblocks.io

Expected behavior
the usual error message would be secretOrPrivateKey must be an asymmetric key when using RS256 expected
Ideally if the credentials are incorrect, an error would be thrown directly at step 1 when creation to fireblocks instance.

Version:

  • fireblocks-sdk version:4.1.0
  • npm version: 8.3.1
  • node version: 16.14.0

[Bug] Missing sourceAddress in TransactionResponse

Describe the bug
Typescript type doesn't match the returned value.

To Reproduce
Steps to reproduce the behavior:
Do this

const transactions = await fireblocks.getTransactions({
        status: args.status,
        after: from
});

Compare the return value with the TransactionResponse type. They don't match.

Expected behavior
Ts type should match the API response more closely and provide similar data structures.

Version:

  • fireblocks-sdk version: 2.0.0
  • Now using node v16.14.0 (npm v8.3.1)

No changelog

Recently the package had a breaking change in his commit history. Tag was updated, but no changelog was found. So I have to pick manually what changed on code by the commit history.

I found it very unpleasing to track changes manually, is there any plan or suggestions to document this changes?

[Bug] Create a New Transaction testnet

Hello, I am trying to create a withdrawal transaction from my Vault wallet but when submitting this, the transaction is "submitted" for signing but marked as "failed" in fire blocks.

This example my TransactionArguments

Values vaultId and destinationAddressMerchant are substituted

{ assetId: 'BNB_TEST', source: { type: PeerType.VAULT_ACCOUNT, id: vaultId }, destination: { type: PeerType.ONE_TIME_ADDRESS, oneTimeAddress: { address: destinationAddressMerchant } }, amount: '0.01', note: `Created withdrawal order on Vault account - ${vaultId}`, operation: TransactionOperation.TRANSFER, feeLevel: FeeLevel.HIGH, }

[Feature Request]support http proxy

It would be nice to support http proxy at the code layer.

For example, if using axios maybe we can add proxy when creating axios instance.

constructor(private authProvider: IAuthProvider, private apiBaseUrl: string, private options: {timeoutInMs?: number}) {
        this.axiosInstance = axios.create({
            baseURL: this.apiBaseUrl,
            proxy: ...,
        });
    }

RAW signing on theta tesnet (ATOM)

Hello, I'm trying to sign a delegate transaction on theta network via the fireblocks RAW signing API.

Here is my code on how to build the transaction:

import { FireblocksSDK, PeerType, TransactionOperation } from 'fireblocks-sdk';
import { coin } from "@cosmjs/proto-signing";
import { MsgDelegate } from "cosmjs-types/cosmos/staking/v1beta1/tx";
import { toHex } from "@cosmjs/encoding";
import { makeSignDoc, serializeSignDoc } from "@cosmjs/amino";

const fs = require('fs');

const apiSecret = fs.readFileSync('./fireblocks_secret.key', 'utf8');
const apiKey = 'xxx';
const fireblocks = new FireblocksSDK(apiSecret, apiKey);

(async () => {
  const vault = await fireblocks.getVaultAccountsWithPageInfo({
    namePrefix: 'account name',
  });

  const vaultId = vault.accounts[0].id;

  try {
    const msg = MsgDelegate.fromPartial({
      delegatorAddress: 'cosmos19c9fdh488vqjclltwp68jm50ydwyh36jqeatev',
      validatorAddress: 'cosmosvaloper178h4s6at5v9cd8m9n7ew3hg7k9eh0s6wptxpcn',
      amount: coin('5000', "uatom"),
    });

    const memo = "Use your power wisely";
    const feeAmount = coin(5193, "uatom");
    const sendMsg = {
      type: "/cosmos.staking.v1beta1.MsgDelegate",
      value: msg,
    };

    const fee = {
      amount: [feeAmount],
      gas: '300000',
    };

    const accountNumber = 698081;
    const sequence = 0;

    const doc = makeSignDoc(
      [sendMsg],
      fee,
      'theta-testnet-001',
      memo,
      accountNumber,
      sequence,
    );

    const encoded = toHex(serializeSignDoc(doc));

    const res = await fireblocks.createTransaction({
      assetId: 'ATOM_COS_TEST',
      note: 'Automated ATOM staking transaction',
      source: {
        type: PeerType.VAULT_ACCOUNT,
        id: vaultId,
      },
      operation: TransactionOperation.RAW,
      extraParameters: {
        rawMessageData: {
          messages: [
            {
              content: encoded,
            },
          ],
        },
      },
    });
    console.log('success:', res);
  } catch (err) {
    console.log(err);
  }
})();

Do you see any issue with this code? When submitting this, the transaction is "submitted" for signing but marked as "failed" in fireblocks.

[Feature Request] Expose substatuses in Typescript

Is your feature request related to a problem? Please describe.
I've been surprised not to find substatuses Enum or Union in Typescript; and found myself to recode it.

The trouble is now I'll have to follow Fireblocks releases and enrich it over the months

Describe the solution you'd like
Some types and runtime exposed to help with substatutes.

Additional context

Here is a proposal :

export const fireblocksSubstatusesPending3rdParty = [
  '3RD_PARTY_PROCESSING',
] as const

export type FireblocksSubstatusPending3rdParty =
  (typeof fireblocksSubstatusesPending3rdParty)[number]

export const isFireblocksSubstatusPending3rdParty = (
  substatus: string,
): substatus is FireblocksSubstatusPending3rdParty =>
  fireblocksSubstatusesPending3rdParty.includes(
    substatus as FireblocksSubstatusPending3rdParty,
  )

export const fireblocksSubstatusesConfirming = [
  '3RD_PARTY_CONFIRMING',
  'PENDING_BLOCKCHAIN_CONFIRMATIONS',
] as const

export type FireblocksSubstatusConfirming =
  (typeof fireblocksSubstatusesConfirming)[number]

export const isFireblocksSubstatusConfirming = (
  substatus: string,
): substatus is FireblocksSubstatusConfirming =>
  fireblocksSubstatusesConfirming.includes(
    substatus as FireblocksSubstatusConfirming,
  )

export type FireblocksSubstatusPending =
  | FireblocksSubstatusPending3rdParty
  | FireblocksSubstatusConfirming

export const isFireblocksSubstatusPending = (
  substatus: string,
): substatus is FireblocksSubstatusPending =>
  isFireblocksSubstatusPending3rdParty(substatus) ||
  isFireblocksSubstatusConfirming(substatus)

export const fireblocksSubstatusesCompleted = [
  '3RD_PARTY_COMPLETED',
  'COMPLETED_BUT_3RD_PARTY_FAILED',
  'COMPLETED_BUT_3RD_PARTY_REJECTED',
  'CONFIRMED',
] as const

export type FireblocksSubstatusCompleted =
  (typeof fireblocksSubstatusesCompleted)[number]

export const isFireblocksSubstatusCompleted = (
  substatus: string,
): substatus is FireblocksSubstatusCompleted =>
  fireblocksSubstatusesCompleted.includes(
    substatus as FireblocksSubstatusCompleted,
  )

export const fireblocksSubstatusesBlocked = ['BLOCKED_BY_POLICY'] as const

export type FireblocksSubstatusBlocked =
  (typeof fireblocksSubstatusesBlocked)[number]

export const isFireblocksSubstatusBlocked = (
  substatus: string,
): substatus is FireblocksSubstatusBlocked =>
  fireblocksSubstatusesBlocked.includes(substatus as FireblocksSubstatusBlocked)

export const fireblocksSubstatusesCancelled = [
  '3RD_PARTY_CANCELLED',
  '3RD_PARTY_REJECTED',
  'CANCELLED_BY_USER',
  'CANCELLED_BY_USER_REQUEST',
  'REJECTED_BY_USER',
] as const

export type FireblocksSubstatusCancelled =
  (typeof fireblocksSubstatusesCancelled)[number]

export const isFireblocksSubstatusCancelled = (
  substatus: string,
): substatus is FireblocksSubstatusCancelled =>
  fireblocksSubstatusesCancelled.includes(
    substatus as FireblocksSubstatusCancelled,
  )

export const fireblocksSubstatusesRejected = [
  'AUTO_FREEZE',
  'FROZEN_MANUALLY',
  'REJECTED_AML_SCREENING',
] as const

export type FireblocksSubstatusRejected =
  (typeof fireblocksSubstatusesRejected)[number]

export const isFireblocksSubstatusRejected = (
  substatus: string,
): substatus is FireblocksSubstatusRejected =>
  fireblocksSubstatusesRejected.includes(
    substatus as FireblocksSubstatusRejected,
  )

export const fireblocksSubstatusesFailedUserInput = [
  'ACTUAL_FEE_TOO_HIGH',
  'ADDRESS_WHITELISTING_SUSPENDED',
  'AMOUNT_TOO_SMALL',
  'AUTHORIZATION_FAILED',
  'AUTHORIZER_NOT_FOUND',
  'ENV_UNSUPPORTED_ASSET',
  'ERROR_UNSUPPORTED_TRANSACTION_TYPE',
  'FAIL_ON_LOW_FEE',
  'GAS_LIMIT_TOO_LOW',
  'GAS_PRICE_TOO_LOW_FOR_RBF',
  'INCOMPLETE_USER_SETUP',
  'INSUFFICIENT_FUNDS',
  'INSUFFICIENT_FUNDS_FOR_FEE',
  'INTEGRATION_SUSPENDED',
  'INVALID_ADDRESS',
  'INVALID_CONTRACT_CALL_DATA',
  'INVALID_FEE_PARAMS',
  'INVALID_NONCE_FOR_RBF',
  'INVALID_TAG_OR_MEMO',
  'INVALID_UNMANAGED_WALLET',
  'MAX_FEE_EXCEEDED',
  'MISSING_TAG_OR_MEMO',
  'NEED_MORE_TO_CREATE_DESTINATION',
  'NO_MORE_PREPROCESSED_INDEXES',
  'NON_EXISTING_ACCOUNT_NAME',
  'RAW_MSG_EMPTY_OR_INVALID',
  'RAW_MSG_LEN_INVALID',
  'TOO_MANY_INPUTS',
  'UNAUTHORISED_DEVICE',
  'UNAUTHORISED_USER',
  'UNALLOWED_RAW_PARAM_COMBINATION',
  'UNSUPPORTED_OPERATION',
  'UNSUPPORTED_TRANSACTION_TYPE',
  'ZERO_BALANCE_IN_PERMANENT_ADDRESS',
] as const

export type FireblocksSubstatusFailedUserInput =
  (typeof fireblocksSubstatusesFailedUserInput)[number]

export const isFireblocksSubstatusFailedUserInput = (
  substatus: string,
): substatus is FireblocksSubstatusFailedUserInput =>
  fireblocksSubstatusesFailedUserInput.includes(
    substatus as FireblocksSubstatusFailedUserInput,
  )

export const fireblocksSubstatusesFailedSystemIssue = [
  'CONNECTIVITY_ERROR',
  'ERROR_ASYNC_TX_IN_FLIGHT',
  'INTERNAL_ERROR',
  'INVALID_NONCE_TOO_HIGH',
  'INVALID_NONCE_TOO_LOW',
  'INVALID_ROUTING_DESTINATION',
  'LOCKING_NONCE_ACCOUNT_TIMEOUT',
  'NETWORK_ROUTING_MISMATCH',
  'NONCE_ALLOCATION_FAILED',
  'RESOURCE_ALREADY_EXISTS',
  'SIGNER_NOT_FOUND',
  'SIGNING_ERROR',
  'TIMEOUT',
  'TX_OUTDATED',
  'UNKNOWN_ERROR',
  'UNSUPPORTED_MEDIA_TYPE',
  'VAULT_WALLET_NOT_READY',
] as const

export type FireblocksSubstatusFailedSystemIssue =
  (typeof fireblocksSubstatusesFailedSystemIssue)[number]

export const isFireblocksSubstatusFailedSystemIssue = (
  substatus: string,
): substatus is FireblocksSubstatusFailedSystemIssue =>
  fireblocksSubstatusesFailedSystemIssue.includes(
    substatus as FireblocksSubstatusFailedSystemIssue,
  )

export const fireblocksSubstatusesFailedThirdParty = [
  'ADDRESS_NOT_WHITELISTED',
  'API_KEY_MISMATCH',
  'ASSET_NOT_ENABLED_ON_DESTINATION',
  'DEST_TYPE_NOT_SUPPORTED',
  'EXCEEDED_DECIMAL_PRECISION',
  'EXCHANGE_CONFIGURATION_MISMATCH',
  'EXCHANGE_VERSION_INCOMPATIBLE',
  'INVALID_EXCHANGE_ACCOUNT',
  'METHOD_NOT_ALLOWED',
  'NON_EXISTENT_AUTO_ACCOUNT',
  'ON_PREMISE_CONNECTIVITY_ERROR',
  'PEER_ACCOUNT_DOES_NOT_EXIST',
  'THIRD_PARTY_MISSING_ACCOUNT',
  'UNAUTHORISED_IP_WHITELISTING',
  'UNAUTHORISED_MISSING_CREDENTIALS',
  'UNAUTHORISED_MISSING_PERMISSION',
  'UNAUTHORISED_OTP_FAILED',
  'WITHDRAW_LIMIT',
] as const

export type FireblocksSubstatusFailedThirdParty =
  (typeof fireblocksSubstatusesFailedThirdParty)[number]

export const isFireblocksSubstatusFailedThirdParty = (
  substatus: string,
): substatus is FireblocksSubstatusFailedThirdParty =>
  fireblocksSubstatusesFailedThirdParty.includes(
    substatus as FireblocksSubstatusFailedThirdParty,
  )

export const fireblocksSubstatusesFailedBlockchain = [
  'DOUBLE_SPENDING',
  'DROPPED_BY_BLOCKCHAIN',
  'INSUFFICIENT_RESERVED_FUNDING',
  'INVALID_SIGNATURE',
  'PARTIALLY_FAILED',
  'POWERUP_SUGGESTION_FAILURE',
  'REACHED_MEMPOOL_LIMIT_FOR_ACCOUNT',
  'REJECTED_BY_BLOCKCHAIN',
  'TOO_LONG_MEMPOOL_CHAIN',
] as const

export type FireblocksSubstatusFailedBlockchain =
  (typeof fireblocksSubstatusesFailedBlockchain)[number]

export const isFireblocksSubstatusFailedBlockchain = (
  substatus: string,
): substatus is FireblocksSubstatusFailedBlockchain =>
  fireblocksSubstatusesFailedBlockchain.includes(
    substatus as FireblocksSubstatusFailedBlockchain,
  )

export type FireblocksSubstatusFailed =
  | FireblocksSubstatusFailedUserInput
  | FireblocksSubstatusFailedSystemIssue
  | FireblocksSubstatusFailedThirdParty
  | FireblocksSubstatusFailedBlockchain

export const isFireblocksSubstatusFailed = (
  substatus: string,
): substatus is FireblocksSubstatusFailed =>
  isFireblocksSubstatusFailedUserInput(substatus) ||
  isFireblocksSubstatusFailedSystemIssue(substatus) ||
  isFireblocksSubstatusFailedThirdParty(substatus) ||
  isFireblocksSubstatusFailedBlockchain(substatus)

export type FireblocksSubstatusNotCompleted =
  | FireblocksSubstatusBlocked
  | FireblocksSubstatusCancelled
  | FireblocksSubstatusRejected
  | FireblocksSubstatusFailed

export const isFireblocksSubstatusNotCompleted = (
  substatus: string,
): substatus is FireblocksSubstatusNotCompleted =>
  isFireblocksSubstatusBlocked(substatus) ||
  isFireblocksSubstatusCancelled(substatus) ||
  isFireblocksSubstatusRejected(substatus) ||
  isFireblocksSubstatusFailed(substatus)

export type FireblocksSubstatus =
  | FireblocksSubstatusPending
  | FireblocksSubstatusCompleted
  | FireblocksSubstatusNotCompleted

export const isFireblocksSubstatus = (
  substatus: string,
): substatus is FireblocksSubstatus =>
  isFireblocksSubstatusPending(substatus) ||
  isFireblocksSubstatusCompleted(substatus) ||
  isFireblocksSubstatusNotCompleted(substatus)

Types, arrays and typeguards

Outdated HTTP libraries

The request libraries are no longer maintained. Are you planning to switch to a different library?

npm i fireblocks-sdk
npm WARN deprecated [email protected]: request-promise-native has been deprecated because it extends the now deprecated request package, see https://github.com/request/request/issues/3142
npm WARN deprecated [email protected]: request has been deprecated, see https://github.com/request/request/issues/3142

Wrong return type of `createVaultAsset()`

    /**
     * Creates a new asset within an existing vault account
     * @param vaultAccountId The vault account ID
     * @param assetId The asset to add
     */
    public async createVaultAsset(vaultAccountId: string, assetId: string): Promise<AssetResponse> {
        return await this.apiClient.issuePostRequest(`/v1/vault/accounts/${vaultAccountId}/${assetId}`, {});
    }

The return type of this function seems to be incorrect. It should be:

interface CreateVaultAssetResponse {
  id: string;
  address: string;
  legacyAddress: string;
  tag: string;
  eosAccountName: string;
}

This is more in line with the documentation.
Screenshot 2021-03-13 at 13 05 42

[Bug] getVaultAccountsWithPageInfo with namePrefix and nameSuffix

Describe the bug
I have an vault account named Account#104 and when I run the following code:

try {
    const pagedVaultAccounts = await this.fireblocks.getVaultAccountsWithPageInfo({
        namePrefix: 'Account#',
        nameSuffix: '104'
        limit: 1
    });
} catch (error) {
    console.error(error);
}

I get:

Error: Request failed with status code 400
    at createError (/xxx/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/xxx/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/xxx/node_modules/axios/lib/adapters/http.js:293:11)
    at IncomingMessage.emit (events.js:412:35)
    at endReadableNT (internal/streams/readable.js:1334:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21) {config: {…}, request: ClientRequest, response: {…}, isAxiosError: true, toJSON: ƒ, …}

To Reproduce
Steps to reproduce the behavior:

  1. Create a vault account named Account#104
  2. Run the code above
  3. See error

Expected behavior
Have the account in pagedVaultAccounts.accounts[0]

Screenshots
N/A

Version:

  • fireblocks-sdk version: 2.1.0
  • npm version: 6.14.15
  • node version: v14.18.1

Additional context
N/A

[Bug] `type` field in `AddressResponse` is `number`, but was `string` in soon-to-be-deprecated `DepositAddressResponse`

Describe the bug
getDepositAddresses is being deprecated and replaced by its paginated version getPaginatedAddresses.
Original interface DepositAddressResponse had type?: string but the replacement interface AddressResponse has type?: number.
The raw json has string values such as Permanent.

API documentation shows correct datatype - type?: string.
But the Response 200 object is array of AddressResponse instead of object which has 2 fields - addresses: AddressResponse[] and paging...

paging?: {
  before?: string;
  after?: string;
};

Deprecated API: https://developers.fireblocks.com/reference/get_vault-accounts-vaultaccountid-assetid-addresses

Replacement API: https://developers.fireblocks.com/reference/get_vault-accounts-vaultaccountid-assetid-addresses-paginated

To Reproduce
Steps to reproduce the behavior:

  • Check raw json response for replacement API.

Expected behavior

  • In interface AddressResponse, type?: number should be changed to type?: string.
  • 200 Response documentation to be updated for replacement API.

Version:

  • fireblocks-sdk version: 5.21.0

[Feature Request] - test

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Additional context
Add any other context or screenshots about the feature request here.

[Bug] getVaultAccountsWithPageInfo not working when namePrefix contains a pound symbol

Describe the bug
When calling getVaultAccountsWithPageInfo with a namePrefix that contains a pound symbol (ex. 'Account#'), I am unable to query past the first page of results (i.e the function always returns the same accounts).

   const requestFilters: PagedVaultAccountsRequestFilters = {
         namePrefix: 'Account#',
         orderBy: 'ASC',
         limit: 2 
    };

    let vaultAccounts = await this.fireblocks.getVaultAccountsWithPageInfo(requestFilters);
    
    while (vaultAccounts.paging.after) {
          console.log(vaultAccounts.accounts); //ALWAYS PRINTS THE SAME 2 ACCOUNTS
          requestFilters.after = vaultAccounts.paging.after; 
          vaultAccounts = await this.fireblocks.getVaultAccountsWithPageInfo(requestFilters);
    }

To Reproduce

  1. Create more than 2 vault accounts that have names that start with 'Account#'
  2. Run the code above
  3. Same accounts are printed repeatedly and loop does not exit

Expected behavior
After updating the after cursor in the requestFilters object, getVaultAccountsWithPageInfo should return the next 2 accounts and not the initially queried accounts when called. The loop in the code above should exit after moving through the full list of vaults.

Version:

  • fireblocks-sdk version: 2.1.0
  • npm version: 8.11.0
  • node version: v16.15.1

Additional context
When I remove the pound symbol from namePrefix, the paging seems to work fine.

[Bug] jsonwebtoken <=8.5.1

npm audit fix error
jsonwebtoken <=8.5.1
Severity: high

To Reproduce
Steps to reproduce the behavior:

  1. Run npm install fireblocks-sdk
  2. Run npm audit fix
  3. See below error:
# npm audit report

jsonwebtoken  <=8.5.1
Severity: high
jsonwebtoken's insecure implementation of key retrieval function could lead to Forgeable Public/Private Tokens from RSA to HMAC - https://github.com/advisories/GHSA-hjrf-2m68-5959
jsonwebtoken vulnerable to signature validation bypass due to insecure default algorithm in jwt.verify() - https://github.com/advisories/GHSA-qwph-4952-7xr6
jsonwebtoken unrestricted key type could lead to legacy keys usage  - https://github.com/advisories/GHSA-8cf7-32gw-wr33
jsonwebtoken has insecure input validation in jwt.verify function - https://github.com/advisories/GHSA-27h2-hvpr-p74q
No fix available
node_modules/jsonwebtoken
  fireblocks-sdk  *
  Depends on vulnerable versions of jsonwebtoken
  node_modules/fireblocks-sdk

Version:

  • fireblocks-sdk version: 2.5.3
  • npm version: 8.19.2
  • node version: v16.14.2

[Feature Request] Fireblocks-defi-sdk support

Is your feature request related to a problem? Please describe.
Fireblocks-defi-sdk and the ethers bridge no longer work with latest version.

Describe the solution you'd like
Update the fireblocks-defi-sdk package to use the new methods.

Additional context
Fireblocks-defi-sdk is very convenient for ethers users, we would like to see it in use, or the ethers bridge added into this sdk.

Asynchronous jwt sign

Sorry for the late response.

I believe some users would like to inject their own Token provider and in some instance, signing jwt is an asynchronous process. For instance, signing jwt via a cloud provider is asynchronous if user stores private key on cloud service and it's not possible to be retrieved as plain text

Originally posted by @Henry-bee in #70 (comment)

`getTransactionsWithPageInfo` won't iterate through pages when `pageFilter` is defined

getTransactionsWithPageInfo accepts both pageFilter as well as a nextOrPreviousPath argument. The current logic will only use pageFilter when it is defined, even if nextOrPreviousPath is also defined. This leads to unexpected behaviour where providing nextOrPreviousPath on subsequent calls to attempt to page through the transaction list will not page at all, and instead keep on returning the same result set from the first page.

public async getTransactionsWithPageInfo(pageFilter?: TransactionPageFilter, nextOrPreviousPath?: string): Promise<TransactionPageResponse> {
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);
}

I'd propose either swapping the logic around such that nextOrPreviousPath takes priority over pageFilter so that consumers of the SDK can do something like

const fireblocksClient = new FireblocksSDK(...)
let transactions: TransactionResponse[] = []
let nextPage: string | undefined
do {
  const response = await fireblocksClient.getTransactionsWithPageInfo(fbFilters, nextPage)
  transactions = transactions.concat(response.transactions)
  nextPage = response.pageDetails.nextPage
} while (nextPage.length)
// `transactions` now contains all transactions

As it currently stands, the above code is also the way to reproduce this current unexpected behaviour, where transactions will just be full of duplicates from the first page of results.

Alternatively, throw an error when both pageFilter and nextOrPreviousPath are defined, to force consumer to implement the sdk is the following kind of way, which will make it clear and remove the possibility to assume behaviour

const response = await fireblocksClient.getTransactionsWithPageInfo(nextPage ? undefined : fbFilters, nextPage)

[Bug] Resend webhooks wrong type

Describe the bug
https://developers.fireblocks.com/reference/post_webhooks-resend
According to the API docs and confirmed by the live API, the response from the Resend failed webhooks endpoint should be

export interface ResendWebhooksResponse {
    messagesCount: number;
}

but is currently the following

export interface ResendWebhooksResponse {
    webhooksCount: number;
}

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Screenshots
If applicable, add screenshots to help explain your problem.

Version:

  • fireblocks-sdk version: [e.g. 1.7.0]
  • npm version:
  • node version:

Additional context
Add any other context about the problem here.

generateNewAddress's customerRefId parameter is character sensitive

Describe the bug
Calling these works fine:

fireblocks.generateNewAddress('42', 'BTC_TEST', '104', '104');
fireblocks.generateNewAddress('42', 'BTC_TEST', 'user#104', '104');

Calling this produces an error:

fireblocks.generateNewAddress('42', 'BTC_TEST', 'user#104', 'user#104');
2022-05-23T03:55:50.762Z error - unhandledRejection error: Request failed with status code 400
Error: Request failed with status code 400
    at createError (/xxx/node_modules/axios/lib/core/createError.js:16:15)
    at settle (/xxx/node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (/xxx/node_modules/axios/lib/adapters/http.js:293:11)
    at IncomingMessage.emit (events.js:412:35)
    at endReadableNT (internal/streams/readable.js:1334:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21)

To Reproduce
See above

Expected behavior
Expecting to be able to provide special characters in customerRefId when calling generateNewAddress()

Screenshots
Not applicable

Version:

  • fireblocks-sdk version: ?
  • npm version: 2.1.0
  • node version: v14.18.1

Additional context
None

Creates a new ETH deposit address for an asset of a vault account not generated

const randomNumber = '65465464'

const vaultAccountId = '0';
const assetId = 'ETH';
const description = 'New Ethereum Address';
const customerRefId = randomNumber;

// Optional: Define additional request options
const requestOptions = {
// You can specify additional request options here, such as a time window for the request, etc.
};

const generateAddress = await fireblocks.generateNewAddress(
vaultAccountId,
assetId,
description,
customerRefId,
requestOptions
);

image

response from fireblocks => Request failed with status code 400

[Bug] Version 3.1.0 broke export/import of SDK

Describe the bug
After the latest release I'm unable to build my application successfully and get the following error:
Error: Cannot find module '/var/app/current/node_modules/fireblocks-sdk/dist/src/fireblocks-sdk.js'. Please verify that the package.json has a valid "main" entry

To Reproduce
Steps to reproduce the behavior:

  1. remove node_module
  2. yarn install
  3. start app
  4. See error

Expected behavior
module to be found

Screenshots
If applicable, add screenshots to help explain your problem.

Version:

  • fireblocks-sdk version: 3.1.0
  • npm version: yarn ^1.22.19
  • node version: >=14.0.0

Additional context
Add any other context about the problem here.

[Feature Request] Allow the txId parameter to be either a transaction hash or a fireblocks id in POST /v1/webhooks/resend/{txId}

The documentation for POST /v1/webhooks/resend/{txId} is vague:
https://docs.fireblocks.com/api/#resend-missed-webhooks-per-transaction

One would expect that txId is actually a blockchain transaction hash, not a fireblocks id, but sending a tx hash returns a 404 error.

It would be useful if we could actually send tx hash for the case when a customer reports their tx hash transaction didn't get processed on our backend, and we don't actually know the fireblocks Id for that transaction.

wrong getSupportedAsset return type

According to the documentation, the method getSupportedAsset should return a AssetTypeResponse, but instead it returns a VaultAccountResponse.

More detail on types:

Expected:

interface AssetTypeResponse {
    id: string
    name: string 
    type: string 
    contractAddress: string
}

Got:

interface VaultAccountResponse {
    id: string;
    name: string;
    hiddenOnUI: boolean;
    assets: AssetResponse[];
    customerRefId?: string;
    autoFuel: boolean;
}

[Feature Request]

Return fireblocks error message on 400 error
I'm always frustrated when i get 400 error from fireblocks service but i have no clue what is the issue

Describe the solution you'd like
I have introduced a new Error called Fireblocks error and it will be returned to the caller when an error happens

Additional context
Add any other context or screenshots about the feature request here.

[Bug] calling validateAddress only produces Errors

Describe the bug

const validation = await fireblocks.validateAddress(assetId, address);

Whatever I provide as assetId and address, I get an error:

Error: Request failed with status code 400
    at createError (./node_modules/axios/lib/core/createError.js:16:15)
    at settle (./node_modules/axios/lib/core/settle.js:17:12)
    at IncomingMessage.handleStreamEnd (./node_modules/axios/lib/adapters/http.js:293:11)
    at IncomingMessage.emit (events.js:412:35)
    at endReadableNT (internal/streams/readable.js:1334:12)
    at processTicksAndRejections (internal/process/task_queues.js:82:21)

Expected behavior
Have validation be an ValidateAddressResponse.

Version:

  • fireblocks-sdk version: 2.3.1
  • npm version: v14.18.1
  • node version: 6.14.15

[Feature Request] Enhance getVaultAccountsWithPageInfo with Optional nextOrPreviousPath for Consistent Pagination Feature

Hello Fireblocks SDK Team,

I've noticed a discrepancy in the pagination capabilities of the SDK. The getTransactionsWithPageInfo method supports an optional nextOrPreviousPath parameter for enhanced pagination, but this feature is absent in the getVaultAccountsWithPageInfo method.

Implementing a similar parameter for getVaultAccountsWithPageInfo would not only bring consistency across the SDK but also improve usability for clients needing advanced pagination features.

Would it be possible to add this feature to the getVaultAccountsWithPageInfo method?

Thank you for your consideration.

Best regards,
Søren

[Bug] SDK not returning any errorcodes

The bug
according to the docs I am supposed to get an ErrorCode whenever something goes wrong. Instead I only get the HTTP status code ex.400 in the status l like so:
{ "message":"Request failed with status code 400", "name":"AxiosError", "config":{ ... }, "code":"ERR_BAD_REQUEST", "status":400 }
This makes catching errors very difficult.

My code
try{ const depositAddresses = await fireblocks.getDepositAddresses(vId, aId); } catch(error){ return res.status(500).json({ 'error':JSON.stringify(error) }); }
Version:

  • fireblocks-sdk version: 3.1.3

get VaultAccountResponse from (assetId + address)

Is your feature request related to a problem? Please describe.
Is there a way to get the VaultAccountResponse from an assetId and a address?

Describe the solution you'd like
What about adding an endpoint like:

getVaultAccount(assetId: string, address: string): Promise<VaultAccountResponse>;

Additional context

[Bug] Missing type(s) from `TransactionStatus` enum

Describe the bug
Some statuses related to transaction creation response seem to be missing from the TransactionStatus enum, for instance, "PENDING_ENRICHMENT"

To Reproduce
Steps to reproduce the behavior:

  1. Create an ETH transaction (createTransaction)
  2. Review the response to the transaction creation request :
{
   "type":"TRANSACTION_STATUS_UPDATED",
   "tenantId":"***redacted***",
   "timestamp":1713976676073,
   "data":{
      "id":"a6c238b4-b203-4ab8-919d-afa40d244f1f",
      "createdAt":1713976661089,
      "lastUpdated":1713976661557,
      "assetId":"ETH",
      "source":{
         "id":"3",
         "type":"VAULT_ACCOUNT",
         "name":"Withdrawal 1",
         "subType":""
      },
      "destination":{
         "id":"6564f824-4c35-69f7-b392-4f956c0dade4",
         "type":"INTERNAL_WALLET",
         "name":"***redacted***",
         "subType":"Internal"
      },
      "amount":30,
      "sourceAddress":"",
      "destinationAddress":"",
      "destinationAddressDescription":"",
      "destinationTag":"",
      "status":"PENDING_ENRICHMENT",
      "txHash":"",
      "subStatus":"",
      "signedBy":[
         
      ],
      "createdBy":"52849aef-cd83-4de0-bb64-6963a3e30ac5",
      "rejectedBy":"",
      "amountUSD":94973.41,
      "addressType":"WHITELISTED",
      "note":"Rebalance",
      "exchangeTxId":"",
      "requestedAmount":30,
      "feeCurrency":"ETH",
      "operation":"TRANSFER",
      "customerRefId":null,
      "amountInfo":{
         "amount":"30",
         "requestedAmount":"30",
         "amountUSD":"94973.41"
      },
      "feeInfo":{
         
      },
      "destinations":[
         
      ],
      "externalTxId":null,
      "blockInfo":{
         
      },
      "signedMessages":[
         
      ],
      "assetType":"BASE_ASSET"
   }
}
  1. The fireblocks-sdk-js is missing the mapping for the status above (PENDING_ENRICHMENT).

Expected behavior
TransactionStatus to contain all expected mappings related to Transaction statuses.

Version:

  • fireblocks-sdk version: v5.25.1

[Feature Request] Archive Vault / Wallet *via* API

In a context where we abstract the wallet creation behind a REST API of our own; we have a use case where we probably should archive the vault account + wallet linked to a user.

I discovered it can be done via the console; but not via API.

Any plans to support it ?

Crypto not found while initialising the SDK

Describe the bug
Crypto not found while initialising the SDK

To Reproduce
Steps to reproduce the behavior:

const fireblocks = new FireblocksSDK(apiSecret, apiKey, baseUrl);
Expected behavior
It should initialise the SDK, but it is not

Screenshots
Simulator Screenshot - iPhone 14 Pro - 2024-02-23 at 17 31 14

Version:

fireblocks-sdk version: [5.20.0]
npm version: [9.7.2]
node version:[20.4.0]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.