Skip to content

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Repository files navigation

Bitget Wallet TypeScript Library

fern shield npm shield

The Bitget Wallet TypeScript library provides convenient access to the Bitget Wallet APIs from TypeScript and JavaScript.

Table of Contents

Installation

npm install @bitget-wallet/api

Requires Node.js >=18 (relies on the built-in global fetch and node:crypto).

Usage

Instantiate the client, then call any of the resource methods. Every method returns a Promise that resolves to the response body:

import { BitgetWalletApiClient } from "@bitget-wallet/api";
import { createSigningFetch } from "@bitget-wallet/api/auth";

const client = new BitgetWalletApiClient({
    // Auto-sign every request (see Authentication below).
    fetch: createSigningFetch({
        apiKey: process.env.BGW_API_KEY!,
        apiSecret: process.env.BGW_API_SECRET!,
    }),
});

const quote = await client.instructionMode.instructionQuote({
    fromChain: "bnb",
    fromContract: "0x...",
    fromAmount: "1000000000000000000",
    toChain: "bnb",
    toContract: "0x...",
});

console.log(quote);

The client exposes the following resources:

Resource Description
client.instructionMode Instruction-mode trading (/swapx/pro): quote, swap, send.
client.orderMode Order-mode trading (/swapx/order): price, make/submit/query order.
client.chain On-chain queries and broadcasting: balances, gas price, send.
client.market Market data: K-line, transaction info.
client.token Token base info, rankings, liquidity pools, security audits.
client.rwa RWA (Real World Asset) market data.

A few representative calls:

// Query native + token balances for an address.
await client.chain.chainBalancesV3({ chain: "eth", address: "0x..." });

// Fetch a K-line series.
await client.market.getKline({ chain: "eth", contract: "0x...", period: "1m", size: 100 });

// Batch token info (up to 100 items).
await client.token.batchGetBaseInfo({
    list: [{ chain: "eth", contract: "0x..." }],
});

// RWA stock list (empty request body).
await client.rwa.stockList({});

Authentication

Bitget Wallet OpenAPI requires a per-request HMAC-SHA256 signature. Each request must carry three headers:

  • x-api-key — your API key
  • x-api-timestamp — the request timestamp in milliseconds
  • x-api-signature — base64 HMAC-SHA256 of the canonical payload, keyed by your API secret

The recommended approach is to let the SDK compute and inject these headers for you. createSigningFetch (exported from @bitget-wallet/api/auth) wraps fetch, so the signature is computed over the exact bytes that go on the wire — after the request body and URL have been finalized. Your API secret is used only as the HMAC key and is never sent over the network:

import { BitgetWalletApiClient } from "@bitget-wallet/api";
import { createSigningFetch } from "@bitget-wallet/api/auth";

const client = new BitgetWalletApiClient({
    fetch: createSigningFetch({
        apiKey: process.env.BGW_API_KEY!,
        apiSecret: process.env.BGW_API_SECRET!,
    }),
});

Note: createSigningFetch uses Node's built-in node:crypto and is intended for server-side (Node.js) usage. Do not ship your API secret to a browser. For a browser build, compute the signature with the Web Crypto API (crypto.subtle) and pass the resulting headers via apiTimestamp / apiSignature (below).

Providing the signature yourself

If you compute the signature externally (e.g. in a browser via Web Crypto, or in a signing proxy), pass the pre-computed header values directly. These can be supplied as static values, per-request overrides, or Supplier functions:

const client = new BitgetWalletApiClient({
    apiTimestamp: () => String(Date.now()),
    apiSignature: () => mySignatureFor(/* ... */),
    headers: { "x-api-key": process.env.BGW_API_KEY! },
});

Environments

The default base URL is https://bopenapi.bgwapi.io. Use the BitgetWalletApiEnvironment enum, or configure an arbitrary baseUrl — useful for pointing at a test environment:

import { BitgetWalletApiClient, BitgetWalletApiEnvironment } from "@bitget-wallet/api";

const client = new BitgetWalletApiClient({
    environment: BitgetWalletApiEnvironment.Default,
    // or:
    baseUrl: "https://your-test-host.example.com",
});

Errors

API calls that return a non-success status code throw a typed error. Every error extends BitgetWalletApiError, which exposes statusCode, body, and the x-request-id (via requestId). Catch and inspect it like so:

