This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where content has been compressed (code blocks are separated by ⋮---- delimiter).

================================================================
File Summary
================================================================

Purpose:
--------
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.

File Format:
------------
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  a. A separator line (================)
  b. The file path (File: path/to/file)
  c. Another separator line
  d. The full contents of the file
  e. A blank line

Usage Guidelines:
-----------------
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.

Notes:
------
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: .github/, examples/apidoc/, docs/images/, docs/endpointFunctionList.md, test/, src/util/, dist/, lib/
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)


================================================================
Directory Structure
================================================================
examples/
  AdvancedTrade/
    Private/
      closePosition.ts
      getAccounts.ts
      getOrders.ts
      submitOrderPerps.ts
      submitOrderSpot.ts
    Public/
      advanced-public-rest-all.ts
    WebSockets/
      privateWs.ts
      publicWs.ts
  CoinbaseApp/
    Private/
      cb-app-private.ts
      depositFunds.ts
      sendMoney.ts
      transferMoney.ts
      withdrawFunds.ts
    Public/
      cbapp-public-rest-all.ts
  Institutional/
    CBExchange/
      Rest/
        cb-exchange-private.ts
        cb-exchange-public.ts
      WebSockets/
        privateWs.ts
        publicWs.ts
    CBInternationalExchange/
      cb-intx-public.ts
      cb-intx-ws.ts
  README.md
src/
  lib/
    websocket/
      logger.ts
      typeGuards.ts
      websocket-util.ts
      WsStore.ts
      WsStore.types.ts
    BaseRestClient.ts
    BaseWSClient.ts
    jwtNode.ts
    misc-util.ts
    requestUtils.ts
    webCryptoAPI.ts
  types/
    request/
      advanced-trade-client.ts
      coinbase-app-client.ts
      coinbase-exchange.ts
      coinbase-international.ts
      coinbase-prime.ts
    response/
      advanced-trade-client.ts
      coinbase-app-client.ts
      coinbase-exchange.ts
      coinbase-international.ts
      coinbase-prime.ts
      ws.ts
    websockets/
      client.ts
      events.ts
      requests.ts
      wsAPI.ts
    shared.types.ts
  CBAdvancedTradeClient.ts
  CBAppClient.ts
  CBCommerceClient.ts
  CBExchangeClient.ts
  CBInternationalClient.ts
  CBPrimeClient.ts
  index.ts
  WebsocketClient.ts
webpack/
  webpack.config.cjs
.eslintrc.cjs
.gitignore
.nvmrc
.prettierrc
index.js
jest.config.ts
LICENSE.md
package.json
postBuild.sh
README.md
tsconfig.cjs.json
tsconfig.esm.json
tsconfig.json
tsconfig.linting.json

================================================================
Files
================================================================

================
File: examples/AdvancedTrade/Public/advanced-public-rest-all.ts
================
import { CBAdvancedTradeClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 * const { CBAdvancedTradeClient } = require('coinbase-api');
 */
⋮----
// you can initialise public client without api keys as public calls do not require auth
⋮----
async function publicCalls()
⋮----
// Get server time
⋮----
// Get public product book
⋮----
// List all public products
⋮----
// Get single public product
⋮----
// Get public product candles
⋮----
// Get public market trades

================
File: examples/AdvancedTrade/WebSockets/publicWs.ts
================
import {
  // DefaultLogger,
  WebsocketClient,
  WsTopicRequest,
} from '../../../src/index.js';
⋮----
// DefaultLogger,
⋮----
/**
 * import { WebsocketClient } from 'coinbase-api';
 * const { WebsocketClient } = require('coinbase-api');
 */
⋮----
async function start()
⋮----
// Optional: fully customise the logging experience by injecting a custom logger
// const logger: typeof DefaultLogger = {
//   ...DefaultLogger,
//   trace: (...params) => {
//     if (
//       [
//         'Sending ping',
//         'Sending upstream ws message: ',
//         'Received pong, clearing pong timer',
//         'Received ping, sending pong frame',
//       ].includes(params[0])
//     ) {
//       return;
//     }
//     console.log('trace', params);
//   },
// };
// const client = new WebsocketClient({}, logger);
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
// throw new Error('res?');
⋮----
/**
     * Use the client subscribe(topic, market) pattern to subscribe to any websocket topic.
     *
     * You can subscribe to topics one at a time or many one one request.
     *
     * Topics can be sent as simple strings, if no parameters are required:
     */
// client.subscribe('heartbeats', 'advTradeMarketData');
// client.subscribe('futures_balance_summary', 'advTradeUserData');
⋮----
// /**
//  * Or, as an array of simple strings.
//  *
//  * Any requests sent to the "advTradeUserData" wsKey are
//  * automatically authenticated, if API keys are avaiable:
//  */
// client.subscribe(
//   ['heartbeats', 'futures_balance_summary'],
//   'advTradeUserData',
// );
⋮----
/**
     * Or send a more structured object with parameters, e.g. if parameters are required
     */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
⋮----
/**
       * Anything in the payload will be merged into the subscribe "request",
       * allowing you to send misc parameters supported by the exchange (such as `product_ids: string[]`)
       */
⋮----
/**
     * Subscribe to the "status" topic for a few symbols
     */
⋮----
/**
     * To subscribe to more product IDs for the same topic, just send an additional request:
     */
⋮----
// /**
//  * Or, send an array of structured objects with parameters, if you wanted to send multiple in one request
//  */
// // client.subscribe([level2SubscribeRequest, anotherRequest, etc], 'advTradeMarketData');
⋮----
/**
     * Other adv trade public websocket topics:
     */

================
File: examples/CoinbaseApp/Public/cbapp-public-rest-all.ts
================
import { CBAppClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAppClient } from 'coinbase-api';
 * const { CBAppClient } = require('coinbase-api');
 */
⋮----
// Initialize the client, you can pass in api keys here if you have them but they are not required for public endpoints
⋮----
async function publicCalls()
⋮----
// Get fiat currencies
⋮----
// Get cryptocurrencies
⋮----
// Get exchange rates
⋮----
// Get buy price
⋮----
// Get sell price
⋮----
// Get spot price
⋮----
// Get current time

================
File: examples/README.md
================
# Examples

These samples can be executed using `ts-node` or `tsx`:

```
ts-node ./examples/ws-public.ts
```

Most examples also have minimal typescript, so if you rename them to "js" they should execute fine with just node. TypeScript is recommended but completely optional:

```
node ./examples/spot/getTickers.js
```

To find all endpoints and corresponding functions, you can use the [endpoint mapping file](../docs/endpointFunctionList.md). This file contains a pattern that matches the endpoints and corresponding functions in the SDK with the clients you can use!

Even though most of the function names are the same as the endpoint name in the official docs, some functions have slightly different names so you can search for them through the links. For more help on how to use the SDK, you can check out the Wiki page of our public repository [awesome-crypto-examples](https://github.com/tiagosiebler/awesome-crypto-examples/wiki/How-to-find-SDK-functions-that-match-API-docs-endpoint).

================
File: src/lib/websocket/logger.ts
================
export type LogParams = null | any;
⋮----
// eslint-disable-next-line @typescript-eslint/no-unused-vars
⋮----
// console.log(_params);

================
File: src/lib/websocket/typeGuards.ts
================
/* eslint-disable @typescript-eslint/no-unused-vars */
import {
  CBAdvancedTradeErrorEvent,
  CBAdvancedTradeEvent,
  CBExchangeBaseEvent,
} from '../../types/websockets/events.js';
import {
  WsExchangeRequestOperation,
  WsInternationalRequestOperation,
  WsPrimeRequestOperation,
} from '../../types/websockets/requests.js';
import { WS_KEY_MAP, WsKey } from './websocket-util.js';
⋮----
function isDefinedObject(value: unknown): value is object
⋮----
export function isCBAdvancedTradeWSEvent(
  event: unknown,
): event is CBAdvancedTradeEvent
⋮----
/**
 * Type guard that checks whether this event is/extends CBExchangeBaseEvent
 */
export function isCBExchangeWSEvent(
  event: unknown,
  wsKey: WsKey,
): event is CBExchangeBaseEvent
⋮----
/**
 * Type guard for error-type response events seen for the Advnaced Trade WS channel
 */
export function isCBAdvancedTradeErrorEvent(
  event: unknown,
): event is CBAdvancedTradeErrorEvent
⋮----
/**
 * Silly type guard for the structure of events being sent to the server
 * (e.g. when subscribing to a topic)
 */
export function isCBExchangeWSRequestOperation<
  TWSTopic extends string = string,
>(evt: unknown, wsKey: WsKey): evt is WsExchangeRequestOperation<TWSTopic>
⋮----
/**
 * Silly type guard for the structure of events being sent to the server
 * (e.g. when subscribing to a topic)
 */
export function isCBINTXWSRequestOperation<TWSTopic extends string = string>(
  evt: unknown,
  wsKey: WsKey,
): evt is WsInternationalRequestOperation<TWSTopic>
⋮----
/**
 * Silly type guard for the structure of events being sent to the server
 * (e.g. when subscribing to a topic)
 */
export function isCBPrimeWSRequestOperation<TWSTopic extends string = string>(
  evt: unknown,
  wsKey: WsKey,
): evt is WsPrimeRequestOperation<TWSTopic>

================
File: src/lib/websocket/websocket-util.ts
================
import WebSocket from 'isomorphic-ws';
⋮----
import {
  WsExchangeRequestOperation,
  WsInternationalRequestOperation,
} from '../../types/websockets/requests.js';
import { signMessage } from '../webCryptoAPI.js';
⋮----
/**
 * Each websocket URL (domain + endpoint) is represented as a "WS Key". Authentication is handled automatically if required.
 */
⋮----
/**
   * Market Data is the traditional feed that provides updates for both orders and trades.
   * Most channels are now available without authentication.
   *
   * https://docs.cdp.coinbase.com/advanced-trade/docs/ws-overview
   */
⋮----
/**
   * User Order Data provides updates for the orders of the user.
   *
   * https://docs.cdp.coinbase.com/advanced-trade/docs/ws-overview
   */
⋮----
/**
   * Coinbase Market Data (part of Coinbase Exchange API) is the traditional feed which is available without authentication.
   *
   * https://docs.cdp.coinbase.com/exchange/docs/websocket-overview
   */
⋮----
/**
   * Coinbase Direct Market Data has direct access to Coinbase Exchange servers and requires Authentication.
   *
   * https://docs.cdp.coinbase.com/exchange/docs/websocket-overview
   */
⋮----
/**
   * The INTX WebSocket feed is publicly available and provides real-time market data updates for orders and trades.
   * The SDK must authenticate when subscribing to the WebSocket Feed the very first time.
   *
   * https://docs.cdp.coinbase.com/intx/docs/websocket-overview
   */
⋮----
/**
   * The Prime WebSocket feed provides real-time market data updates for orders and trades. To begin
   * receiving feed messages, you must send a signed subscribe message to the server indicating
   * which channels and products to receive. The SDK will handle this automatically.
   *
   * https://docs.cdp.coinbase.com/prime/docs/websocket-feed
   */
⋮----
/** This is used to differentiate between each of the available websocket streams */
export type WsKey = (typeof WS_KEY_MAP)[keyof typeof WS_KEY_MAP];
⋮----
/**
 * Normalised internal format for a request (subscribe/unsubscribe/etc) on a topic, with optional parameters.
 *
 * - Topic: the topic this event is for
 * - Payload: the parameters to include, optional. E.g. auth requires key + sign. Some topics allow configurable parameters.
 */
export interface WsTopicRequest<
  TWSTopic extends string = string,
  TWSPayload = any,
> {
  topic: TWSTopic;
  /**
   * Any parameters to include with the request. These are automatically merged into the request.
   */
  payload?: TWSPayload;
}
⋮----
/**
   * Any parameters to include with the request. These are automatically merged into the request.
   */
⋮----
/**
 * Conveniently allow users to request a topic either as string topics or objects (containing string topic + params)
 */
export type WsTopicRequestOrStringTopic<
  TWSTopic extends string,
  TWSPayload = any,
> = WsTopicRequest<TWSTopic, TWSPayload> | string;
⋮----
export interface MessageEventLike {
  target: WebSocket;
  type: 'message';
  data: string;
}
⋮----
export function isMessageEvent(msg: unknown): msg is MessageEventLike
⋮----
/**
 * Some exchanges have two livenet environments, some have test environments, some dont. This allows easy flexibility for different exchanges.
 * Examples:
 *  - One livenet and one testnet: NetworkMap<'livenet' | 'testnet'>
 *  - One livenet, sometimes two, one testnet: NetworkMap<'livenet' | 'testnet', 'livenet2'>
 *  - Only one livenet, no other networks: NetworkMap<'livenet'>
 */
type NetworkMap<
  TRequiredKeys extends string,
  TOptionalKeys extends string | undefined = undefined,
> = Record<TRequiredKeys, string> &
  (TOptionalKeys extends string
    ? Record<TOptionalKeys, string | undefined>
    : Record<TRequiredKeys, string>);
⋮----
/**
 * Merge one or more WS Request operations (e.g. subscribe request) for
 * CB Exchange into one, allowing them to be sent as one request
 */
export function getMergedCBExchangeWSRequestOperations<
  TWSTopic extends string = string,
>(operations: WsExchangeRequestOperation<TWSTopic>[])
⋮----
// The CB Exchange WS supports sending multiple topics in one request.
// Merge all requests into one
⋮----
/**
 * Merge one or more WS Request operations (e.g. subscribe request) for
 * CB Exchange into one, allowing them to be sent as one request
 */
export function getMergedCBINTXRequestOperations<
  TWSTopic extends string = string,
>(operations: WsInternationalRequestOperation<TWSTopic>[])
⋮----
// The CB Exchange WS supports sending multiple topics in one request.
// Merge all requests into one
⋮----
/**
 * Return sign used to authenticate CB Exchange WS requests
 */
export async function getCBExchangeWSSign(apiSecret: string): Promise<
⋮----
/**
 * Return sign used to authenticate CB INTX WS requests
 */
export async function getCBInternationalWSSign(
  apiKey: string,
  apiSecret: string,
  apiPassphrase: string,
): Promise<
⋮----
/**
 * Return sign used to authenticate CB Prime WS requests
 */
export async function getCBPrimeWSSign(params: {
  channelName: string;
  svcAccountId: string;
  portfolioId: string;
  apiKey: string;
  apiSecret: string;
  product_ids?: string[];
}): Promise<
⋮----
// channelName + accessKey + svcAccountId + timestamp + portfolioId + products
⋮----
/**
 * ws.terminate() is undefined in browsers.
 * This only works in node.js, not in browsers.
 * Does nothing if `ws` is undefined. Does nothing in browsers.
 */
export function safeTerminateWs(
  ws?: WebSocket | any,
  fallbackToClose?: boolean,
): boolean

================
File: src/lib/websocket/WsStore.types.ts
================
import WebSocket from 'isomorphic-ws';
⋮----
export enum WsConnectionStateEnum {
  INITIAL = 0,
  CONNECTING = 1,
  CONNECTED = 2,
  CLOSING = 3,
  RECONNECTING = 4,
  ERROR_RECONNECTING = 5,
  // ERROR = 5,
}
⋮----
// ERROR = 5,
⋮----
export interface DeferredPromise<TSuccess = any, TError = any> {
  resolve?: (value: TSuccess) => TSuccess;
  reject?: (value: TError) => TError;
  promise?: Promise<TSuccess>;
}
⋮----
export interface WSConnectedResult {
  wsKey: string;
}
⋮----
export interface WsStoredState<TWSTopicSubscribeEvent extends string | object> {
  /** The currently active websocket connection */
  ws?: WebSocket;
  /** The current lifecycle state of the connection (enum) */
  connectionState?: WsConnectionStateEnum;
  /** A timer that will send an upstream heartbeat (ping) when it expires */
  activePingTimer?: ReturnType<typeof setTimeout> | undefined;
  /** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */
  activePongTimer?: ReturnType<typeof setTimeout> | undefined;
  /** If a reconnection is in progress, this will have the timer for the delayed reconnect */
  activeReconnectTimer?: ReturnType<typeof setTimeout> | undefined;
  /**
   * When a connection attempt is in progress (even for reconnect), a promise is stored here.
   *
   * This promise will resolve once connected (and will then get removed);
   */
  // connectionInProgressPromise?: DeferredPromise | undefined;
  deferredPromiseStore: Record<string, DeferredPromise>;
  /**
   * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops)
   *
   * A "Set" and a deep-object-match are used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
   */
  subscribedTopics: Set<TWSTopicSubscribeEvent>;
  /** Whether this connection is ready for events (welcome message received after connection) */
  isReadyForEvents?: boolean;
  /** Whether this connection has completed authentication (only applies to private connections) */
  isAuthenticated?: boolean;
  /** Whether this connection has completed authentication before for the Websocket API, so it knows to automatically reauth if reconnected */
  didAuthWSAPI?: boolean;
  /** To reauthenticate on the WS API, which channel do we send to? */
  WSAPIAuthChannel?: string;
}
⋮----
/** The currently active websocket connection */
⋮----
/** The current lifecycle state of the connection (enum) */
⋮----
/** A timer that will send an upstream heartbeat (ping) when it expires */
⋮----
/** A timer tracking that an upstream heartbeat was sent, expecting a reply before it expires */
⋮----
/** If a reconnection is in progress, this will have the timer for the delayed reconnect */
⋮----
/**
   * When a connection attempt is in progress (even for reconnect), a promise is stored here.
   *
   * This promise will resolve once connected (and will then get removed);
   */
// connectionInProgressPromise?: DeferredPromise | undefined;
⋮----
/**
   * All the topics we are expected to be subscribed to on this connection (and we automatically resubscribe to if the connection drops)
   *
   * A "Set" and a deep-object-match are used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
   */
⋮----
/** Whether this connection is ready for events (welcome message received after connection) */
⋮----
/** Whether this connection has completed authentication (only applies to private connections) */
⋮----
/** Whether this connection has completed authentication before for the Websocket API, so it knows to automatically reauth if reconnected */
⋮----
/** To reauthenticate on the WS API, which channel do we send to? */

================
File: src/lib/misc-util.ts
================
export function neverGuard(x: never, msg: string): Error

================
File: src/lib/requestUtils.ts
================
import { CustomOrderIdProperty } from '../types/shared.types.js';
⋮----
/**
 * Used to switch how authentication/requests work under the hood
 */
⋮----
/** Coinbase Advanced Trade API */
⋮----
/** Coinbase App API */
⋮----
/** Coinbase Exchange API */
⋮----
/** Coinbase Prime API */
⋮----
/** Coinbase International API */
⋮----
/** Coinbase Commerce API */
⋮----
export type RestClientType =
  (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM];
⋮----
export interface RestClientOptions {
  /**
   * Your API key name.
   *
   * - For the Advanced Trade or App APIs, this is your API Key Name.
   */
  apiKey?: string;

  /**
   * Your API key secret.
   *
   * - For the Advanced Trade or App APIs, this is your API private key (including the -----BEGIN EC PRIVATE KEY-----\n etc).
   */
  apiSecret?: string;

  /**
   * Your API passphrase (NOT your account password). Only used for the API groups that use an API passphrase:
   * - Coinbase Exchange API
   * - Coinbase International API
   * - Coinbase Prime API
   */
  apiPassphrase?: string;

  /**
   * For the Advanced Trade or App APIs, instead of passing the key name and
   * private key, you can also parse the exported "cdp_api_key.json" into an object and pass it here.
   *
   * It will automatically get parsed into the apiKey & apiSecret configuration parameters.
   */
  cdpApiKey?: {
    name: string;
    privateKey: string;
  };

  /**
   * https://docs.cdp.coinbase.com/coinbase-app/docs/localization
   *
   * The Coinbase App API supports localization for error messages and other strings.
   * Localization is defined in each request with Accept-Language header.
   *
   * Accepted values are currently as below. Note: this may not work for all coinbase product groups.
   */
  localisation?:
    | 'de'
    | 'en'
    | 'es'
    | 'es-mx'
    | 'fr'
    | 'id'
    | 'it'
    | 'nl'
    | 'pt'
    | 'pt-br';

  /**
   * Connect to the sandbox for supported products
   *
   * - Coinbase Exchange: https://docs.cdp.coinbase.com/exchange/docs/sandbox
   * - Coinbase International: https://docs.cdp.coinbase.com/intx/docs/sandbox
   *
   * - Coinbase App: No sandbox available.
   * - Coinbase Advanced Trade: No sandbox available.
   * - Coinbase Prime: No sandbox available.
   */
  useSandbox?: boolean;

  /**
   * Enable keep alive for REST API requests (via axios).
   * See: https://github.com/tiagosiebler/bybit-api/issues/368
   */
  keepAlive?: boolean;

  /**
   * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
   * Only relevant if keepAlive is set to true.
   * Default: 1000 (defaults comes from https agent)
   */
  keepAliveMsecs?: number;

  /**
   * For JWT auth (adv trade & app API), seconds until jwt expires. Defaults to 120 seconds.
   */
  jwtExpiresSeconds?: number;

  /** Default: false. If true, we'll throw errors if any params are undefined */
  strictParamValidation?: boolean;

  /**
   * Optionally override API protocol + domain
   * e.g baseUrl: 'https://api.differentUrl.com'
   **/
  baseUrl?: string;

  /** Default: true. whether to try and post-process request exceptions (and throw them). */
  parseExceptions?: boolean;
}
⋮----
/**
   * Your API key name.
   *
   * - For the Advanced Trade or App APIs, this is your API Key Name.
   */
⋮----
/**
   * Your API key secret.
   *
   * - For the Advanced Trade or App APIs, this is your API private key (including the -----BEGIN EC PRIVATE KEY-----\n etc).
   */
⋮----
/**
   * Your API passphrase (NOT your account password). Only used for the API groups that use an API passphrase:
   * - Coinbase Exchange API
   * - Coinbase International API
   * - Coinbase Prime API
   */
⋮----
/**
   * For the Advanced Trade or App APIs, instead of passing the key name and
   * private key, you can also parse the exported "cdp_api_key.json" into an object and pass it here.
   *
   * It will automatically get parsed into the apiKey & apiSecret configuration parameters.
   */
⋮----
/**
   * https://docs.cdp.coinbase.com/coinbase-app/docs/localization
   *
   * The Coinbase App API supports localization for error messages and other strings.
   * Localization is defined in each request with Accept-Language header.
   *
   * Accepted values are currently as below. Note: this may not work for all coinbase product groups.
   */
⋮----
/**
   * Connect to the sandbox for supported products
   *
   * - Coinbase Exchange: https://docs.cdp.coinbase.com/exchange/docs/sandbox
   * - Coinbase International: https://docs.cdp.coinbase.com/intx/docs/sandbox
   *
   * - Coinbase App: No sandbox available.
   * - Coinbase Advanced Trade: No sandbox available.
   * - Coinbase Prime: No sandbox available.
   */
⋮----
/**
   * Enable keep alive for REST API requests (via axios).
   * See: https://github.com/tiagosiebler/bybit-api/issues/368
   */
⋮----
/**
   * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000.
   * Only relevant if keepAlive is set to true.
   * Default: 1000 (defaults comes from https agent)
   */
⋮----
/**
   * For JWT auth (adv trade & app API), seconds until jwt expires. Defaults to 120 seconds.
   */
⋮----
/** Default: false. If true, we'll throw errors if any params are undefined */
⋮----
/**
   * Optionally override API protocol + domain
   * e.g baseUrl: 'https://api.differentUrl.com'
   **/
⋮----
/** Default: true. whether to try and post-process request exceptions (and throw them). */
⋮----
export function serializeParams<T extends Record<string, any> | undefined = {}>(
  params: T,
  strict_validation: boolean | undefined,
  encodeValues: boolean,
  prefixWith: string,
  explodeArrayParameters: boolean,
): string
⋮----
/**
     * Coinbase expected array parameters to be sent individually in GET requests, e.g:
     * ?order_side=SELL&order_status=OPEN&product_ids=BTC-USDC&product_ids=ETH-USDC
     *
     * This handles that repetition instead of sending arrays as-is
     */
⋮----
// Only prefix if there's a value...
⋮----
export function logInvalidOrderId(
  orderIdProperty: CustomOrderIdProperty,
  expectedOrderIdPrefix: string,
  params: unknown,
)
⋮----
export function getRestBaseUrl(
  restClientOptions: RestClientOptions,
  restClientType: RestClientType,
): string
⋮----
/**
 * Extract and separate request parameters in query string from the rest of the endpoint, to prevent sign issues.
 *
 * @param url endpoint containing params in query string; "/v2/accounts/123123213?someParam=xyz"
 * @returns
 */
export function getParamsFromURL(url: string):

================
File: src/lib/webCryptoAPI.ts
================
import { neverGuard } from './misc-util.js';
⋮----
function bufferToB64(buffer: ArrayBuffer): string
⋮----
function b64StringToBuffer(input: string): Uint8Array
⋮----
const binaryString = atob(input); // Decode base64 string
⋮----
// Convert binary string to a Uint8Array
⋮----
export type SignEncodeMethod = 'hex' | 'base64';
export type SignAlgorithm = 'SHA-256' | 'SHA-512';
⋮----
/**
 * Similar to node crypto's `createHash()` function
 */
export async function hashMessage(
  message: string,
  method: SignEncodeMethod,
  algorithm: SignAlgorithm,
): Promise<string>
⋮----
/**
 * Sign a message, with a secret, using the Web Crypto API
 */
export async function signMessage(
  message: string,
  secret: string,
  method: SignEncodeMethod,
  algorithm: SignAlgorithm,
  secretEncodeMethod: 'base64:web' | 'utf',
): Promise<string>
⋮----
// case 'base64:node': {
//   encodedSecret = Buffer.from(secret, 'base64');
//   break;
// }

================
File: src/types/request/advanced-trade-client.ts
================
/**
 *
 * Account Endpoints
 *
 */
⋮----
import { OrderConfiguration } from '../shared.types.js';
⋮----
/**
 *
 * Products Endpoints
 *
 */
⋮----
export interface GetAdvTradeProductsRequest {
  limit?: number;
  offset?: number;
  product_type?: 'UNKNOWN_PRODUCT_TYPE' | 'FUTURE' | 'SPOT';
  product_ids?: string[];
  contract_expiry_type?:
    | 'UNKNOWN_CONTRACT_EXPIRY_TYPE'
    | 'PERPETUAL'
    | 'EXPIRING';
  expiring_contract_status?:
    | 'UNKNOWN_EXPIRING_CONTRACT_STATUS'
    | 'STATUS_UNEXPIRED'
    | 'STATUS_EXPIRED'
    | 'STATUS_ALL';
  get_tradability_status?: boolean;
  get_all_products?: boolean;
}
⋮----
export interface GetAdvTradeProductCandlesRequest {
  product_id: string;
  start: string;
  end: string;
  granularity:
    | 'UNKNOWN_GRANULARITY'
    | 'ONE_MINUTE'
    | 'FIVE_MINUTE'
    | 'FIFTEEN_MINUTE'
    | 'THIRTY_MINUTE'
    | 'ONE_HOUR'
    | 'TWO_HOUR'
    | 'SIX_HOUR'
    | 'ONE_DAY';
  limit?: number;
}
⋮----
export interface GetAdvTradeMarketTradesRequest {
  product_id: string;
  limit: number;
  start?: string;
  end?: string;
}
⋮----
/**
 *
 * Orders Endpoints
 *
 */
⋮----
/**
 * Note: client_order_id is optional, because the SDK will automatically generate a value for you during the request.
 *
 * If you are generating your own, make sure you either use the client.generateNewOrderId() method or make sure to prefix your value with "cbnode".
 * The SDK will automatically add the prefix if the prefix is missing.
 */
export interface SubmitAdvTradeOrderRequest {
  client_order_id?: string;
  product_id: string;
  side: 'BUY' | 'SELL';
  order_configuration: OrderConfiguration;
  attached_order_configuration?: OrderConfiguration;
  leverage?: string;
  margin_type?: 'CROSS' | 'ISOLATED';
  retail_portfolio_id?: string; // deprecated
  preview_id?: string;
}
⋮----
retail_portfolio_id?: string; // deprecated
⋮----
export interface GetAdvTradeOrdersRequest {
  order_ids?: string[];
  product_ids?: string[];
  product_type?: 'UNKNOWN_PRODUCT_TYPE' | 'SPOT' | 'FUTURE';
  order_status?: string[];
  time_in_forces?: string[];
  order_types?: string[];
  order_side?: 'BUY' | 'SELL';
  start_date?: string;
  end_date?: string;
  order_placement_source?:
    | 'UNKNOWN_PLACEMENT_SOURCE'
    | 'RETAIL_SIMPLE'
    | 'RETAIL_ADVANCED';
  contract_expiry_type?:
    | 'UNKNOWN_CONTRACT_EXPIRY_TYPE'
    | 'PERPETUAL'
    | 'EXPIRING';
  asset_filters?: string[];
  retail_portfolio_id?: string;
  limit?: number;
  cursor?: string;
  sort_by?: 'UNKNOWN_SORT_BY' | 'LIMIT_PRICE' | 'LAST_FILL_TIME';
  user_native_currency?: string; // deprecated
}
⋮----
user_native_currency?: string; // deprecated
⋮----
export interface GetAdvTradeFillsRequest {
  order_ids?: string[];
  trade_ids?: string[];
  product_ids?: string[];
  start_sequence_timestamp?: string;
  end_sequence_timestamp?: string;
  retail_portfolio_id?: string;
  limit?: number;
  cursor?: string;
  sort_by?: 'UNKNOWN_SORT_BY' | 'PRICE' | 'TRADE_TIME';
}
⋮----
export interface PreviewAdvTradeOrderRequest {
  product_id: string;
  side: 'BUY' | 'SELL';
  order_configuration: OrderConfiguration;
  leverage?: string;
  margin_type?: 'ISOLATED' | 'CROSS';
  retail_portfolio_id?: string;
}
⋮----
/**
 * Note: client_order_id is optional, because the SDK will automatically generate a value for you during the request.
 *
 * If you are generating your own, make sure you either use the client.generateNewOrderId() method or make sure to prefix your value with "cbnode".
 * The SDK will automatically add the prefix if the prefix is missing.
 */
export interface CloseAdvTradePositionRequest {
  client_order_id?: string;
  product_id: string;
  size?: string;
}
⋮----
/**
 *
 * Portfolios Endpoints
 *
 */
⋮----
export interface MoveAdvTradePortfolioFundsRequest {
  funds: {
    value: string;
    currency: string;
  };
  source_portfolio_uuid: string;
  target_portfolio_uuid: string;
}
⋮----
/**
 *
 * Futures Endpoints
 *
 */
⋮----
/**
 *
 * Perpetuals Endpoints
 *
 */
⋮----
export interface AllocateAdvTradePortfolioRequest {
  portfolio_uuid: string;
  symbol: string;
  amount: string;
  currency: string;
}
/**
 *
 * Fees Endpoints
 *
 */
⋮----
export interface GetAdvTradeTransactionSummaryRequest {
  product_type?: 'UNKNOWN_PRODUCT_TYPE' | 'SPOT' | 'FUTURE';
  contract_expiry_type?: 'UNKNOWN_CONTRACT_EXPIRY_TYPE' | 'SPOT' | 'FUTURE';
  product_venue?: 'UNKNOWN_VENUE_TYPE' | 'CBE' | 'FCM' | 'INTX';
}
⋮----
/**
 *
 * Converts Endpoints
 *
 */
⋮----
export interface SubmitAdvTradeConvertQuoteRequest {
  from_account: string;
  to_account: string;
  amount: string;
  trade_incentive_metadata?: {
    user_incentive_id?: string;
    code_val?: string;
  };
}
⋮----
/**
 *
 * Public Endpoints
 *
 */
⋮----
export interface GetAdvTradePublicProductsRequest {
  limit?: number;
  offset?: number;
  product_type?: 'UNKNOWN_PRODUCT_TYPE' | 'SPOT' | 'FUTURE';
  product_ids?: string[];
  contract_expiry_type?: 'UNKNOWN_CONTRACT_EXPIRY_TYPE' | 'SPOT' | 'FUTURE';
  expiring_contract_status?:
    | 'UNKNOWN_EXPIRING_CONTRACT_STATUS'
    | 'STATUS_UNEXPIRED'
    | 'STATUS_EXPIRED'
    | 'STATUS_ALL';
  get_all_products?: boolean;
}
⋮----
export interface GetAdvTradePublicProductCandlesRequest {
  product_id: string;
  start: string;
  end: string;
  granularity:
    | 'UNKNOWN_GRANULARITY'
    | 'ONE_MINUTE'
    | 'FIVE_MINUTE'
    | 'FIFTEEN_MINUTE'
    | 'THIRTY_MINUTE'
    | 'ONE_HOUR'
    | 'TWO_HOUR'
    | 'SIX_HOUR'
    | 'ONE_DAY';
  limit?: number;
}
⋮----
export interface GetAdvTradePublicMarketTradesRequest {
  product_id: string;
  limit: number;
  start?: string;
  end?: string;
}
/**
 *
 * Payment Methods Endpoints
 *
 */
⋮----
/**
 *
 * Data API Endpoints
 *
 */

================
File: src/types/request/coinbase-app-client.ts
================
/**
 *
 * Account Endpoints
 *
 */
⋮----
/**
 *
 * Address Endpoints
 *
 */
⋮----
/**
 *
 * Transactions Endpoints
 *
 */
⋮----
export interface CBAppBeneficiaryAddress {
  address1: string;
  address2?: string;
  address3?: string;
  city?: string;
  state?: string;
  country?: string; // ISO 3166-1 alpha-2 country code
  postal_code?: string;
}
⋮----
country?: string; // ISO 3166-1 alpha-2 country code
⋮----
export interface CBAppTravelRuleData {
  beneficiary_wallet_type: 'WALLET_TYPE_SELF_HOSTED' | 'WALLET_TYPE_EXCHANGE';
  is_self: 'IS_SELF_FALSE' | 'IS_SELF_TRUE';
  beneficiary_name: string;
  beneficiary_address: CBAppBeneficiaryAddress;
  beneficiary_financial_institution: string;
  transfer_purpose: string;
}
⋮----
export interface CBAppSendMoneyRequest {
  account_id: string;
  type: 'send';
  to: string;
  amount: string;
  currency: string;
  description?: string;
  skip_notifications?: boolean;
  idem?: string;
  destination_tag?: string;
  network?: string;
  travel_rule_data?: CBAppTravelRuleData;
}
⋮----
export interface CBAppTransferMoneyRequest {
  account_id: string;
  type: 'transfer';
  to: string;
  amount: string;
  currency: string;
  description?: string;
}
/**
 *
 * Deposits Endpoints
 *
 */
⋮----
export interface CBAppDepositFundsRequest {
  account_id: string;
  amount: string;
  currency: string;
  payment_method: string;
  commit?: boolean;
}
⋮----
/**
 *
 * Withdrawals Endpoints
 *
 */
⋮----
export interface CBAppWithdrawFundsRequest {
  account_id: string;
  amount: string;
  currency: string;
  payment_method: string;
  commit?: boolean;
}
⋮----
/**
 *
 * DATA - Currencies Endpoints
 *
 */
⋮----
/**
 *
 * DATA- Exchange rates Endpoints
 *
 */
⋮----
/**
 *
 * DATA - Prices Endpoints
 *
 */
⋮----
/**
 *
 * DATA - Time Endpoints
 *
 */

================
File: src/types/request/coinbase-exchange.ts
================
/**
 *
 * Accounts Endpoints
 *
 */
export interface GetCBExchAccountHoldsRequest {
  account_id: string;
  before?: string;
  after?: string;
  limit?: number;
}
export interface GetCBExchAccountLedgerRequest {
  account_id: string;
  start_date?: string;
  end_date?: string;
  before?: string;
  after?: string;
  limit?: number;
  profile_id?: string;
}
⋮----
export interface GetCBExchAccountTransfersRequest {
  account_id: string;
  before?: string;
  after?: string;
  limit?: number;
  type?: string;
}
⋮----
/**
 *
 * Address book Endpoints
 *
 */
⋮----
export interface GetCBExchAddressBookRequest {
  addresses: {
    currency: string;
    to: {
      address: string;
      destination_tag?: string;
    };
    label?: string;
    is_verified_self_hosted_wallet?: boolean;
    vasp_id?: string;
  }[];
}
⋮----
/**
 *
 * Coinbase Account Endpoints
 *
 */
⋮----
export interface CreateCBExchNewCryptoAddress {
  account_id: string;
  profile_id?: string;
  network?: string;
}
⋮----
/**
 *
 * Conversions Endpoints
 *
 */
⋮----
export interface ConvertCBExchCurrencyRequest {
  profile_id: string;
  from: string;
  to: string;
  amount: string;
  nonce: string;
}
⋮----
/**
 *
 * Currencies Endpoints
 *
 */
⋮----
/**
 *
 * Transfers Endpoints
 *
 */
⋮----
export interface CBExchDepositFromCoinbaseAccount {
  profile_id: string;
  amount: string;
  coinbase_account_id: string;
  currency: string;
}
⋮----
export interface CBExchDepositFromPaymentMethod {
  profile_id: string;
  amount: string;
  payment_method_id: string;
  currency: string;
}
⋮----
export interface CBExchGetTransfersRequest {
  profile_id?: string;
  before?: string;
  after?: string;
  limit?: number;
  type?: string;
  currency_type?: string;
  transfer_reason?: string;
  currency?: string;
}
⋮----
export interface SubmitCBExchTravelInformation {
  transfer_id: string;
  originator_name: string;
  originator_country: string;
}
⋮----
export interface CBExchWithdrawToCBAccount {
  profile_id: string;
  amount: string;
  coinbase_account_id: string;
  currency: string;
}
⋮----
export interface CBExchWithdrawToCryptoAddress {
  profile_id: string;
  amount: string;
  currency: string;
  crypto_address: string;
  destination_tag?: string;
  no_destination_tag?: boolean;
  nonce?: number;
  network?: string;
  add_network_fee_to_total?: boolean;
  is_intermediary?: boolean;
  intermediary_jurisdiction?: string;
  travel_rule_data?: object;
}
⋮----
export interface CBExchGetCryptoWithdrawalFeeEstimate {
  currency: string;
  crypto_address: string;
  network?: string;
}
⋮----
export interface CBExchWithdrawToPaymentMethod {
  profile_id: string;
  amount: string;
  payment_method_id: string;
  currency: string;
}
⋮----
/**
 *
 * Fees Endpoints
 *
 */
⋮----
/**
 *
 * Orders Endpoints
 *
 */
⋮----
export interface GetCBExchFillsRequest {
  order_id?: string;
  product_id?: string;
  limit?: number;
  before?: string;
  after?: string;
  market_type?: string;
  start_date?: string;
  end_date?: string;
}
⋮----
export interface GetCBExchOrdersRequest {
  profile_id?: string;
  product_id?: string;
  sortedBy?: string;
  sorting?: string;
  start_date?: string;
  end_date?: string;
  before?: string;
  after?: string;
  limit: number;
  status: string[];
  market_type?: string;
}
⋮----
export interface SubmitCBExchOrderRequest {
  profile_id?: string;
  type: string;
  side: string;
  product_id: string;
  stp?: string;
  stop?: string;
  stop_price?: string;
  price?: string;
  size?: string;
  funds?: string;
  time_in_force?: string;
  cancel_after?: string;
  post_only?: boolean;
  client_oid?: string;
  max_floor?: string;
  stop_limit_price?: string;
}
⋮----
export interface CancelCBExchOrderRequest {
  order_id: string;
  profile_id?: string;
  product_id?: string;
}
⋮----
/**
 *
 * Loans Endpoints
 *
 */
⋮----
export interface SubmitCBExchNewLoan {
  loan_id: string;
  currency: string;
  native_amount: string;
  interest_rate: string;
  term_start_date: string;
  term_end_date: string;
  profile_id: string;
}
⋮----
export interface RepayCBExchLoanInterest {
  idem: string;
  from_profile_id: string;
  currency: string;
  native_amount: string;
}
⋮----
export interface RepayCBExchLoanPrincipal {
  loan_id: string;
  idem: string;
  from_profile_id: string;
  currency: string;
  native_amount: string;
}
⋮----
export interface GetCBExchPrincipalRepaymentPreview {
  loan_id: string;
  currency: string;
  native_amount: string;
}
/**
 *
 * Coinbase Price Oracle Endpoints
 *
 */
⋮----
/**
 *
 * Products Endpoints
 *
 */
⋮----
export interface GetCBExchProductCandles {
  product_id: string;
  granularity: number;
  start?: string;
  end?: string;
}
⋮----
export interface GetCBExchProductTrades {
  product_id: string;
  limit?: number;
  before?: string;
  after?: string;
}
⋮----
/**
 *
 * Profiles Endpoints
 *
 */
⋮----
export interface TransferCBExchFundsBetweenProfiles {
  from: string;
  to: string;
  currency: string;
  amount: string;
}
⋮----
/**
 *
 * Reports Endpoints
 *
 */
⋮----
export interface GetAllCBExchReports {
  profile_id?: string;
  after?: string;
  limit?: number;
  type?: string;
  ignore_expired?: boolean;
}
⋮----
export interface CreateCBExchReport {
  type: string;
  year?: string;
  format?: string;
  email?: string;
  profile_id?: string;
  balance?: { datetime?: string; group_by_profile?: boolean };
  fills?: { start_date?: string; end_date?: string; product_id?: string };
  account?: { start_date?: string; end_date?: string; account_id?: string };
  otc_fills?: { start_date?: string; end_date?: string; product_id?: string };
  tax_invoice?: {
    start_date?: string;
    end_date?: string;
    product_id?: string;
  };
  rfq_fills?: { start_date?: string; end_date?: string; product_id?: string };
}
⋮----
/**
 *
 * Travel Rule Endpoints
 *
 */
⋮----
export interface GetCBExchTravelRuleInformation {
  before?: string;
  after?: string;
  limit?: number;
  address?: string;
}
/**
 *
 * Users Endpoints
 *
 */
⋮----
/**
 *
 * Wrapped Assets Endpoints
 *
 */
⋮----
export interface GetCBExchAllStakeWraps {
  before?: string;
  after?: string;
  limit?: number;
  from?: string;
  to?: string;
  status?: string;
}

================
File: src/types/request/coinbase-prime.ts
================
/**
 *
 * Allocation Endpoints
 *
 */
⋮----
export interface CreatePrimePortfolioAllocationsRequest {
  allocation_id?: string;
  source_portfolio_id?: string;
  product_id?: string;
  order_ids?: string[];
  allocation_legs: {
    allocation_leg_id: string;
    destination_portfolio_id: string;
    amount: string;
  }[];
  size_type?: 'BASE' | 'QUOTE' | 'PERCENT';
  remainder_destination_portfolio?: string;
}
⋮----
export interface CreatePrimePortfolioNetAllocationsRequest {
  netting_id?: string;
  source_portfolio_id?: string;
  product_id?: string;
  order_ids?: string[];
  allocation_legs: {
    allocation_leg_id: string;
    destination_portfolio_id: string;
    amount: string;
  }[];
  size_type?: 'BASE' | 'QUOTE' | 'PERCENT';
  remainder_destination_portfolio?: string;
}
⋮----
export interface GetPrimePortfolioAllocationsRequest {
  portfolio_id: string;
  product_ids?: string[];
  order_side?: 'BUY' | 'SELL';
  start_date?: string;
  end_date?: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'DESC' | 'ASC';
}
/**
 *
 * Invoice Endpoints
 *
 */
⋮----
export interface GetPrimeInvoicesRequest {
  entity_id: string;
  states?: string[];
  billing_year?: number;
  billing_month?: number;
  cursor?: number;
  limit?: number;
}
/**
 *
 * Assets Endpoints
 *
 */
⋮----
/**
 *
 * Payment Methods Endpoints
 *
 */
⋮----
/**
 *
 * Users Endpoints
 *
 */
⋮----
export interface GetPrimeUsersRequest {
  entity_id: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'ASC' | 'DESC';
}
⋮----
export interface GetPrimePortfolioUsersRequest {
  portfolio_id: string;
  cursor?: string;
  limit?: number;
  sort_direction?: string;
}
/**
 *
 * Portfolios Endpoints
 *
 */
⋮----
/**
 *
 * Activities Endpoints
 *
 */
⋮----
export interface GetPrimeActivitiesRequest {
  portfolio_id: string;
  symbols?: string[];
  categories?: string[];
  statuses?: string[];
  start_time?: string;
  end_time?: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'ASC' | 'DESC';
}
⋮----
export interface GetPrimeEntityActivitiesRequest {
  entity_id: string;
  activity_level?: 'ACTIVITY_LEVEL_ALL';
  symbols?: string[];
  categories?: string[];
  statuses?: string[];
  start_time?: string;
  end_time?: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'ASC' | 'DESC';
}
⋮----
export interface GetPrimePortfolioActivityByIdRequest {
  portfolio_id: string;
  activity_id: string;
}
/**
 *
 * Address Book Endpoints
 *
 */
⋮----
export interface GetPrimeAddressBookRequest {
  portfolio_id: string;
  currency_symbol?: string;
  search?: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'DESC' | 'ASC';
}
⋮----
export interface CreatePrimeAddressBookEntryRequest {
  portfolio_id: string;
  address: string;
  currency_symbol: string;
  name: string;
  account_identifier?: string;
}
/**
 *
 * Balances Endpoints
 *
 */
⋮----
export interface GetPrimeWeb3WalletBalancesRequest {
  portfolio_id: string;
  wallet_id: string;
  visibility_statuses?: string[];
  cursor?: string;
  limit?: number;
}
⋮----
/**
 *
 * Commission Endpoints
 *
 */
⋮----
/**
 *
 * Orders Endpoints
 *
 */
⋮----
export interface GetPrimePortfolioFillsRequest {
  portfolio_id: string;
  start_date: string;
  end_date?: string;
  limit?: number;
  cursor?: string;
  sort_direction?: 'DESC' | 'ASC';
}
⋮----
export interface GetPrimeOpenOrdersRequest {
  portfolio_id: string;
  product_ids?: string[];
  order_type?: 'MARKET' | 'LIMIT' | 'TWAP' | 'BLOCK' | 'VWAP' | 'STOP_LIMIT';
  sort_direction?: 'DESC' | 'ASC';
  start_date: string;
  order_side?: 'BUY' | 'SELL';
  end_date?: string;
}
⋮----
export interface SubmitPrimeOrderRequest {
  portfolio_id: string;
  product_id: string;
  side: 'BUY' | 'SELL';
  client_order_id?: string;
  type?: 'MARKET' | 'LIMIT' | 'TWAP' | 'VWAP' | 'STOP_LIMIT';
  base_quantity?: string;
  quote_value?: string;
  limit_price?: string;
  stop_price?: string;
  start_time?: string;
  expiry_time?: string;
  time_in_force?:
    | 'FILL_OR_KILL'
    | 'GOOD_UNTIL_DATE_TIME'
    | 'GOOD_UNTIL_CANCELLED'
    | 'IMMEDIATE_OR_CANCEL';
  stp_id?: string;
  display_quote_size?: string;
  display_base_size?: string;
  is_raise_exact?: boolean;
  historical_pov?: string;
}
⋮----
export interface GetPrimeOrderPreviewRequest {
  portfolio_id: string;
  product_id: string;
  side: 'BUY' | 'SELL';
  type?: 'MARKET' | 'LIMIT' | 'TWAP' | 'BLOCK' | 'VWAP' | 'STOP_LIMIT';
  base_quantity?: string;
  quote_value?: string;
  limit_price?: string;
  stop_price?: string;
  start_time?: string;
  expiry_time?: string;
  time_in_force?:
    | 'FILL_OR_KILL'
    | 'GOOD_UNTIL_DATE_TIME'
    | 'GOOD_UNTIL_CANCELLED'
    | 'IMMEDIATE_OR_CANCEL';
  is_raise_exact?: boolean;
  historical_pov?: string;
}
⋮----
export interface GetPrimePortfolioOrdersRequest {
  portfolio_id: string;
  order_statuses?: (
    | 'FILLED'
    | 'CANCELLED'
    | 'EXPIRED'
    | 'FAILED'
    | 'PENDING'
  )[];
  product_ids?: string[];
  order_type?: 'MARKET' | 'LIMIT' | 'TWAP' | 'BLOCK' | 'VWAP' | 'STOP_LIMIT';
  cursor?: string;
  limit?: number;
  sort_direction?: 'DESC' | 'ASC';
  order_side?: 'BUY' | 'SELL';
  start_date?: string;
  end_date?: string;
}
⋮----
export interface GetPrimeOrderFillsRequest {
  portfolio_id: string;
  order_id: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'DESC' | 'ASC';
}
/**
 *
 * Products Endpoints
 *
 */
⋮----
export interface GetPrimePortfolioProductsRequest {
  portfolio_id: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'DESC' | 'ASC';
}
⋮----
/**
 *
 * Transactions Endpoints
 *
 */
⋮----
export interface GetPrimePortfolioTransactionsRequest {
  portfolio_id: string;
  symbols?: string[];
  types?: string[];
  start_time?: string;
  end_time?: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'DESC' | 'ASC';
}
⋮----
export interface CreatePrimeConversionRequest {
  portfolio_id: string;
  wallet_id: string;
  amount: string;
  destination: string;
  idempotency_key: string;
  source_symbol: string;
  destination_symbol: string;
}
⋮----
export interface GetPrimeWalletTransactionsRequest {
  portfolio_id: string;
  wallet_id: string;
  types?: string[];
  start_time?: string;
  end_time?: string;
  cursor?: string;
  limit?: number;
  sort_direction?: 'DESC' | 'ASC';
}
⋮----
export interface CreatePrimeTransferRequest {
  portfolio_id: string;
  wallet_id: string;
  amount: string;
  destination: string;
  idempotency_key: string;
  currency_symbol: string;
}
⋮----
export interface CreatePrimeWithdrawalRequest {
  portfolio_id: string;
  wallet_id: string;
  amount: string;
  destination_type: 'DESTINATION_PAYMENT_METHOD' | 'DESTINATION_BLOCKCHAIN';
  idempotency_key: string;
  currency_symbol: string;
  payment_method?: {
    payment_method_id: string;
  };
  blockchain_address?: {
    address: string;
    account_identifier?: string;
  };
}
/**
 *
 * Wallets Endpoints
 *
 */
⋮----
export interface GetPrimePortfolioWalletsRequest {
  portfolio_id: string;
  type: 'VAULT' | 'TRADING' | 'WALLET_TYPE_OTHER' | 'WEB3';
  cursor?: string;
  limit?: number;
  sort_direction?: 'DESC' | 'ASC';
  symbols?: string[];
}
⋮----
export interface CreatePrimeWalletRequest {
  portfolio_id: string;
  name: string;
  symbol: string;
  wallet_type: 'VAULT' | 'TRADING' | 'WALLET_TYPE_OTHER' | 'WEB3';
}
⋮----
export interface GetPrimeWalletDepositInstructionsRequest {
  portfolio_id: string;
  wallet_id: string;
  deposit_type?:
    | 'UNKNOWN_WALLET_DEPOSIT_TYPE'
    | 'CRYPTO'
    | 'WIRE'
    | 'SEN'
    | 'SWIFT';
}
⋮----
/**
 *
 * Financing Endpoints
 *
 */
⋮----
export interface GetPrimeEntityAccrualsRequest {
  entity_id: string;
  portfolio_id?: string;
  start_date?: string;
  end_date?: string;
}
⋮----
export interface GetPrimeEntityLocateAvailabilitiesRequest {
  entity_id: string;
  conversion_date?: string;
  locate_date?: string;
}
⋮----
export interface GetPrimeEntityMarginSummariesRequest {
  entity_id: string;
  start_date?: string;
  end_date?: string;
}
⋮----
export interface GetPrimeEntityTFTieredFeesRequest {
  entity_id: string;
  effective_at?: string;
}
⋮----
export interface GetPrimePortfolioAccrualsRequest {
  portfolio_id: string;
  start_date?: string;
  end_date?: string;
}
⋮----
export interface GetPrimePortfolioBuyingPowerRequest {
  portfolio_id: string;
  base_currency: string;
  quote_currency: string;
}
⋮----
export interface GetPrimePortfolioLocatesRequest {
  portfolio_id: string;
  locate_ids?: string[];
  conversion_date?: string;
  locate_date?: string;
}
⋮----
export interface GetPrimePortfolioMarginConversionsRequest {
  portfolio_id: string;
  start_date?: string;
  end_date?: string;
}
⋮----
export interface GetPrimePortfolioWithdrawalPowerRequest {
  portfolio_id: string;
  symbol: string;
}

================
File: src/types/response/advanced-trade-client.ts
================
/**
 *
 * Account Endpoints
 *
 */
⋮----
import { OrderConfiguration } from '../shared.types.js';
⋮----
interface Balance {
  value: string;
  currency: string;
}
⋮----
export interface AdvTradeAccount {
  uuid: string;
  name: string;
  currency: string;
  available_balance: Balance;
  default: boolean;
  active: boolean;
  created_at: string;
  updated_at: string;
  deleted_at: string;
  type: string;
  ready: boolean;
  hold: Balance;
  retail_portfolio_id: string;
  platform: string;
}
⋮----
export interface AdvTradeAccountsList {
  accounts: AdvTradeAccount[];
  has_next: boolean;
  cursor: string;
  size: number;
}
⋮----
/**
 *
 * Products Endpoints
 *
 */
⋮----
interface PriceLevel {
  price: string;
  size: string;
}
⋮----
export interface AdvTradePricebook {
  product_id: string;
  bids: PriceLevel[];
  asks: PriceLevel[];
  time: string;
}
⋮----
interface FCMTradingSessionDetails {
  is_session_open: boolean;
  open_time: string;
  close_time: string;
  session_state: string;
  after_hours_order_entry_disabled: boolean;
}
⋮----
interface PerpetualDetails {
  open_interest: string;
  funding_rate: string;
  funding_time: string;
  max_leverage: string;
  base_asset_uuid: string;
  underlying_type: string;
}
⋮----
interface FutureProductDetails {
  venue: string;
  contract_code: string;
  contract_expiry: string;
  contract_size: string;
  contract_root_unit: string;
  group_description: string;
  contract_expiry_timezone: string;
  group_short_description: string;
  risk_managed_by: string;
  contract_expiry_type: string;
  perpetual_details: PerpetualDetails;
  contract_display_name: string;
  time_to_expiry_ms: string;
  non_crypto: boolean;
  contract_expiry_name: string;
}
⋮----
export interface AdvTradeProduct {
  product_id: string;
  price: string;
  price_percentage_change_24h: string;
  volume_24h: string;
  volume_percentage_change_24h: string;
  base_increment: string;
  quote_increment: string;
  quote_min_size: string;
  quote_max_size: string;
  base_min_size: string;
  base_max_size: string;
  base_name: string;
  quote_name: string;
  watched: boolean;
  is_disabled: boolean;
  new: boolean;
  status: string;
  cancel_only: boolean;
  limit_only: boolean;
  post_only: boolean;
  trading_disabled: boolean;
  auction_mode: boolean;
  product_type: string;
  quote_currency_id: string;
  base_currency_id: string;
  fcm_trading_session_details: FCMTradingSessionDetails;
  mid_market_price: string;
  alias: string;
  alias_to: string[];
  base_display_symbol: string;
  quote_display_symbol: string;
  view_only: boolean;
  price_increment: string;
  display_name: string;
  product_venue: string;
  approximate_quote_24h_volume: string;
  future_product_details: FutureProductDetails;
}
⋮----
export interface AdvTradeCandle {
  start: string;
  low: string;
  high: string;
  open: string;
  close: string;
  volume: string;
}
⋮----
interface Trade {
  trade_id: string;
  product_id: string;
  price: string;
  size: string;
  time: string; // RFC3339 Timestamp
  side: 'BUY' | 'SELL';
}
⋮----
time: string; // RFC3339 Timestamp
⋮----
export interface AdvTradeMarketTrades {
  trades: Trade[];
  best_bid: string;
  best_ask: string;
}
⋮----
/**
 *
 * Orders Endpoints
 *
 */
⋮----
// Response interfaces
interface SuccessOrderResponse {
  order_id: string;
  product_id: string;
  side: 'BUY' | 'SELL';
  client_order_id: string;
}
⋮----
interface ErrorOrderResponse {
  error?: string;
  message: string;
  error_details: string;
  preview_failure_reason?: string;
  new_order_failure_reason: string;
}
⋮----
export interface AdvTradeSubmitOrderResponse {
  success: boolean;
  success_response?: SuccessOrderResponse;
  error_response?: ErrorOrderResponse;
  order_configuration: OrderConfiguration;
}
⋮----
export interface AdvTradeCancelOrdersResponse {
  results: {
    success: boolean;
    failure_reason: string;
    order_id: string;
  }[];
}
⋮----
export interface AdvTradeEditOrderResponse {
  success: boolean;
  success_response?: {
    order_id: string;
  };
  error_response?: {
    error_details?: string;
    edit_order_failure_reason: string;
    errors?: {
      edit_failure_reason?: string;
      preview_failure_reason?: string;
    }[];
  };
}
⋮----
export interface AdvTradeEditOrderPreviewResponse {
  errors?: {
    edit_failure_reason?: string;
    preview_failure_reason?: string;
  };
  slippage?: string;
  order_total?: string;
  commission_total?: string;
  quote_size?: number;
  base_size?: number;
  best_bid?: string;
  best_ask?: string;
  average_filled_price?: string;
}
⋮----
export interface AdvTradeOrder {
  order_id: string;
  product_id: string;
  user_id: string;
  order_configuration: OrderConfiguration;
  side: 'BUY' | 'SELL';
  client_order_id: string;
  status: string;
  time_in_force?: string;
  created_time: string;
  completion_percentage: string;
  filled_size: string;
  average_filled_price: string;
  fee?: string;
  number_of_fills: string;
  filled_value: string;
  pending_cancel: boolean;
  size_in_quote: boolean;
  total_fees: string;
  size_inclusive_of_fees: boolean;
  total_value_after_fees: string;
  trigger_status?: string;
  order_type: string;
  reject_reason?: string;
  settled: boolean;
  product_type: string;
  reject_message?: string;
  cancel_message?: string;
  order_placement_source: string;
  outstanding_hold_amount: string;
  is_liquidation: boolean;
  last_fill_time?: string;
  edit_history?: Array<{
    price: string;
    size: string;
    replace_accept_timestamp: string;
  }>;
  leverage?: string;
  margin_type?: string;
  retail_portfolio_id?: string;
}
⋮----
export interface AdvTradeFill {
  entry_id: string;
  trade_id: string;
  order_id: string;
  trade_time: string; // RFC3339 Timestamp
  trade_type: string;
  price: string;
  size: string;
  commission: string;
  product_id: string;
  sequence_timestamp: string; // RFC3339 Timestamp
  liquidity_indicator: string;
  size_in_quote: boolean;
  user_id: string;
  side: string;
  retail_portfolio_id: string;
}
⋮----
trade_time: string; // RFC3339 Timestamp
⋮----
sequence_timestamp: string; // RFC3339 Timestamp
⋮----
export interface AdvTradeOrderPreview {
  order_total: string;
  commission_total: string;
  errs: string[];
  warning: string[];
  quote_size: string;
  base_size: string;
  best_bid: string;
  best_ask: string;
  is_max: boolean;
  order_margin_total?: string;
  leverage?: string;
  long_leverage?: string;
  short_leverage?: string;
  slippage?: string;
  preview_id?: string;
  current_liquidation_buffer?: string;
  projected_liquidation_buffer?: string;
  max_leverage?: string;
}
⋮----
export interface AdvTradeClosePositionResponse {
  success: boolean;
  success_response?: {
    order_id: string;
    product_id: string;
    side: string;
    client_order_id: string;
  };
  error_response?: {
    error: string;
    message: string;
    error_details: string;
    preview_failure_reason: string;
    new_order_failure_reason: string;
  };
  order_configuration?: OrderConfiguration;
}
/**
 *
 * Portfolios Endpoints
 *
 */
⋮----
export interface AdvTradePortfolio {
  name: string;
  uuid: string;
  type: 'UNDEFINED' | 'DEFAULT' | 'CONSUMER' | 'INTX';
  deleted: boolean;
}
⋮----
export interface AdvTradeMonetaryAmount {
  value: string;
  currency: string;
}
⋮----
export interface SpotAdvTradePortfolioPosition {
  asset: string;
  account_uuid: string;
  total_balance_fiat: number;
  total_balance_crypto: number;
  available_to_trade_fiat: number;
  allocation: number;
  one_day_change: number;
  cost_basis: AdvTradeMonetaryAmount;
  asset_img_url: string;
  is_cash: boolean;
}
⋮----
export interface PerpAdvTradePortfolioPosition {
  product_id: string;
  product_uuid: string;
  symbol: string;
  asset_image_url: string;
  vwap: AdvTradeMonetaryAmount;
  userNativeCurrency: AdvTradeMonetaryAmount;
  rawCurrency: AdvTradeMonetaryAmount;
  position_side:
    | 'FUTURES_POSITION_SIDE_UNSPECIFIED'
    | 'FUTURES_POSITION_SIDE_LONG'
    | 'FUTURES_POSITION_SIDE_SHORT';
  net_size: string;
  buy_order_size: string;
  sell_order_size: string;
  im_contribution: string;
  unrealized_pnl: AdvTradeMonetaryAmount;
  mark_price: AdvTradeMonetaryAmount;
  liquidation_price: AdvTradeMonetaryAmount;
  leverage: string;
  im_notional: AdvTradeMonetaryAmount;
  mm_notional: AdvTradeMonetaryAmount;
  position_notional: AdvTradeMonetaryAmount;
  margin_type:
    | 'MARGIN_TYPE_UNSPECIFIED'
    | 'MARGIN_TYPE_CROSS'
    | 'MARGIN_TYPE_ISOLATED';
  liquidation_buffer: string;
  liquidation_percentage: string;
}
⋮----
export interface FuturesAdvTradePortfolioPosition {
  product_id: string;
  contract_size: string;
  side:
    | 'FUTURES_POSITION_SIDE_UNSPECIFIED'
    | 'FUTURES_POSITION_SIDE_LONG'
    | 'FUTURES_POSITION_SIDE_SHORT';
  amount: string;
  avg_entry_price: string;
  current_price: string;
  unrealized_pnl: string;
  expiry: string; // RFC3339 Timestamp
  underlying_asset: string;
  asset_img_url: string;
  product_name: string;
  venue: string;
  notional_value: string;
}
⋮----
expiry: string; // RFC3339 Timestamp
⋮----
interface PortfolioBalances {
  total_balance: AdvTradeMonetaryAmount;
  total_futures_balance: AdvTradeMonetaryAmount;
  total_cash_equivalent_balance: AdvTradeMonetaryAmount;
  total_crypto_balance: AdvTradeMonetaryAmount;
  futures_unrealized_pnl: AdvTradeMonetaryAmount;
  perp_unrealized_pnl: AdvTradeMonetaryAmount;
}
⋮----
export interface AdvTradePortfolioBreakdown {
  portfolio: AdvTradePortfolio;
  portfolio_balances: PortfolioBalances;
  spot_positions: SpotAdvTradePortfolioPosition[];
  perp_positions: PerpAdvTradePortfolioPosition[];
  futures_positions: FuturesAdvTradePortfolioPosition[];
}
⋮----
/**
 *
 * Futures Endpoints
 *
 */
⋮----
export interface AdvTradeFuturesBalance {
  futures_buying_power: {
    value: string;
    currency: string;
  };
  total_usd_balance: {
    value: string;
    currency: string;
  };
  cbi_usd_balance: {
    value: string;
    currency: string;
  };
  cfm_usd_balance: {
    value: string;
    currency: string;
  };
  total_open_orders_hold_amount: {
    value: string;
    currency: string;
  };
  unrealized_pnl: {
    value: string;
    currency: string;
  };
  daily_realized_pnl: {
    value: string;
    currency: string;
  };
  initial_margin: {
    value: string;
    currency: string;
  };
  available_margin: {
    value: string;
    currency: string;
  };
  liquidation_threshold: {
    value: string;
    currency: string;
  };
  liquidation_buffer_amount: {
    value: string;
    currency: string;
  };
  liquidation_buffer_percentage: string;
  intraday_margin_window_measure: {
    margin_window_type: string;
    margin_level: string;
    initial_margin: string;
    maintenance_margin: string;
    liquidation_buffer: string;
    total_hold: string;
    futures_buying_power: string;
  };
  overnight_margin_window_measure: {
    margin_window_type: string;
    margin_level: string;
    initial_margin: string;
    maintenance_margin: string;
    liquidation_buffer: string;
    total_hold: string;
    futures_buying_power: string;
  };
}
⋮----
export interface AdvTradeCurrentMarginWindow {
  margin_window: {
    margin_window_type:
      | 'MARGIN_WINDOW_TYPE_UNSPECIFIED'
      | 'MARGIN_WINDOW_TYPE_OVERNIGHT'
      | 'MARGIN_WINDOW_TYPE_WEEKEND'
      | 'MARGIN_WINDOW_TYPE_INTRADAY'
      | 'MARGIN_WINDOW_TYPE_TRANSITION';
    end_time: string; // RFC3339 Timestamp
  };
  is_intraday_margin_killswitch_enabled: boolean;
  is_intraday_margin_enrollment_killswitch_enabled: boolean;
}
⋮----
end_time: string; // RFC3339 Timestamp
⋮----
export interface AdvTradeFuturesPosition {
  product_id: string;
  expiration_time: string; // RFC3339 Timestamp
  side: 'UNKNOWN' | 'LONG' | 'SHORT';
  number_of_contracts: string;
  current_price: string;
  avg_entry_price: string;
  unrealized_pnl: string;
  daily_realized_pnl: string;
}
⋮----
expiration_time: string; // RFC3339 Timestamp
⋮----
export interface AdvTradeFuturesSweep {
  id: string;
  requested_amount: {
    value: string;
    currency: string;
  };
  should_sweep_all: boolean;
  status: 'UNKNOWN_FCM_SWEEP_STATUS' | 'PENDING' | 'PROCESSING';
  scheduled_time: string; // RFC3339 Timestamp
}
⋮----
scheduled_time: string; // RFC3339 Timestamp
⋮----
/**
 *
 * Perpetuals Endpoints
 *
 */
⋮----
export interface AdvTradePerpetualsPortfolio {
  portfolios: {
    portfolio_uuid: string;
    collateral: string;
    position_notional: string;
    open_position_notional: string;
    pending_fees: string;
    borrow: string;
    accrued_interest: string;
    rolling_debt: string;
    portfolio_initial_margin: string;
    portfolio_im_notional: {
      value: string;
      currency: string;
    };
    portfolio_maintenance_margin: string;
    portfolio_mm_notional: {
      value: string;
      currency: string;
    };
    liquidation_percentage: string;
    liquidation_buffer: string;
    margin_type: 'MARGIN_TYPE_UNSPECIFIED';
    margin_flags: 'PORTFOLIO_MARGIN_FLAGS_UNSPECIFIED';
    liquidation_status: 'PORTFOLIO_LIQUIDATION_STATUS_UNSPECIFIED';
    unrealized_pnl: {
      value: string;
      currency: string;
    };
    total_balance: {
      value: string;
      currency: string;
    };
  }[];
  summary: {
    unrealized_pnl: {
      value: string;
      currency: string;
    };
    buying_power: {
      value: string;
      currency: string;
    };
    total_balance: {
      value: string;
      currency: string;
    };
    max_withdrawal_amount: {
      value: string;
      currency: string;
    };
  };
}
⋮----
export interface AdvTradePerpetualsPosition {
  product_id: string;
  product_uuid: string;
  portfolio_uuid: string;
  symbol: string;
  vwap: {
    value: string;
    currency: string;
  };
  entry_vwap: {
    value: string;
    currency: string;
  };
  position_side: string;
  margin_type: string;
  net_size: string;
  buy_order_size: string;
  sell_order_size: string;
  im_contribution: string;
  unrealized_pnl: {
    value: string;
    currency: string;
  };
  mark_price: {
    value: string;
    currency: string;
  };
  liquidation_price: {
    value: string;
    currency: string;
  };
  leverage: string;
  im_notional: {
    value: string;
    currency: string;
  };
  mm_notional: {
    value: string;
    currency: string;
  };
  position_notional: {
    value: string;
    currency: string;
  };
  aggregated_pnl: {
    value: string;
    currency: string;
  };
}
export interface AdvTradePerpetualsPositionSummary {
  positions: AdvTradePerpetualsPosition[];
  summary: {
    aggregated_pnl: {
      value: string;
      currency: string;
    };
  };
}
⋮----
export interface AdvTradePerpetualsAsset {
  asset_id: string;
  asset_uuid: string;
  asset_name: string;
  status: string;
  collateral_weight: string;
  account_collateral_limit: string;
  ecosystem_collateral_limit_breached: boolean;
  asset_icon_url: string;
  supported_networks_enabled: boolean;
}
⋮----
export interface AdvTradePortfolioBalance {
  portfolio_uuid: string;
  balances: {
    asset: AdvTradePerpetualsAsset;
    quantity: string;
    hold: string;
    transfer_hold: string;
    collateral_value: string;
    collateral_weight: string;
    max_withdraw_amount: string;
    loan: string;
    loan_collateral_requirement_usd: string;
    pledged_quantity: string;
  }[];
  is_margin_limit_reached: boolean;
}
⋮----
/**
 *
 * Fees Endpoints
 *
 */
⋮----
export interface AdvTradeFeeTier {
  pricing_tier: string;
  usd_from: string;
  usd_to: string;
  taker_fee_rate: string;
  maker_fee_rate: string;
  aop_from: string;
  aop_to: string;
  margin_rate: {
    value: string;
  };
  goods_and_services_tax: {
    rate: string;
    type: string;
  };
}
⋮----
export interface AdvTradeTransactionSummary {
  total_volume: number;
  total_fees: number;
  fee_tier: AdvTradeFeeTier;
  advanced_trade_only_volume: number;
  advanced_trade_only_fees: number;
  margin_rate: number;
  goods_and_services_tax: {
    rate: string;
    type: string;
  };
  coinbase_pro_volume: number;
  coinbase_pro_fees: number;
  total_balance: string;
}
⋮----
/**
 *
 * Converts Endpoints
 *
 */
⋮----
/**
 *
 * Public Endpoints
 *
 */
⋮----
export interface AdvTradePublicProduct {
  product_id: string;
  price: string;
  price_percentage_change_24h: string;
  volume_24h: string;
  volume_percentage_change_24h: string;
  base_increment: string;
  quote_increment: string;
  quote_min_size: string;
  quote_max_size: string;
  base_min_size: string;
  base_max_size: string;
  base_name: string;
  quote_name: string;
  watched: boolean;
  is_disabled: boolean;
  new: boolean;
  status: string;
  cancel_only: boolean;
  limit_only: boolean;
  post_only: boolean;
  trading_disabled: boolean;
  auction_mode: boolean;
  product_type: string;
  quote_currency_id: string;
  base_currency_id: string;
  fcm_trading_session_details?: {
    is_session_open: boolean;
    open_time: string; // RFC3339 Timestamp
    close_time: string; // RFC3339 Timestamp
    session_state: string;
    after_hours_order_entry_disabled: boolean;
  };
  mid_market_price?: string;
  alias?: string;
  alias_to?: string[];
  base_display_symbol: string;
  quote_display_symbol: string;
  view_only: boolean;
  price_increment: string;
  display_name: string;
  product_venue: string;
  approximate_quote_24h_volume?: string;
  future_product_details?: {
    venue: string;
    contract_code: string;
    contract_expiry: string; // RFC3339 Timestamp
    contract_size: string;
    contract_root_unit: string;
    group_description: string;
    contract_expiry_timezone: string;
    group_short_description: string;
    risk_managed_by: string;
    contract_expiry_type: string;
    perpetual_details?: {
      open_interest: string;
      funding_rate: string;
      funding_time: string; // RFC3339 Timestamp
      max_leverage: string;
      base_asset_uuid: string;
      underlying_type: string;
    };

    contract_display_name: string;
    time_to_expiry_ms: number;
    non_crypto: boolean;
    contract_expiry_name: string;
  };
}
⋮----
open_time: string; // RFC3339 Timestamp
close_time: string; // RFC3339 Timestamp
⋮----
contract_expiry: string; // RFC3339 Timestamp
⋮----
funding_time: string; // RFC3339 Timestamp
⋮----
/**
 *
 * Payment Methods Endpoints
 *
 */
⋮----
export interface AdvTradePaymentMethod {
  id: string;
  type: string;
  name: string;
  currency: string;
  verified: boolean;
  allow_buy: boolean;
  allow_sell: boolean;
  allow_deposit: boolean;
  allow_withdraw: boolean;
  created_at: string; // RFC3339 Timestamp
  updated_at: string; // RFC3339 Timestamp
}
⋮----
created_at: string; // RFC3339 Timestamp
updated_at: string; // RFC3339 Timestamp
⋮----
/**
 *
 * Data API Endpoints
 *
 */
⋮----
export interface AdvTradeApiKeyPermissions {
  can_view: boolean;
  can_trade: boolean;
  can_transfer: boolean;
  portfolio_uuid: string;
  portfolio_type: string;
}

================
File: src/types/response/coinbase-exchange.ts
================
/**
 *
 * Accounts Endpoints
 *
 */
⋮----
/**
 *
 * Address book Endpoints
 *
 */
⋮----
/**
 *
 * Coinbase Account Endpoints
 *
 */
⋮----
/**
 *
 * Conversions Endpoints
 *
 */
⋮----
/**
 *
 * Currencies Endpoints
 *
 */
⋮----
/**
 *
 * Transfers Endpoints
 *
 */
⋮----
/**
 *
 * Fees Endpoints
 *
 */
⋮----
/**
 *
 * Orders Endpoints
 *
 */
⋮----
/**
 *
 * Loans Endpoints
 *
 */
⋮----
/**
 *
 * Coinbase Price Oracle Endpoints
 *
 */
⋮----
/**
 *
 * Products Endpoints
 *
 */
⋮----
/**
 *
 * Profiles Endpoints
 *
 */
⋮----
/**
 *
 * Reports Endpoints
 *
 */
⋮----
/**
 *
 * Travel Rule Endpoints
 *
 */
⋮----
/**
 *
 * Users Endpoints
 *
 */
⋮----
/**
 *
 * Wrapped Assets Endpoints
 *
 */

================
File: src/types/response/coinbase-international.ts
================
/**
 *
 * Assets Endpoints
 *
 */
⋮----
/**
 *
 * Instruments Endpoints
 *
 */
⋮----
/**
 *
 * Position Offsets Endpoints
 *
 */
⋮----
/**
 *
 * Orders Endpoints
 *
 */
⋮----
/**
 *
 * Portfolios Endpoints
 *
 */
⋮----
/**
 *
 * Rankings Endpoints
 *
 */
⋮----
/**
 *
 * Transfers Endpoints
 *
 */
⋮----
/**
 *
 * Fee Rates Endpoints
 *
 */

================
File: src/types/response/coinbase-prime.ts
================
/**
 *
 * Allocation Endpoints
 *
 */
⋮----
/**
 *
 * Invoice Endpoints
 *
 */
⋮----
/**
 *
 * Assets Endpoints
 *
 */
⋮----
/**
 *
 * Payment Methods Endpoints
 *
 */
⋮----
/**
 *
 * Users Endpoints
 *
 */
⋮----
/**
 *
 * Portfolios Endpoints
 *
 */
⋮----
/**
 *
 * Activities Endpoints
 *
 */
⋮----
/**
 *
 * Address Book Endpoints
 *
 */
⋮----
/**
 *
 * Balances Endpoints
 *
 */
⋮----
/**
 *
 * Commission Endpoints
 *
 */
⋮----
/**
 *
 * Orders Endpoints
 *
 */
⋮----
/**
 *
 * Products Endpoints
 *
 */
⋮----
/**
 *
 * Transactions Endpoints
 *
 */
⋮----
/**
 *
 * Wallets Endpoints
 *
 */

================
File: src/types/response/ws.ts
================
export interface WsInfo {
  endpoint: string;
  encrypt: boolean;
  protocol: string;
  pingInterval: number;
  pingTimeout: number;
}

================
File: src/types/websockets/events.ts
================
import { WS_KEY_MAP } from '../../lib/websocket/websocket-util.js';
⋮----
export interface WsDataEvent<TData = any, TWSKey = string> {
  data: TData;
  table: string;
  wsKey: TWSKey;
}
⋮----
/**
 * General event structure for events from the advanced trade websocket
 */
export interface CBAdvancedTradeEvent {
  channel: string;
  client_id: string;
  timestamp: string;
  sequence_num: number;
  events: Record<'subscriptions', Record<string, string[]>>;
}
⋮----
export interface CBAdvancedTradeErrorEvent {
  type: 'error';
  message: string;
  wsKey:
    | typeof WS_KEY_MAP.advTradeMarketData
    | typeof WS_KEY_MAP.advTradeUserData;
}
⋮----
/**
 * General event structure for events from the Coinbase Exchange websocket.
 * All Coinbase Exchange events extend this schema.
 */
export interface CBExchangeBaseEvent {
  type: 'subscriptions' | string;
  wsKey:
    | typeof WS_KEY_MAP.exchangeMarketData
    | typeof WS_KEY_MAP.exchangeDirectMarketData;
}
⋮----
/**
 * Sent after subscribing to one or more channels
 */
export type CBExchangeSubscriptionsEvent = CBExchangeBaseEvent & {
  type: 'subscriptions';
  channels?: { name: string; product_ids: string[]; account_ids: null }[];
};

================
File: src/types/websockets/requests.ts
================
/* eslint-disable @typescript-eslint/no-unused-vars */
export type WsOperation = 'subscribe' | 'unsubscribe';
⋮----
/**
 * This is the format used for commands sent upstream for this websocket connection.
 *
 * Docs:
 * - Adv Trade: https://docs.cdp.coinbase.com/advanced-trade/docs/ws-auth#subscribing
 */
export interface WsAdvTradeRequestOperation<TWSTopic extends string = string> {
  type: WsOperation;
  channel: TWSTopic;
  product_ids?: string[];
  jwt?: string;
}
⋮----
export interface WsExchangeChannelWithParams<TWSTopic extends string = string> {
  name: TWSTopic;
  product_ids: string[];
}
⋮----
/**
 * Public subscribe/unsubscribe requests for the Coinbase Exchange product group
 */
export interface WsExchangeRequestOperation<TWSTopic extends string = string> {
  type: WsOperation;
  channels: (TWSTopic | WsExchangeChannelWithParams)[];
  product_ids?: string[];
}
⋮----
/**
 * Private (authenticated) subscribe/unsubscribe requests for the Coinbase Exchange product group
 * https://docs.cdp.coinbase.com/exchange/docs/websocket-auth
 */
export type WsExchangeAuthenticatedRequestOperation<
  TWSTopic extends string = string,
> = WsExchangeRequestOperation<TWSTopic> & {
  signature: string;
  key: string;
  passphrase: string;
  timestamp: string;
};
⋮----
/**
 * Public subscribe/unsubscribe requests for the Coinbase International product group
 */
export interface WsInternationalRequestOperation<
  TWSTopic extends string = string,
> {
  type: Uppercase<WsOperation>;
  channels: TWSTopic[];
  product_ids?: string[];
}
⋮----
/**
 * Private (authenticated) subscribe/unsubscribe requests for the Coinbase International product group
 * https://docs.cdp.coinbase.com/intx/docs/websocket-auth
 */
export type WsInternationalAuthenticatedRequestOperation<
  TWSTopic extends string = string,
> = WsInternationalRequestOperation<TWSTopic> & {
  time: string;
  key: string;
  passphrase: string;
  signature: string;
};
⋮----
/**
 * Public subscribe/unsubscribe requests for the Coinbase Prime product group
 */
export interface WsPrimeRequestOperation<TWSTopic extends string = string> {
  type: WsOperation;
  channel: TWSTopic;
  // these should be provided as a payload with the request, else auth will fail
  svcAccountId: string;
  portfolio_id: string;
  product_ids: string[];
}
⋮----
// these should be provided as a payload with the request, else auth will fail
⋮----
/**
 * Private (authenticated) subscribe/unsubscribe requests for the Coinbase Prime product group
 *
 * - https://docs.cdp.coinbase.com/prime/docs/websocket-feed#signing-messages
 * - https://docs.cdp.coinbase.com/prime/docs/websocket-channels
 */
export type WsPrimeAuthenticatedRequestOperation<
  TWSTopic extends string = string,
> = WsPrimeRequestOperation<TWSTopic> & {
  access_key: string;
  api_key_id: string;
  passphrase: string;
  signature: string;
  timestamp: string;
};

================
File: src/types/websockets/wsAPI.ts
================
export interface WsAPIWsKeyTopicMap {
  [k: string]: never;
}
⋮----
export interface WsAPITopicRequestParamMap {
  [k: string]: never;
}
⋮----
export interface WsAPITopicResponseMap {
  [k: string]: never;
}

================
File: src/types/shared.types.ts
================
// Order configuration types
interface MarketMarketIOC {
  quote_size?: string;
  base_size?: string;
}
⋮----
interface SORLimitIOC {
  base_size: string;
  limit_price: string;
}
⋮----
interface LimitLimitGTC {
  base_size: string;
  quote_size?: string;
  limit_price: string;
  post_only?: boolean;
}
⋮----
interface LimitLimitGTD {
  base_size: string;
  quote_size?: string;
  limit_price: string;
  end_time: string; // RFC3339 Timestamp
  post_only?: boolean;
}
⋮----
end_time: string; // RFC3339 Timestamp
⋮----
interface LimitLimitFOK {
  quote_size?: string;
  base_size: string;
  limit_price: string;
}
⋮----
interface StopLimitStopLimitGTC {
  base_size: string;
  limit_price: string;
  stop_price: string;
  stop_direction: 'STOP_DIRECTION_STOP_UP' | 'STOP_DIRECTION_STOP_DOWN';
}
⋮----
interface StopLimitStopLimitGTD {
  base_size: string;
  limit_price: string;
  stop_price: string;
  end_time: string; // RFC3339 Timestamp
  stop_direction: 'STOP_DIRECTION_STOP_UP' | 'STOP_DIRECTION_STOP_DOWN';
}
⋮----
end_time: string; // RFC3339 Timestamp
⋮----
interface TriggerBracketGTC {
  base_size: string;
  limit_price: string;
  stop_trigger_price: string;
}
⋮----
interface TriggerBracketGTD {
  base_size: string;
  limit_price: string;
  stop_trigger_price: string;
  end_time: string; // RFC3339 Timestamp
}
⋮----
end_time: string; // RFC3339 Timestamp
⋮----
interface TWAPLimitGTD {
  quote_size: string;
  base_size: string;
  start_time: string; // RFC3339 Timestamp
  end_time: string; // RFC3339 Timestamp
  limit_price: string;
}
⋮----
start_time: string; // RFC3339 Timestamp
end_time: string; // RFC3339 Timestamp
⋮----
// Main order configuration type
export interface OrderConfiguration {
  market_market_ioc?: MarketMarketIOC;
  sor_limit_ioc?: SORLimitIOC;
  limit_limit_gtc?: LimitLimitGTC;
  limit_limit_gtd?: LimitLimitGTD;
  limit_limit_fok?: LimitLimitFOK;
  twap_limit_gtd?: TWAPLimitGTD;
  stop_limit_stop_limit_gtc?: StopLimitStopLimitGTC;
  stop_limit_stop_limit_gtd?: StopLimitStopLimitGTD;
  trigger_bracket_gtc?: TriggerBracketGTC;
  trigger_bracket_gtd?: TriggerBracketGTD;
}
⋮----
export type CustomOrderIdProperty = 'client_order_id' | 'client_oid';

================
File: src/CBCommerceClient.ts
================
import { AxiosRequestConfig } from 'axios';
⋮----
import { BaseRestClient } from './lib/BaseRestClient.js';
import {
  REST_CLIENT_TYPE_ENUM,
  RestClientOptions,
  RestClientType,
} from './lib/requestUtils.js';
⋮----
/**
 * REST client for Coinbase Prime API:
 * https://docs.cdp.coinbase.com/commerce-onchain/docs/welcome
 */
export class CBCommerceClient extends BaseRestClient
⋮----
constructor(
    restClientOptions: RestClientOptions = {},
    requestOptions: AxiosRequestConfig = {},
)
⋮----
getClientType(): RestClientType
⋮----
/**
   *
   * Charges Endpoints
   *
   */
⋮----
/**
   * Creates a Charge
   *
   * Creates a charge.
   */
createCharge(params: {
    buyer_locale?: string;
    cancel_url?: string;
    checkout_id?: string;
    local_price: {
      amount: string;
      currency: string;
    };
    metadata?: {
      custom_field?: string;
      custom_field_two?: string;
    };
    pricing_type: string;
    redirect_url?: string;
}): Promise<any>
⋮----
/**
   * Returns All Charges
   *
   * Returns all charges.
   */
getAllCharges(): Promise<any>
⋮----
/**
   * Returns the Charge with the Order Code
   *
   * Returns the charge with the order code.
   */
getCharge(params:
⋮----
/**
   *
   * Checkouts Endpoints
   *
   */
⋮----
/**
   * Creates a New Checkout
   *
   * Creates a new checkout.
   */
createCheckout(params: {
    buyer_locale?: string;
    total_price: {
      amount: string;
      currency: string;
    };
    metadata?: {
      custom_field?: string;
      custom_field_two?: string;
    };
    pricing_type: string;
    requested_info?: string[];
}): Promise<any>
⋮----
/**
   * Returns All Checkout Sessions
   *
   * Returns all checkout sessions.
   */
getAllCheckouts(): Promise<any>
⋮----
/**
   * Returns a Specific Checkout Session
   *
   * Returns a specific checkout session.
   */
getCheckout(params:
⋮----
/**
   *
   * Events Endpoints
   *
   */
⋮----
/**
   * List Events
   *
   * Lists all events.
   */
listEvents(headers:
⋮----
/**
   * Show an Event
   *
   * Retrieves the details of an event. Supply the unique identifier of the event, which you might have received in a webhook.
   */
showEvent(
    params: { event_id: string },
    headers: { 'X-CC-Version': string },
): Promise<any>

================
File: src/CBExchangeClient.ts
================
import { AxiosRequestConfig } from 'axios';
⋮----
import { BaseRestClient } from './lib/BaseRestClient.js';
import {
  REST_CLIENT_TYPE_ENUM,
  RestClientOptions,
  RestClientType,
} from './lib/requestUtils.js';
import {
  CancelCBExchOrderRequest,
  CBExchDepositFromCoinbaseAccount,
  CBExchDepositFromPaymentMethod,
  CBExchGetCryptoWithdrawalFeeEstimate,
  CBExchGetTransfersRequest,
  CBExchWithdrawToCBAccount,
  CBExchWithdrawToCryptoAddress,
  CBExchWithdrawToPaymentMethod,
  ConvertCBExchCurrencyRequest,
  CreateCBExchNewCryptoAddress,
  CreateCBExchReport,
  GetAllCBExchReports,
  GetCBExchAccountHoldsRequest,
  GetCBExchAccountLedgerRequest,
  GetCBExchAccountTransfersRequest,
  GetCBExchAddressBookRequest,
  GetCBExchAllStakeWraps,
  GetCBExchFillsRequest,
  GetCBExchOrdersRequest,
  GetCBExchPrincipalRepaymentPreview,
  GetCBExchProductCandles,
  GetCBExchProductTrades,
  GetCBExchTravelRuleInformation,
  RepayCBExchLoanInterest,
  RepayCBExchLoanPrincipal,
  SubmitCBExchNewLoan,
  SubmitCBExchOrderRequest,
  SubmitCBExchTravelInformation,
  TransferCBExchFundsBetweenProfiles,
} from './types/request/coinbase-exchange.js';
⋮----
/**
 * REST client for Coinbase's Institutional Exchange API:
 * https://docs.cdp.coinbase.com/exchange/docs/welcome
 */
export class CBExchangeClient extends BaseRestClient
⋮----
constructor(
    restClientOptions: RestClientOptions = {},
    requestOptions: AxiosRequestConfig = {},
)
⋮----
getClientType(): RestClientType
⋮----
/**
   *
   * Accounts Endpoints
   *
   */
⋮----
/**
   * Get all accounts for a profile
   *
   * Get a list of trading accounts from the profile of the API key.
   * Your trading accounts are separate from your Coinbase accounts. See Deposit from Coinbase account for documentation on how to deposit funds to begin trading.
   */
getAccounts(): Promise<any>
⋮----
/**
   * Get a single account by id
   *
   * Information for a single account. Use this endpoint when you know the account_id. API key must belong to the same profile as the account.
   */
getAccount(params:
⋮----
/**
   * Get a single account's holds
   *
   * List the holds of an account that belong to the same profile as the API key. Holds are placed on an account for any active orders or
   * pending withdraw requests. As an order is filled, the hold amount is updated.
   * If an order is canceled, any remaining hold is removed. For withdrawals, the hold is removed after it is completed.
   */
getAccountHolds(params: GetCBExchAccountHoldsRequest): Promise<any>
⋮----
/**
   * Get a single account's ledger
   *
   * Lists ledger activity for an account. This includes anything that would affect the account's balance - transfers, trades, fees, etc.
   * If neither start_date nor end_date is set, the endpoint will return ledger activity for the past 1 day only.
   * List account activity of the API key's profile. Account activity either increases or decreases your account balance.
   *
   * Entry Types:
   * - transfer: Funds moved to/from Coinbase to Coinbase Exchange
   * - match: Funds moved as a result of a trade
   * - fee: Fee as a result of a trade
   * - rebate: Fee rebate as per our fee schedule
   * - conversion: Funds converted between fiat currency and a stablecoin
   */
getAccountLedger(params: GetCBExchAccountLedgerRequest): Promise<any>
⋮----
/**
   * Get a single account's transfers
   *
   * Lists past withdrawals and deposits for an account.
   */
getAccountTransfers(params: GetCBExchAccountTransfersRequest): Promise<any>
⋮----
/**
   *
   * Address book Endpoints
   *
   */
⋮----
/**
   * Get address book
   *
   * Get all addresses stored in the address book.
   */
getAddressBook(): Promise<any>
⋮----
/**
   * Add addresses
   *
   * Add new addresses to address book.
   */
addAddresses(params: GetCBExchAddressBookRequest): Promise<any>
⋮----
/**
   * Delete address
   *
   * Delete address from address book.
   */
deleteAddress(params:
⋮----
/**
   *
   * Coinbase Accounts Endpoints
   *
   */
⋮----
/**
   * Get all Coinbase wallets
   *
   * Gets all the user's available Coinbase wallets. These are the wallets/accounts that are used for buying and selling on www.coinbase.com.
   */
getCoinbaseWallets(): Promise<any>
⋮----
/**
   * Generate crypto address
   *
   * Generates a one-time crypto address for depositing crypto.
   */
createNewCryptoAddress(params: CreateCBExchNewCryptoAddress): Promise<any>
⋮----
/**
   *
   * Conversions Endpoints
   *
   */
⋮----
/**
   * Convert currency
   *
   * Converts funds from one currency to another. Funds are converted on the from account in the profile_id profile.
   */
convertCurrency(params: ConvertCBExchCurrencyRequest): Promise<any>
⋮----
/**
   * Get conversion fee rates
   *
   * Gets a list of current conversion fee rates and trailing 30 day volume by currency pair.
   */
getConversionFeeRates(): Promise<any>
⋮----
/**
   * Get a conversion
   *
   * Gets a currency conversion by id (i.e. USD -> USDC).
   */
getConversion(params: {
    conversion_id: string;
    profile_id?: string;
}): Promise<any>
⋮----
/**
   * Get all conversions
   *
   * Get all conversions associated with the profile tied to the API key used to make the request.
   */
getAllConversions(params: {
    profile_id: string;
    before?: string;
    after?: string;
    limit?: number;
}): Promise<any>
⋮----
/**
   *
   * Currencies Endpoints
   *
   */
⋮----
/**
   * Get all known currencies
   *
   * Gets a list of all known currencies. Note: Not all currencies may be currently in use for trading.
   */
getCurrencies(): Promise<any>
⋮----
/**
   * Get a currency
   *
   * Gets a single currency by id.
   */
getCurrency(currency_id: string): Promise<any>
⋮----
/**
   *
   * Transfers Endpoints
   *
   */
⋮----
/**
   * Deposit from Coinbase account
   *
   * Deposits funds from a www.coinbase.com wallet to the specified profile_id.
   */
depositFromCoinbaseAccount(
    params: CBExchDepositFromCoinbaseAccount,
): Promise<any>
⋮----
/**
   * Deposit from payment method
   *
   * Deposits funds from a linked external payment method to the specified profile_id.
   * See Get all payment methods. The SEPA payment method is not allowed for depositing funds because it is a push payment method.
   */
depositFromPaymentMethod(
    params: CBExchDepositFromPaymentMethod,
): Promise<any>
⋮----
/**
   * Get all payment methods
   *
   * Gets a list of the user's linked payment methods.
   */
getPaymentMethods(): Promise<any>
⋮----
/**
   * Get all transfers
   *
   * Gets a list of in-progress and completed transfers of funds in/out of any of the user's accounts.
   */
getTransfers(params?: CBExchGetTransfersRequest): Promise<any>
⋮----
/**
   * Get a single transfer
   *
   * Get information on a single transfer.
   */
getTransfer(params:
⋮----
/**
   * Submit travel information for a transfer
   *
   * Submit travel information for a transfer.
   */
submitTravelInformation(params: SubmitCBExchTravelInformation): Promise<any>
⋮----
/**
   * Withdraw to Coinbase account
   *
   * Withdraws funds from the specified profile_id to a www.coinbase.com wallet.
   * You can move funds between your Coinbase accounts and your Coinbase Exchange trading accounts within your daily limits. Moving funds between Coinbase and Coinbase Exchange is instant and free.
   * See the Coinbase Accounts section for retrieving your Coinbase accounts.
   */
withdrawToCoinbaseAccount(params: CBExchWithdrawToCBAccount): Promise<any>
⋮----
/**
   * Withdraw to crypto address
   *
   * Withdraws funds from the specified profile_id to an external crypto address.
   */
withdrawToCryptoAddress(params: CBExchWithdrawToCryptoAddress): Promise<any>
⋮----
/**
   * Get fee estimate for crypto withdrawal
   *
   * Gets the fee estimate for the crypto withdrawal to a crypto address.
   */
getCryptoWithdrawalFeeEstimate(
    params: CBExchGetCryptoWithdrawalFeeEstimate,
): Promise<any>
⋮----
/**
   * Withdraw to payment method
   *
   * Withdraws funds from the specified profile_id to a linked external payment method.
   * See the Payment Methods section for retrieving your payment methods.
   */
withdrawToPaymentMethod(params: CBExchWithdrawToPaymentMethod): Promise<any>
⋮----
/**
   *
   * Fees Endpoints
   *
   */
⋮----
/**
   * Get fees
   *
   * Get fee rates and 30 days trailing volume.
   * This request returns your current maker & taker fee rates, as well as your 30-day trailing volume. Quoted rates are subject to change.
   */
getFees(): Promise<any>
⋮----
/**
   *
   * Orders Endpoints
   *
   */
⋮----
/**
   * Get all fills
   *
   * Get a list of recent fills of the API key's profile. A fill is a partial or complete match on a specific order.
   */
getFills(params?: GetCBExchFillsRequest): Promise<any>
⋮----
/**
   * Get all orders
   *
   * List your current open orders. Only open or un-settled orders are returned by default. As soon as an order is no longer open and settled, it will no longer appear in the default request.
   * Open orders may change state between the request and the response depending on market conditions.
   */
getOrders(params?: GetCBExchOrdersRequest): Promise<any>
⋮----
/**
   * Cancel all orders
   *
   * With best effort, cancel all open orders. This may require you to make the request multiple times until all of the open orders are deleted.
   */
cancelAllOrders(params?: {
    profile_id?: string;
    product_id?: string;
}): Promise<any>
⋮----
/**
   * Create a new order
   *
   * Create an order. You can place two types of orders: limit and market. Orders can only be placed if your account has sufficient funds.
   * Once an order is placed, your account funds will be put on hold for the duration of the order.
   */
submitOrder(params: SubmitCBExchOrderRequest): Promise<any>
⋮----
/**
   * Get single order
   *
   * Get a single order by id.
   */
getOrder(params:
⋮----
/**
   * Cancel an order
   *
   * Cancel a single open order by id.
   */
cancelOrder(params: CancelCBExchOrderRequest): Promise<any>
⋮----
/**
   *
   * Loans Endpoints
   *
   */
⋮----
/**
   * List loans
   *
   * Accepts zero or more loan IDs as input. If no loan IDs are specified, it returns all loans for the user. Otherwise, it returns only the loan IDs specified.
   */
getLoans(params?:
⋮----
/**
   * List loan assets
   *
   * Get a list of lendable assets, a map of assets we accept as collateral for loans, and the haircut weight.
   */
getLoanAssets(): Promise<any>
⋮----
/**
   * List interest summaries
   *
   * List summaries of interest owed by asset.
   */
getInterestSummaries(): Promise<any>
⋮----
/**
   * List interest rate history
   *
   * List interest rate history for a loan.
   */
getInterestRateHistory(params:
⋮----
/**
   * List interest charges
   *
   * List interest charges for a loan.
   */
getInterestCharges(params:
⋮----
/**
   * Get lending overview
   *
   * This API summarizes lending for a given client. It calculates the overall loan balance, collateral level, and amounts available to borrow.
   * It also returns any withdrawal restrictions in force on the client.
   *
   * Get lending overview returns all amounts in USD notional values, except available_per_asset mappings which are returned in both notional and native values.
   */
getLendingOverview(): Promise<any>
⋮----
/**
   * Get new loan preview
   *
   * This API is similar to lending-overview but is used to preview the results of opening a new loan.
   * The values returned in the preview response take the existing loans, collateral and the potential change being previewed into account.
   * Note the preview request accepts native currency amounts as input.
   */
getNewLoanPreview(params: {
    currency: string;
    native_amount: string;
}): Promise<any>
⋮----
/**
   * Open new loan
   *
   * This API triggers a loan open request. Funding is not necessarily instantaneous and there is no SLA.
   * You are notified when funds have settled in your Exchange account. Loan open requests, once initiated, cannot be canceled.
   */
submitNewLoan(params: SubmitCBExchNewLoan): Promise<any>
⋮----
/**
   * List new loan options
   *
   * Get available currencies and interest rates for new loans. All amounts returned by this API are notional values (i.e., USD).
   */
getNewLoanOptions(): Promise<any>
⋮----
/**
   * Repay loan interest
   *
   * Submit an interest repayment for a loan.
   */
repayLoanInterest(params: RepayCBExchLoanInterest): Promise<any>
⋮----
/**
   * Repay loan principal
   *
   * Submit a principal repayment for a loan.
   */
repayLoanPrincipal(params: RepayCBExchLoanPrincipal): Promise<any>
⋮----
/**
   * Get principal repayment preview
   *
   * Preview the results of a loan principal repayment.
   * Like the Get lending overview API, all values are notional except available_per_asset which returns both notional and native values per currency.
   */
getPrincipalRepaymentPreview(
    params: GetCBExchPrincipalRepaymentPreview,
): Promise<any>
⋮----
/**
   *
   * Coinbase Price Oracle Endpoints
   *
   */
⋮----
/**
   * Get signed prices
   *
   * Get cryptographically signed prices ready to be posted on-chain using Compound's Open Oracle smart contract.
   */
getSignedPrices(): Promise<any>
⋮----
/**
   *
   * Products Endpoints
   *
   */
⋮----
/**
   * Get all known trading pairs
   *
   * Gets a list of available currency pairs for trading.
   */
getAllTradingPairs(params?:
⋮----
/**
   * Get all product volume
   *
   * Gets 30-day and 24-hour volume for all products and market types.
   */
getAllProductVolume(): Promise<any>
⋮----
/**
   * Get single product
   *
   * Get information on a single product.
   */
getProduct(params:
⋮----
/**
   * Get product book
   *
   * Get a list of open orders for a product. The amount of detail shown can be customized with the level parameter.
   * By default, only the inside (i.e., the best) bid and ask are returned. This is equivalent to a book depth of 1 level.
   * To see a larger order book, specify the level query parameter.
   */
getProductBook(params:
⋮----
/**
   * Get product candles
   *
   * Historic rates for a product. Rates are returned in grouped buckets.
   * Candle schema is of the form [timestamp, price_low, price_high, price_open, price_close].
   */
getProductCandles(params: GetCBExchProductCandles): Promise<any>
⋮----
/**
   * Get product stats
   *
   * Gets 30-day and 24-hour stats for a product.
   */
getProductStats(params:
⋮----
/**
   * Get product ticker
   *
   * Gets snapshot information about the last trade (tick), best bid/ask, and 24h volume.
   */
getProductTicker(params:
⋮----
/**
   * Get product trades
   *
   * Gets a list of the latest trades for a product.
   */
getProductTrades(params: GetCBExchProductTrades): Promise<any>
⋮----
/**
   *
   * Profiles Endpoints
   *
   */
⋮----
/**
   * Get profiles
   *
   * Gets a list of all of the current user's profiles.
   */
getProfiles(params?:
⋮----
/**
   * Create a profile
   *
   * Create a new profile. Will fail if no name is provided or if user already has max number of profiles.
   */
createProfile(params:
⋮----
/**
   * Transfer funds between profiles
   *
   * Transfer an amount of currency from one profile to another.
   */
transferFundsBetweenProfiles(
    params: TransferCBExchFundsBetweenProfiles,
): Promise<any>
⋮----
/**
   * Get profile by id
   *
   * Information for a single profile. Use this endpoint when you know the profile_id.
   */
getProfileById(params: {
    profile_id: string;
    active?: boolean;
}): Promise<any>
⋮----
/**
   * Rename a profile
   *
   * Rename a profile. Names 'default' and 'margin' are reserved.
   */
renameProfile(params:
⋮----
/**
   * Delete a profile
   *
   * Deletes the profile specified by profile_id and transfers all funds to the profile specified by to.
   * Fails if there are any open orders on the profile to be deleted.
   */
deleteProfile(params:
⋮----
/**
   *
   * Reports Endpoints
   *
   */
⋮----
/**
   * Get all reports
   *
   * Gets a list of all user-generated reports.
   */
getAllReports(params?: GetAllCBExchReports): Promise<any>
⋮----
/**
   * Create a report
   *
   * Generates a report. You can create reports with historical data for all report types.
   * Balance reports can be snapshots of historical or current data.
   */
createReport(params: CreateCBExchReport): Promise<any>
⋮----
/**
   * Get a report
   *
   * Get a specific report by report_id.
   */
getReport(params:
⋮----
/**
   *
   * Travel Rule Endpoints
   *
   */
⋮----
/**
   * Get all travel rule information
   *
   * Return a list of all stored travel rule information.
   */
getTravelRuleInformation(
    params?: GetCBExchTravelRuleInformation,
): Promise<any>
⋮----
/**
   * Create travel rule entry
   *
   * Create travel rule entry for sending address.
   */
createTravelRuleEntry(params: {
    address: string;
    originator_name: string;
    originator_country: string;
}): Promise<any>
⋮----
/**
   * Delete existing travel rule entry
   *
   * Delete existing travel rule entry.
   */
deleteTravelRuleEntry(params:
⋮----
/**
   *
   * Users Endpoints
   *
   */
⋮----
/**
   * Get user exchange limits
   *
   * Gets exchange limits information for a single user.
   */
getUserExchangeLimits(params:
⋮----
/**
   * Update settlement preference
   *
   * Updates the settlement preference to hold funds in either USDC or USD.
   */
updateSettlementPreference(params: {
    user_id: string;
    settlement_preference: string;
}): Promise<any>
⋮----
/**
   * Get user trading volume
   *
   * Gets aggregated and individual trading volumes for users.
   */
getUserTradingVolume(params:
⋮----
/**
   *
   * Wrapped Assets Endpoints
   *
   */
⋮----
/**
   * Get all wrapped assets
   *
   * Returns a list of all supported wrapped assets details objects.
   */
getAllWrappedAssets(): Promise<any>
⋮----
/**
   * Get all stake-wraps
   *
   * Get details for all stake-wraps in the profile associated with the API key.
   */
getAllStakeWraps(params?: GetCBExchAllStakeWraps): Promise<any>
⋮----
/**
   * Create a new stake-wrap
   *
   * Stakes and wraps from_currency to to_currency. Funds are stake-wrapped in the profile associated with the API key.
   */
createStakeWrap(params: {
    from_currency: string;
    to_currency: string;
    amount: string;
}): Promise<any>
⋮----
/**
   * Get a single stake-wrap
   *
   * Get details for a specific stake-wrap in the profile associated with the API key.
   */
getStakeWrap(params:
⋮----
/**
   * Get wrapped asset details
   *
   * Returns the circulating and total supply of a wrapped asset, and its conversion rate.
   */
getWrappedAssetDetails(params:
⋮----
/**
   * Get wrapped asset conversion rate
   *
   * Returns the conversion rate of a wrapped asset.
   */
getWrappedAssetConversionRate(params: {
    wrapped_asset_id: string;
}): Promise<any>

================
File: src/CBPrimeClient.ts
================
import { AxiosRequestConfig } from 'axios';
⋮----
import { BaseRestClient } from './lib/BaseRestClient.js';
import {
  REST_CLIENT_TYPE_ENUM,
  RestClientOptions,
  RestClientType,
} from './lib/requestUtils.js';
import {
  CreatePrimeAddressBookEntryRequest,
  CreatePrimeConversionRequest,
  CreatePrimePortfolioAllocationsRequest,
  CreatePrimePortfolioNetAllocationsRequest,
  CreatePrimeTransferRequest,
  CreatePrimeWalletRequest,
  CreatePrimeWithdrawalRequest,
  GetPrimeActivitiesRequest,
  GetPrimeAddressBookRequest,
  GetPrimeEntityAccrualsRequest,
  GetPrimeEntityActivitiesRequest,
  GetPrimeEntityLocateAvailabilitiesRequest,
  GetPrimeEntityMarginSummariesRequest,
  GetPrimeEntityTFTieredFeesRequest,
  GetPrimeInvoicesRequest,
  GetPrimeOpenOrdersRequest,
  GetPrimeOrderFillsRequest,
  GetPrimeOrderPreviewRequest,
  GetPrimePortfolioAccrualsRequest,
  GetPrimePortfolioAllocationsRequest,
  GetPrimePortfolioBuyingPowerRequest,
  GetPrimePortfolioFillsRequest,
  GetPrimePortfolioLocatesRequest,
  GetPrimePortfolioMarginConversionsRequest,
  GetPrimePortfolioOrdersRequest,
  GetPrimePortfolioProductsRequest,
  GetPrimePortfolioTransactionsRequest,
  GetPrimePortfolioUsersRequest,
  GetPrimePortfolioWalletsRequest,
  GetPrimePortfolioWithdrawalPowerRequest,
  GetPrimeUsersRequest,
  GetPrimeWalletDepositInstructionsRequest,
  GetPrimeWalletTransactionsRequest,
  GetPrimeWeb3WalletBalancesRequest,
  SubmitPrimeOrderRequest,
} from './types/request/coinbase-prime.js';
⋮----
/**
 * REST client for Coinbase Prime API:
 * https://docs.cdp.coinbase.com/prime/docs/welcome
 */
export class CBPrimeClient extends BaseRestClient
⋮----
constructor(
    restClientOptions: RestClientOptions = {},
    requestOptions: AxiosRequestConfig = {},
)
⋮----
getClientType(): RestClientType
⋮----
/**
   *
   * Activities Endpoints
   *
   */
⋮----
/**
   * List Activities
   *
   * List all activities associated with a given entity.
   */
getActivities(params: GetPrimeActivitiesRequest): Promise<any>
⋮----
/**
   * Get Activity by Activity ID
   *
   * Retrieve an activity by its activity ID - this endpoint can retrieve both portfolio and entity activities when passed the appropriate API key.
   */
getActivityById(params:
⋮----
/**
   * List Entity Activities
   *
   * List all activities associated with a given entity.
   */
getEntityActivities(params: GetPrimeEntityActivitiesRequest): Promise<any>
⋮----
/**
   * Get Portfolio Activity by Activity ID
   *
   * Retrieve an activity by its activity ID for a specific portfolio.
   */
getPortfolioActivityById(params: {
    portfolio_id: string;
    activity_id: string;
}): Promise<any>
⋮----
/**
   *
   * Allocation Endpoints
   *
   */
⋮----
/**
   * Create Portfolio Allocations
   *
   * Create allocation for a given portfolio.
   */
createPortfolioAllocations(
    params: CreatePrimePortfolioAllocationsRequest,
): Promise<any>
⋮----
/**
   * Create Portfolio Net Allocations
   *
   * Create net allocation for a given portfolio.
   */
createPortfolioNetAllocations(
    params: CreatePrimePortfolioNetAllocationsRequest,
): Promise<any>
⋮----
/**
   * List Portfolio Allocations
   *
   * Retrieve historical allocations for a given portfolio.
   */
getPortfolioAllocations(
    params: GetPrimePortfolioAllocationsRequest,
): Promise<any>
⋮----
/**
   * Get Allocation By ID
   *
   * Retrieve an allocation by allocation ID.
   */
getAllocationById(params: {
    portfolio_id: string;
    allocation_id: string;
}): Promise<any>
⋮----
/**
   * Get Net Allocations By Netting ID
   *
   * Retrieve an allocation by netting ID.
   */
getNetAllocationsByNettingId(params: {
    portfolio_id: string;
    netting_id: string;
}): Promise<any>
⋮----
/**
   *
   * Financing Endpoints
   *
   */
⋮----
/**
   * List Interest Accruals
   *
   * Lists interest accruals for an entity between the specified date range given.
   */
getEntityAccruals(params: GetPrimeEntityAccrualsRequest): Promise<any>
⋮----
/**
   * Get Entity Locate Availabilities
   *
   * Get currencies available to be located with their corresponding amount and rate.
   */
getEntityLocateAvailabilities(
    params: GetPrimeEntityLocateAvailabilitiesRequest,
): Promise<any>
⋮----
/**
   * Get Margin Information
   *
   * Gets real-time evaluation of the margin model based on current positions and spot rates.
   */
getEntityMargin(params:
⋮----
/**
   * List Margin Call Summaries
   *
   * Lists the margin call history for a given entity ID.
   */
getEntityMarginSummaries(
    params: GetPrimeEntityMarginSummariesRequest,
): Promise<any>
⋮----
/**
   * Get Trade Finance Tiered Pricing Fees
   *
   * Get trade finance tiered pricing fees for a given entity at a specific time, default to current time.
   */
getEntityTFTieredFees(
    params: GetPrimeEntityTFTieredFeesRequest,
): Promise<any>
⋮----
/**
   * List Interest Accruals For Portfolio
   *
   * Lists interest accruals between the specified date range for a specific portfolio ID.
   */
getPortfolioAccruals(params: GetPrimePortfolioAccrualsRequest): Promise<any>
⋮----
/**
   * Get Portfolio Buying Power
   *
   * Returns the size of a buy trade that can be performed based on existing holdings and available credit.
   */
getPortfolioBuyingPower(
    params: GetPrimePortfolioBuyingPowerRequest,
): Promise<any>
⋮----
/**
   * List Existing Locates
   *
   * List locates for the portfolio.
   */
getPortfolioLocates(params: GetPrimePortfolioLocatesRequest): Promise<any>
⋮----
/**
   * List Margin Conversions
   *
   * Lists conversions and short collateral requirement between specified date range.
   * This endpoint is deprecated and will be removed in the future. Use /v1/entities/{entity_id}/margin_summaries instead.
   */
getPortfolioMarginConversions(
    params: GetPrimePortfolioMarginConversionsRequest,
): Promise<any>
⋮----
/**
   * Get Portfolio Withdrawal Power
   *
   * Returns the nominal quantity of a given asset that can be withdrawn based on holdings and current portfolio equity.
   */
getPortfolioWithdrawalPower(
    params: GetPrimePortfolioWithdrawalPowerRequest,
): Promise<any>
⋮----
/**
   *
   * Invoice Endpoints
   *
   */
⋮----
/**
   * List Invoices
   *
   * Retrieve a list of invoices belonging to an entity.
   */
getInvoices(params: GetPrimeInvoicesRequest): Promise<any>
⋮----
/**
   *
   * Position Endpoints
   *
   */
⋮----
/**
   * List Aggregate Entity Positions
   *
   * List paginated aggregate positions for a specific entity.
   */
getEntityAggregatePositions(params: {
    entity_id: string;
    cursor?: string;
    limit?: number;
}): Promise<any>
⋮----
/**
   * List Entity Positions
   *
   * List paginated positions for a specific entity.
   */
getEntityPositions(params: {
    entity_id: string;
    cursor?: string;
    limit?: number;
}): Promise<any>
⋮----
/**
   *
   * Assets Endpoints
   *
   */
⋮----
/**
   * List Assets
   *
   * List all assets available for a given entity.
   */
getAssets(params:
⋮----
/**
   *
   * Payment Methods Endpoints
   *
   */
⋮----
/**
   * List Entity Payment Methods
   *
   * Retrieve all payment methods for a given entity.
   */
getEntityPaymentMethods(params:
⋮----
/**
   * Get Entity Payment Method
   *
   * Get payment method details by id for a given entity.
   */
getEntityPaymentMethod(params: {
    entity_id: string;
    payment_method_id: string;
}): Promise<any>
⋮----
/**
   *
   * Users Endpoints
   *
   */
⋮----
/**
   * List Users
   *
   * List all users associated with a given entity.
   */
getUsers(params: GetPrimeUsersRequest): Promise<any>
⋮----
/**
   * List Portfolio Users
   *
   * List all users associated with a given portfolio.
   */
getPortfolioUsers(params: GetPrimePortfolioUsersRequest): Promise<any>
⋮----
/**
   *
   * Portfolios Endpoints
   *
   */
⋮----
/**
   * List Portfolios
   *
   * List all portfolios for which the current API key has read access.
   */
getPortfolios(): Promise<any>
⋮----
/**
   * Get Portfolio by Portfolio ID
   *
   * Retrieve a given portfolio by its portfolio ID.
   */
getPortfolioById(params:
⋮----
/**
   * Get Portfolio Credit Information
   *
   * Retrieve a portfolio's post-trade credit information.
   */
getPortfolioCreditInformation(params: {
    portfolio_id: string;
}): Promise<any>
⋮----
/**
   *
   * Address Book Endpoints
   *
   */
⋮----
/**
   * Get Address Book
   *
   * Gets a list of address book addresses.
   */
getAddressBook(params: GetPrimeAddressBookRequest): Promise<any>
⋮----
/**
   * Create Address Book Entry
   *
   * Creates an entry for a portfolio's trusted addresses.
   */
createAddressBookEntry(
    params: CreatePrimeAddressBookEntryRequest,
): Promise<any>
⋮----
/**
   *
   * Balances Endpoints
   *
   */
⋮----
/**
   * List Portfolio Balances
   *
   * List all balances for a specific portfolio.
   */
getPortfolioBalances(params: {
    portfolio_id: string;
    symbols?: string[];
    balance_type?: 'TRADING_BALANCES' | 'VAULT_BALANCES' | 'TOTAL_BALANCES';
}): Promise<any>
⋮----
/**
   * Get Wallet Balance
   *
   * Query balance for a specific wallet.
   */
getWalletBalance(params: {
    portfolio_id: string;
    wallet_id: string;
}): Promise<any>
⋮----
/**
   * List Web3 Wallet Balances
   *
   * Query balances for a specific web3 wallet.
   */
getWeb3WalletBalances(
    params: GetPrimeWeb3WalletBalancesRequest,
): Promise<any>
⋮----
/**
   *
   * Commission Endpoints
   *
   */
⋮----
/**
   * Get Portfolio Commission
   *
   * Retrieve commission associated with a given portfolio.
   */
getPortfolioCommission(params:
⋮----
/**
   *
   * Orders Endpoints
   *
   */
⋮----
/**
   * List Portfolio Fills
   *
   * Retrieve fills on a given portfolio.
   *
   * Note: This endpoint requires a start_date and returns a payload with a default
   * limit of 100 if not specified. The maximum allowed limit is 3000.
   */
getPortfolioFills(params: GetPrimePortfolioFillsRequest): Promise<any>
⋮----
/**
   * List Open Orders
   *
   * List all open orders for a given portfolio.
   */
getOpenOrders(params: GetPrimeOpenOrdersRequest): Promise<any>
⋮----
/**
   * Create Order
   *
   * Create an order for a given portfolio.
   */
submitOrder(params: SubmitPrimeOrderRequest): Promise<any>
⋮----
/**
   * Get Order Preview
   *
   * Retrieve an order preview for a given portfolio.
   */
getOrderPreview(params: GetPrimeOrderPreviewRequest): Promise<any>
⋮----
/**
   * List Portfolio Orders
   *
   * List historical orders for a given portfolio.
   */
getPortfolioOrders(params: GetPrimePortfolioOrdersRequest): Promise<any>
⋮----
/**
   * Get Order by Order ID
   *
   * Retrieve an order by order ID.
   */
getOrderById(params: {
    portfolio_id: string;
    order_id: string;
}): Promise<any>
⋮----
/**
   * Cancel Order
   *
   * Cancel an order. (Filled orders cannot be canceled.)
   */
cancelOrder(params: {
    portfolio_id: string;
    order_id: string;
}): Promise<any>
⋮----
/**
   * List Order Fills
   *
   * Retrieve fills on a given order.
   */
getOrderFills(params: GetPrimeOrderFillsRequest): Promise<any>
⋮----
/**
   *
   * Products Endpoints
   *
   */
⋮----
/**
   * List Portfolio Products
   *
   * List tradable products for a given portfolio.
   */
getPortfolioProducts(params: GetPrimePortfolioProductsRequest): Promise<any>
⋮----
/**
   *
   * Transactions Endpoints
   *
   */
⋮----
/**
   * List Portfolio Transactions
   *
   * List transactions for a given portfolio (only transactions that affect balances are accessible).
   */
getPortfolioTransactions(
    params: GetPrimePortfolioTransactionsRequest,
): Promise<any>
⋮----
/**
   * Get Transaction by Transaction ID
   *
   * Retrieve a specific transaction by its transaction ID (only transactions that affect balances are accessible).
   */
getTransactionById(params: {
    portfolio_id: string;
    transaction_id: string;
}): Promise<any>
⋮----
/**
   * Create Conversion
   *
   * Perform a conversion between 2 assets.
   */
createConversion(params: CreatePrimeConversionRequest): Promise<any>
⋮----
/**
   * List Wallet Transactions
   *
   * Retrieve transactions for a given wallet (only transactions that affect balances are accessible).
   */
getWalletTransactions(
    params: GetPrimeWalletTransactionsRequest,
): Promise<any>
⋮----
/**
   * Create Transfer
   *
   * Create a wallet transfer.
   */
createTransfer(params: CreatePrimeTransferRequest): Promise<any>
⋮----
/**
   * Create Withdrawal
   *
   * Create a withdrawal.
   */
createWithdrawal(params: CreatePrimeWithdrawalRequest): Promise<any>
⋮----
/**
   *
   * Wallets Endpoints
   *
   */
⋮----
/**
   * List Portfolio Wallets
   *
   * List all wallets associated with a given portfolio.
   */
getPortfolioWallets(params: GetPrimePortfolioWalletsRequest): Promise<any>
⋮----
/**
   * Create Wallet
   *
   * Create a wallet.
   */
createWallet(params: CreatePrimeWalletRequest): Promise<any>
⋮----
/**
   * Get Wallet by Wallet ID
   *
   * Retrieve a specific wallet by Wallet ID.
   */
getWalletById(params: {
    portfolio_id: string;
    wallet_id: string;
}): Promise<any>
⋮----
/**
   * Get Wallet Deposit Instructions
   *
   * Retrieve a specific wallet's deposit instructions.
   */
getWalletDepositInstructions(
    params: GetPrimeWalletDepositInstructionsRequest,
): Promise<any>

================
File: src/index.ts
================


================
File: .prettierrc
================
{
  "tabWidth": 2,
  "singleQuote": true,
  "trailingComma": "all"
}

================
File: index.js
================


================
File: postBuild.sh
================
#!/bin/bash
#
#   Add package.json files to cjs/mjs subtrees
#

cat >dist/cjs/package.json <<!EOF
{
    "type": "commonjs"
}
!EOF

cat >dist/mjs/package.json <<!EOF
{
    "type": "module"
}
!EOF

find src -name '*.d.ts' -exec cp {} dist/mjs \;
find src -name '*.d.ts' -exec cp {} dist/cjs \;

================
File: tsconfig.cjs.json
================
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist/cjs",
    "target": "esnext"
  },
  "include": ["src/**/*.*"]
}

================
File: tsconfig.esm.json
================
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "esnext",
    "outDir": "dist/mjs",
    "target": "esnext"
  },
  "include": ["src/**/*.*"]
}

================
File: tsconfig.linting.json
================
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "module": "commonjs",
    "outDir": "dist/cjs",
    "target": "esnext",
    "rootDir": "../",
    "allowJs": true
  },
  "include": [
    "src/**/*.*",
    "test/**/*.*",
    "examples/**/*.*",
    ".eslintrc.cjs",
    "jest.config.ts"
  ]
}

================
File: examples/AdvancedTrade/Private/closePosition.ts
================
import { CBAdvancedTradeClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 * const { CBAdvancedTradeClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
// this function is suggested to used with spot market orders
// If you want to close futures, it is recommended to use submitOrder() with the opposite side of the current position
⋮----
/* Closing Futures Positions - Exchange docs
When a contract expires, we automatically close your open position at the exchange settlement price.
You can also close your position before the contract expires
(for example, you may want to close your position if you’ve reached your profit target,
you want to prevent further losses, or you need to satisfy a margin requirement).

There are two ways to close your futures positions:
(1) Close your position with this endpoint, or
(2) Create a separate trade to take the opposite position in the same futures contract you are currently holding in your account.
For example, to close an open long position in the BTC 23 Feb 24 contract, place an order to sell the same number of BTC 23 Feb 24 contracts.
If you were short to begin with, go long the same number of contracts to close your position.

More info on https://docs.cdp.coinbase.com/advanced-trade/reference/retailbrokerageapi_closeposition#closing-futures-positions */
⋮----
async function closePosition()
⋮----
// close position
⋮----
//

================
File: examples/AdvancedTrade/Private/getAccounts.ts
================
import { CBAdvancedTradeClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 * const { CBAdvancedTradeClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function getAccounts()
⋮----
// Get all accounts
⋮----
// Get specific account details

================
File: examples/AdvancedTrade/Private/getOrders.ts
================
import { CBAdvancedTradeClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 * const { CBAdvancedTradeClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function getOrders()
⋮----
// Get all orders
⋮----
// Get order details

================
File: examples/AdvancedTrade/Private/submitOrderPerps.ts
================
import { CBAdvancedTradeClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 * const { CBAdvancedTradeClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function submitOrder()
⋮----
// submit market futures order
⋮----
//
⋮----
async function submitLimitOrder()
⋮----
// Submit limit futures order

================
File: examples/AdvancedTrade/Private/submitOrderSpot.ts
================
import { CBAdvancedTradeClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 * const { CBAdvancedTradeClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function submitOrder()
⋮----
// submit market spot order
⋮----
//
⋮----
async function submitLimitOrder()
⋮----
// Submit limit spot order

================
File: examples/CoinbaseApp/Private/cb-app-private.ts
================
/**
 * import { CBAppClient } from 'coinbase-api';
 * const { CBAppClient } = require('coinbase-api');
 */
⋮----
import { CBAppClient } from '../../../src/index.js';
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function main()
⋮----
// Deposit funds to your fiat account
⋮----
// Withdraw funds from fiat account
⋮----
// Send money to another user
⋮----
// Transfer money between your own accounts

================
File: examples/CoinbaseApp/Private/depositFunds.ts
================
import { CBAppClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAppClient } from 'coinbase-api';
 * const { CBAppClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function depositFunds()
⋮----
// Deposit funds to your fiat account

================
File: examples/CoinbaseApp/Private/sendMoney.ts
================
import { CBAppClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAppClient } from 'coinbase-api';
 * const { CBAppClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function sendMoney()
⋮----
// Send money to another user

================
File: examples/CoinbaseApp/Private/transferMoney.ts
================
import { CBAppClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAppClient } from 'coinbase-api';
 * const { CBAppClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function transferMoney()
⋮----
// Transfer money between your own accounts

================
File: examples/CoinbaseApp/Private/withdrawFunds.ts
================
import { CBAppClient } from '../../../src/index.js';
⋮----
/**
 * import { CBAppClient } from 'coinbase-api';
 * const { CBAppClient } = require('coinbase-api');
 */
⋮----
// initialise the client
/**
 *
 * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
 *
 * ECDSA:
 *
 * {
 *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
 *   apiSecret:
 *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
 * }
 *
 * ED25519:
 * {
 *   apiKey: 'your-api-key-id',
 *   apiSecret: 'yourExampleApiSecretEd25519Version==',
 * }
 *
 *
 */
⋮----
async function withdrawFunds()
⋮----
// Withdraw funds from your fiat account

================
File: examples/Institutional/CBExchange/Rest/cb-exchange-private.ts
================
import { CBExchangeClient } from '../../../../src/index.js';
⋮----
/**
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 * const { CBAdvancedTradeClient } = require('coinbase-api');
 */
⋮----
// Initialize the client, you can pass in api keys here if you have them but they are not required for public endpoints
⋮----
//This is the passphrase you provided when creating this API key. NOT your account password.
⋮----
// Optional, connect to sandbox instead: https://public-sandbox.exchange.coinbase.com/apikeys
// useSandbox: true,
⋮----
async function privateExchangeCalls()

================
File: examples/Institutional/CBExchange/Rest/cb-exchange-public.ts
================
import { CBExchangeClient } from '../../../../src/index.js';
⋮----
/**
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 * const { CBAdvancedTradeClient } = require('coinbase-api');
 */
⋮----
// Initialize the client, you can pass in api keys here if you have them but they are not required for public endpoints
⋮----
async function publicExchangeCalls()
⋮----
// Get all known currencies
⋮----
// Get a single currency by id
⋮----
// Get all known trading pairs
⋮----
// Get all product volume
⋮----
// Get all wrapped assets

================
File: examples/Institutional/CBExchange/WebSockets/privateWs.ts
================
import { WebsocketClient } from '../../../../src/index.js';
⋮----
/**
 * import { WebsocketClient } from 'coinbase-api';
 * const { WebsocketClient } = require('coinbase-api');
 */
⋮----
async function start()
⋮----
//This is the passphrase you provided when creating this API key. NOT your account password.
⋮----
// Optional, connect to sandbox instead: https://public-sandbox.exchange.coinbase.com/apikeys
// useSandbox: true,
⋮----
// logger,
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
/**
     * Use the client subscribe(topic, market) pattern to subscribe to any websocket topic.
     * - You can subscribe to topics one at a time or many one one request.
     * - Topics can be sent as simple strings, if no parameters are required.
     * - If parameters are required, pass them in the "payload" property - they will be merged into the subscription request automatically
     * - Any subscribe requests on the "exchangeDirectMarketData" market are automatically authenticated with the available credentials
     */
⋮----
/**
     * Other examples for some of the authenticated Coinbase Exchange "direct market data" channels:
     */
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#full-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#user-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#level2-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#balance-channel

================
File: examples/Institutional/CBExchange/WebSockets/publicWs.ts
================
import { WebsocketClient } from '../../../../src/index.js';
⋮----
/**
 * import { WebsocketClient } from 'coinbase-api';
 * const { WebsocketClient } = require('coinbase-api');
 */
⋮----
async function start()
⋮----
/**
   * All websockets are available via the unified WebsocketClient.
   *
   * Below are examples specific to websockets in this product group.
   */
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
// throw new Error('res?');
⋮----
/**
     * Use the client subscribe(topic, market) pattern to subscribe to any websocket topic.
     *
     * - You can subscribe to topics one at a time or many one one request.
     * - Topics can be sent as simple strings, if no parameters are required.
     * - Coinbase Market Data is the traditional feed which is available without authentication.
     * - To use this feed, use 'exchangeMarketData' as the wsKey for each subscription command:
     */
// client.subscribe('status', 'exchangeMarketData');
⋮----
/**
     * Or send a more structured object with parameters, e.g. if parameters are required
     */
// const tickerSubscribeRequest: WsTopicRequest = {
//   topic: 'ticker',
//   /**
//    * Anything in the payload will be merged into the subscribe "request",
//    * allowing you to send misc parameters supported by the exchange (such as `product_ids: string[]`)
//    */
//   payload: {
//     product_ids: ['ETH-USD', 'ETH-EUR'],
//   },
// };
// client.subscribe(tickerSubscribeRequest, 'exchangeMarketData');
⋮----
/**
     * Subscribe to the "heartbeat" topic for a few symbols
     */
// client.subscribe(
//   {
//     topic: 'heartbeat',
//     payload: {
//       product_ids: ['ETH-USD', 'BTC-USD'],
//     },
//   },
//   'exchangeMarketData',
// );
⋮----
// client.subscribe(
//   {
//     topic: 'level2',
//     payload: {
//       product_ids: ['ETH-USD', 'BTC-USD'],
//     },
//   },
//   'exchangeMarketData',
// );
⋮----
// /**
//  * Or, send an array of structured objects with parameters, if you wanted to send multiple in one request
//  */
// // client.subscribe([level2SubscribeRequest, anotherRequest, etc], 'advTradeMarketData');
⋮----
/**
     * Other Coinbase Exchange public websocket topics:
     */
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#heartbeat-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#status-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#auction-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#matches-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#rfq-matches-channel
⋮----
// Optional:
// product_ids: ['ETH-USD', 'BTC-USD'],
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#ticker-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#ticker-batch-channel
⋮----
// https://docs.cdp.coinbase.com/exchange/docs/websocket-channels#level2-batch-channel

================
File: examples/Institutional/CBInternationalExchange/cb-intx-public.ts
================
import { CBInternationalClient } from '../../../src/index.js';
⋮----
/**
 * import { CBInternationalClient } from 'coinbase-api';
 * const { CBInternationalClient } = require('coinbase-api');
 */
⋮----
// Initialize the client, you can pass in api keys here if you have them but they are not required for public endpoints
⋮----
async function publicInternationalCalls()
⋮----
// List assets
⋮----
// Get asset details
⋮----
// Get supported networks per asset
⋮----
// List instruments
⋮----
// Get instrument details
⋮----
// Get quote per instrument
⋮----
// Get daily trading volumes
⋮----
// Get aggregated candles data per instrument
⋮----
// Get historical funding rates
⋮----
// List position offsets

================
File: examples/Institutional/CBInternationalExchange/cb-intx-ws.ts
================
import { WebsocketClient, WsTopicRequest } from '../../../src/index.js';
⋮----
/**
 * import { WebsocketClient, WsTopicRequest } from 'coinbase-api';
 * const { WebsocketClient, WsTopicRequest } = require('coinbase-api');
 */
⋮----
// logger,
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
topic: 'LEVEL1', // ws topic
/**
   * Anything in the payload will be merged into the subscribe "request",
   * allowing you to send misc parameters supported by the exchange (such as `product_ids: string[]`)
   */

================
File: src/types/request/coinbase-international.ts
================
/**
 *
 * Assets Endpoints
 *
 */
⋮----
/**
 *
 * Index Endpoints
 *
 */
⋮----
export interface GetINTXIndexCompositionHistory {
  index: string;
  time_from?: string;
  result_limit?: number;
  result_offset?: number;
}
⋮----
export interface GetINTXIndexCandlesRequest {
  index: string;
  granularity: string;
  start: string;
  end?: string;
}
⋮----
/**
 *
 * Instruments Endpoints
 *
 */
⋮----
export interface GetINTXDailyTradingVolumes {
  instruments: string;
  result_limit?: number;
  result_offset?: number;
  time_from?: string;
  show_other?: boolean;
}
⋮----
export interface GetINTXAggregatedCandlesData {
  instrument: string;
  granularity: string;
  start: string;
  end?: string;
}
/**
 *
 * Position Offsets Endpoints
 *
 */
⋮----
/**
 *
 * Orders Endpoints
 *
 */
⋮----
export interface SubmitINTXOrderRequest {
  client_order_id?: string;
  side: string;
  size: string;
  tif: string;
  instrument: string;
  type: string;
  price?: string;
  stop_price?: string;
  stop_limit_price?: string;
  expire_time?: string;
  portfolio?: string;
  user?: string;
  stp_mode?: string;
  post_only?: boolean;
  close_only?: boolean;
  algo_strategy?: boolean;
}
⋮----
export interface GetINTXOpenOrdersRequest {
  portfolio?: string;
  instrument?: string;
  instrument_type?: string;
  client_order_id?: string;
  event_type?: string;
  order_type?: string;
  side?: string;
  ref_datetime?: string;
  result_limit?: number;
  result_offset?: number;
}
⋮----
export interface CancelINTXOrdersRequest {
  portfolio: string;
  instrument?: string;
  side?: string;
  instrument_type?: string;
}
⋮----
export interface UpdateINTXOpenOrderRequest {
  id: string;
  client_order_id?: string;
  portfolio?: string;
  price?: string;
  stop_price?: string;
  size?: string;
}
⋮----
/**
 *
 * Portfolios Endpoints
 *
 */
⋮----
export interface UpdateINTXPortfolioParametersRequest {
  auto_margin_enabled?: boolean;
  cross_collateral_enabled?: boolean;
  position_offsets_enabled?: boolean;
  pre_launch_trading_enabled?: boolean;
  portfolio_name?: string;
}
⋮----
export interface GetINTXFillsByPortfoliosRequest {
  portfolios?: string;
  order_id?: string;
  client_order_id?: string;
  ref_datetime?: string;
  result_limit?: number;
  result_offset?: number;
  time_from?: string;
}
⋮----
export interface GetINTXPortfolioFillsRequest {
  portfolio: string;
  order_id?: string;
  client_order_id?: string;
  ref_datetime?: string;
  result_limit?: number;
  result_offset?: number;
  time_from?: string;
}
⋮----
export interface TransferINTXFundsBetweenPortfoliosRequest {
  from: string;
  to: string;
  asset: string;
  amount: string;
}
⋮----
export interface TransferINTXPositionsBetweenPortfoliosRequest {
  from: string;
  to: string;
  instrument: string;
  quantity: string;
  side: string;
}
⋮----
/**
 *
 * Rankings Endpoints
 *
 */
⋮----
/**
 *
 * Transfers Endpoints
 *
 */
⋮----
export interface GetINTXMatchingTransfersRequest {
  portfolio?: string;
  portfolios?: string;
  time_from?: string;
  time_to?: string;
  result_limit?: number;
  result_offset?: number;
  status?: string;
  type?: string;
}
⋮----
export interface INTXWithdrawToCryptoAddressRequest {
  portfolio: string;
  asset: string;
  amount: string;
  add_network_fee_to_total?: boolean;
  network_arn_id: string;
  address: string;
  nonce: number;
}
⋮----
export interface INTXWithdrawToCounterpartyIdRequest {
  portfolio: string;
  counterparty_id: string;
  asset: string;
  amount: string;
  nonce: number;
}
/**
 *
 * Fee Rates Endpoints
 *
 */

================
File: src/types/response/coinbase-app-client.ts
================
export interface CBAppPagination {
  ending_before?: string | null;
  starting_after?: string | null;
  limit?: number;
  order?: string;
  previous_uri: string | null;
  next_uri: string | null;
}
⋮----
/**
 *
 * Account Endpoints
 *
 */
⋮----
interface AccountCurrency {
  address_regex: string;
  asset_id: string;
  code: string;
  color: string;
  exponent: number;
  name: string;
  slug: string;
  sort_index: number;
  type: string;
}
⋮----
interface AccountBalance {
  amount: string;
  currency: string;
}
⋮----
export interface CBAppAccount {
  id: string;
  name: string;
  primary: boolean;
  type: string;
  currency: AccountCurrency;
  balance: AccountBalance;
  created_at: string;
  updated_at: string;
  resource: string;
  resource_path: string;
  ready: boolean;
}
⋮----
/**
 *
 * Address Endpoints
 *
 */
⋮----
export interface CBAppAddress {
  id: string;
  address: string;
  name?: string;
  network: string;
  created_at: string;
  updated_at: string;
  resource: string;
  resource_path: string;
}
⋮----
/**
 *
 * Transactions Endpoints
 *
 */
⋮----
interface TransactionAmount {
  amount: string;
  currency: string;
}
⋮----
interface TransactionNetwork {
  status: string;
  name: string;
  hash?: string;
  transaction_fee?: TransactionAmount;
  transaction_amount?: TransactionAmount;
  network_name?: string;
  status_description?: string | null;
}
⋮----
interface TransactionFrom {
  id: string;
  resource: string;
  resource_path?: string;
}
⋮----
interface TransactionTo {
  resource: string;
  address?: string;
  email?: string;
  id?: string;
  resource_path?: string;
}
⋮----
interface TransactionDetails {
  title: string;
  subtitle: string;
  header?: string;
  health?: string;
  subsidebar_label?: string | null;
}
⋮----
interface AdvancedTradeFill {
  fill_price: string;
  product_id: string;
  order_id: string;
  commission: string;
  order_side: 'BUY' | 'SELL';
}
⋮----
export interface CBAppTransaction {
  id: string;
  type: string;
  status: string;
  amount: TransactionAmount;
  native_amount: TransactionAmount;
  description: string | null;
  created_at: string;
  updated_at: string;
  resource: string;
  resource_path: string;
  network?: TransactionNetwork;
  from?: TransactionFrom;
  to?: TransactionTo;
  details?: TransactionDetails;
  instant_exchange?: boolean;
  advanced_trade_fill?: AdvancedTradeFill;
  cancelable?: boolean;
  idem?: string;
}
⋮----
/**
 *
 * Deposits/Withdrawal Endpoints
 *
 */
⋮----
interface DepositWithdrawalPaymentMethod {
  id: string;
  resource: string;
  resource_path: string;
}
⋮----
interface DepositWithdrawalTransaction {
  id: string;
  resource: string;
  resource_path: string;
}
⋮----
interface DepositWithdrawalAmountCurrency {
  amount: string;
  currency: string;
}
⋮----
export interface CBAppDepositWithdrawal {
  id: string;
  status: string;
  payment_method: DepositWithdrawalPaymentMethod;
  transaction: DepositWithdrawalTransaction;
  amount: DepositWithdrawalAmountCurrency;
  subtotal: DepositWithdrawalAmountCurrency;
  created_at: string;
  updated_at: string;
  resource: string;
  resource_path: string;
  committed: boolean;
  fee: DepositWithdrawalAmountCurrency;
  payout_at: string;
}
⋮----
interface TransferAmount {
  value: string;
  currency: string;
}
⋮----
interface TransferOwner {
  id: string;
  uuid: string;
  user_uuid: string;
  type: string;
}
⋮----
interface TransferLedgerAccount {
  account_id: string;
  currency: string;
  owner: TransferOwner;
}
⋮----
interface TransferExternalPaymentMethod {
  payment_method_id: string;
}
⋮----
interface TransferSource {
  type: string;
  network: string;
  payment_method_id: string;
  external_payment_method: TransferExternalPaymentMethod;
}
⋮----
interface TransferTarget {
  type: string;
  network: string;
  payment_method_id: string;
  ledger_account: TransferLedgerAccount;
}
⋮----
interface TransferFee {
  title: string;
  description: string;
  amount: TransferAmount;
  type: string;
}
⋮----
export interface CBAppTransferDepositWithdrawal {
  user_entered_amount: TransferAmount;
  amount: TransferAmount;
  total: TransferAmount;
  subtotal: TransferAmount;
  idem: string;
  committed: boolean;
  id: string;
  instant: boolean;
  source: TransferSource;
  target: TransferTarget;
  payout_at: string;
  status: string;
  user_reference: string;
  type: string;
  created_at: string | null;
  updated_at: string | null;
  user_warnings: any[];
  fees: any[];
  total_fee: TransferFee;
  cancellation_reason: string | null;
  hold_days: number;
  nextStep: any | null;
  checkout_url: string;
  requires_completion_step: boolean;
}
⋮----
export interface CBAppTransfer {
  transfer: CBAppTransferDepositWithdrawal;
}
/**
 *
 * DATA - Currencies Endpoints
 *
 */
⋮----
export interface CBAppFiatCurrency {
  id: string;
  name: string;
  min_size: string;
}
⋮----
export interface CBAppCryptocurrency {
  code: string;
  name: string;
  color: string;
  sort_index: number;
  exponent: number;
  type: string;
  address_regex: string;
  asset_id: string;
}
⋮----
/**
 *
 * DATA- Exchange rates Endpoints
 *
 */
⋮----
/**
 *
 * DATA - Prices Endpoints
 *
 */
⋮----
/**
 *
 * DATA - Time Endpoints
 *
 */

================
File: src/CBAdvancedTradeClient.ts
================
import { AxiosRequestConfig } from 'axios';
⋮----
import { BaseRestClient } from './lib/BaseRestClient.js';
import {
  REST_CLIENT_TYPE_ENUM,
  RestClientOptions,
  RestClientType,
} from './lib/requestUtils.js';
import {
  AllocateAdvTradePortfolioRequest,
  CloseAdvTradePositionRequest,
  GetAdvTradeFillsRequest,
  GetAdvTradeMarketTradesRequest,
  GetAdvTradeOrdersRequest,
  GetAdvTradeProductCandlesRequest,
  GetAdvTradeProductsRequest,
  GetAdvTradePublicMarketTradesRequest,
  GetAdvTradePublicProductCandlesRequest,
  GetAdvTradePublicProductsRequest,
  GetAdvTradeTransactionSummaryRequest,
  MoveAdvTradePortfolioFundsRequest,
  PreviewAdvTradeOrderRequest,
  SubmitAdvTradeConvertQuoteRequest,
  SubmitAdvTradeOrderRequest,
} from './types/request/advanced-trade-client.js';
import {
  AdvTradeAccount,
  AdvTradeAccountsList,
  AdvTradeApiKeyPermissions,
  AdvTradeCancelOrdersResponse,
  AdvTradeCandle,
  AdvTradeClosePositionResponse,
  AdvTradeCurrentMarginWindow,
  AdvTradeEditOrderPreviewResponse,
  AdvTradeEditOrderResponse,
  AdvTradeFill,
  AdvTradeFuturesBalance,
  AdvTradeFuturesPosition,
  AdvTradeFuturesSweep,
  AdvTradeMarketTrades,
  AdvTradeOrder,
  AdvTradeOrderPreview,
  AdvTradePaymentMethod,
  AdvTradePerpetualsPortfolio,
  AdvTradePerpetualsPosition,
  AdvTradePerpetualsPositionSummary,
  AdvTradePortfolio,
  AdvTradePortfolioBalance,
  AdvTradePortfolioBreakdown,
  AdvTradePricebook,
  AdvTradeProduct,
  AdvTradePublicProduct,
  AdvTradeSubmitOrderResponse,
  AdvTradeTransactionSummary,
} from './types/response/advanced-trade-client.js';
⋮----
/**
 * REST client for Coinbase's Advanced Trade API:
 * https://docs.cdp.coinbase.com/advanced-trade/docs/api-overview/
 */
export class CBAdvancedTradeClient extends BaseRestClient
⋮----
constructor(
    restClientOptions: RestClientOptions = {},
    requestOptions: AxiosRequestConfig = {},
)
⋮----
/**
   *
   * Custom SDK functions
   *
   */
⋮----
/**
   * This method is used to get the latency and time sync between the client and the server.
   * This is not official API endpoint and is only used for internal testing purposes.
   * Use this method to check the latency and time sync between the client and the server.
   * Final values might vary slightly, but it should be within few ms difference.
   * If you have any suggestions or improvements to this measurement, please create an issue or pull request on GitHub.
   */
async fetchLatencySummary(): Promise<any>
⋮----
// Adjust server time by adding estimated one-way latency
⋮----
// Calculate time difference between adjusted server time and local time
⋮----
getClientType(): RestClientType
⋮----
/**
   *
   * Account Endpoints
   *
   */
⋮----
/**
   * List Accounts
   *
   * Get a list of authenticated accounts for the current user.
   */
getAccounts(params?: {
    limit?: number;
    cursor?: string;
    retail_portfolio_id?: string; // deprecated
}): Promise<AdvTradeAccountsList>
⋮----
retail_portfolio_id?: string; // deprecated
⋮----
/**
   * Get Account
   *
   * Get a list of information about single account, given an account UUID.
   * Tip: Use List Accounts (getAccounts funcion) to find account UUIDs.
   */
getAccount(params:
⋮----
/**
   *
   * Products Endpoints
   *
   */
⋮----
/**
   * Get Best Bid/Ask
   *
   * Get the best bid/ask for all products. A subset of all products can be returned instead by using the product_ids input.
   */
getBestBidAsk(params?:
⋮----
/**
   * Get Product Book
   *
   * Get a list of bids/asks for a single product. The amount of detail shown can be customized with the limit parameter.
   */
getProductBook(params: {
    product_id: string;
    limit?: number;
    aggregation_price_increment?: string;
}): Promise<
⋮----
/**
   * List Products
   *
   * Get a list of the available currency pairs for trading.
   *
   */
getProducts(params?: GetAdvTradeProductsRequest): Promise<
⋮----
/**
   * Get Product
   *
   * Get information on a single product by product ID.
   */
getProduct(params: {
    product_id: string;
    get_tradability_status?: boolean;
}): Promise<AdvTradeProduct>
⋮----
/**
   * Get Product Candles
   *
   * Get rates for a single product by product ID, grouped in buckets.
   */
getProductCandles(params: GetAdvTradeProductCandlesRequest): Promise<
⋮----
/**
   * Get Market Trades
   *
   * Get snapshot information by product ID about the last trades (ticks) and best bid/ask.
   */
getMarketTrades(
    params: GetAdvTradeMarketTradesRequest,
): Promise<AdvTradeMarketTrades>
⋮----
/**
   *
   * Orders Endpoints
   *
   */
⋮----
/**
   * Create Order
   *
   * Create an order with a specified product_id (asset-pair), side (buy/sell), etc.
   *
   */
submitOrder(
    params: SubmitAdvTradeOrderRequest,
): Promise<AdvTradeSubmitOrderResponse>
⋮----
/**
   * Cancel Orders
   *
   * Initiate cancel requests for one or more orders.
   * The maximum number of order_ids that can be cancelled per request is 100.
   * This number may be subject to change in emergency, but if a request exceeds the max,
   * then an InvalidArgument error code will be returned with an error message denoting the limit.
   */
cancelOrders(params: {
    order_ids: string[];
}): Promise<AdvTradeCancelOrdersResponse>
⋮----
/**
   * Edit Order
   *
   * Edit an order with a specified new size, or new price.
   *
   * - Your request moves to the back of the queue if you increase the size or increase or decrease the price.
   * - If you decrease the size, you keep your place in line.
   * - A client can only send an Edit Order request after the previous request for the same order has been fully processed.
   */
updateOrder(params: {
    order_id: string;
    price?: string;
    size?: string;
}): Promise<AdvTradeEditOrderResponse>
⋮----
/**
   * Edit Order Preview
   *
   * Preview an edit order request with a specified new size, or new price.
   *
   */
updateOrderPreview(params: {
    order_id: string;
    price?: string;
    size?: string;
}): Promise<AdvTradeEditOrderPreviewResponse>
⋮----
/**
   * List Orders
   *
   * Get a list of orders filtered by optional query parameters.
   *
   * - The maximum number of OPEN orders returned is 1000.
   * - The parameters start_date and end_date don't apply to open orders.
   * - You cannot pair open orders with other order types.
   * - You cannot query for OPEN orders with other order types.
   */
getOrders(params?: GetAdvTradeOrdersRequest): Promise<
⋮----
/**
   * List Fills
   *
   * Get a list of fills filtered by optional query parameters (product_id, order_id, etc).
   *
   */
getFills(params?: GetAdvTradeFillsRequest): Promise<
⋮----
/**
   * Get Order
   *
   * Get a single order by order ID.
   */
getOrder(params: {
    order_id: string;
    client_order_id?: string;
    user_native_currency?: string;
}): Promise<
⋮----
/**
   * Preview Order
   *
   * Preview an order.
   *
   */
previewOrder(
    params: PreviewAdvTradeOrderRequest,
): Promise<AdvTradeOrderPreview>
⋮----
/**
   * Close Position
   *
   * Places an order to close any open positions for a specified product_id.
   *
   */
closePosition(
    params: CloseAdvTradePositionRequest,
): Promise<AdvTradeClosePositionResponse>
⋮----
/**
   *
   * Portfolios Endpoints
   *
   */
⋮----
/**
   * List Portfolios
   *
   * Get all portfolios of a user.
   */
getPortfolios(params?: {
    portfolio_type?: 'UNDEFINED' | 'DEFAULT' | 'CONSUMER' | 'INTX';
}): Promise<
⋮----
/**
   * Create Portfolio
   *
   * Create a portfolio.
   */
createPortfolio(params:
⋮----
/**
   * Move Portfolio Funds
   *
   * Move funds between portfolios.
   */
movePortfolioFunds(params: MoveAdvTradePortfolioFundsRequest): Promise<
⋮----
/**
   * Get Portfolio Breakdown
   *
   * Get the breakdown of a portfolio.
   */
getPortfolioBreakdown(params: {
    portfolio_uuid: string;
    currency?: string;
}): Promise<
⋮----
/**
   * Delete Portfolio
   *
   * Delete a portfolio.
   */
deletePortfolio(params:
⋮----
/**
   * Edit Portfolio
   *
   * Edit a portfolio.
   *
   */
updatePortfolio(params: {
    portfolio_uuid: string;
    name: string;
}): Promise<
⋮----
/**
   *
   * Futures Endpoints
   *
   */
⋮----
/**
   * Get Futures Balance Summary
   *
   * Get a summary of balances for CFM trading.
   *
   * Futures vs Spot Accounts:
   * - Futures and spot balances are held in different accounts.
   * - Cash is always deposited into your Coinbase Inc. (CBI) spot account.
   * - Cash is automatically transferred to your Coinbase Financial Markets (CFM) futures account to satisfy margin requirements.
   * - You can transfer cash that isn't being used to margin or maintain futures positions into your CBI spot account.
   * - Funds held in a CBI spot account do not receive the preferential treatment given to funds held in a regulated futures account.
   *
   * Intraday vs. Overnight Margin Health:
   * - If you are opted in to receive increased leverage on futures trades during the intraday window (from 8am-4pm ET), this endpoint will return your intraday and overnight margin health.
   */
getFuturesBalanceSummary(): Promise<
⋮----
/**
   * Get Intraday Margin Setting
   *
   * Get the futures intraday margin setting.
   */
getIntradayMarginSetting(): Promise<
⋮----
/**
   * Set Intraday Margin Setting
   *
   * Set the futures intraday margin setting.
   */
setIntradayMarginSetting(params?: {
    setting?:
      | 'INTRADAY_MARGIN_SETTING_UNSPECIFIED'
      | 'INTRADAY_MARGIN_SETTING_STANDARD'
      | 'INTRADAY_MARGIN_SETTING_INTRADAY';
}): Promise<any>
⋮----
/**
   * Get Current Margin Window
   *
   * Get the futures current margin window.
   */
getCurrentMarginWindow(params?: {
    margin_profile_type?:
      | 'MARGIN_PROFILE_TYPE_UNSPECIFIED'
      | 'MARGIN_PROFILE_TYPE_RETAIL_REGULAR'
      | 'MARGIN_PROFILE_TYPE_RETAIL_INTRADAY_MARGIN_1';
}): Promise<AdvTradeCurrentMarginWindow>
⋮----
/**
   * List Futures Positions
   *
   * Get a list of positions in CFM products.
   */
getFuturesPositions(): Promise<
⋮----
/**
   * Get Futures Position
   *
   * Get positions for a specific CFM product.
   */
getFuturesPosition(params: {
    product_id: string;
}): Promise<
⋮----
/**
   * Schedule Futures Sweep
   *
   * Schedules a sweep of funds from FCM wallet to USD Spot wallet.
   *
   * Futures Sweep Processing:
   * - Sweep requests submitted before 5PM ET each day are processed the following business day.
   * - Sweep requests submitted after 5PM ET each day are processed in 2 business days.
   * - You can have at most one pending sweep request at a time.
   *
   * Market movements related to your open positions may impact the final amount that is transferred into your spot account.
   * The final funds transferred, up to your specified amount, depend on the available excess in your futures account.
   */
scheduleFuturesSweep(params?: {
    usd_amount?: string;
}): Promise<
⋮----
/**
   * List Futures Sweeps
   *
   * Get pending and processing sweeps of funds from FCM wallet to USD Spot wallet.
   *
   * Pending vs. Processing Sweeps:
   * - A pending sweep is a sweep that has not started processing and can be cancelled.
   * - A processing sweep is a sweep that is currently being processed and cannot be cancelled.
   * - Once a sweep is complete, it no longer appears in the list of sweeps.
   */
getFuturesSweeps(): Promise<
⋮----
/**
   * Cancel Pending Futures Sweep
   *
   * Cancel the pending sweep of funds from FCM wallet to USD Spot wallet.
   */
cancelPendingFuturesSweep(): Promise<
⋮----
/**
   *
   * Perpetuals Endpoints
   *
   */
⋮----
/**
   * Allocate Portfolio
   *
   * Allocate portfolio funds to a sub-portfolio on Intx Portfolio.
   *
   */
allocatePortfolio(params: AllocateAdvTradePortfolioRequest): Promise<any>
⋮----
/**
   * Get Perpetuals Portfolio Summary
   *
   * Get a summary of your Perpetuals portfolio.
   */
getPerpetualsPortfolioSummary(params: {
    portfolio_uuid: string;
}): Promise<AdvTradePerpetualsPortfolio>
⋮----
/**
   * List Perpetuals Positions
   *
   * Get a list of open positions in your Perpetuals portfolio.
   */
getPerpetualsPositions(params: {
    portfolio_uuid: string;
}): Promise<AdvTradePerpetualsPositionSummary>
⋮----
/**
   * Get Perpetuals Position
   *
   * Get a specific open position on Intx.
   *
   */
getPerpetualsPosition(params: {
    portfolio_uuid: string;
    symbol: string;
}): Promise<
⋮----
/**
   * Get Portfolios Balances
   *
   * Get a list of asset balances on Intx for a given Portfolio.
   */
getPortfoliosBalances(params:
⋮----
/**
   * Opt In or Out of Multi Asset Collateral
   *
   * Enable or Disable Multi Asset Collateral for a given Portfolio.
   */
updateMultiAssetCollateral(params?: {
    portfolio_uuid?: string;
    multi_asset_collateral_enabled?: boolean;
}): Promise<
⋮----
/**
   *
   * Fees Endpoints
   *
   */
⋮----
/**
   * Get Transaction Summary
   *
   * Get a summary of transactions with fee tiers, total volume, and fees.
   */
getTransactionSummary(
    params?: GetAdvTradeTransactionSummaryRequest,
): Promise<AdvTradeTransactionSummary>
⋮----
/**
   *
   * Converts Endpoints
   *
   */
⋮----
/**
   * Create Convert Quote
   *
   * Create a convert quote with a specified source account, target account, and amount.
   * Convert is applicable for USDC-USD and EURC-EUR conversion.
   */
submitConvertQuote(params: SubmitAdvTradeConvertQuoteRequest): Promise<any>
⋮----
/**
   * Get Convert Trade
   *
   * Gets a list of information about a convert trade with a specified trade id, source account, and target account.
   */
getConvertTrade(params: {
    trade_id: string;
    from_account: string;
    to_account: string;
}): Promise<any>
⋮----
/**
   * Commit Convert Trade
   *
   * Commits a convert trade with a specified trade id, source account, and target account.
   */
commitConvertTrade(params: {
    trade_id: string;
    from_account: string;
    to_account: string;
}): Promise<any>
⋮----
/**
   *
   * Public Endpoints
   *
   */
⋮----
getServerTime(): Promise<
⋮----
/**
   * Get Public Product Book
   *
   * Get a list of bids/asks for a single product. The amount of detail shown can be customized with the limit parameter.
   */
getPublicProductBook(params: {
    product_id: string;
    limit?: number;
    aggregation_price_increment?: string;
}): Promise<
⋮----
/**
   * List Public Products
   *
   * Get a list of the available currency pairs for trading.
   */
getPublicProducts(params?: GetAdvTradePublicProductsRequest): Promise<
⋮----
/**
   * Get Public Product
   *
   * Get information on a single product by product ID.
   */
getPublicProduct(params: {
    product_id: string;
}): Promise<AdvTradePublicProduct>
⋮----
/**
   * Get Public Product Candles
   *
   * Get rates for a single product by product ID, grouped in buckets.
   */
getPublicProductCandles(
    params: GetAdvTradePublicProductCandlesRequest,
): Promise<
⋮----
/**
   * Get Public Market Trades
   *
   * Get snapshot information by product ID about the last trades (ticks) and best bid/ask.
   */
getPublicMarketTrades(
    params: GetAdvTradePublicMarketTradesRequest,
): Promise<AdvTradeMarketTrades>
⋮----
/**
   *
   * Payment Methods Endpoints
   *
   */
⋮----
/**
   * List Payment Methods
   *
   * Get a list of payment methods for the current user.
   */
getPaymentMethods(): Promise<
⋮----
/**
   * Get Payment Method
   *
   * Get information about a payment method for the current user.
   */
getPaymentMethod(params:
⋮----
/**
   *
   * Data API Endpoints
   *
   */
⋮----
/**
   * Get API Key Permissions
   *
   * Get information about your CDP API key permissions.
   */
getApiKeyPermissions(): Promise<AdvTradeApiKeyPermissions>

================
File: src/CBAppClient.ts
================
import { AxiosRequestConfig } from 'axios';
⋮----
import { BaseRestClient } from './lib/BaseRestClient.js';
import {
  getParamsFromURL,
  REST_CLIENT_TYPE_ENUM,
  RestClientOptions,
  RestClientType,
} from './lib/requestUtils.js';
import {
  CBAppDepositFundsRequest,
  CBAppSendMoneyRequest,
  CBAppTransferMoneyRequest,
  CBAppWithdrawFundsRequest,
} from './types/request/coinbase-app-client.js';
import {
  CBAppAccount,
  CBAppAddress,
  CBAppCryptocurrency,
  CBAppDepositWithdrawal,
  CBAppFiatCurrency,
  CBAppPagination,
  CBAppTransaction,
  CBAppTransfer,
} from './types/response/coinbase-app-client.js';
⋮----
/**
 * REST client for Coinbase's Coinbase App API:
 * https://docs.cdp.coinbase.com/coinbase-app/docs/welcome
 */
export class CBAppClient extends BaseRestClient
⋮----
constructor(
    restClientOptions: RestClientOptions = {},
    requestOptions: AxiosRequestConfig = {},
)
⋮----
// Some endpoints return a warning if a version header isn't included: https://docs.cdp.coinbase.com/coinbase-app/docs/versioning
// Currently set to a date from the changelog: https://docs.cdp.coinbase.com/coinbase-app/docs/changelog
⋮----
getClientType(): RestClientType
⋮----
/**
   *
   * Account Endpoints
   *
   */
⋮----
/**
   * List Accounts
   *
   * List a current user's accounts to which the authentication method has access to.
   *
   * This endpoint is paginated. In case you are calling it first time, leave paginationURL empty.
   * If you are paginating, provide the paginationURL value from the previous response and you will receive the next page of accounts.
   */
getAccounts(params?: {
    paginationURL?: string;
    starting_after?: string;
}): Promise<
⋮----
/**
   * Show Account
   *
   * Get a current user's account by account ID or currency string.
   */
getAccount(params:
⋮----
/**
   *
   * Address Endpoints
   *
   */
⋮----
/**
   * Create Address
   *
   * Creates a new address for an account. Addresses can be created for wallet account types.
   */
createAddress(params:
⋮----
/**
   * List Addresses
   *
   * Lists addresses for an account.
   *
   * This endpoint is paginated. In case you are calling it first time, leave paginationURL empty.
   * If you are paginating, provide the paginationURL value from the previous response and you will receive the next page of addresses.
   */
getAddresses(params: {
    account_id: string;
    paginationURL?: string;
}): Promise<
⋮----
/**
   * Show Address
   *
   * Get an single address for an account.
   * A regular cryptocurrency address can be used in place of address_id but the address must be associated with the correct account.
   *
   * !! An address can only be associated with one account. See Create Address to create new addresses.
   */
getAddress(params:
⋮----
/**
   * List Address Transactions
   *
   * List transactions that have been sent to a specific address.
   * A regular cryptocurrency address can be used in place of address_id but the address must be associated with the correct account.
   *
   * This endpoint is paginated. In case you are calling it first time, leave paginationURL empty.
   * If you are paginating, provide the paginationURL value from the previous response and you will receive the next page of transactions.
   */
getAddressTransactions(params: {
    account_id: string;
    addressId: string;
    paginationURL?: string;
}): Promise<
⋮----
/**
   *
   * Transactions Endpoints
   *
   */
⋮----
/**
   * Send Money
   *
   * Send funds to a network address for any Coinbase supported asset, or email address of the recipient.
   * No transaction fees are required for off-blockchain cryptocurrency transactions.
   *
   * TRAVEL RULE DATA GUIDE: https://docs.cdp.coinbase.com/coinbase-app/docs/coinbase-app-travel-rule
   */
sendMoney(
    params: CBAppSendMoneyRequest,
): Promise<
⋮----
/**
   * Transfer Money
   *
   * Transfer any Coinbase supported digital asset between two of a single user's accounts.
   * Accounts must support the same currency for transfers to be successful.
   */
transferMoney(
    params: CBAppTransferMoneyRequest,
): Promise<
⋮----
/**
   * List Transactions
   *
   * Lists the transactions of an account by account ID.
   *
   * This endpoint is paginated. In case you are calling it first time, leave paginationURL empty.
   * If you are paginating, provide the paginationURL value from the previous response and you will receive the next page of transactions.
   */
getTransactions(params: {
    account_id: string;
    paginationURL?: string;
}): Promise<
⋮----
/**
   * Show Transaction
   *
   * Get a single transaction for an account.
   */
getTransaction(params: {
    account_id: string;
    transactionId: string;
}): Promise<
⋮----
/**
   *
   * Deposits Endpoints
   *
   */
⋮----
/**
   * Deposit Funds
   *
   * Deposits user-defined amount of funds to a fiat account.
   */
depositFunds(params: CBAppDepositFundsRequest): Promise<CBAppTransfer>
⋮----
/**
   * Commit Deposit
   *
   * Completes a deposit that is created in commit: false state.
   */
commitDeposit(params: {
    account_id: string;
    deposit_id: string;
}): Promise<CBAppTransfer>
⋮----
/**
   * List Deposits
   *
   * Lists fiat deposits for an account.
   *
   * This endpoint is paginated. In case you are calling it first time, leave paginationURL empty.
   * If you are paginating, provide the paginationURL value from the previous response and you will receive the next page of deposits.
   */
getDeposits(params:
⋮----
/**
   * Show Deposit
   *
   * Get one deposit by deposit Id.
   */
getDeposit(params:
⋮----
/**
   *
   * Withdrawals Endpoints
   *
   */
⋮----
/**
   * Withdraw Funds
   *
   * Withdraws a user-defined amount of funds from a fiat account.
   */
withdrawFunds(params: CBAppWithdrawFundsRequest): Promise<CBAppTransfer>
⋮----
/**
   * Commit Withdrawal
   *
   * Completes a withdrawal that is created in commit: false state.
   */
commitWithdrawal(params: {
    account_id: string;
    withdrawal_id: string;
}): Promise<CBAppTransfer>
⋮----
/**
   * List Withdrawals
   *
   * Lists withdrawals for an account.
   *
   * This endpoint is paginated. In case you are calling it first time, leave paginationURL empty.
   * If you are paginating, provide the paginationURL value from the previous response and you will receive the next page of withdrawals.
   */
getWithdrawals(params: {
    account_id: string;
    paginationURL?: string;
}): Promise<
⋮----
/**
   * Show Withdrawal
   *
   * Get a single withdrawal.
   */
getWithdrawal(params: {
    account_id: string;
    withdrawal_id: string;
}): Promise<
⋮----
/**
   *
   * DATA - Currencies Endpoints
   *
   */
⋮----
/**
   * Get Fiat Currencies
   *
   * Lists known fiat currencies. Currency codes conform to the ISO 4217 standard where possible.
   * Currencies with no representation in ISO 4217 may use a custom code.
   */
getFiatCurrencies(): Promise<
⋮----
/**
   * Get Cryptocurrencies
   *
   * Lists known cryptocurrencies.
   */
getCryptocurrencies(): Promise<CBAppCryptocurrency[]>
⋮----
/**
   *
   * DATA- Exchange rates Endpoints
   *
   */
⋮----
/**
   * Get Exchange Rates
   *
   * Get current exchange rates. Default base currency is USD but it can be defined as any supported currency.
   * Returned rates will define the exchange rate for one unit of the base currency.
   */
getExchangeRates(params?:
⋮----
/**
   *
   * DATA - Prices Endpoints
   *
   */
⋮----
/**
   * Get Buy Price
   *
   * Get the total price to buy one bitcoin or ether.
   * This endpoint doesn't require authentication.
   */
getBuyPrice(params:
⋮----
/**
   * Get Sell Price
   *
   * Get the total price to sell one bitcoin or ether.
   * This endpoint doesn't require authentication.
   */
getSellPrice(params:
⋮----
/**
   * Get Spot Price
   *
   * Get the current market price for bitcoin. This is usually somewhere in between the buy and sell price.
   * This endpoint doesn't require authentication.
   */
getSpotPrice(params:
⋮----
/**
   *
   * DATA - Time Endpoints
   *
   */
⋮----
/**
   * Get Current Time
   *
   * Get the API server time.
   * This endpoint doesn't require authentication.
   */
getCurrentTime(): Promise<

================
File: src/CBInternationalClient.ts
================
import { AxiosRequestConfig } from 'axios';
⋮----
import { BaseRestClient } from './lib/BaseRestClient.js';
import {
  REST_CLIENT_TYPE_ENUM,
  RestClientOptions,
  RestClientType,
} from './lib/requestUtils.js';
import {
  CancelINTXOrdersRequest,
  GetINTXAggregatedCandlesData,
  GetINTXDailyTradingVolumes,
  GetINTXFillsByPortfoliosRequest,
  GetINTXIndexCandlesRequest,
  GetINTXIndexCompositionHistory,
  GetINTXMatchingTransfersRequest,
  GetINTXOpenOrdersRequest,
  GetINTXPortfolioFillsRequest,
  INTXWithdrawToCounterpartyIdRequest,
  INTXWithdrawToCryptoAddressRequest,
  SubmitINTXOrderRequest,
  TransferINTXFundsBetweenPortfoliosRequest,
  TransferINTXPositionsBetweenPortfoliosRequest,
  UpdateINTXOpenOrderRequest,
  UpdateINTXPortfolioParametersRequest,
} from './types/request/coinbase-international.js';
⋮----
/**
 * REST client for Coinbase's Institutional International Exchange API:
 * https://docs.cdp.coinbase.com/intx/docs/welcome
 */
export class CBInternationalClient extends BaseRestClient
⋮----
constructor(
    restClientOptions: RestClientOptions = {},
    requestOptions: AxiosRequestConfig = {},
)
⋮----
getClientType(): RestClientType
⋮----
/**
   *
   * Assets Endpoints
   *
   */
⋮----
/**
   * List assets
   *
   * Returns a list of all supported assets.
   */
getAssets(): Promise<any>
⋮----
/**
   * Get asset details
   *
   * Retrieves information for a specific asset.
   */
getAssetDetails(params:
⋮----
/**
   * Get supported networks per asset
   *
   * Returns a list of supported networks and network information for a specific asset.
   */
getSupportedNetworksPerAsset(params:
⋮----
/**
   *
   * Index Endpoints
   *
   */
⋮----
/**
   * Get index composition
   *
   * Retrieves the latest index composition (metadata) with an ordered set of constituents.
   */
getIndexComposition(params:
⋮----
/**
   * Get index composition history
   *
   * Retrieves a history of index composition records in a descending time order.
   * The results are an array of index composition data recorded at different "timestamps".
   */
getIndexCompositionHistory(
    params: GetINTXIndexCompositionHistory,
): Promise<any>
⋮----
/**
   * Get index price
   *
   * Retrieves the latest index price.
   */
getIndexPrice(params:
⋮----
/**
   * Get index candles
   *
   * Retrieves the historical daily index prices in time descending order.
   * The daily values are represented as aggregated entries for the day in typical OHLC format.
   */
getIndexCandles(params: GetINTXIndexCandlesRequest): Promise<any>
⋮----
/**
   *
   * Instruments Endpoints
   *
   */
⋮----
/**
   * List instruments
   *
   * Returns all of the instruments available for trading.
   */
getInstruments(): Promise<any>
⋮----
/**
   * Get instrument details
   *
   * Retrieves market information for a specific instrument.
   */
getInstrumentDetails(params:
⋮----
/**
   * Get quote per instrument
   *
   * Retrieves the current quote for a specific instrument.
   */
getQuotePerInstrument(params:
⋮----
/**
   * Get daily trading volumes
   *
   * Retrieves the trading volumes for each instrument separated by day.
   */
getDailyTradingVolumes(params: GetINTXDailyTradingVolumes): Promise<any>
⋮----
/**
   * Get aggregated candles data per instrument
   *
   * Retrieves a list of aggregated candles data for a given instrument, granularity, and time range.
   */
getAggregatedCandlesData(params: GetINTXAggregatedCandlesData): Promise<any>
⋮----
/**
   * Get historical funding rates
   *
   * Retrieves the historical funding rates for a specific instrument.
   */
getHistoricalFundingRates(params: {
    instrument: string;
    result_limit?: number;
    result_offset?: number;
}): Promise<any>
⋮----
/**
   *
   * Position Offsets Endpoints
   *
   */
⋮----
/**
   * List position offsets
   *
   * Returns all active position offsets.
   */
getPositionOffsets(): Promise<any>
⋮----
/**
   *
   * Orders Endpoints
   *
   */
⋮----
/**
   * Create order
   *
   * Creates a new order.
   */
submitOrder(params: SubmitINTXOrderRequest): Promise<any>
⋮----
/**
   * List open orders
   *
   * Returns a list of active orders resting on the order book matching the requested criteria.
   * Does not return any rejected, cancelled, or fully filled orders as they are not active.
   */
getOpenOrders(params?: GetINTXOpenOrdersRequest): Promise<any>
⋮----
/**
   * Cancel orders
   *
   * Cancels all orders matching the requested criteria.
   */
cancelOrders(params: CancelINTXOrdersRequest): Promise<any>
⋮----
/**
   * Modify open order
   *
   * Modifies an open order.
   */
updateOpenOrder(params: UpdateINTXOpenOrderRequest): Promise<any>
⋮----
/**
   * Get order details
   *
   * Retrieves a single order. The order retrieved can be either active or inactive.
   */
getOrderDetails(params:
⋮----
/**
   * Cancel order
   *
   * Cancels a single open order.
   */
cancelOrder(params:
⋮----
/**
   *
   * Portfolios Endpoints
   *
   */
⋮----
/**
   * List all user portfolios
   *
   * Returns all of the user's portfolios.
   */
getUserPortfolios(): Promise<any>
⋮----
/**
   * Create portfolio
   *
   * Create a new portfolio. Request will fail if no name is provided or if user already has max number of portfolios. Max number of portfolios is 20.
   */
createPortfolio(params:
⋮----
/**
   * Patch portfolio
   *
   * Update parameters for existing portfolio.
   */
updatePortfolioParameters(
    params: UpdateINTXPortfolioParametersRequest,
): Promise<any>
⋮----
/**
   * Get user portfolio
   *
   * Returns the user's specified portfolio.
   */
getUserPortfolio(params:
⋮----
/**
   * Update portfolio
   *
   * Update existing user portfolio.
   */
updatePortfolio(params:
⋮----
/**
   * Get portfolio details
   *
   * Retrieves the summary, positions, and balances of a portfolio.
   */
getPortfolioDetails(params:
⋮----
/**
   * Get portfolio summary
   *
   * Retrieves the high level overview of a portfolio.
   */
getPortfolioSummary(params:
⋮----
/**
   * List portfolio balances
   *
   * Returns all of the balances for a given portfolio.
   */
getPortfolioBalances(params:
⋮----
/**
   * Get balance for portfolio/asset
   *
   * Retrieves the balance for a given portfolio and asset.
   */
getBalanceForPortfolioAsset(params: {
    portfolio: string;
    asset: string;
}): Promise<any>
⋮----
/**
   * List active loans for the portfolio
   *
   * Retrieves all loan info for a given portfolio.
   */
getActiveLoansForPortfolio(params:
⋮----
/**
   * Get loan info for portfolio/asset
   *
   * Retrieves the loan info for a given portfolio and asset.
   */
getLoanInfoForPortfolioAsset(params: {
    portfolio: string;
    asset: string;
}): Promise<any>
⋮----
/**
   * Acquire/repay loan
   *
   * Acquire or repay loan for a given portfolio and asset.
   */
acquireOrRepayLoan(params: {
    portfolio: string;
    asset: string;
    amount: number;
    action: 'ACQUIRE' | 'REPAY';
}): Promise<any>
⋮----
/**
   * Preview loan update
   *
   * Preview acquire or repay loan for a given portfolio and asset.
   */
previewLoanUpdate(params: {
    portfolio: string;
    asset: string;
    action: 'ACQUIRE' | 'REPAY';
    amount: string;
}): Promise<any>
⋮----
/**
   * View max loan availability
   *
   * View the maximum amount of loan that could be acquired now for a given portfolio and asset.
   */
getMaxLoanAvailability(params: {
    portfolio: string;
    asset: string;
}): Promise<any>
⋮----
/**
   * List portfolio positions
   *
   * Returns all of the positions for a given portfolio.
   */
getPortfolioPositions(params:
⋮----
/**
   * Get position for portfolio/instrument
   *
   * Retrieves the position for a given portfolio and symbol.
   */
getPositionForPortfolioInstrument(params: {
    portfolio: string;
    instrument: string;
}): Promise<any>
⋮----
/**
   * Get total open position limit
   *
   * Retrieves the total open position limit across instruments for a given portfolio.
   */
getTotalOpenPositionLimit(params:
⋮----
/**
   * List open position limits for all instruments
   *
   * Retrieves position limits for all positions a given portfolio currently has or has opened in the past.
   */
getOpenPositionLimitsForAllInstruments(params: {
    portfolio: string;
}): Promise<any>
⋮----
/**
   * Get open position limits for portfolio instrument
   *
   * Retrieves the position limits for a given portfolio and symbol.
   */
getOpenPositionLimitsForInstrument(params: {
    portfolio: string;
    instrument: string;
}): Promise<any>
⋮----
/**
   * List fills by portfolios
   *
   * Returns fills for specified portfolios or fills for all portfolios if none are provided.
   */
getFillsByPortfolios(params?: GetINTXFillsByPortfoliosRequest): Promise<any>
⋮----
/**
   * List portfolio fills
   *
   * Returns all of the fills for a given portfolio.
   */
getPortfolioFills(params: GetINTXPortfolioFillsRequest): Promise<any>
⋮----
/**
   * Enable/Disable portfolio cross collateral
   *
   * Enable or disable the cross collateral feature for the portfolio, which allows the portfolio to use non-USDC assets as collateral for margin trading.
   */
setCrossCollateral(params: {
    portfolio: string;
    enabled: boolean;
}): Promise<any>
⋮----
/**
   * Enable/Disable portfolio auto margin mode
   *
   * Enable or disable the auto margin feature, which lets the portfolio automatically
   * post margin amounts required to exceed the high leverage position restrictions.
   */
setAutoMargin(params:
⋮----
/**
   * Set portfolio margin override
   *
   * Specify the margin override value for a portfolio to either increase notional requirements or opt-in to higher leverage.
   */
setPortfolioMarginOverride(params: {
    portfolio_id: string;
    margin_override: string;
}): Promise<any>
⋮----
/**
   * Get fund transfer limit between portfolios
   *
   * Retrieves the maximum amount that can be transferred between portfolios for a specific asset.
   * This applies to transfers between portfolios of the same beneficial owner.
   */
getFundTransferLimit(params: {
    portfolio: string;
    asset: string;
}): Promise<any>
⋮----
/**
   * Transfer funds between portfolios
   *
   * Transfer assets from one portfolio to another.
   */
transferFundsBetweenPortfolios(
    params: TransferINTXFundsBetweenPortfoliosRequest,
): Promise<any>
⋮----
/**
   * Transfer positions between portfolios
   *
   * Transfer an existing position from one portfolio to another. The position transfer must fulfill the same portfolio-level margin requirements as submitting a new order on the opposite side for the sender's portfolio and a new order on the same side for the recipient's portfolio.
   * Additionally, organization-level requirements must be satisfied when evaluating the outcome of the position transfer.
   */
transferPositionsBetweenPortfolios(
    params: TransferINTXPositionsBetweenPortfoliosRequest,
): Promise<any>
⋮----
/**
   * List portfolio fee rates
   *
   * Retrieves the Perpetual Future and Spot fee rate tiers for the user.
   */
getPortfolioFeeRates(): Promise<any>
/**
   *
   * Rankings Endpoints
   *
   */
⋮----
/**
   * Get your rankings
   *
   * Retrieve your volume rankings for maker, taker, and total volume.
   */
getRankings(params: {
    instrument_type: string;
    period?: string;
    instruments?: string;
}): Promise<any>
⋮----
/**
   *
   * Transfers Endpoints
   *
   */
⋮----
/**
   * List matching transfers
   *
   * List matching transfers.
   */
getMatchingTransfers(params?: GetINTXMatchingTransfersRequest): Promise<any>
⋮----
/**
   * Get transfer
   *
   * Get transfer.
   */
getTransfer(params:
⋮----
/**
   * Withdraw to crypto address
   *
   * Withdraw to crypto address.
   */
withdrawToCryptoAddress(
    params: INTXWithdrawToCryptoAddressRequest,
): Promise<any>
⋮----
/**
   * Create crypto address
   *
   * Create crypto address.
   */
createCryptoAddress(params: {
    portfolio: string;
    asset: string;
    network_arn_id: string;
}): Promise<any>
⋮----
/**
   * Create counterparty Id
   *
   * Create counterparty Id.
   */
createCounterpartyId(params:
⋮----
/**
   * Validate counterparty Id
   *
   * Validate counterparty Id.
   */
validateCounterpartyId(params:
⋮----
/**
   * Get counterparty withdrawal limit
   *
   * Retrieves the maximum amount that can be withdrawn to a counterparty within the Coinbase transfer network
   * for a specific portfolio and asset.
   */
getCounterpartyWithdrawalLimit(params: {
    portfolio: string;
    asset: string;
}): Promise<any>
⋮----
/**
   * Withdraw to counterparty Id
   *
   * Withdraw to counterparty Id.
   */
withdrawToCounterpartyId(
    params: INTXWithdrawToCounterpartyIdRequest,
): Promise<any>
/**
   *
   * Fee Rates Endpoints
   *
   */
⋮----
/**
   * List fee rate tiers
   *
   * Return all the fee rate tiers.
   */
getFeeRateTiers(): Promise<any>

================
File: webpack/webpack.config.cjs
================
function generateConfig(name)
⋮----
// Add '.ts' and '.tsx' as resolvable extensions.
⋮----
// Node.js core modules not available in browsers
// The REST client's https.Agent (for keepAlive) is Node.js-only and won't work in browsers
⋮----
// Code is already transpiled from TypeScript, no additional loaders needed

================
File: .nvmrc
================
v22.17.1

================
File: jest.config.ts
================
/**
 * For a detailed explanation regarding each configuration property, visit:
 * https://jestjs.io/docs/configuration
 */
⋮----
import type { Config } from 'jest';
⋮----
// All imported modules in your tests should be mocked automatically
// automock: false,
⋮----
// Stop running tests after `n` failures
// bail: 0,
bail: false, // enable to stop test when an error occur,
⋮----
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/private/var/folders/kf/2k3sz4px6c9cbyzj1h_b192h0000gn/T/jest_dx",
⋮----
// Automatically clear mock calls, instances, contexts and results before every test
⋮----
// Indicates whether the coverage information should be collected while executing the test
⋮----
// An array of glob patterns indicating a set of files for which coverage information should be collected
⋮----
// The directory where Jest should output its coverage files
⋮----
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
//   "/node_modules/"
// ],
⋮----
// Indicates which provider should be used to instrument code for coverage
⋮----
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
//   "json",
//   "text",
//   "lcov",
//   "clover"
// ],
⋮----
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
⋮----
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
⋮----
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
⋮----
// The default configuration for fake timers
// fakeTimers: {
//   "enableGlobally": false
// },
⋮----
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
⋮----
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
⋮----
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
⋮----
// A set of global variables that need to be available in all test environments
// globals: {},
⋮----
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
⋮----
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
//   "node_modules"
// ],
⋮----
// An array of file extensions your modules use
⋮----
// modulePaths: ['src'],
⋮----
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
⋮----
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
⋮----
// Activates notifications for test results
// notify: false,
⋮----
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
⋮----
// A preset that is used as a base for Jest's configuration
// preset: undefined,
⋮----
// Run tests from one or more projects
// projects: undefined,
⋮----
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
⋮----
// Automatically reset mock state before every test
// resetMocks: false,
⋮----
// Reset the module registry before running each individual test
// resetModules: false,
⋮----
// A path to a custom resolver
// resolver: undefined,
⋮----
// Automatically restore mock state and implementation before every test
// restoreMocks: false,
⋮----
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
⋮----
// A list of paths to directories that Jest should use to search for files in
// roots: [
//   "<rootDir>"
// ],
⋮----
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
⋮----
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
⋮----
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
⋮----
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
⋮----
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
⋮----
// The test environment that will be used for testing
// testEnvironment: "jest-environment-node",
⋮----
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
⋮----
// Adds a location field to test results
// testLocationInResults: false,
⋮----
// The glob patterns Jest uses to detect test files
⋮----
// "**/__tests__/**/*.[jt]s?(x)",
⋮----
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
//   "/node_modules/"
// ],
⋮----
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
⋮----
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
⋮----
// This option allows use of a custom test runner
// testRunner: "jest-circus/runner",
⋮----
// A map from regular expressions to paths to transformers
// transform: undefined,
⋮----
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
//   "/node_modules/",
//   "\\.pnp\\.[^\\/]+$"
// ],
⋮----
// Prevents import esm module error from v1 axios release, issue #5026
⋮----
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
⋮----
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
verbose: true, // report individual test
⋮----
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
⋮----
// Whether to use watchman for file crawling
// watchman: true,

================
File: LICENSE.md
================
Copyright 2025 Tiago Siebler

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

================
File: tsconfig.json
================
{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "baseUrl": ".",
    "noEmitOnError": true,
    "declaration": true,
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": false,
    "inlineSourceMap": false,
    "lib": ["esnext"],
    "listEmittedFiles": false,
    "listFiles": false,
    "moduleResolution": "node",
    "noFallthroughCasesInSwitch": true,
    "noImplicitAny": true,
    "noUnusedParameters": true,
    "pretty": true,
    "removeComments": false,
    "resolveJsonModule": true,
    "skipLibCheck": false,
    "sourceMap": true,
    "strict": true,
    "strictNullChecks": true,
    "types": ["node", "jest"],
    "module": "commonjs",
    "outDir": "dist/cjs",
    "target": "esnext"
  },
  "compileOnSave": true,
  "exclude": ["node_modules", "dist"],
  "include": ["src/**/*.*", "test/**/*.*", ".eslintrc.cjs"]
}

================
File: examples/AdvancedTrade/WebSockets/privateWs.ts
================
import {
  // DefaultLogger,
  WebsocketClient,
  // WS_KEY_MAP,
  WsTopicRequest,
} from '../../../src/index.js';
⋮----
// DefaultLogger,
⋮----
// WS_KEY_MAP,
⋮----
/**
 * import { WebsocketClient } from 'coinbase-api';
 * const { WebsocketClient } = require('coinbase-api');
 */
⋮----
async function start()
⋮----
// key name & private key, as returned by coinbase when creating your API keys.
// Note: the below example is a dummy key and won't actually work
⋮----
// Optional: fully customise the logging experience by injecting a custom logger
// const logger: typeof DefaultLogger = {
//   ...DefaultLogger,
//   trace: (...params) => {
//     if (
//       [
//         'Sending ping',
//         'Sending upstream ws message: ',
//         'Received pong, clearing pong timer',
//         'Received ping, sending pong frame',
//       ].includes(params[0])
//     ) {
//       return;
//     }
//     console.log('trace', params);
//   },
// };
⋮----
// Either pass the full JSON object that can be downloaded when creating your API keys
// cdpApiKey: advancedTradeCdpAPIKey,
⋮----
// initialise the client
/**
       *
       * You can add both ED25519 and ECDSA keys, client will recognize both types of keys
       *
       * ECDSA:
       *
       * {
       *   apiKey: 'organizations/your_org_id/apiKeys/your_api_key_id',
       *   apiSecret:
       *     '-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIPT/TTZPxw0kDGvpuCENJp9A4/2INAt9/QKKfyidTWM8oAoGCCqGSM49\nAwEHoUQDQgAEd+cnxrKl536ly5eYBi+8dvXt1MJXYRo+/v38h9HrFKVGBRndU9DY\npV357xIfqeJEzb/MBuk3EW8cG9RTrYBwjg==\n-----END EC PRIVATE KEY-----\n',
       * }
       *
       * ED25519:
       * {
       *   apiKey: 'your-api-key-id',
       *   apiSecret: 'yourExampleApiSecretEd25519Version==',
       * }
       *
       *
       */
⋮----
// logger,
⋮----
// Data received
⋮----
// Something happened, attempting to reconenct
⋮----
// Reconnect successful
⋮----
// Connection closed. If unexpected, expect reconnect -> reconnected.
⋮----
// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
⋮----
// throw new Error('res?');
⋮----
/**
     * Use the client subscribe(topic, market) pattern to subscribe to any websocket topic.
     *
     * You can subscribe to topics one at a time or many one one request.
     *
     * Topics can be sent as simple strings, if no parameters are required.
     *
     * Any subscribe requests on the "advTradeUserData" market are automatically authenticated with the available credentials
     */
// client.subscribe('heartbeats', 'advTradeUserData');
⋮----
// This is the same as above, but uses WS_KEY_MAP as an enum (do this if you're not sure what value to put)
// client.subscribe('futures_balance_summary', WS_KEY_MAP.advTradeUserData);
⋮----
// Subscribe to the user feed for the advanced trade websocket
⋮----
// /**
//  * Or, as an array of simple strings.
//  *
//  * Any requests sent to the "advTradeUserData" wsKey are
//  * automatically authenticated, if API keys are avaiable:
//  */
// client.subscribe(
//   ['futures_balance_summary', 'user'],
//   'advTradeUserData',
// );
⋮----
/**
     * Or send a more structured object with parameters, e.g. if parameters are required
     */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
⋮----
/**
       * Anything in the payload will be merged into the subscribe "request",
       * allowing you to send misc parameters supported by the exchange (such as `product_ids: string[]`)
       */
⋮----
// In this case, the "futures_balance_summary" channel doesn't support any parameters
// product_ids: ['ETH-USD', 'BTC-USD'],

================
File: src/lib/websocket/WsStore.ts
================
import WebSocket from 'isomorphic-ws';
⋮----
import { DefaultLogger } from './logger.js';
import {
  DeferredPromise,
  WSConnectedResult,
  WsConnectionStateEnum,
  WsStoredState,
} from './WsStore.types.js';
⋮----
/**
 * Simple comparison of two objects, recursive for nested objects
 */
export function isDeepObjectMatch(object1: unknown, object2: unknown): boolean
⋮----
type DeferredPromiseRef =
  (typeof DEFERRED_PROMISE_REF)[keyof typeof DEFERRED_PROMISE_REF];
⋮----
export class WsStore<
WsKey extends string,
⋮----
constructor(logger: typeof DefaultLogger)
⋮----
/** Get WS stored state for key, optionally create if missing */
get(
    key: WsKey,
    createIfMissing?: true,
  ): WsStoredState<TWSTopicSubscribeEventArgs>;
⋮----
get(
    key: WsKey,
    createIfMissing?: false,
  ): WsStoredState<TWSTopicSubscribeEventArgs> | undefined;
⋮----
get(
    key: WsKey,
    createIfMissing?: boolean,
): WsStoredState<TWSTopicSubscribeEventArgs> | undefined
⋮----
getKeys(): WsKey[]
⋮----
create(key: WsKey): WsStoredState<TWSTopicSubscribeEventArgs> | undefined
⋮----
delete(key: WsKey): void
⋮----
// TODO: should we allow this at all? Perhaps block this from happening...
⋮----
/* connection websocket */
⋮----
hasExistingActiveConnection(key: WsKey): boolean
⋮----
getWs(key: WsKey): WebSocket | undefined
⋮----
setWs(key: WsKey, wsConnection: WebSocket): WebSocket
⋮----
getDeferredPromise<TSuccessResult = any>(
    wsKey: WsKey,
    promiseRef: string | DeferredPromiseRef,
): DeferredPromise<TSuccessResult> | undefined
⋮----
createDeferredPromise<TSuccessResult = any>(
    wsKey: WsKey,
    promiseRef: string | DeferredPromiseRef,
    throwIfExists: boolean,
): DeferredPromise<TSuccessResult>
⋮----
// console.log('existing promise');
⋮----
// console.log('create promise');
⋮----
// TODO: Once stable, use Promise.withResolvers in future
⋮----
resolveDeferredPromise(
    wsKey: WsKey,
    promiseRef: string | DeferredPromiseRef,
    value: unknown,
    removeAfter: boolean,
): void
⋮----
rejectDeferredPromise(
    wsKey: WsKey,
    promiseRef: string | DeferredPromiseRef,
    value: unknown,
    removeAfter: boolean,
): void
⋮----
removeDeferredPromise(
    wsKey: WsKey,
    promiseRef: string | DeferredPromiseRef,
): void
⋮----
// Just in case it's pending
⋮----
rejectAllDeferredPromises(wsKey: WsKey, reason: string): void
⋮----
// Skip reserved keys, such as the connection promise
⋮----
/** Get promise designed to track a connection attempt in progress. Resolves once connected. */
getConnectionInProgressPromise(
    wsKey: WsKey,
): DeferredPromise<WSConnectedResult> | undefined
⋮----
/**
   * Create a deferred promise designed to track a connection attempt in progress.
   *
   * Will throw if existing promise is found.
   */
createConnectionInProgressPromise(
    wsKey: WsKey,
    throwIfExists: boolean,
): DeferredPromise<WSConnectedResult>
⋮----
/** Remove promise designed to track a connection attempt in progress */
removeConnectingInProgressPromise(wsKey: WsKey): void
⋮----
/* connection state */
⋮----
isWsOpen(key: WsKey): boolean
⋮----
getConnectionState(key: WsKey): WsConnectionStateEnum
⋮----
setConnectionState(key: WsKey, state: WsConnectionStateEnum)
⋮----
// console.log(new Date(), `setConnectionState(${key}, ${state})`);
⋮----
isConnectionState(key: WsKey, state: WsConnectionStateEnum): boolean
⋮----
/**
   * Check if we're currently in the process of opening a connection for any reason. Safer than only checking "CONNECTING" as the state
   * @param key
   * @returns
   */
isConnectionAttemptInProgress(key: WsKey): boolean
⋮----
/* subscribed topics */
⋮----
getTopics(key: WsKey): Set<TWSTopicSubscribeEventArgs>
⋮----
getTopicsByKey(): Record<string, Set<TWSTopicSubscribeEventArgs>>
⋮----
// Since topics are objects we can't rely on the set to detect duplicates
/**
   * Find matching "topic" request from the store
   * @param key
   * @param topic
   * @returns
   */
getMatchingTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs)
⋮----
// if (typeof topic === 'string') {
//   return this.getMatchingTopic(key, { channel: topic });
// }
⋮----
addTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs)
⋮----
// console.log(`wsStore.addTopic(${key}, ${topic})`);
// Check for duplicate topic. If already tracked, don't store this one
⋮----
deleteTopic(key: WsKey, topic: TWSTopicSubscribeEventArgs)
⋮----
// Check if we're subscribed to a topic like this

================
File: src/lib/jwtNode.ts
================
import { createPrivateKey } from 'crypto';
import { importPKCS8, SignJWT } from 'jose';
import { nanoid } from 'nanoid';
⋮----
interface JWTSignParams {
  algorithm?: 'ES256' | 'EdDSA';
  timestampMs: number;
  jwtExpiresSeconds: number;
  apiPubKey: string;
  apiPrivKey: string;
}
⋮----
interface KeyInfo {
  algorithm: 'ES256' | 'EdDSA';
  privateKey: string;
}
⋮----
/**
 * Auto-detect key type and format based on the private key content
 */
function detectKeyTypeAndFormat(privateKeyPem: string): KeyInfo
⋮----
// ECDSA key detection (PEM format)
⋮----
// Ed25519 key detection (base64 string without PEM headers)
// Ed25519 private keys from Coinbase are provided as base64-encoded PKCS#8 keys
⋮----
// Try to decode as base64 to validate it's a valid base64 string
⋮----
// Ed25519 PKCS#8 keys are typically 48 bytes (44 bytes + padding)
// Raw Ed25519 keys are 32 bytes, but Coinbase provides PKCS#8 encoded keys
⋮----
// Convert base64 Ed25519 key to PEM format for jose
⋮----
// Not a valid base64 string, fall through
⋮----
// Default to ECDSA if we can't determine the type
⋮----
/**
 * Convert EC private key to PKCS#8 format if needed
 */
function ensurePKCS8Format(privateKeyPem: string): string
⋮----
// Convert EC private key to PKCS#8 format
⋮----
/**
 * Convert base64 Ed25519 private key to PKCS#8 format
 */
function convertEd25519ToPKCS8(base64Key: string): string
⋮----
// Handle different Ed25519 key formats
⋮----
// Raw 32-byte Ed25519 private key
⋮----
// libsodium format: 32 bytes private key + 32 bytes public key
// Extract just the private key (first 32 bytes)
⋮----
// Already PKCS#8 encoded, convert to PEM
⋮----
// Validate the key
⋮----
// Create PKCS#8 DER encoding for Ed25519 private key
// PKCS#8 structure for Ed25519:
// SEQUENCE {
//   INTEGER 0 (version)
//   SEQUENCE {
//     OBJECT IDENTIFIER 1.3.101.112 (Ed25519)
//   }
//   OCTET STRING {
//     OCTET STRING privateKey (32 bytes)
//   }
// }
⋮----
const ed25519Oid = Buffer.from([0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70]); // Ed25519 OID
⋮----
Buffer.from([0x04, 0x22, 0x04, 0x20]), // OCTET STRING header + inner OCTET STRING header
⋮----
Buffer.from([0x30, 0x2e]), // SEQUENCE, total length 46 bytes
Buffer.from([0x02, 0x01, 0x00]), // INTEGER 0 (version)
ed25519Oid, // Algorithm identifier
privateKeyOctetString, // Private key
⋮----
// Convert to PEM format
⋮----
// Validate the generated key
⋮----
export async function signJWT(
  params: {
    url: string;
    method: string;
  } & JWTSignParams,
): Promise<string>
⋮----
// Remove https:// but keep the rest
⋮----
// Auto-detect key type and format, or use provided algorithm
⋮----
// Import the private key
⋮----
// Create and sign the JWT
⋮----
export async function signWSJWT(params: JWTSignParams): Promise<string>
⋮----
// Auto-detect key type and format, or use provided algorithm
⋮----
// Import the private key
⋮----
// Create and sign the JWT

================
File: src/types/websockets/client.ts
================
import type { ClientRequestArgs } from 'http';
import WebSocket from 'isomorphic-ws';
⋮----
/** General configuration for the WebsocketClient */
export interface WSClientConfigurableOptions {
  /**
   * Your API key name.
   *
   * - For the Advanced Trade or App APIs, this is your API Key Name.
   */
  apiKey?: string;

  /**
   * Your API key secret.
   *
   * - For the Advanced Trade or App APIs, this is your API private key (including the -----BEGIN EC PRIVATE KEY-----\n etc).
   */
  apiSecret?: string;

  /**
   * Your API passphrase (NOT your account password). Only used for the API groups that use an API passphrase:
   * - Coinbase Exchange API
   * - Coinbase International API
   * - Coinbase Prime API
   */
  apiPassphrase?: string;

  /**
   * For JWT auth (adv trade & app API), seconds until jwt expires. Defaults to 120 seconds.
   */
  jwtExpiresSeconds?: number;

  /** How often to check if the connection is alive */
  pingInterval?: number;

  /** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */
  pongTimeout?: number;

  /** Delay in milliseconds before respawning the connection */
  reconnectTimeout?: number;

  wsUrl?: string;

  wsOptions?: {
    protocols?: string[];
    agent?: any;
  } & Partial<WebSocket.ClientOptions | ClientRequestArgs>;

  /**
   * Connect to the sandbox for supported products
   *
   * - Coinbase Exchange: https://docs.cdp.coinbase.com/exchange/docs/sandbox
   * - Coinbase International: https://docs.cdp.coinbase.com/intx/docs/sandbox
   *
   * - Coinbase App: No sandbox available.
   * - Coinbase Advanced Trade: No sandbox available.
   * - Coinbase Prime: No sandbox available.
   */
  useSandbox?: boolean;

  /**
   * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
   *
   * Look in the examples folder for a demonstration on using node's createHmac instead.
   */
  customSignMessageFn?: (message: string, secret: string) => Promise<string>;

  /**
   * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason.
   */
  reauthWSAPIOnReconnect?: boolean;
}
⋮----
/**
   * Your API key name.
   *
   * - For the Advanced Trade or App APIs, this is your API Key Name.
   */
⋮----
/**
   * Your API key secret.
   *
   * - For the Advanced Trade or App APIs, this is your API private key (including the -----BEGIN EC PRIVATE KEY-----\n etc).
   */
⋮----
/**
   * Your API passphrase (NOT your account password). Only used for the API groups that use an API passphrase:
   * - Coinbase Exchange API
   * - Coinbase International API
   * - Coinbase Prime API
   */
⋮----
/**
   * For JWT auth (adv trade & app API), seconds until jwt expires. Defaults to 120 seconds.
   */
⋮----
/** How often to check if the connection is alive */
⋮----
/** How long to wait for a pong (heartbeat reply) before assuming the connection is dead */
⋮----
/** Delay in milliseconds before respawning the connection */
⋮----
/**
   * Connect to the sandbox for supported products
   *
   * - Coinbase Exchange: https://docs.cdp.coinbase.com/exchange/docs/sandbox
   * - Coinbase International: https://docs.cdp.coinbase.com/intx/docs/sandbox
   *
   * - Coinbase App: No sandbox available.
   * - Coinbase Advanced Trade: No sandbox available.
   * - Coinbase Prime: No sandbox available.
   */
⋮----
/**
   * Allows you to provide a custom "signMessage" function, e.g. to use node's much faster createHmac method
   *
   * Look in the examples folder for a demonstration on using node's createHmac instead.
   */
⋮----
/**
   * If you authenticated the WS API before, automatically try to re-authenticate the WS API if you're disconnected/reconnected for any reason.
   */
⋮----
/**
 * WS configuration that's always defined, regardless of user configuration
 * (usually comes from defaults if there's no user-provided values)
 */
export interface WebsocketClientOptions extends WSClientConfigurableOptions {
  pingInterval: number;
  pongTimeout: number;
  reconnectTimeout: number;
  useSandbox: boolean;
  recvWindow: number;
  /**
   * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type)
   */
  requireConnectionReadyConfirmation: boolean;
  authPrivateConnectionsOnConnect: boolean;
  authPrivateRequests: boolean;
  reauthWSAPIOnReconnect: boolean;
}
⋮----
/**
   * If true, require a "receipt" that the connection is ready for use (e.g. a specific event type)
   */
⋮----
export type WsMarket = 'advancedTrade' | 'exchange' | 'international' | 'prime';

================
File: .eslintrc.cjs
================
// 'no-unused-vars': ['warn'],

================
File: src/WebsocketClient.ts
================
import { BaseWebsocketClient, EmittableEvent } from './lib/BaseWSClient.js';
import { signWSJWT } from './lib/jwtNode.js';
import { neverGuard } from './lib/misc-util.js';
import {
  isCBAdvancedTradeErrorEvent,
  isCBAdvancedTradeWSEvent,
  isCBExchangeWSEvent,
  isCBExchangeWSRequestOperation,
  isCBINTXWSRequestOperation,
  isCBPrimeWSRequestOperation,
} from './lib/websocket/typeGuards.js';
import {
  getCBExchangeWSSign,
  getCBInternationalWSSign,
  getCBPrimeWSSign,
  getMergedCBExchangeWSRequestOperations,
  MessageEventLike,
  WS_KEY_MAP,
  WS_URL_MAP,
  WsKey,
  WsTopicRequest,
} from './lib/websocket/websocket-util.js';
import { WSConnectedResult } from './lib/websocket/WsStore.types.js';
import { WsMarket } from './types/websockets/client.js';
import {
  WsAdvTradeRequestOperation,
  WsExchangeAuthenticatedRequestOperation,
  WsExchangeRequestOperation,
  WsInternationalAuthenticatedRequestOperation,
  WsInternationalRequestOperation,
  WsOperation,
  WsPrimeAuthenticatedRequestOperation,
  WsPrimeRequestOperation,
} from './types/websockets/requests.js';
import {
  WsAPITopicRequestParamMap,
  WsAPITopicResponseMap,
  WsAPIWsKeyTopicMap,
} from './types/websockets/wsAPI.js';
⋮----
/**
 * Any WS keys in this list will trigger automatic auth as required, if credentials are available
 */
⋮----
// Account data (fills), requires auth.
⋮----
// Coinbase Direct Market Data has direct access to Coinbase Exchange servers and requires auth.
⋮----
// The INTX feed always requires auth.
⋮----
// The Prime feed always requires auth.
⋮----
/**
 * Any WS keys in this list will ALWAYS skip the authentication process, even if credentials are available
 */
⋮----
/**
 * WS topics are always a string for this exchange. Some exchanges use complex objects.
 */
type WsTopic = string;
⋮----
export class WebsocketClient extends BaseWebsocketClient<WsKey>
⋮----
/**
   * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library
   */
public connectAll(): Promise<(WSConnectedResult | undefined)[]>
⋮----
/**
   * Request subscription to one or more topics. Pass topics as either an array of strings, or array of objects (if the topic has parameters).
   * Objects should be formatted as {topic: string, params: object}.
   *
   * - Subscriptions are automatically routed to the correct websocket connection.
   * - Authentication/connection is automatic.
   * - Resubscribe after network issues is automatic.
   *
   * Call `unsubscribe(topics)` to remove topics
   */
public subscribe(
    requests:
      | (WsTopicRequest<WsTopic> | WsTopic)
      | (WsTopicRequest<WsTopic> | WsTopic)[],
    wsKey: WsKey,
)
⋮----
/**
   * Unsubscribe from one or more topics. Similar to subscribe() but in reverse.
   *
   * - Requests are automatically routed to the correct websocket connection.
   * - These topics will be removed from the topic cache, so they won't be subscribed to again.
   */
public unsubscribe(
    requests:
      | (WsTopicRequest<WsTopic> | WsTopic)
      | (WsTopicRequest<WsTopic> | WsTopic)[],
    wsKey: WsKey,
)
⋮----
/**
   * Not supported by this exchange, do not use
   */
⋮----
// This overload allows the caller to omit the 3rd param, if it isn't required (e.g. for the login call)
async sendWSAPIRequest<
    TWSKey extends keyof WsAPIWsKeyTopicMap,
    TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey],
    TWSParams extends
      WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel],
    TWSAPIResponse extends
      | WsAPITopicResponseMap[TWSChannel]
      | object = WsAPITopicResponseMap[TWSChannel],
  >(
    wsKey: TWSKey,
    channel: TWSChannel,
    ...params: TWSParams extends undefined ? [] : [TWSParams]
  ): Promise<TWSAPIResponse>;
⋮----
async sendWSAPIRequest<
    TWSKey extends keyof WsAPIWsKeyTopicMap = keyof WsAPIWsKeyTopicMap,
    TWSChannel extends WsAPIWsKeyTopicMap[TWSKey] = WsAPIWsKeyTopicMap[TWSKey],
    TWSParams extends
      WsAPITopicRequestParamMap[TWSChannel] = WsAPITopicRequestParamMap[TWSChannel],
  >(
    wsKey: TWSKey,
    channel: TWSChannel,
    params?: TWSParams,
): Promise<undefined>
⋮----
/**
   *
   * Internal methods
   *
   */
⋮----
/**
   * Return a websocket URL, which is connected to as-is.
   * If a token or anything else is needed in the URL, this is a good place to add it.
   */
protected async getWsUrl(wsKey: WsKey): Promise<string>
⋮----
protected sendPingEvent(wsKey: WsKey)
⋮----
protected sendPongEvent(wsKey: WsKey)
⋮----
// Send a protocol layer pong
⋮----
protected isWsPing(msg: any): boolean
⋮----
protected isWsPong(msg: any): boolean
⋮----
// this.logger.info(`Not a pong: `, msg);
⋮----
protected resolveEmittableEvents(
    wsKey: WsKey,
    event: MessageEventLike,
): EmittableEvent[]
⋮----
// E.g. {"type":"error","message":"rate limit exceeded","wsKey":"advTradeMarketData"}
⋮----
// Parse Advanced Trade WS events (update & response)
⋮----
// These are request/reply pattern events (e.g. after subscribing to topics or authenticating)
⋮----
// Generic data for a channel
⋮----
// Parse CB Exchange WS events
⋮----
// Generic data for a channel
⋮----
/**
   * Determines if a topic is for a private channel, using a hardcoded list of strings
   */
protected isPrivateTopicRequest(
    request: WsTopicRequest<string>,
    wsKey: WsKey,
): boolean
⋮----
protected getWsKeyForMarket(market: WsMarket, isPrivate: boolean): WsKey
⋮----
protected getWsMarketForWsKey(wsKey: WsKey): WsMarket
⋮----
protected getPrivateWSKeys(): WsKey[]
⋮----
/** Force subscription requests to be sent in smaller batches, if a number is returned */
protected getMaxTopicsPerSubscribeEvent(wsKey: WsKey): number | null
⋮----
// Technically, INTX supports request batching but not with nested parameters, so we'll send one at a time
⋮----
// Exchange supports request batching, no known limit to max topics per request
⋮----
/**
   * Map one or more topics into fully prepared "subscribe request" events (already stringified and ready to send)
   */
protected async getWsOperationEventsForTopics(
    topicRequests: WsTopicRequest<string>[],
    wsKey: WsKey,
    operation: WsOperation,
): Promise<string[]>
⋮----
/**
     * Operations need to be structured in a way that this exchange understands.
     * Parse the internal format into the format expected by the exchange. One request per operation.
     */
⋮----
// In case there's ever more operation types than "subscribe" and "unsubscribe"
⋮----
// As of Sep 2024, parameters (such as product_id[]) cannot be nested with the channels array
⋮----
// This merges parametrs (such as product_id[]) into the top level request object
⋮----
/**
     * - Merge commands into one if the exchange supports batch requests,
     * - Apply auth/sign, if needed,
     * - Apply any final formatting to return a string array, ready to be sent upstream.
     */
⋮----
// Events that are ready to send (usually stringified JSON)
// ADV trade only supports sending one at a time, so we don't try to merge them
// These are already signed, if needed.
⋮----
/**
           * No batching is supported for this product group, so we can already
           * handle sign here and return it as is
           */
⋮----
// Don't expect this to ever happen, but just to please typescript...
⋮----
// We're under the max topics per request limit.
// Send operation requests as one merged request
⋮----
// We're over the max topics per request limit. Break into batches.
⋮----
// Don't expect this to ever happen, but just to please typescript...
⋮----
// We're over the max topics per request limit. Break into batches.
⋮----
// throw new Error(
//   'CB INTX is not fully implemented yet - awaiting test environment... if you need this, please get in touch.',
// );
⋮----
// Don't expect this to ever happen, but just to please typescript...
⋮----
// throw new Error(
//   'CB Prime is not fully implemented yet - awaiting test environment... if you need this, please get in touch.',
// );
⋮----
// throw new Error(`Not implemented for "${wsKey}" yet`);
⋮----
/**
   * Events are signed per-request, so this function isn't needed for Coinbase.
   */
protected async getWsAuthRequestEvent(wsKey: WsKey): Promise<object>

================
File: .gitignore
================
examples/futures-private-test.ts
examples/spot-private-test.ts
node_modules

rest-spot-private-ts-test.ts

localtest.sh
testfile.ts
dist
cbtests.sh
doc

coverage
ts-adv-trade-test-private.ts
examples/ts-app-priv.ts
examples/ts-commerce.ts
ts-exchange-priv.ts
testfile-cbexch.ts
restClientRegex.ts
privaterepotracker.txt
examples/_TiagoTests
testfile.ts
cbapidocs.txt
repomix.sh

================
File: src/lib/BaseWSClient.ts
================
import EventEmitter from 'events';
import WebSocket from 'isomorphic-ws';
⋮----
import {
  WebsocketClientOptions,
  WSClientConfigurableOptions,
} from '../types/websockets/client.js';
import { WsOperation } from '../types/websockets/requests.js';
import { WS_LOGGER_CATEGORY } from '../WebsocketClient.js';
import { DefaultLogger } from './websocket/logger.js';
import {
  isMessageEvent,
  MessageEventLike,
  safeTerminateWs,
  WsTopicRequest,
  WsTopicRequestOrStringTopic,
} from './websocket/websocket-util.js';
import { WsStore } from './websocket/WsStore.js';
import {
  WSConnectedResult,
  WsConnectionStateEnum,
} from './websocket/WsStore.types.js';
⋮----
interface WSClientEventMap<WsKey extends string> {
  /** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */
  open: (evt: { wsKey: WsKey; event: any }) => void;
  /** Reconnecting a dropped connection */
  reconnect: (evt: { wsKey: WsKey; event: any }) => void;
  /** Successfully reconnected a connection that dropped */
  reconnected: (evt: { wsKey: WsKey; event: any }) => void;
  /** Connection closed */
  close: (evt: { wsKey: WsKey; event: any }) => void;
  /** Received reply to websocket command (e.g. after subscribing to topics) */
  response: (response: any & { wsKey: WsKey }) => void;
  /** Received data for topic */
  update: (response: any & { wsKey: WsKey }) => void;
  /** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */
  exception: (response: any & { wsKey: WsKey }) => void;
  error: (response: any & { wsKey: WsKey }) => void;
  /** Confirmation that a connection successfully authenticated */
  authenticated: (event: { wsKey: WsKey; event: any }) => void;
}
⋮----
/** Connection opened. If this connection was previously opened and reconnected, expect the reconnected event instead */
⋮----
/** Reconnecting a dropped connection */
⋮----
/** Successfully reconnected a connection that dropped */
⋮----
/** Connection closed */
⋮----
/** Received reply to websocket command (e.g. after subscribing to topics) */
⋮----
/** Received data for topic */
⋮----
/** Exception from ws client OR custom listeners (e.g. if you throw inside your event handler) */
⋮----
/** Confirmation that a connection successfully authenticated */
⋮----
export interface EmittableEvent<TEvent = any> {
  eventType:
    | 'response'
    | 'update'
    | 'exception'
    | 'authenticated'
    | 'connectionReady'; // tied to "requireConnectionReadyConfirmation"
  event: TEvent;
}
⋮----
| 'connectionReady'; // tied to "requireConnectionReadyConfirmation"
⋮----
// Type safety for on and emit handlers: https://stackoverflow.com/a/61609010/880837
export interface BaseWebsocketClient<TWSKey extends string> {
  on<U extends keyof WSClientEventMap<TWSKey>>(
    event: U,
    listener: WSClientEventMap<TWSKey>[U],
  ): this;

  emit<U extends keyof WSClientEventMap<TWSKey>>(
    event: U,
    ...args: Parameters<WSClientEventMap<TWSKey>[U]>
  ): boolean;
}
⋮----
on<U extends keyof WSClientEventMap<TWSKey>>(
    event: U,
    listener: WSClientEventMap<TWSKey>[U],
  ): this;
⋮----
emit<U extends keyof WSClientEventMap<TWSKey>>(
    event: U,
    ...args: Parameters<WSClientEventMap<TWSKey>[U]>
  ): boolean;
⋮----
/**
 * Users can conveniently pass topics as strings or objects (object has topic name + optional params).
 *
 * This method normalises topics into objects (object has topic name + optional params).
 */
function getNormalisedTopicRequests(
  wsTopicRequests: WsTopicRequestOrStringTopic<string>[],
): WsTopicRequest<string>[]
⋮----
// passed as string, convert to object
⋮----
// already a normalised object, thanks to user
⋮----
type WSTopic = string;
⋮----
// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging
export abstract class BaseWebsocketClient<
TWSKey extends string,
⋮----
constructor(
    options?: WSClientConfigurableOptions,
    logger?: typeof DefaultLogger,
)
⋮----
// Requires a confirmation "response" from the ws connection before assuming it is ready
⋮----
// Automatically auth after opening a connection?
⋮----
// Automatically include auth/sign with every WS request
⋮----
// Automatically re-auth WS API, if we were auth'd before and get reconnected
⋮----
protected abstract sendPingEvent(wsKey: TWSKey, ws: WebSocket): void;
⋮----
protected abstract sendPongEvent(wsKey: TWSKey, ws: WebSocket): void;
⋮----
protected abstract isWsPong(data: any): boolean;
⋮----
protected abstract isWsPing(data: any): boolean;
⋮----
protected abstract getWsAuthRequestEvent(wsKey: TWSKey): Promise<object>;
⋮----
protected abstract isPrivateTopicRequest(
    request: WsTopicRequest<WSTopic>,
    wsKey: TWSKey,
  ): boolean;
⋮----
/**
   * Returns a list of string events that can be individually sent upstream to complete subscribing/unsubscribing/etc to these topics
   */
protected abstract getWsOperationEventsForTopics(
    topics: WsTopicRequest<WSTopic>[],
    wsKey: TWSKey,
    operation: WsOperation,
  ): Promise<string[]>;
⋮----
protected abstract getPrivateWSKeys(): TWSKey[];
⋮----
protected abstract getWsUrl(wsKey: TWSKey): Promise<string>;
⋮----
protected abstract getMaxTopicsPerSubscribeEvent(
    wsKey: TWSKey,
  ): number | null;
⋮----
/**
   * Abstraction called to sort ws events into emittable event types (response to a request, data update, etc)
   */
protected abstract resolveEmittableEvents(
    wsKey: TWSKey,
    event: MessageEventLike,
  ): EmittableEvent[];
⋮----
/**
   * Request connection of all dependent (public & private) websockets, instead of waiting for automatic connection by library
   */
protected abstract connectAll(): Promise<(WSConnectedResult | undefined)[]>;
⋮----
protected isPrivateWsKey(wsKey: TWSKey): boolean
⋮----
/** Returns auto-incrementing request ID, used to track promise references for async requests */
protected getNewRequestId(): string
⋮----
protected abstract sendWSAPIRequest(
    wsKey: TWSKey,
    channel: WSTopic,
    params?: any,
  ): Promise<unknown>;
⋮----
protected abstract sendWSAPIRequest(
    wsKey: TWSKey,
    channel: WSTopic,
    params: any,
  ): Promise<unknown>;
⋮----
/**
   * Subscribe to one or more topics on a WS connection (identified by WS Key).
   *
   * - Topics are automatically cached
   * - Connections are automatically opened, if not yet connected
   * - Authentication is automatically handled
   * - Topics are automatically resubscribed to, if something happens to the connection, unless you call unsubsribeTopicsForWsKey(topics, key).
   *
   * @param wsTopicRequests array of topics to subscribe to
   * @param wsKey ws key referring to the ws connection these topics should be subscribed on
   */
public subscribeTopicsForWsKey(
    wsTopicRequests: WsTopicRequestOrStringTopic<WSTopic>[],
    wsKey: TWSKey,
)
⋮----
// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically
⋮----
// start connection process if it hasn't yet begun. Topics are automatically subscribed to on-connect
⋮----
// Subscribe should happen automatically once connected, nothing to do here after topics are added to wsStore.
⋮----
/**
       * Are we in the process of connection? Nothing to send yet.
       */
⋮----
// We're connected. Check if auth is needed and if already authenticated
⋮----
/**
       * If not authenticated yet and auth is required, don't request topics yet.
       *
       * Auth should already automatically be in progress, so no action needed from here. Topics will automatically subscribe post-auth success.
       */
⋮----
// Finally, request subscription to topics if the connection is healthy and ready
⋮----
protected unsubscribeTopicsForWsKey(
    wsTopicRequests: WsTopicRequestOrStringTopic<string>[],
    wsKey: TWSKey,
)
⋮----
// Store topics, so future automation (post-auth, post-reconnect) has everything needed to resubscribe automatically
⋮----
// If not connected, don't need to do anything.
// Removing the topic from the store is enough to stop it from being resubscribed to on reconnect.
⋮----
// We're connected. Check if auth is needed and if already authenticated
⋮----
/**
       * If not authenticated yet and auth is required, don't need to do anything.
       * We don't subscribe to topics until auth is complete anyway.
       */
⋮----
// Finally, request subscription to topics if the connection is healthy and ready
⋮----
/**
   * Splits topic requests into two groups, public & private topic requests
   */
private sortTopicRequestsIntoPublicPrivate(
    wsTopicRequests: WsTopicRequest<string>[],
    wsKey: TWSKey,
):
⋮----
/** Get the WsStore that tracks websockets & topics */
public getWsStore(): WsStore<TWSKey, WsTopicRequest<string>>
⋮----
public close(wsKey: TWSKey, force?: boolean)
⋮----
public closeAll(force?: boolean)
⋮----
public isConnected(wsKey: TWSKey): boolean
⋮----
/**
   * Request connection to a specific websocket, instead of waiting for automatic connection.
   */
public async connect(wsKey: TWSKey): Promise<WSConnectedResult | undefined>
⋮----
// Important: don't check for RECONNECTING here, or this clashes with reconnectWithDelay()!
⋮----
private connectToWsUrl(url: string, wsKey: TWSKey): WebSocket
⋮----
private parseWsError(context: string, error: any, wsKey: TWSKey)
⋮----
/** Get a signature, build the auth request and send it */
private async sendAuthRequest(wsKey: TWSKey): Promise<void>
⋮----
private reconnectWithDelay(wsKey: TWSKey, connectionDelayMs: number)
⋮----
private ping(wsKey: TWSKey)
⋮----
private clearTimers(wsKey: TWSKey)
⋮----
// Send a ping at intervals
private clearPingTimer(wsKey: TWSKey)
⋮----
// Expect a pong within a time limit
private clearPongTimer(wsKey: TWSKey)
⋮----
// this.logger.trace(`Cleared pong timeout for "${wsKey}"`);
⋮----
// this.logger.trace(`No active pong timer for "${wsKey}"`);
⋮----
/**
   * Simply builds and sends subscribe events for a list of topics for a ws key
   *
   * @private Use the `subscribe(topics)` or `subscribeTopicsForWsKey(topics, wsKey)` method to subscribe to topics. Send WS message to subscribe to topics.
   */
private async requestSubscribeTopics(
    wsKey: TWSKey,
    topics: WsTopicRequest<string>[],
)
⋮----
// Automatically splits requests into smaller batches, if needed
⋮----
// `Subscribing to ${topics.length} "${wsKey}" topics in ${subscribeWsMessages.length} batches.`, // Events: "${JSON.stringify(topics)}"
⋮----
/**
   * Simply builds and sends unsubscribe events for a list of topics for a ws key
   *
   * @private Use the `unsubscribe(topics)` method to unsubscribe from topics. Send WS message to unsubscribe from topics.
   */
private async requestUnsubscribeTopics(
    wsKey: TWSKey,
    wsTopicRequests: WsTopicRequest<string>[],
)
⋮----
/**
   * Try sending a string event on a WS connection (identified by the WS Key)
   */
public tryWsSend(wsKey: TWSKey, wsMessage: string)
⋮----
private async onWsOpen(event: any, wsKey: TWSKey)
⋮----
private onWsPing(_event: any, wsKey: TWSKey, ws: WebSocket, source: string)
⋮----
private onWsPong(_event: any, wsKey: TWSKey, source: string)
⋮----
/**
   * Called automatically once a connection is ready.
   * - Some exchanges are ready immediately after the connections open.
   * - Some exchanges send an event to confirm the connection is ready for us.
   *
   * This method is called to act when the connection is ready. Use `requireConnectionReadyConfirmation` to control how this is called.
   */
private async onWsReadyForEvents(wsKey: TWSKey)
⋮----
// Resolve & cleanup deferred "connection attempt in progress" promise
⋮----
// Remove before resolving, in case there's more requests queued
⋮----
// Some websockets require an auth packet to be sent after opening the connection
⋮----
// Reconnect to topics known before it connected
⋮----
// Request sub to public topics, if any
⋮----
// Request sub to private topics, if auth on connect isn't needed
⋮----
/**
   * Handle subscription to private topics _after_ authentication successfully completes asynchronously.
   *
   * Only used for exchanges that require auth before sending private topic subscription requests
   */
private onWsAuthenticated(
    wsKey: TWSKey,
    event: { isWSAPI?: boolean; WSAPIAuthChannel?: string },
)
⋮----
private onWsMessage(event: unknown, wsKey: TWSKey, ws: WebSocket)
⋮----
// any message can clear the pong timer - wouldn't get a message if the ws wasn't working
⋮----
// console.log(`raw event: `, { data, dataType, emittableEvents });
⋮----
private onWsClose(event: unknown, wsKey: TWSKey)
⋮----
// clean up any pending promises for this connection
⋮----
// clean up any pending promises for this connection
⋮----
// This was an intentional close, delete all state for this connection, as if it never existed:
⋮----
private getWs(wsKey: TWSKey)
⋮----
private setWsState(wsKey: TWSKey, state: WsConnectionStateEnum)
⋮----
/**
   * Promise-driven method to assert that a ws has successfully connected (will await until connection is open)
   */
protected async assertIsConnected(wsKey: TWSKey): Promise<unknown>
⋮----
// Already in progress? Await shared promise and retry
⋮----
// Start connection, it should automatically store/return a promise.

================
File: README.md
================
# Node.js & JavaScript SDK for Coinbase's Advanced Trade, App, Exchange, International, Prime & Commerce REST APIs and WebSockets

<p align="center">
  <a href="https://www.npmjs.com/package/coinbase-api">
    <picture>
      <source media="(prefers-color-scheme: dark)" srcset="https://github.com/tiagosiebler/coinbase-api/blob/master/docs/images/logoDarkMode2.svg?raw=true#gh-dark-mode-only">
      <img alt="SDK Logo" src="https://github.com/tiagosiebler/coinbase-api/blob/master/docs/images/logoBrightMode2.svg?raw=true#gh-light-mode-only">
    </picture>
  </a>
</p>

[![npm version](https://img.shields.io/npm/v/coinbase-api)][1]
[![npm size](https://img.shields.io/bundlephobia/min/coinbase-api/latest)][1]
[![npm downloads](https://img.shields.io/npm/dt/coinbase-api)][1]
[![Build & Test](https://github.com/tiagosiebler/coinbase-api/actions/workflows/e2etest.yml/badge.svg?branch=master)](https://github.com/tiagosiebler/coinbase-api/actions/workflows/e2etest.yml)
[![last commit](https://img.shields.io/github/last-commit/tiagosiebler/coinbase-api)][1]
[![Telegram](https://img.shields.io/badge/chat-on%20telegram-blue.svg)](https://t.me/nodetraders)

[1]: https://www.npmjs.com/package/coinbase-api

> [!TIP]
> Upcoming change: As part of the [Siebly.io](https://siebly.io/?ref=ghcoinbase) brand, this SDK will soon be hosted under the [Siebly.io GitHub organisation](https://github.com/sieblyio). The migration is seamless and requires no user changes.

Updated & performant JavaScript & Node.js SDK for Coinbase's Advanced Trade, App, Exchange, International, Prime & Commerce REST APIs and WebSockets:

- Professional, robust & performant Coinbase SDK with extensive production use in live trading environments.
- Complete integration with all Coinbase APIs - supports both retail and institutional REST clients and WebSockets:
  - [Coinbase Advanced Trade](https://docs.cdp.coinbase.com/advanced-trade/docs/welcome) - Modern trading platform
  - [Coinbase App](https://docs.cdp.coinbase.com/coinbase-app/docs/welcome) - Consumer mobile/web application
  - [Coinbase Exchange](https://docs.cdp.coinbase.com/exchange/docs/welcome) - Professional trading platform
  - [Coinbase International Exchange](https://docs.cdp.coinbase.com/intx/docs/welcome) - International institutional trading
  - [Coinbase Prime](https://docs.cdp.coinbase.com/prime/docs/welcome) - Institutional custody and trading
  - [Coinbase Commerce](https://docs.cdp.coinbase.com/commerce-onchain/docs/welcome) - Payments and commerce solutions
- Complete TypeScript support (with type declarations for most API requests & responses).
  - Strongly typed requests and responses.
  - Automated end-to-end tests ensuring reliability.
- Actively maintained with a modern, promise-driven interface.
- Supports both ECDSA and ED25519 API keys with automatic key type detection.
- Robust WebSocket integration with configurable connection heartbeats & automatic reconnect then resubscribe workflows.
  - Event driven messaging.
  - Smart WebSocket persistence with automatic reconnection handling.
  - Emit `reconnected` event when dropped connection is restored.
  - Support for both public and private WebSocket streams across all platforms.
- Automatically supports both ESM and CJS projects.
- Proxy support via axios integration.
- Heavy automated end-to-end testing with real API calls.
- Active community support & collaboration in telegram: [Node.js Algo Traders](https://t.me/nodetraders).
- Extensive examples for interacting with the Coinbase API offering in Node.js/JavaScript/TypeScript: [/examples/](./examples).

## Table of Contents

- [Installation](#installation)
- [Examples](#examples)
- [Issues & Discussion](#issues--discussion)
- [Related Projects](#related-projects)
- [Documentation](#documentation)
- [Structure](#structure)
- [Usage](#usage)
  - [REST API Clients](#rest-api)
    - [CBAdvancedTradeClient](#cbadvancedtradeclient)
    - [CBAppClient](#cbappclient)
    - [CBExchangeClient](#cbexchangeclient)
    - [CBInternationalClient](#cbinternationalclient)
    - [CBPrimeClient](#cbprimeclient)
    - [CBCommerceClient](#cbcommerceclient)
  - [WebSocket Client](#websockets)
    - [Public WebSocket Streams](#public-websocket)
    - [Private WebSocket Streams](#private-websocket)
    - [WebSocket Event Handling](#listening-and-subscribing-to-websocket-events)
- [Customise Logging](#customise-logging)
- [Browser/Frontend Usage](#browserfrontend-usage)
  - [Webpack](#webpack)
- [LLMs & AI](#use-with-llms--ai)
- [Used By](#used-by)
- [Contributions & Thanks](#contributions--thanks)

## Installation

`npm install --save coinbase-api`

## Examples

Refer to the [examples](./examples) folder for implementation examples.

## Issues & Discussion

- Issues? Check the [issues tab](https://github.com/tiagosiebler/coinbase-api/issues).
- Discuss & collaborate with other node devs? Join our [Node.js Algo Traders](https://t.me/nodetraders) engineering community on telegram.
- Follow our announcement channel for real-time updates on [X/Twitter](https://x.com/sieblyio)

<!-- template_related_projects -->

## Related Projects

Check out our JavaScript/TypeScript/Node.js SDKs & Projects:

- Visit our website: [https://Siebly.io](https://siebly.io/?ref=gh)
- Try our REST API & WebSocket SDKs published on npmjs:
  - [Bybit Node.js SDK: bybit-api](https://www.npmjs.com/package/bybit-api)
  - [Kraken Node.js SDK: @siebly/kraken-api](https://www.npmjs.com/package/@siebly/kraken-api)
  - [OKX Node.js SDK: okx-api](https://www.npmjs.com/package/okx-api)
  - [Binance Node.js SDK: binance](https://www.npmjs.com/package/binance)
  - [Gate (gate.com) Node.js SDK: gateio-api](https://www.npmjs.com/package/gateio-api)
  - [Bitget Node.js SDK: bitget-api](https://www.npmjs.com/package/bitget-api)
  - [Kucoin Node.js SDK: kucoin-api](https://www.npmjs.com/package/kucoin-api)
  - [Coinbase Node.js SDK: coinbase-api](https://www.npmjs.com/package/coinbase-api)
  - [Bitmart Node.js SDK: bitmart-api](https://www.npmjs.com/package/bitmart-api)
- Try my misc utilities:
  - [OrderBooks Node.js: orderbooks](https://www.npmjs.com/package/orderbooks)
  - [Crypto Exchange Account State Cache: accountstate](https://www.npmjs.com/package/accountstate)
- Check out my examples:
  - [awesome-crypto-examples Node.js](https://github.com/tiagosiebler/awesome-crypto-examples)
  <!-- template_related_projects_end -->

## Documentation

Most methods accept JS objects. These can be populated using parameters specified by Coinbase's API documentation, or check the type definition in each class within this repository.

### API Documentation Links

- [Coinbase Developer Platform - Product APIs](https://docs.cdp.coinbase.com/product-apis/docs/welcome)
  - [Advanced Trade API](https://docs.cdp.coinbase.com/advanced-trade/docs/welcome)
  - [Coinbase App API](https://docs.cdp.coinbase.com/coinbase-app/docs/welcome)
  - [Exchange API](https://docs.cdp.coinbase.com/exchange/docs/welcome)
  - [International Exchange API](https://docs.cdp.coinbase.com/intx/docs/welcome)
  - [Prime API](https://docs.cdp.coinbase.com/prime/docs/welcome)
  - [Commerce API](https://docs.cdp.coinbase.com/commerce-onchain/docs/welcome)
- [REST Endpoint Function List](./docs/endpointFunctionList.md)

## Structure

This project uses typescript. Resources are stored in 2 key structures:

- [src](./src) - the whole connector written in typescript
- [examples](./examples) - some implementation examples & demonstrations. Contributions are welcome!

---

# Usage

Create API credentials on Coinbase's website:

- [Coinbase API Key Management](https://www.coinbase.com/settings/api)

## REST API

The SDK provides dedicated REST clients for each of Coinbase's API groups. Each client is designed for specific use cases and user types:

To use any of Coinbase's REST APIs in JavaScript/TypeScript/Node.js, import (or require) the client you want to use. We currently support the following clients:

- [CBAdvancedTradeClient](./src/CBAdvancedTradeClient.ts)
- [CBAppClient](./src/CBAppClient.ts)
- [CBExchangeClient](./src/CBExchangeClient.ts)
- [CBInternationalClient](./src/CBInternationalClient.ts)
- [CBPrimeClient](./src/CBPrimeClient.ts)
- [CBCommerceClient](./src/CBCommerceClient.ts)

#### CBAdvancedTradeClient

```javascript
const { CBAdvancedTradeClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { CBAdvancedTradeClient } from 'coinbase-api';
 */

// insert your API key details here from Coinbase API Key Management
const advancedTradeCdpAPIKey = {
  // dummy example keys to understand the structure
  name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2',
  privateKey:
    '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n',
};

/*
 * You can add ECDSA keys like the example above, or ED25519 keys like the example below.
 * Client will recognize both types of keys automatically.
 * ED25519:
 * {
 *   name: 'your-api-key-id',
 *   privateKey: 'yourExampleApiSecretEd25519Version==',
 * }
 */

const client = new CBAdvancedTradeClient({
  // Either pass the full JSON object that can be downloaded when creating your API keys
  // cdpApiKey: advancedTradeCdpAPIKey,

  // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret"
  apiKey: advancedTradeCdpAPIKey.name,
  apiSecret: advancedTradeCdpAPIKey.privateKey,
});

async function doAPICall() {
  // Example usage of the CBAdvancedTradeClient
  try {
    const accounts = await client.getAccounts();
    console.log('Get accounts result: ', accounts);
  } catch (e) {
    console.error('Exception: ', JSON.stringify(e));
  }
}

doAPICall();
```

#### CBAppClient

```javascript
const { CBAppClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { CBAppClient } from 'coinbase-api';
 */

// insert your API key details here from Coinbase API Key Management
const CBAppKeys = {
  // dummy example keys to understand the structure
  name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2',
  privateKey:
    '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n',
};

/*
 * You can add ECDSA keys like the example above, or ED25519 keys like the example below.
 * Client will recognize both types of keys automatically.
 * ED25519:
 * {
 *   name: 'your-api-key-id',
 *   privateKey: 'yourExampleApiSecretEd25519Version==',
 * }
 */

const client = new CBAppClient({
  // Either pass the full JSON object that can be downloaded when creating your API keys
  // cdpApiKey: CBAppCdpAPIKey,

  // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret"
  apiKey: CBAppKeys.name,
  apiSecret: CBAppKeys.privateKey,
});

async function doAPICall() {
  try {
    // Transfer money between your own accounts
    const transferMoneyResult = await client.transferMoney({
      account_id: 'your_source_account_id',
      type: 'transfer',
      to: 'your_destination_account_id',
      amount: '0.01',
      currency: 'BTC',
    });
    console.log('Transfer Money Result: ', transferMoneyResult);
  } catch (e) {
    console.error('Error: ', e);
  }
}

doAPICall();
```

#### CBInternationalClient

```javascript
const { CBInternationalClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { CBInternationalClient } from 'coinbase-api';
 */

// insert your API key details here from Coinbase API Key Management
const client = new CBInternationalClient({
  apiKey: 'insert_api_key_here',
  apiSecret: 'insert_api_secret_here',
  apiPassphrase: 'insert_api_passphrase_here',
  // Set "useSandbox" to use the CoinBase International API sandbox environment
  // useSandbox: true,
});

async function doAPICall() {
  try {
    // Get asset details
    const assetDetails = await client.getAssetDetails({ asset: 'BTC' });
    console.log('Asset Details: ', assetDetails);
  } catch (e) {
    console.error('Exception: ', JSON.stringify(e, null, 2));
  }
}

doAPICall();
```

#### CBExchangeClient

```javascript
const { CBExchangeClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { CBExchangeClient } from 'coinbase-api';
 */

// insert your API key details here from Coinbase API Key Management
const client = new CBExchangeClient({
  apiKey: 'insert_api_key_here',
  apiSecret: 'insert_api_secret_here',
  apiPassphrase: 'insert_api_passphrase_here',
  // Set "useSandbox" to use the CoinBase International API sandbox environment
  // useSandbox: true,
});

async function doAPICall() {
  try {
    // Get a single currency by id
    const currency = await client.getCurrency('BTC');
    console.log('Currency: ', currency);
  } catch (e) {
    console.error('Exception: ', JSON.stringify(e, null, 2));
  }
}

doAPICall();
```

See all clients [here](./src/) for more information on all the functions or the [examples](./examples/) for lots of usage examples. You can also check the endpoint function list [here](./docs/endpointFunctionList.md) to find all available functions!

## WebSockets

All available WebSockets can be used via a shared `WebsocketClient`. The WebSocket client will automatically open/track/manage connections as needed. Each unique connection (one per server URL) is tracked using a WsKey (each WsKey is a string - see [WS_KEY_MAP](src/lib/websocket/websocket-util.ts) for a list of supported values - `WS_KEY_MAP` can also be used like an enum).

Any subscribe/unsubscribe events will need to include a WsKey, so the WebSocket client understands which connection the event should be routed to. See examples below or in the [examples](./examples/) folder on GitHub.

Data events are emitted from the WebsocketClient via the `update` event, see example below:

#### Public Websocket

```javascript
const { WebsocketClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { WebsocketClient } from 'coinbase-api';
 */

// public ws client, doesnt need any api keys to run
const client = new WebsocketClient();

// The WS Key (last parameter) dictates which WS feed this request goes to (aka if auth is required).
// As long as the WS feed doesn't require auth, you should be able to subscribe to channels without api credentials.
client.subscribe(
  {
    topic: 'status',
    payload: {
      product_ids: ['XRP-USD'],
    },
  },
  'advTradeMarketData',
);
```

#### Private Websocket

```javascript
const { WebsocketClient } = require('coinbase-api');
/**
 * Or, with import:
 * import { WebsocketClient } from 'coinbase-api';
 */

// key name & private key, as returned by coinbase when creating your API keys.
// Note: the below example is a dummy key and won't actually work
const advancedTradeCdpAPIKey = {
  name: 'organizations/13232211d-d7e2-d7e2-d7e2-d7e2d7e2d7e2/apiKeys/d7e2d7e2-d7e2-d7e2-d7e2-d7e2d7e2d7e2',
  privateKey:
    '-----BEGIN EC PRIVATE KEY-----\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+oAoGCCqGSM49\nAwEHoUQDQgAEhtAep/ADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj+bzduY3iYXEmj/KtCk\nADFGHmkgnjdfg16k165kuu1kdtyudtyjdtyjytj\n-----END EC PRIVATE KEY-----\n',
};

/*
 * You can add ECDSA keys like the example above, or ED25519 keys like the example below.
 * Client will recognize both types of keys automatically.
 * ED25519:
 * {
 *   name: 'your-api-key-id',
 *   privateKey: 'yourExampleApiSecretEd25519Version==',
 * }
 */

const client = new WebsocketClient({
  // Either pass the full JSON object that can be downloaded when creating your API keys
  // cdpApiKey: advancedTradeCdpAPIKey,

  // Or use the key name as "apiKey" and private key (WITH the "begin/end EC PRIVATE KEY" comment) as "apiSecret"
  apiKey: advancedTradeCdpAPIKey.name,
  apiSecret: advancedTradeCdpAPIKey.privateKey,
});
```

#### Listening and subscribing to Websocket events

```javascript
// add event listeners for websocket clients

client.on('open', (data) => {
  console.log('open: ', data?.wsKey);
});

// Data received
client.on('update', (data) => {
  console.info(new Date(), 'data received: ', JSON.stringify(data));
});

// Something happened, attempting to reconenct
client.on('reconnect', (data) => {
  console.log('reconnect: ', data);
});

// Reconnect successful
client.on('reconnected', (data) => {
  console.log('reconnected: ', data);
});

// Connection closed. If unexpected, expect reconnect -> reconnected.
client.on('close', (data) => {
  console.error('close: ', data);
});

// Reply to a request, e.g. "subscribe"/"unsubscribe"/"authenticate"
client.on('response', (data) => {
  console.info('response: ', JSON.stringify(data, null, 2));
  // throw new Error('res?');
});

client.on('exception', (data) => {
  console.error('exception: ', data);
});

/**
 * Use the client subscribe(topic, market) pattern to subscribe to any websocket topic.
 *
 * You can subscribe to topics one at a time or many in one request.
 *
 * Topics can be sent as simple strings, if no parameters are required:
 */

// market data
client.subscribe('heartbeats', 'advTradeMarketData');
// This is the same as above, but using WS_KEY_MAP like an enum to reduce any uncertainty on what value to use:
// client.subscribe('heartbeats', WS_KEY_MAP.advTradeMarketData);

// user data
client.subscribe('futures_balance_summary', 'advTradeUserData');
client.subscribe('user', 'advTradeUserData');

/**
 * Or send a more structured object with parameters, e.g. if parameters are required
 */
const tickerSubscribeRequest = {
  topic: 'ticker',
  /**
   * Anything in the payload will be merged into the subscribe "request",
   * allowing you to send misc parameters supported by the exchange (such as `product_ids: string[]`)
   */
  payload: {
    product_ids: ['ETH-USD', 'BTC-USD'],
  },
};
client.subscribe(tickerSubscribeRequest, 'advTradeMarketData');

/**
 * Other adv trade public websocket topics:
 */
client.subscribe(
  [
    {
      topic: 'candles',
      payload: {
        product_ids: ['ETH-USD'],
      },
    },
    {
      topic: 'market_trades',
      payload: {
        product_ids: ['ETH-USD', 'BTC-USD'],
      },
    },
    {
      topic: 'ticker',
      payload: {
        product_ids: ['ETH-USD', 'BTC-USD'],
      },
    },
    {
      topic: 'ticker_batch',
      payload: {
        product_ids: ['ETH-USD', 'BTC-USD'],
      },
    },
    {
      topic: 'level2',
      payload: {
        product_ids: ['ETH-USD', 'BTC-USD'],
      },
    },
  ],
  'advTradeMarketData',
);
```

See [WebsocketClient](./src/WebsocketClient.ts) for further information and make sure to check the [examples](./examples/) folder for much more usage examples, especially [publicWs.ts](./examples/AdvancedTrade/WebSockets/publicWs.ts) and [privateWs.ts](./examples/AdvancedTrade/WebSockets/privateWs.ts), which explains a lot of small details.

---

## Customise Logging

Pass a custom logger which supports the log methods `trace`, `info` and `error`, or override methods from the default logger as desired.

```javascript
const { WebsocketClient, DefaultLogger } = require('coinbase-api');
/**
 * Or, with import:
 * import { WebsocketClient, DefaultLogger } from 'coinbase-api';
 */

// E.g. customise logging for only the trace level:
const logger = {
  // Inherit existing logger methods, using an object spread
  ...DefaultLogger,
  // Define a custom trace function to override only that function
  trace: (...params) => {
    if (
      [
        'Sending ping',
        'Sending upstream ws message: ',
        'Received pong, clearing pong timer',
        'Received ping, sending pong frame',
      ].includes(params[0])
    ) {
      return;
    }
    console.log('trace', params);
  },
};

const ws = new WebsocketClient(
  {
    apiKey: 'apiKeyHere',
    apiSecret: 'apiSecretHere',
    apiPassphrase: 'apiPassPhraseHere',
  },
  logger,
);
```

## Browser/Frontend Usage

### Webpack

Build a bundle using webpack:

- `npm install`
- `npm run build`
- `npm run pack`

The bundle can be found in `dist/`. Altough usage should be largely consistent, smaller differences will exist. Documentation is still TODO.

## Use with LLMs & AI

This SDK includes a bundled `llms.txt` file in the root of the repository. If you're developing with LLMs, use the included `llms.txt` with your LLM - it will significantly improve the LLMs understanding of how to correctly use this SDK.

This file contains AI optimised structure of all the functions in this package, and their parameters for easier use with any learning models or artificial intelligence.

---

## Used By

[![Repository Users Preview Image](https://dependents.info/tiagosiebler/coinbase-api/image)](https://github.com/tiagosiebler/coinbase-api/network/dependents)

---

<!-- template_contributions -->

### Contributions & Thanks

Have my projects helped you? Share the love, there are many ways you can show your thanks:

- Star & share my projects.
- Are my projects useful? Sponsor me on Github and support my effort to maintain & improve them: https://github.com/sponsors/tiagosiebler
- Have an interesting project? Get in touch & invite me to it.
- Or buy me all the coffee:
  - ETH(ERC20): `0xA3Bda8BecaB4DCdA539Dc16F9C54a592553Be06C` <!-- metamask -->
- Sign up with my referral links:
  - OKX (receive a 20% fee discount!): https://www.okx.com/join/42013004
  - Binance (receive a 20% fee discount!): https://accounts.binance.com/register?ref=OKFFGIJJ
  - HyperLiquid (receive a 4% fee discount!): https://app.hyperliquid.xyz/join/SDK
  - Gate: https://www.gate.io/signup/NODESDKS?ref_type=103

<!---
old ones:
  - BTC: `1C6GWZL1XW3jrjpPTS863XtZiXL1aTK7Jk`
  - BTC(SegWit): `bc1ql64wr9z3khp2gy7dqlmqw7cp6h0lcusz0zjtls`
  - ETH(ERC20): `0xe0bbbc805e0e83341fadc210d6202f4022e50992`
  - USDT(TRC20): `TA18VUywcNEM9ahh3TTWF3sFpt9rkLnnQa
  - gate: https://www.gate.io/signup/AVNNU1WK?ref_type=103

-->
<!-- template_contributions_end -->

### Contributions & Pull Requests

Contributions are encouraged, I will review any incoming pull requests. See the issues tab for todo items.

<!-- template_star_history -->

## Star History

[![Star History Chart](https://api.star-history.com/svg?repos=tiagosiebler/bybit-api,tiagosiebler/okx-api,tiagosiebler/binance,tiagosiebler/bitget-api,tiagosiebler/bitmart-api,tiagosiebler/gateio-api,tiagosiebler/kucoin-api,tiagosiebler/coinbase-api,tiagosiebler/orderbooks,tiagosiebler/accountstate,tiagosiebler/awesome-crypto-examples&type=Date)](https://star-history.com/#tiagosiebler/bybit-api&tiagosiebler/okx-api&tiagosiebler/binance&tiagosiebler/bitget-api&tiagosiebler/bitmart-api&tiagosiebler/gateio-api&tiagosiebler/kucoin-api&tiagosiebler/coinbase-api&tiagosiebler/orderbooks&tiagosiebler/accountstate&tiagosiebler/awesome-crypto-examples&Date)

<!-- template_star_history_end -->

================
File: src/lib/BaseRestClient.ts
================
import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios';
// NOTE: https.Agent is Node.js-only and not available in browser environments
// Browser builds (via webpack) exclude this module - see webpack.config.js fallback settings
import https from 'https';
import { nanoid } from 'nanoid';
⋮----
import {
  CloseAdvTradePositionRequest,
  SubmitAdvTradeOrderRequest,
} from '../types/request/advanced-trade-client.js';
import { SubmitCBExchOrderRequest } from '../types/request/coinbase-exchange.js';
import { SubmitINTXOrderRequest } from '../types/request/coinbase-international.js';
import { SubmitPrimeOrderRequest } from '../types/request/coinbase-prime.js';
import { CustomOrderIdProperty } from '../types/shared.types.js';
import { signJWT } from './jwtNode.js';
import { neverGuard } from './misc-util.js';
import {
  APIIDPrefix,
  getRestBaseUrl,
  logInvalidOrderId,
  REST_CLIENT_TYPE_ENUM,
  RestClientOptions,
  RestClientType,
  serializeParams,
} from './requestUtils.js';
import { signMessage } from './webCryptoAPI.js';
⋮----
interface SignedRequest<T extends object | undefined = {}> {
  originalParams: T;
  paramsWithSign?: T & { sign: string };
  serializedParams: string;
  sign: string;
  queryParamsWithSign: string;
  timestamp: number;
  recvWindow: number;
  headers: object;
}
⋮----
interface UnsignedRequest<T extends object | undefined = {}> {
  originalParams: T;
  paramsWithSign: T;
}
⋮----
type SignMethod = 'coinbase';
⋮----
/**
 * Some requests require some params to be in the query string, some in the body, some even in the headers.
 * This type anticipates either are possible in any combination.
 *
 * The request builder will automatically handle where parameters should go.
 */
type ParamsInRequest = {
  query?: object;
  body?: object;
  headers?: object;
};
⋮----
// request: {
//   url: response.config.url,
//   method: response.config.method,
//   data: response.config.data,
//   headers: response.config.headers,
// },
⋮----
/**
 * Impure, mutates params to remove any values that have a key but are undefined.
 */
function deleteUndefinedValues(params?: any): void
⋮----
export abstract class BaseRestClient
⋮----
/** Defines the client type (affecting how requests & signatures behave) */
abstract getClientType(): RestClientType;
⋮----
/**
   * Create an instance of the REST client. Pass API credentials in the object in the first parameter.
   * @param {RestClientOptions} [restClientOptions={}] options to configure REST API connectivity
   * @param {AxiosRequestConfig} [networkOptions={}] HTTP networking options for axios
   */
constructor(
    restClientOptions: RestClientOptions = {},
    networkOptions: AxiosRequestConfig = {},
)
⋮----
/** Throw errors if any request params are empty */
⋮----
/** in ms == 5 minutes by default */
⋮----
/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */
⋮----
// If enabled, configure a https agent with keepAlive enabled
// NOTE: This is Node.js-only functionality. In browser environments, this code is skipped
// as the 'https' module is excluded via webpack fallback configuration.
// Browser connection pooling is handled automatically by the browser itself.
⋮----
// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely
⋮----
// For more advanced configuration, raise an issue on GitHub or use the "networkOptions"
// parameter to define a custom httpsAgent with the desired properties
⋮----
// Newline escapes needed, if passed as env vars
⋮----
// Throw if one of these values is missing, and at least one of them is set
⋮----
// commerce only needs keys, not key and secret
⋮----
/**
   * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism
   */
getSignTimestampMs(): number
⋮----
get(endpoint: string, params?: object)
⋮----
post(endpoint: string, params?: ParamsInRequest)
⋮----
getPrivate(endpoint: string, params?: object)
⋮----
postPrivate(endpoint: string, params?: ParamsInRequest)
⋮----
deletePrivate(endpoint: string, params?: ParamsInRequest)
⋮----
putPrivate(endpoint: string, params?: ParamsInRequest)
⋮----
patchPrivate(endpoint: string, params?: ParamsInRequest)
⋮----
/**
   * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed.
   */
private async _call(
    method: Method,
    endpoint: string,
    params?: ParamsInRequest,
    isPublicApi?: boolean,
): Promise<any>
⋮----
// Sanity check to make sure it's only ever prefixed by one forward slash
⋮----
// Build a request and handle signature process
⋮----
// Dispatch request
⋮----
// Throw if API returns an error (e.g. insufficient balance)
⋮----
public generateNewOrderId(): string
⋮----
/**
   * Validate syntax meets requirements set by coinbase. Log warning if not.
   */
protected validateOrderId(
    params:
      | SubmitAdvTradeOrderRequest
      | CloseAdvTradePositionRequest
      | SubmitCBExchOrderRequest
      | SubmitINTXOrderRequest
      | SubmitPrimeOrderRequest,
    orderIdProperty: CustomOrderIdProperty,
): void
⋮----
// Not the cleanest but strict checks aren't quite necessary here either
⋮----
/**
   * @private generic handler to parse request exceptions
   */
parseException(e: any, requestParams: any): unknown
⋮----
// Something happened in setting up the request that triggered an error
⋮----
// request made but no response received
⋮----
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
⋮----
// console.error('err: ', response?.data);
⋮----
// Prevent credentials from leaking into error messages
⋮----
/**
   * @private sign request and set recv window
   */
private async signRequest<T extends ParamsInRequest | undefined = {}>(
    data: T,
    url: string,
    endpoint: string,
    method: Method,
    signMethod: SignMethod,
): Promise<SignedRequest<T>>
⋮----
// if there is body, use body - otherwise empty string
⋮----
// https://docs.cdp.coinbase.com/product-apis/docs/welcome
⋮----
// Both adv trade & app API use the same JWT auth mechanism
// Advanced Trade: https://docs.cdp.coinbase.com/advanced-trade/docs/rest-api-auth
// App: https://docs.cdp.coinbase.com/coinbase-app/docs/api-key-authentication
⋮----
// TODO: is there demand for oauth support?
// Docs: https://docs.cdp.coinbase.com/coinbase-app/docs/coinbase-app-integration
// See: https://github.com/tiagosiebler/coinbase-api/issues/24
⋮----
// Docs: https://docs.cdp.coinbase.com/exchange/docs/rest-auth
⋮----
const timestampInSeconds = timestampInMs / 1000; // decimals are OK
⋮----
// console.log('sign res: ', { signInput, ...headers });
⋮----
// For CB Exchange, is there demand for FIX
// Docs, FIX: https://docs.cdp.coinbase.com/exchange/docs/fix-connectivity
⋮----
// Docs: https://docs.cdp.coinbase.com/intx/docs/rest-auth
⋮----
const timestampInSeconds = timestampInMs / 1000; // decimals are OK
⋮----
// For CB International, no query params are used in the signature
⋮----
// console.log('sign res: ', { signInput, ...headers });
⋮----
// For CB International, is there demand for FIX
// Docs, FIX: https://docs.cdp.coinbase.com/intx/docs/fix-overview
⋮----
// Docs: https://docs.cdp.coinbase.com/prime/docs/rest-authentication
⋮----
const timestampInSeconds = Math.floor(timestampInMs / 1000); // decimal not allowed
⋮----
// For CB Prime, is there demand for FIX
// Docs, FIX: https://docs.cdp.coinbase.com/prime/docs/fix-connectivity
⋮----
// https://docs.cdp.coinbase.com/commerce-onchain/docs/getting-started
// No auth?
⋮----
private async prepareSignParams<TParams extends object | undefined>(
    method: Method,
    url: string,
    endpoint: string,
    signMethod: SignMethod,
    params?: TParams,
    isPublicApi?: true,
  ): Promise<UnsignedRequest<TParams>>;
⋮----
private async prepareSignParams<TParams extends object | undefined>(
    method: Method,
    url: string,
    endpoint: string,
    signMethod: SignMethod,
    params?: TParams,
    isPublicApi?: false | undefined,
  ): Promise<SignedRequest<TParams>>;
⋮----
private async prepareSignParams<TParams extends object | undefined>(
    method: Method,
    url: string,
    endpoint: string,
    signMethod: SignMethod,
    params?: TParams,
    isPublicApi?: boolean,
)
⋮----
/** Returns an axios request object. Handles signing process automatically if this is a private API call */
private async buildRequest(
    method: Method,
    endpoint: string,
    url: string,
    params?: any | undefined,
    isPublicApi?: boolean,
): Promise<AxiosRequestConfig>
⋮----
// request parameter headers for this request
⋮----
// auth headers for this request
⋮----
// global headers for every request

================
File: package.json
================
{
  "name": "coinbase-api",
  "version": "1.1.11",
  "description": "Node.js SDK for Coinbase's Advanced Trade, App, Exchange, International, Prime & Commerce REST APIs and WebSockets, with TypeScript & strong end to end tests.",
  "scripts": {
    "clean": "rm -rf dist",
    "build": "npm run clean && tsc -p tsconfig.esm.json && tsc -p tsconfig.cjs.json && bash ./postBuild.sh",
    "pack": "webpack --config webpack/webpack.config.cjs",
    "test": "NODE_OPTIONS='--experimental-vm-modules --no-warnings' jest --passWithNoTests --config=jest.config.ts",
    "test:watch:raw": "jest --watch --passWithNoTests",
    "test:watch": "npm run test -- --watch",
    "test:watch:v": "node --no-warnings --experimental-vm-modules $( [ -f ./node_modules/.bin/jest ] && echo ./node_modules/.bin/jest || which jest ) --watch --passWithNoTests",
    "betapublish": "npm publish --tag beta",
    "lint": "eslint src"
  },
  "main": "dist/cjs/index.js",
  "module": "dist/mjs/index.js",
  "types": "dist/mjs/index.d.ts",
  "exports": {
    ".": {
      "import": "./dist/mjs/index.js",
      "require": "./dist/cjs/index.js",
      "types": "./dist/mjs/index.d.ts"
    }
  },
  "type": "module",
  "files": [
    "dist/*",
    "llms.txt"
  ],
  "author": "Tiago Siebler (https://siebly.io)",
  "contributors": [
    "Jerko J (https://github.com/JJ-Cro)"
  ],
  "dependencies": {
    "axios": "^1.13.2",
    "isomorphic-ws": "^4.0.1",
    "jose": "^6.1.3",
    "nanoid": "^3.3.11",
    "ws": "^7.4.0"
  },
  "devDependencies": {
    "@types/jest": "^29.5.12",
    "@types/node": "^22.10.2",
    "@types/ws": "^8.5.10",
    "@typescript-eslint/eslint-plugin": "^8.18.0",
    "@typescript-eslint/parser": "^8.18.0",
    "eslint": "^8.29.0",
    "eslint-config-prettier": "^9.1.0",
    "eslint-plugin-prettier": "^5.1.3",
    "eslint-plugin-require-extensions": "^0.1.3",
    "eslint-plugin-simple-import-sort": "^12.1.1",
    "jest": "^29.7.0",
    "prettier": "^3.3.3",
    "ts-jest": "^29.2.4",
    "ts-node": "^10.9.2",
    "typescript": "^5.7.3"
  },
  "optionalDependencies": {
    "webpack": "^5.0.0",
    "webpack-bundle-analyzer": "^5.1.1",
    "webpack-cli": "^4.0.0"
  },
  "keywords": [
    "coinbase",
    "coinbase api",
    "coinbase node",
    "coinbase node api",
    "api",
    "sdk",
    "coinbase sdk",
    "websocket",
    "rest",
    "rest api",
    "trading bots",
    "nodejs",
    "trading",
    "cryptocurrency",
    "bitcoin",
    "best"
  ],
  "funding": {
    "type": "individual",
    "url": "https://github.com/sponsors/tiagosiebler"
  },
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/tiagosiebler/coinbase-api.git"
  },
  "bugs": {
    "url": "https://github.com/tiagosiebler/coinbase-api/issues"
  },
  "homepage": "https://github.com/tiagosiebler/coinbase-api#readme"
}





================================================================
End of Codebase
================================================================
