npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@zufan_devops/coinbase-sdk

v0.1.18

Published

Unofficial Coinbase REST API SDK built with modern tooling.

Downloads

69

Readme

@zufan_devops/coinbase-sdk

Unofficial TypeScript SDK for the Coinbase Advanced Trade APIs. The initial milestone concentrates on the REST endpoints documented in AI-Doc/CB_Endpoints.md; WebSocket coverage described in AI-Doc/CB_ WebSocket.md will follow once the REST surface is stable.

Status: Active development. Expect rapid iteration and breaking changes until the REST client is feature complete.

Why this SDK

  • TypeScript-first design that ships .d.ts files for editor autocomplete.
  • Strict (and pragmatic) Zod validation that accepts Coinbase response quirks (e.g., null timestamps, numeric strings, missing tickers) without crashing your app.
  • Axios-based HTTP transport with dependency injection hooks for testing.
  • ES256 JWT signing that mirrors the example in AI-Doc/Example/code/example.js.
  • Chalk-powered terminal messaging (usage patterns to be finalized).

Installation

Requirements

  • Node.js 18 or newer (ES2020 features and crypto/Uint8Array support).
  • npm 9+ or pnpm/yarn at comparable versions.

Install from npm

npm install @zufan_devops/coinbase-sdk

Because the package is TypeScript-native, importing it from JavaScript or TypeScript automatically enables IDE autocomplete through the published definitions in dist/types/index.d.ts.

Configure credentials

Create a Coinbase Advanced Trade API key/secret pair in the Coinbase UI and export them as environment variables before running any code. The secret is a PEM-encoded ES256 private key.

export COINBASE_API_KEY="cbkey_xxxxx"
export COINBASE_API_SECRET="$(cat path/to/private-key.pem)"

Additional configuration (such as key versioning or passphrases) will be surfaced through typed schemas in src/schemas/ as the REST surface grows.

Quick start

import { CoinbaseClient } from '@zufan_devops/coinbase-sdk';

if (!process.env.COINBASE_API_KEY || !process.env.COINBASE_API_SECRET) {
  throw new Error('Missing Coinbase Advanced Trade credentials');
}

const client = new CoinbaseClient({
  apiKey: process.env.COINBASE_API_KEY,
  apiSecret: process.env.COINBASE_API_SECRET,
});

const { accounts } = await client.accounts.list();
console.log(`Found ${accounts.length} accounts`);

const account = await client.accounts.get({
  accountId: accounts[0]?.uuid ?? '',
});
console.log(account.name);

const preview = await client.orders.preview({
  product_id: 'BTC-USD',
  side: 'BUY',
  order_configuration: {
    limit_limit_gtc: { base_size: '0.1', limit_price: '45000' },
  },
});
console.log(preview);

const ticker = await client.marketData.getTicker({ product_id: 'BTC-USD' });
console.log(`Latest BTC price: ${ticker.price}`);
  • The constructor Zod-validates credentials and optional transport overrides.
  • A short-lived ES256 JWT (2 minute TTL) is minted per request and attached as the Authorization: Bearer header.
  • REST services are mirrored at the top level (client.accounts, client.orders, etc.) with client.rest retained for compatibility.

Usage examples

Examples assume the client variable from the quick start section is in scope.

Accounts

const { accounts } = await client.accounts.list({ limit: 50 });
const firstAccountId = accounts[0]?.uuid;

if (firstAccountId) {
  const account = await client.accounts.get({ accountId: firstAccountId });
  console.log(account.available_balance?.value);
}

Orders

const preview = await client.orders.preview({
  product_id: 'ETH-USD',
  side: 'SELL',
  order_configuration: {
    limit_limit_gtc: { base_size: '1', limit_price: '3500' },
  },
});

const created = await client.orders.create({
  client_order_id: preview.previews?.[0]?.preview_id,
  product_id: 'ETH-USD',
  side: 'SELL',
  order_configuration: {
    limit_limit_gtc: { base_size: '1', limit_price: '3500' },
  },
});

if (created.order_id) {
  await client.orders.cancel({ order_ids: [created.order_id] });
}

Market data

const { products } = await client.marketData.listProducts({ limit: 10 });
const bestBidAsk = await client.marketData.getBestBidAsk({ product_ids: ['BTC-USD'] });
const ticker = await client.marketData.getTicker({ product_id: 'BTC-USD' });
console.log(products.length, bestBidAsk.pricebooks[0], ticker.price);

Transactions

const summary = await client.transactions.getSummary({
  start_date: '2024-01-01T00:00:00Z',
  end_date: '2024-01-31T23:59:59Z',
});

console.log(summary.total_volume);

Conversions

const quote = await client.conversions.createQuote({
  from_account: 'USD',
  to_account: 'USDC',
  amount: '1000',
});

if (quote.quote.quote_id) {
  await client.conversions.commit({
    tradeId: quote.quote.trade_id ?? quote.quote.quote_id,
    quote_id: quote.quote.quote_id,
  });
}

Portfolios

const portfolios = await client.portfolios.list();
const portfolioId = portfolios.portfolios?.[0]?.uuid;

if (portfolioId) {
  const breakdown = await client.portfolios.getBreakdown({ portfolioUuid: portfolioId });
  console.log(breakdown.positions?.length);
}

Futures

const balance = await client.futures.getBalanceSummary();
const positions = await client.futures.listPositions();

console.log(balance.total?.value, positions.positions?.length);

Perpetuals

const portfolioUuid = 'your-portfolio-uuid';

const summary = await client.perpetuals.getPortfolioSummary({ portfolioUuid });
const positions = await client.perpetuals.listPositions({ portfolioUuid });

console.log(summary.portfolio?.equity, positions.positions?.length);

Payment methods

const paymentMethods = await client.paymentMethods.list();
const fundingId = paymentMethods.payment_methods?.[0]?.id;

if (fundingId) {
  const paymentMethod = await client.paymentMethods.get({ paymentMethodId: fundingId });
  console.log(paymentMethod.name);
}

Utility

const permissions = await client.utility.getApiKeyPermissions();
console.log(permissions.permissions?.map((perm) => perm.permission));

Handling API response quirks

Coinbase occasionally omits or reshapes fields in REST payloads. The SDK smooths over the most common cases, so you can keep working with predictable types:

  • client.accounts.list() treats deleted_at as nullable.
  • client.orders.list() coerces number_of_fills into a number even when the API returns a string.
  • client.marketData.getTicker() tolerates sparse snapshots and backfills the requested product_id when Coinbase omits it.

If you encounter other mismatches, open an issue with a redacted payload and we will extend the schemas accordingly.

Documentation for AI assistants

The package can act as a Model Context Protocol (MCP) documentation server so AI coding assistants can stream SDK references on demand.

npx @zufan_devops/coinbase-sdk --serve-docs
  • Speaks MCP JSON-RPC over stdin/stdout and understands initialize, listTopics, getDocumentation, ping, shutdown, and exit.
  • Serves the package README and all generated Markdown files under docs/.
  • Stop the process with Ctrl+C or send the MCP shutdown/exit commands from the host assistant.

Authentication blueprint

Until the SDK helpers are published, you can experiment with the signing flow showcased in AI-Doc/Example/code/example.js. The outline is:

  1. Build the canonical request string (${METHOD} api.coinbase.com${path}) for the Advanced Trade API.
  2. Sign a JWT with ES256 using your Coinbase private key (COINBASE_API_SECRET), include the kid header (COINBASE_API_KEY), and a random nonce.
  3. Attach the token to the Authorization header and call the REST resource with Axios or your preferred HTTP client.
  4. Compare your response payload with the fixture in AI-Doc/Example/data/example.response.json to validate the flow.

The SDK will encapsulate these steps in reusable utilities so application code never has to manage JWT plumbing directly.

SDK layout

  • CoinbaseClient – Public entry point instantiated with new CoinbaseClient(config). Holds shared config (API key/secret, base URLs, Axios instance) and exposes both the flattened conveniences (client.accounts, client.orders, etc.) and the legacy namespace (client.rest), plus the websocket client (client.websocket).
  • AdvancedTradeSigner – Internal helper class responsible for Zod-validating credential material and minting ES256 JWTs. Injected into REST/WebSocket modules.
  • RestClient – Aggregates REST domain services, ensures every call flows through a single request pipeline, handles retries/logging, and delegates to feature-specific classes. Exposed via client.rest for backwards compatibility.
  • AccountsService, OrdersService, MarketDataService, etc. – Thin service classes per resource group mirroring AI-Doc/CB_Endpoints.md. Each depends on RestClient for HTTP dispatch and on Zod schemas from src/schemas/.
  • CoinbaseWebSocketClient – Wrapper around Coinbase streaming APIs per AI-Doc/CB_ WebSocket.md. Provides connection lifecycle management, subscription helpers, and message validation.
  • ConsoleReporter – Wrapper around Chalk for opinionated terminal output (e.g., warnings on schema validation failures or rate-limit notices). Injected where human-readable messaging is required.

Modules will be arranged under src/coinbase/** and src/shared/** to keep concerns isolated and maintain tree-shakeability.

Project structure

  • src/ – TypeScript source (strict mode). Schemas live in src/schemas/.
  • dist/ – Webpack bundle (index.js + source map) and emitted declaration files (dist/types/).
  • AI-Doc/ – Reference material, endpoint definitions, examples, and design notes. Treat as read-only input when implementing features.
  • docs/ – Generated Markdown documentation (to be produced via npm run doc in a future update).
  • tests/ – Reserved for integration fixtures once the test runner is in place.

The Notes/ directory is intentionally off-limits according to the project guidelines.

Development workflow

  • npm run typecheck – Validate strict TypeScript settings without emitting code.
  • npm run build – Bundle the SDK into dist/index.js using Webpack.
  • npm run build:types – Emit declaration files to dist/types/ for downstream consumers.
  • npm run test – Execute Vitest unit tests for the SDK.

Run the build before pushing any branch and especially after changing the public API shape.

Roadmap

  • ✅ Bootstrap TypeScript, Webpack, and linting pipeline.
  • ✅ Implement authenticated REST clients for List Accounts, Get Account, Create Order, Cancel Orders, List Orders, List Fills, Get Order, Preview Orders, List Products, Get Product, Get Product Candles, Get Product Ticker, Get Best Bid/Ask, and Get Product Book.
  • ▢ Model comprehensive request/response types and Zod schemas for all private and public endpoints.
  • ▢ Emit Markdown docs (npm run doc) sourced from JSDoc blocks.
  • ▢ Layer in WebSocket subscriptions based on AI-Doc/CB_ WebSocket.md.
  • ▢ Provide fixtures and Jest-powered unit tests that mock Coinbase responses.

Contributing & workflow

  • Branch off main using the enforced naming convention (feature/<name>, fix/<name>, chore/<name>).
  • Keep commits focused and descriptive; never commit directly to main.
  • Sanitize secrets—never check API keys or real responses into git.
  • Prefer dependency injection for HTTP clients to simplify testing.
  • Request build + typecheck to stay green before opening a pull request.

Security considerations

  • Load credentials from environment variables or secret managers; do not hard-code them.
  • Rotate API keys regularly and scope permissions to the minimum required (see the tables in AI-Doc/CB_Endpoints.md).
  • Audit dependencies periodically (npm audit) and refresh sensitive packages (e.g. Axios) promptly.

License

ISC © zufans