import {
    BitgetWalletApiError,
    BitgetWalletApiTimeoutError,
} from "@bitget-wallet/api";
import { BitgetWalletApi } from "@bitget-wallet/api";

try {
    await client.instructionMode.instructionQuote({ /* ... */ });
} catch (err) {
    if (err instanceof BitgetWalletApi.BadRequestError) {
        // 400 — inspect err.body for details
        console.error(err.statusCode, err.body, err.requestId);
    } else if (err instanceof BitgetWalletApiTimeoutError) {
        console.error("Request timed out");
    } else if (err instanceof BitgetWalletApiError) {
        console.error(err.statusCode, err.message);
    } else {
        throw err;
    }
}

The typed status errors are BitgetWalletApi.BadRequestError (400), BitgetWalletApi.ForbiddenError (403), and BitgetWalletApi.TooManyRequestsError (429).

Request Options

Options can be set on the client (applied to every request) or per call (the second argument to any method). Per-request options are merged over the client defaults:

const client = new BitgetWalletApiClient({
    fetch: createSigningFetch({ apiKey, apiSecret }),
    timeoutInSeconds: 30,
    maxRetries: 2,
});

// Override for a single request.
await client.market.getKline(
    { chain: "eth", contract: "0x...", period: "1m", size: 100 },
    {
        timeoutInSeconds: 5,
        maxRetries: 0,
        headers: { "x-trace-id": "abc-123" },
    },
);

Available per-request options include timeoutInSeconds, maxRetries, abortSignal, headers, queryParams, and (when signing manually) apiTimestamp / apiSignature.

Advanced

Raw Responses

Awaiting a method call resolves to the response body directly. To inspect the raw HTTP response (status code and headers), call .withRawResponse() on the returned promise:

const { data, rawResponse } = await client.market
    .getKline({ chain: "eth", contract: "0x...", period: "1m", size: 100 })
    .withRawResponse();

console.log(data);                          // parsed body
console.log(rawResponse.status);            // e.g. 200
console.log(rawResponse.headers.get("x-request-id"));

Retries

The SDK automatically retries failed requests with exponential backoff. A request is retried as long as it is deemed retryable and the number of attempts has not exceeded the configured limit (default: 2). Retried status codes are 408 (Timeout), 429 (Too Many Requests), and 5XX (server errors). If a Retry-After header is present, its value is respected over the default backoff.

Configure the limit on the client or per request:

const client = new BitgetWalletApiClient({ maxRetries: 3 });

await client.instructionMode.instructionQuote({ /* ... */ }, { maxRetries: 0 });

Timeouts

The default request timeout is 60 seconds. Override it on the client or per request via timeoutInSeconds:

const client = new BitgetWalletApiClient({ timeoutInSeconds: 20 });

await client.chain.chainGetGasPriceV1({ chain: "eth" }, { timeoutInSeconds: 5 });

Aborting Requests

Pass an AbortSignal to cancel an in-flight request:

const controller = new AbortController();
const promise = client.market.getKline(
    { chain: "eth", contract: "0x...", period: "1m", size: 100 },
    { abortSignal: controller.signal },
);

controller.abort();

Custom Fetch

Provide your own fetch implementation — useful on platforms without a global fetch, or to add instrumentation. Note that createSigningFetch is itself a custom fetch; if you need both signing and instrumentation, pass your fetch as its baseFetch:

import { createSigningFetch } from "@bitget-wallet/api/auth";

const client = new BitgetWalletApiClient({
    fetch: createSigningFetch(
        { apiKey, apiSecret },
        { baseFetch: myInstrumentedFetch },
    ),
});

Logging

Configure logging on the client to observe request/response activity:

const client = new BitgetWalletApiClient({
    fetch: createSigningFetch({ apiKey, apiSecret }),
    logging: { level: "debug" },
});

Passthrough Requests

For endpoints not yet modeled by the SDK, use client.fetch(...). It reuses the client's configured auth, retries, timeout, and logging, and returns a standard Response. Relative paths are resolved against the configured base URL:

const response = await client.fetch("/bgw-pro/some/new/endpoint", {
    method: "POST",
    body: JSON.stringify({ foo: "bar" }),
});
const json = await response.json();

About

No description, website, or topics provided.

Resources

Stars

2 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages