Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

coinbase-advanced-node

Package Overview
Dependencies
Maintainers
0
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

coinbase-advanced-node

Coinbase API for Node.js, written in TypeScript and covered by tests.

  • 4.1.0
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
21
decreased by-50%
Maintainers
0
Weekly downloads
 
Created
Source

Coinbase API

Unofficial Coinbase API for Node.js, written in TypeScript and covered by tests. Covers both the Advanced Trade API & Coinbase App API (Formerly Sign In With Coinbase)

Motivation

The purpose of this coinbase-advanced-node package is to maintain a recent Coinbase API for Node.js with type safety through TypeScript. This project began as a fork of coinbase-pro-node in efforts to provide a smooth transition for anyone migrating to the Advanced Trade API due to the deprecation of the former Exchange/Pro API.

Features

  • Typed. Source code is 100% TypeScript. No need to install external typings.
  • Tested. Code coverage is 100%. No surprises when using "coinbase-advanced-node".
  • Convenient. Request throttling is built-in. Don't worry about rate limiting.
  • Comfortable. More than an API client. You will get extras like candle watching.
  • Maintained. Automated security updates. No threats from outdated dependencies.
  • Documented. Get started with demo scripts
  • Modern. HTTP client with Promise API. Don't lose yourself in callback hell.
  • Robust. WebSocket reconnection is built-in. No problems if your Wi-Fi is gone.
  • Reliable. Following semantic versioning. Get notified about breaking changes.

Installation

npm

npm install coinbase-advanced-node

Yarn

yarn add coinbase-advanced-node

Setup

JavaScript

const {Coinbase} = require('coinbase-advanced-node');
const client = new Coinbase(creds);

TypeScript

import {Coinbase} from 'coinbase-advanced-node';
const client = new Coinbase(creds);

Authentication Schemes

All Advanced Trade & SIWC API calls require authentication, with the exception of the product & time API'S which are public. All websocket channels minus the user channel are public as well. Coinbase has multiple authentication schemes available for different APIs, all schemes are supported in this library. Click here for more info.

Usage

The demo section provides many examples on how to use "coinbase-advanced-node". For a quick start, below is a simple example for a REST request

All authentication methods require that you obtain correct permissions (scopes) to access different API endpoints. Read more about scopes here

For Advanced Trade orders, use the order API. The buy & sell API's exposed are part of the Coinbase App API (Sign In With Coinbase) which have different capabilities and fee structures

REST Example

import {Coinbase} from 'coinbase-advanced-node';

// Cloud API Keys Can be Generated here
// https://cloud.coinbase.com/access/api
const cloudAuth = {
  cloudApiKeyName: 'organizations/{org_id}/apiKeys/{key_id}',
  cloudApiSecret: '-----BEGIN EC PRIVATE KEY-----\nYOUR PRIVATE KEY\n-----END EC PRIVATE KEY-----\n',
};

const cloudClient = new Coinbase(cloudAuth);
cloudClient.rest.product.getProducts().then(prods => {
  const message = `Total Products ${prods.data.length}.`;
  console.log(message);
});

// Legacy API keys and OAuth are supported in
// SIWC API's and some of the Advance Trade API's
// https://docs.cdp.coinbase.com/advanced-trade/docs/auth

// Legacy API Keys can be generated here:
// https://www.coinbase.com/settings/api
const auth = {
  apiKey: 'ohnwkjnefasodh;',
  apiSecret: 'asdlnasdoiujkswdfsdf',
};

const legacyClient = new Coinbase(auth);
legacyClient.rest.account.listAccounts().then(accounts => {
  const message = `Advance Trade accounts "${accounts.data.length}".`;
  console.log(message);
});

// View OAuth setup info here
// https://docs.cdp.coinbase.com/sign-in-with-coinbase/docs/sign-in-with-coinbase-integration#registering-oauth2-client
const oauth = {
  oauthToken: 'ej09joiunasgukddd09ujoh2i4r874nkjnk;lajs;dlfjaljhfds;sdhjfsdf=',
};

const oauthClient = new Coinbase(oauth);
oauthClient.rest.account.listCoinbaseAccounts().then(accounts => {
  const message = `Coinbase accounts ${accounts.data.length}.`;
  console.log(message);
});

Two Factor Authentication

OAuth2 authentication requires two factor authentication when debiting funds with the wallet:transactions:send scope. When 2FA is required, the API will respond with a 402 status and two_factor_required error. To successfully complete the request, you must make the same request again with the user's 2FA token in the CB-2FA-TOKEN header together with the current access token. https://docs.cdp.coinbase.com/sign-in-with-coinbase/docs/sign-in-with-coinbase-2fa

// Example
const client = new Coinbase(creds);
client.rest.transaction.sendTransaction(accountID, info).catch(async err => {
  if (err.status == 402) {
    const token = await promptUserForMFA();
    const configID = client.rest.interceptors.request.use(config => {
      config.headers['CB-2FA-TOKEN'] = token;
      return config;
    });
    return client.rest.transaction.sendTransaction(accountID, info).finally(() => {
      client.rest.interceptors.request.eject(configID);
    });
  }
  throw err;
});

Additional Endpoints

In the instance this package has not been updated to include some endpoint(s) you may need, use the coinbaseRequest which will properly sign & proxy the request. Please open an issue if this occurs.

const client = new Coinbase(creds);
const info = await client.rest.coinbaseRequest({
  baseURL: client.url.REST_ADV_TRADE,
  method: 'get',
  url: '/brokerage/products',
});
console.info('products data: ', info.data);

WebSocket Example

If you want to listen to WebSocket messages, have a look at these demo scripts:

All websocket channels minus the user channel are public

Demos

All demo scripts are executable from the root directory. If you want to use specific credentials with a demo script, simply add a .env file to the root of this package to modify environment variables used in init-client.ts.

npx ts-node ./src/demo/dump-candles.ts

Tip: There is a .env.defaults file which serves as a template. Just remove its .defaults extension and enter your credentials to get started. Do not commit this file (or your credentials) to any repository!

Sandbox

Coinbase does offer a limited sandbox for testing, you can connect to it using the snippet below. For more information visit

const client = new Coinbase({
      advTradeHttpUrl: 'https://api-sandbox.coinbase.com/api/v3',
      apiKey: null,
      apiSecret: null,
    });

const orders = await client.rest.order.getOrders();
console.log('sandbox orders ', orders);

Web Frontend Applications

The "coinbase-advanced-node" library was built to be used in Node.js environments BUT you can also make use of it in web frontend applications (using React, Vue.js, etc.). However, due to the CORS restrictions of modern web browser, you will have to use a proxy server.

A proxy server can be setup with webpack's DevServer proxy configuration or http-proxy-middleware.

Here is an example:

Backend

import {createProxyMiddleware} from 'http-proxy-middleware';
import express from 'express';

const app = express();

app.use(
  '/api-coinbase-siwc',
  createProxyMiddleware({
    target: 'ttps://api.coinbase.com/v2',
    changeOrigin: true,
    pathRewrite: {
      [`^/api-coinbase-siwc`]: '',
    },
  })
);
app.use(
  '/api-coinbase-adv',
  createProxyMiddleware({
    target: 'ttps://api.coinbase.com/v3',
    changeOrigin: true,
    pathRewrite: {
      [`^/api-coinbase-adv`]: '',
    },
  })
);

Later on, you can use the proxy URLs (/api-coinbase-adv from above) in your web application to initialize "coinbase-advanced-node" with it:

Frontend

const client = new Coinbase({
  httpUrl: '/api-coinbase-siwc',
  apiKey: '',
  apiSecret: '',
});

Contributing

Contributions, issues and feature requests are welcome!

Feel free to check the issues page.

The following commits will help you getting started quickly with the code base:

All resources can be found in the Coinbase Advance Trade API reference. For the latest updates, check Coinbase's API Changelog.

License

This project is MIT licensed.

⭐️ Show your support ⭐️

Please leave a star if you find this project useful.

If you'd like to make a donation

BTC: bc1qctv0q7vlcc80x72z40m6d02spu828tw4rt6jjm
SOL: PKFFsyqAGZ63U3KViqxLBTfX3r9LjgxrVeBoxTxzbrB
ATOM: cosmos14c3dsfutycuzjglvhgj4dacmurjsh2wvtehh08

Keywords

FAQs

Package last updated on 28 Oct 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc