From 78c266621360a74a3947cef5266d9b8d361880fb Mon Sep 17 00:00:00 2001 From: "JJ-Cro (Codex)" Date: Mon, 16 Nov 2026 12:30:25 +0100 Subject: [PATCH 1/2] fix(v1.6.9): clarify REST recvWindow handling - Clarify that recvWindow is ignored by REST clients and remove unused REST defaults and signing fields (fixes #154) - Bump SDK version to 1.6.9 and Node.js pin to v24.22.3 --- .nvmrc | 2 +- package-lock.json | 4 ++-- package.json | 2 +- src/lib/BaseRestClient.ts | 7 +------ src/lib/requestUtils.ts | 6 ++++-- 5 files changed, 9 insertions(+), 12 deletions(-) diff --git a/.nvmrc b/.nvmrc index 5bcf9c6..22fbfc0 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v24.18.0 +v24.22.3 diff --git a/package-lock.json b/package-lock.json index 0a9a820..c806c1c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "gateio-api", - "version": "1.6.8", + "version": "1.6.9", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "gateio-api", - "version": "1.6.8", + "version": "1.6.9", "license": "MIT", "dependencies": { "@types/ws": "8.18.1", diff --git a/package.json b/package.json index 995111f..ee9eb18 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "gateio-api", - "version": "1.6.8", + "version": "1.6.9", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*", diff --git a/src/lib/BaseRestClient.ts b/src/lib/BaseRestClient.ts index 85ba9aa..b5e5459 100644 --- a/src/lib/BaseRestClient.ts +++ b/src/lib/BaseRestClient.ts @@ -38,7 +38,6 @@ interface SignedRequest { sign: string; queryParamsWithSign: string; timestamp: number; - recvWindow: number; } interface UnsignedRequest { @@ -151,7 +150,6 @@ export abstract class BaseRestClient { networkOptions: AxiosRequestConfig = {}, ) { this.options = { - recvWindow: 5000, /** Throw errors if any request params are empty */ strictParamValidation: false, ...restClientOptions, @@ -363,7 +361,7 @@ export abstract class BaseRestClient { } /** - * @private sign request and set recv window + * @private sign request and set timestamp */ private async signRequest< T extends ParamsInQueryBodyOrHeader | undefined = {}, @@ -377,13 +375,11 @@ export abstract class BaseRestClient { const res: SignedRequest = { originalParams: { - // recvWindow: this.options.recvWindow, ...data, }, sign: '', timestamp, - recvWindow: 0, serializedParams: '', queryParamsWithSign: '', }; @@ -392,7 +388,6 @@ export abstract class BaseRestClient { return res; } - // It's possible to override the recv window on a per rquest level const strictParamValidation = this.options.strictParamValidation; const encodeQueryStringValues = false; diff --git a/src/lib/requestUtils.ts b/src/lib/requestUtils.ts index 1144efb..477276c 100644 --- a/src/lib/requestUtils.ts +++ b/src/lib/requestUtils.ts @@ -13,8 +13,10 @@ export interface RestClientOptions { useTestnet?: boolean; /** - * Override the default/global max size of the request window (in ms) for signed api calls. - * If you don't include a recv window when making an API call, this value will be used as default + * Ignored by REST clients. Gate REST has no recvWindow; it uses a Timestamp header + * with a fixed 60-second tolerance, so keep the system clock in sync. + * To offset WebSocket signature timestamps, set `recvWindow` in the WebsocketClient options. + * @deprecated Ignored by REST clients; retained for backwards compatibility. */ recvWindow?: number; From 533f580879d3d33ecd2affcc203b6f0945afa1f3 Mon Sep 17 00:00:00 2001 From: JJ-Cro sync bot Date: Mon, 16 Nov 2026 13:07:58 +0100 Subject: [PATCH 2/2] chore: regenerate endpoint docs and examples --- llms.txt | 1887 +++++++++++++++++++++++++++--------------------------- 1 file changed, 943 insertions(+), 944 deletions(-) diff --git a/llms.txt b/llms.txt index fc9b04d..16e7ea4 100644 --- a/llms.txt +++ b/llms.txt @@ -5696,11 +5696,6 @@ File: .npmrc min-release-age=30 save-exact=true -================ -File: .nvmrc -================ -v24.18.0 - ================ File: examples/Rest/otc/submitOTCBankPersonalSupplement.ts ================ @@ -6321,1112 +6316,1116 @@ export interface WebsocketClientOptions extends WSClientConfigurableOptions { } ================ -File: src/lib/BaseRestClient.ts +File: .nvmrc ================ -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 { neverGuard } from './misc-util.js'; -import { - CHANNEL_ID, - getRestBaseUrl, - RestClientOptions, - serializeParams, -} from './requestUtils.js'; -import { - checkWebCryptoAPISupported, - hashMessage, - SignAlgorithm, - SignEncodeMethod, - signMessage, -} from './webCryptoAPI.js'; -⋮---- -/** - * Used to switch how authentication/requests work under the hood +v24.22.3 + +================ +File: src/types/request/autoinvest.ts +================ +/**========================================================================================================================== + * EARN AUTO INVEST + * ========================================================================================================================== */ ⋮---- -export type RestClientType = - (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; -⋮---- -interface SignedRequest { - originalParams: T; - paramsWithSign?: T & { sign: string }; - serializedParams: string; - sign: string; - queryParamsWithSign: string; - timestamp: number; - recvWindow: number; +export interface AutoInvestPlanPortfolioItemInput { + asset: string; + ratio: string; } ⋮---- -interface UnsignedRequest { - originalParams: T; - paramsWithSign: T; +/** POST /earn/autoinvest/plans/create */ +export interface CreateAutoInvestPlanReq { + plan_name?: string; + plan_des?: string; + plan_money: string; + plan_amount: string; + plan_period_type: + | 'daily' + | 'weekly' + | 'biweekly' + | 'monthly' + | 'hourly' + | '4-hourly'; + plan_period_day: number; + plan_period_hour: number; + items: AutoInvestPlanPortfolioItemInput[]; + /** Fund source: `spot` or `earn`; default spot */ + fund_source?: string; + /** Fund flow: `auto_invest` or `earn`; default auto_invest */ + fund_flow?: string; + /** 0 normal creation, 1 quick investment */ + type?: number; } ⋮---- -type SignMethod = 'gateV4'; +/** Fund source: `spot` or `earn`; default spot */ ⋮---- -/** - * Some requests require some params to be in the query string and some in the body. Some even support passing params via headers. - * This type anticipates these are possible in any combination. - * - * The request builder will automatically handle where parameters should go. - */ -type ParamsInQueryBodyOrHeader = { - query?: object; - body?: object; - headers?: object; - /** multipart/form-data body; mutually exclusive with `body` */ - multipart?: FormData; -}; +/** Fund flow: `auto_invest` or `earn`; default auto_invest */ ⋮---- -/** multipart/form-data body; mutually exclusive with `body` */ +/** 0 normal creation, 1 quick investment */ ⋮---- -/** - * Enables: - * - Detailed request/response logging - * - Full request dump in any exceptions thrown from API responses - */ +/** POST /earn/autoinvest/plans/update */ +export interface UpdateAutoInvestPlanReq { + plan_id: number; + fund_source?: string; + fund_flow?: string; +} ⋮---- -// request: { -// url: response.config.url, -// method: response.config.method, -// data: response.config.data, -// headers: response.config.headers, -// }, +/** POST /earn/autoinvest/plans/stop */ +export interface StopAutoInvestPlanReq { + plan_id: number; +} ⋮---- -/** - * Impure, mutates params to remove any values that have a key but are undefined. - */ -function deleteUndefinedValues(params?: any): void +/** POST /earn/autoinvest/plans/add_position */ +export interface AddAutoInvestPlanPositionReq { + plan_id: number; + amount: string; +} ⋮---- -export abstract class BaseRestClient +/** POST /earn/autoinvest/min_invest_amount */ +export interface GetAutoInvestMinAmountReq { + money: string; + /** Asset type, required: 1 cryptocurrency, 2 TradFi stocks */ + asset_type: 1 | 2; + items: AutoInvestPlanPortfolioItemInput[]; +} ⋮---- -/** Defines the client type (affecting how requests & signatures behave) */ -abstract getClientType(): RestClientType; +/** Asset type, required: 1 cryptocurrency, 2 TradFi stocks */ ⋮---- -/** - * 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 = {}, - ) +/** GET /earn/autoinvest/coins */ +export interface GetAutoInvestCoinsReq { + /** Pricing currency: USDT or BTC; default USDT */ + plan_money?: string; +} ⋮---- -/** Throw errors if any request params are empty */ +/** Pricing currency: USDT or BTC; default USDT */ ⋮---- -/** in ms == 5 minutes by default */ +/** GET /earn/autoinvest/plans/records */ +export interface GetAutoInvestPlanRecordsReq { + plan_id: number; + page?: number; + page_size?: number; +} ⋮---- -/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ +/** GET /earn/autoinvest/orders */ +export interface GetAutoInvestOrdersReq { + plan_id: number; + record_id: number; +} ⋮---- -// 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. +/** GET /earn/autoinvest/plans/detail */ +export interface GetAutoInvestPlanDetailReq { + plan_id: number; +} ⋮---- -// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely +/** GET /earn/autoinvest/plans/list_info */ +export interface GetAutoInvestPlansReq { + /** Plan status: e.g. History (history) or Active (active) */ + status: string; + page?: number; + page_size?: number; +} ⋮---- -// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" -// parameter to define a custom httpsAgent with the desired properties +/** Plan status: e.g. History (history) or Active (active) */ + +================ +File: src/types/request/stock.ts +================ +/** Stock / TradFi Spot API request types */ ⋮---- -// Check Web Crypto API support when credentials are provided and no custom sign function is used +export interface GetStockUserAssetsReq { + pnl_calc_type?: number; + pnl_calc_price?: number; +} ⋮---- -// Throw if one of the 3 values is missing, but at least one of them is set +export interface SetStockMarginFeatureReq { + /** Whether to enable margin financing */ + margin_feature: boolean; +} ⋮---- -/** - * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism - */ -getSignTimestampMs(): number +/** Whether to enable margin financing */ ⋮---- -protected get(endpoint: string, params?: object) +export interface GetStockBalanceRecordsReq { + /** Record types, separated by commas */ + type?: string; + /** Business identifiers, separated by commas */ + business?: string; + symbol?: string; + /** Record creation time in seconds; end_time must be greater than begin_time */ + begin_time?: number; + /** Record creation time in seconds; must be greater than begin_time */ + end_time?: number; + /** Return records with a greater primary key ID */ + start_id?: number; + /** Defaults to desc without start_id, or asc with start_id */ + sort_direction?: 'asc' | 'desc'; + /** Return raw detail; defaults to false */ + include_detail?: boolean; + /** Page number, defaults to 1 */ + page?: number; + /** Records per page, defaults to 10, maximum 100 */ + page_size?: number; +} ⋮---- -// GET only supports params in the query string +/** Record types, separated by commas */ ⋮---- -protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) +/** Business identifiers, separated by commas */ ⋮---- -protected getPrivate(endpoint: string, params?: object) +/** Record creation time in seconds; end_time must be greater than begin_time */ ⋮---- -// GET only supports params in the query string +/** Record creation time in seconds; must be greater than begin_time */ ⋮---- -protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +/** Return records with a greater primary key ID */ ⋮---- -/** POST private endpoint with multipart/form-data (empty body hash for signing) */ -protected postPrivateMultipart( - endpoint: string, - formData: FormData, - query?: object, - ) +/** Defaults to desc without start_id, or asc with start_id */ ⋮---- -protected deletePrivate( - endpoint: string, - params?: ParamsInQueryBodyOrHeader, - ) +/** Return raw detail; defaults to false */ ⋮---- -protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +/** Page number, defaults to 1 */ ⋮---- -// protected patchPrivate(endpoint: string, params?: any) { -protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +/** Records per page, defaults to 10, maximum 100 */ ⋮---- -/** - * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. - */ -private async _call( - method: Method, - endpoint: string, - params?: ParamsInQueryBodyOrHeader, - isPublicApi?: boolean, - ): Promise -⋮---- -// Sanity check to make sure it's only ever prefixed by one forward slash -⋮---- -// Build a request and handle signature process -⋮---- -// Dispatch request -⋮---- -// See: https://www.gate.io/docs/developers/apiv4/en/#return-format -⋮---- -// Throw API rejections by parsing the response code from the body +export interface GetStockSymbolsReq { + symbols?: string; + exchange?: string; // us | hk | jp + with_desc_i18n?: boolean; + page?: number; + page_size?: number; +} ⋮---- -/** - * @private generic handler to parse request exceptions - */ -parseException(e: any, request: AxiosRequestConfig): unknown +exchange?: string; // us | hk | jp ⋮---- -// Something happened in setting up the request that triggered an error +export interface GetStockSymbolDetailReq { + symbols?: string; + exchange?: string; // us | hk | jp + page?: number; + page_size?: number; +} ⋮---- -// request made but no response received +exchange?: string; // us | hk | jp ⋮---- -// The request was made and the server responded with a status code -// that falls out of the range of 2xx +export interface GetStockOrdersReq { + symbol?: string; +} ⋮---- -// console.error('err: ', response?.data); +export interface CreateStockOrderReq { + volume: string; + symbol: string; + side: 1 | 2; + price_type: 'market' | 'limit'; + /** Limit: all only; market: regular only */ + trading_session: 'all' | 'regular'; + time_in_force: 'day'; + price?: string; + client_order_id?: string; +} ⋮---- -// Prevent credentials from leaking into error messages +/** Limit: all only; market: regular only */ ⋮---- -/** - * @private sign request and set recv window - */ -private async signRequest< - T extends ParamsInQueryBodyOrHeader | undefined = {}, - >( - data: T, - endpoint: string, - method: Method, - signMethod: SignMethod, - ): Promise> +export interface GetStockOrderHistoryReq { + symbol?: string; + order_ids?: string; + begin_time?: number; + end_time?: number; + side?: 1 | 2; + page?: number; + page_size?: number; +} ⋮---- -const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds +export interface GetStockOrderDealsReq { + order_id: number; + /** Page number, defaults to 1 */ + page?: number; + /** Records per page, defaults to 10, maximum 100 */ + page_size?: number; +} ⋮---- -// recvWindow: this.options.recvWindow, +/** Page number, defaults to 1 */ ⋮---- -// It's possible to override the recv window on a per rquest level +/** Records per page, defaults to 10, maximum 100 */ ⋮---- -// console.log('sign params: ', { -// requestBodyToHash, -// paramsStr: toSign, -// url: this.baseUrl, -// urlPath: this.baseUrlPath, -// }); +export interface UpdateStockOrderReq { + volume: string; + price: string; +} ⋮---- -private async signMessage( - paramsStr: string, - secret: string, - method: 'hex' | 'base64', - algorithm: SignAlgorithm, - ): Promise +export interface GetStockPositionsReq { + pnl_calc_type?: number; + pnl_calc_price?: number; + symbol?: string; + exchange?: string; // us | hk | jp +} ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: true, - ): Promise>; +exchange?: string; // us | hk | jp ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: false | undefined, - ): Promise>; +export interface CloseStockPositionReq { + symbol: string; + close_type: 1 | 2; + close_volume?: string; +} ⋮---- -private async prepareSignParams< - TParams extends ParamsInQueryBodyOrHeader | undefined, - >( - method: Method, - endpoint: string, - signMethod: SignMethod, - params?: TParams, - isPublicApi?: boolean, - ) +export interface GetStockTransactionsReq { + begin_time?: number; + end_time?: number; + ref_id?: string; + type?: string; + page?: number; + page_size?: number; +} ⋮---- -/** 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?: ParamsInQueryBodyOrHeader, - isPublicApi?: boolean, - ): Promise +export interface CreateStockTransactionReq { + asset: string; + change: string; + type: 'deposit' | 'withdraw'; + ref_id: string; +} ================ -File: src/lib/requestUtils.ts +File: src/types/request/unified.ts ================ -import WebSocket from 'isomorphic-ws'; -⋮---- -import { GateBaseUrlKey } from '../types/shared.js'; -⋮---- -export interface RestClientOptions { - /** Your API key */ - apiKey?: string; - - /** Your API secret */ - apiSecret?: string; - - /** Use the Gate TestNet REST host. */ - useTestnet?: boolean; - - /** - * Override the default/global max size of the request window (in ms) for signed api calls. - * If you don't include a recv window when making an API call, this value will be used as default - */ - recvWindow?: 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.gate.io' - **/ - baseUrl?: string; - - // manually override with one of the known base URLs in the library - baseUrlKey?: GateBaseUrlKey; - - /** Default: true. whether to try and post-process request exceptions (and throw them). */ - parseExceptions?: 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; - - /** - * 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; +export interface SubmitUnifiedBorrowOrRepayReq { + currency: string; + type: 'borrow' | 'repay'; + amount: string; + repaid_all?: boolean; + text?: string; } ⋮---- -/** Your API key */ -⋮---- -/** Your API secret */ -⋮---- -/** Use the Gate TestNet REST host. */ +export interface GetUnifiedLoansReq { + currency?: string; + page?: number; + limit?: number; + type?: 'platform' | 'margin'; +} ⋮---- -/** - * Override the default/global max size of the request window (in ms) for signed api calls. - * If you don't include a recv window when making an API call, this value will be used as default - */ +export interface GetUnifiedLoanRecordsReq { + type?: 'borrow' | 'repay'; + currency?: string; + page?: number; + limit?: number; +} +export interface GetUnifiedInterestRecordsReq { + currency?: string; + page?: number; + limit?: number; + from?: number; + to?: number; + type?: 'platform' | 'margin'; +} ⋮---- -/** Default: false. If true, we'll throw errors if any params are undefined */ +export interface SetUnifiedAccountModeReq { + mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; + settings?: { + usdt_futures?: boolean; + spot_hedge?: boolean; + use_funding?: boolean; + options?: boolean; + }; +} ⋮---- -/** - * Optionally override API protocol + domain - * e.g baseUrl: 'https://api.gate.io' - **/ -⋮---- -// manually override with one of the known base URLs in the library -⋮---- -/** Default: true. whether to try and post-process request exceptions (and throw them). */ -⋮---- -/** - * 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) - */ -⋮---- -/** - * 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. - */ -⋮---- -export function serializeParams | undefined = {}>( - params: T, - strict_validation: boolean | undefined, - encodeValues: boolean, - prefixWith: string, -): string +export interface PortfolioMarginCalculatorReq { + spot_balances?: { + currency: string; + equity: string; + }[]; + spot_orders?: { + currency_pairs: string; + order_price: string; + count?: string; + left: string; + type: 'sell' | 'buy'; + }[]; + futures_positions?: { + contract: string; + size: string; + }[]; + futures_orders?: { + contract: string; + size: string; + left: string; + }[]; + options_positions?: { + options_name: string; + size: string; + }[]; + options_orders?: { + options_name: string; + size: string; + left: string; + }[]; + spot_hedge?: boolean; +} ⋮---- -// Only prefix if there's a value +export interface GetUnifiedHistoryLendingRateReq { + currency: string; + tier?: string; + page?: number; + limit?: number; +} ⋮---- -/** Global TestNet REST host. Gate docs: spot and futures. */ +export interface SubmitUnifiedLoanRepayReq { + currency: string; + amount: string; + currency_pair?: string; +} ⋮---- -// Same host as testnet. The old fx-api-testnet.gateio.ws host returns 502. +export interface SetUnifiedCollateralCurrenciesReq { + collateral_type?: 0 | 1; + enable_list?: string[]; + disable_list?: string[]; +} ⋮---- -export function getRestBaseUrl(restClientOptions: RestClientOptions): string +export interface CreateQuickRepaymentReq { + debt_currencies: string[]; + available_currencies: string[]; +} ⋮---- -export interface MessageEventLike { - target: WebSocket; - type: 'message'; - data: string; +/** POST /unified/delta_neutral — v4.106.97 */ +export interface SetUnifiedDeltaNeutralReq { + enabled: boolean; } ⋮---- -export function isMessageEvent(msg: unknown): msg is MessageEventLike +/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ +export interface SetUserLeverageReq { + leverage?: string; +} ================ -File: src/types/request/autoinvest.ts +File: src/types/response/wallet.ts ================ -/**========================================================================================================================== - * EARN AUTO INVEST - * ========================================================================================================================== - */ -⋮---- -export interface AutoInvestPlanPortfolioItemInput { - asset: string; - ratio: string; +export interface CurrencyChain { + chain: string; + name_cn: string; + name_en: string; + contract_address: string; + is_disabled: number; + is_deposit_disabled: number; + is_withdraw_disabled: number; + decimal: string; } ⋮---- -/** POST /earn/autoinvest/plans/create */ -export interface CreateAutoInvestPlanReq { - plan_name?: string; - plan_des?: string; - plan_money: string; - plan_amount: string; - plan_period_type: - | 'daily' - | 'weekly' - | 'biweekly' - | 'monthly' - | 'hourly' - | '4-hourly'; - plan_period_day: number; - plan_period_hour: number; - items: AutoInvestPlanPortfolioItemInput[]; - /** Fund source: `spot` or `earn`; default spot */ - fund_source?: string; - /** Fund flow: `auto_invest` or `earn`; default auto_invest */ - fund_flow?: string; - /** 0 normal creation, 1 quick investment */ - type?: number; +/** GET /wallet/sub_account_balances item */ +export interface SubAccountBalance { + uid: string; + available: { [key: string]: string }; + /** Locked amount per currency */ + locking?: { [key: string]: string }; } ⋮---- -/** Fund source: `spot` or `earn`; default spot */ +/** Locked amount per currency */ ⋮---- -/** Fund flow: `auto_invest` or `earn`; default auto_invest */ +export interface DepositRecord { + id: string; + txid: string; + timestamp: string; + amount: string; + currency: string; + address: string; + memo?: string; + status: + | 'BLOCKED' // Deposit Blocked + | 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock + | 'DONE' // Funds Credited to Spot Account + | 'INVALID' // Invalid Transaction + | 'MANUAL' // Manual Review Required + | 'PEND' // Processing + | 'REVIEW' // Under Compliance Review + | 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit + chain: string; + refund_status?: // v4.106.95: Blocked deposit refund status + 'REFUNDING' | 'REFUNDED' | 'REFUND_FAILED' | 'REJECTED'; +} ⋮---- -/** 0 normal creation, 1 quick investment */ +| 'BLOCKED' // Deposit Blocked +| 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock +| 'DONE' // Funds Credited to Spot Account +| 'INVALID' // Invalid Transaction +| 'MANUAL' // Manual Review Required +| 'PEND' // Processing +| 'REVIEW' // Under Compliance Review +| 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit ⋮---- -/** POST /earn/autoinvest/plans/update */ -export interface UpdateAutoInvestPlanReq { - plan_id: number; - fund_source?: string; - fund_flow?: string; -} +refund_status?: // v4.106.95: Blocked deposit refund status ⋮---- -/** POST /earn/autoinvest/plans/stop */ -export interface StopAutoInvestPlanReq { - plan_id: number; +export interface CreateDepositAddressResp { + currency: string; + address: string; + multichain_addresses: { + chain: string; + address: string; + payment_id: string; + payment_name: string; + obtain_failed: number; + }[]; } ⋮---- -/** POST /earn/autoinvest/plans/add_position */ -export interface AddAutoInvestPlanPositionReq { - plan_id: number; +export interface SubAccountTransferRecord { + currency: string; + sub_account: string; + direction: 'to' | 'from'; amount: string; + uid: string; + client_order_id: string; + timest: string; + source: string; + sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; } ⋮---- -/** POST /earn/autoinvest/min_invest_amount */ -export interface GetAutoInvestMinAmountReq { - money: string; - /** Asset type, required: 1 cryptocurrency, 2 TradFi stocks */ - asset_type: 1 | 2; - items: AutoInvestPlanPortfolioItemInput[]; +export interface WithdrawalStatus { + currency: string; + name: string; + name_cn: string; + deposit: string; + withdraw_percent: string; + withdraw_fix: string; + withdraw_day_limit: string; + withdraw_amount_mini: string; + withdraw_day_limit_remain: string; + withdraw_eachtime_limit: string; + withdraw_fix_on_chains: { [key: string]: string }; + withdraw_percent_on_chains: { [key: string]: string }; } ⋮---- -/** Asset type, required: 1 cryptocurrency, 2 TradFi stocks */ -⋮---- -/** GET /earn/autoinvest/coins */ -export interface GetAutoInvestCoinsReq { - /** Pricing currency: USDT or BTC; default USDT */ - plan_money?: string; +export interface SubAccountMarginBalance { + currency_pair: string; + locked: boolean; + risk: string; + base: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; + quote: { + currency: string; + available: string; + locked: string; + borrowed: string; + interest: string; + }; } ⋮---- -/** Pricing currency: USDT or BTC; default USDT */ -⋮---- -/** GET /earn/autoinvest/plans/records */ -export interface GetAutoInvestPlanRecordsReq { - plan_id: number; - page?: number; - page_size?: number; +export interface SubAccountFuturesBalancesResp { + uid: string; + available: { + [key: string]: { + total: string; + unrealised_pnl: string; + position_margin: string; + order_margin: string; + available: string; + point: string; + currency: string; + in_dual_mode: boolean; + enable_credit: boolean; + position_initial_margin: string; + maintenance_margin: string; + bonus: string; + enable_evolved_classic: boolean; + cross_order_margin: string; + cross_initial_margin: string; + cross_maintenance_margin: string; + cross_unrealised_pnl: string; + cross_available: string; + isolated_position_margin: string; + history: { + dnw: string; + pnl: string; + fee: string; + refr: string; + fund: string; + point_dnw: string; + point_fee: string; + point_refr: string; + bonus_dnw: string; + bonus_offset: string; + }; + }; + }; } ⋮---- -/** GET /earn/autoinvest/orders */ -export interface GetAutoInvestOrdersReq { - plan_id: number; - record_id: number; +export interface SubAccountCrossMarginBalancesResp { + uid: string; + available: { + user_id: number; + locked: boolean; + balances: { + [key: string]: { + available: string; + freeze: string; + borrowed: string; + interest: string; + }; + }; + total: string; + borrowed: string; + borrowed_net: string; + net: string; + leverage: string; + interest: string; + risk: string; + total_initial_margin: string; + total_margin_balance: string; + total_maintenance_margin: string; + total_initial_margin_rate: string; + total_maintenance_margin_rate: string; + total_available_margin: string; + }; } ⋮---- -/** GET /earn/autoinvest/plans/detail */ -export interface GetAutoInvestPlanDetailReq { - plan_id: number; +export interface SavedAddress { + currency: string; + chain: string; + address: string; + name: string; + tag: string; + verified: string; } ⋮---- -/** GET /earn/autoinvest/plans/list_info */ -export interface GetAutoInvestPlansReq { - /** Plan status: e.g. History (history) or Active (active) */ - status: string; - page?: number; - page_size?: number; +export interface TradingFees { + user_id: number; + taker_fee: string; + maker_fee: string; + gt_discount: boolean; + gt_taker_fee: string; + gt_maker_fee: string; + loan_fee: string; + point_type: string; + futures_taker_fee: string; + futures_maker_fee: string; + delivery_taker_fee: string; + delivery_maker_fee: string; + debit_fee: number; } ⋮---- -/** Plan status: e.g. History (history) or Active (active) */ - -================ -File: src/types/request/stock.ts -================ -/** Stock / TradFi Spot API request types */ -⋮---- -export interface GetStockUserAssetsReq { - pnl_calc_type?: number; - pnl_calc_price?: number; +export interface GetBalancesResp { + total: { + amount: string; + currency: string; + unrealised_pnl?: string; + borrowed?: string; + }; + details: { + [key: string]: { + amount: string; + currency: string; + unrealised_pnl?: string; + borrowed?: string; + }; + }; } ⋮---- -export interface SetStockMarginFeatureReq { - /** Whether to enable margin financing */ - margin_feature: boolean; +export interface SmallBalanceRecord { + currency: string; + available_balance: string; + estimated_as_btc: string; + convertible_to_gt: string; } ⋮---- -/** Whether to enable margin financing */ -⋮---- -export interface GetStockBalanceRecordsReq { - /** Record types, separated by commas */ - type?: string; - /** Business identifiers, separated by commas */ - business?: string; - symbol?: string; - /** Record creation time in seconds; end_time must be greater than begin_time */ - begin_time?: number; - /** Record creation time in seconds; must be greater than begin_time */ - end_time?: number; - /** Return records with a greater primary key ID */ - start_id?: number; - /** Defaults to desc without start_id, or asc with start_id */ - sort_direction?: 'asc' | 'desc'; - /** Return raw detail; defaults to false */ - include_detail?: boolean; - /** Page number, defaults to 1 */ - page?: number; - /** Records per page, defaults to 10, maximum 100 */ - page_size?: number; +export interface SmallBalanceHistoryRecord { + id: string; + currency: string; + amount: string; + gt_amount: string; + create_time: number; } ⋮---- -/** Record types, separated by commas */ -⋮---- -/** Business identifiers, separated by commas */ -⋮---- -/** Record creation time in seconds; end_time must be greater than begin_time */ -⋮---- -/** Record creation time in seconds; must be greater than begin_time */ -⋮---- -/** Return records with a greater primary key ID */ -⋮---- -/** Defaults to desc without start_id, or asc with start_id */ -⋮---- -/** Return raw detail; defaults to false */ -⋮---- -/** Page number, defaults to 1 */ -⋮---- -/** Records per page, defaults to 10, maximum 100 */ -⋮---- -export interface GetStockSymbolsReq { - symbols?: string; - exchange?: string; // us | hk | jp - with_desc_i18n?: boolean; - page?: number; - page_size?: number; +export interface PushOrder { + id: string; + push_uid: number; + receive_uid: number; + currency: string; + amount: string; + create_time: number; + status: + | 'CREATING' + | 'PENDING' + | 'CANCELLING' + | 'CANCELLED' + | 'REFUSING' + | 'REFUSED' + | 'RECEIVING' + | 'RECEIVED'; + message: string; } ⋮---- -exchange?: string; // us | hk | jp -⋮---- -export interface GetStockSymbolDetailReq { - symbols?: string; - exchange?: string; // us | hk | jp - page?: number; - page_size?: number; +/** GET /wallet/transfers — AccountTransferDetail */ +export interface AccountTransferDetail { + tx_id: string; + status: 'pending' | 'success' | 'fail'; + currency: string; + amount: string; + from_account: + | 'spot' + | 'margin' + | 'futures' + | 'delivery' + | 'options' + | 'unknown'; + to_account: + | 'spot' + | 'margin' + | 'futures' + | 'delivery' + | 'options' + | 'unknown'; + settle?: string | null; + currency_pair?: string | null; } + +================ +File: src/types/shared.ts +================ +export type GateBaseUrlKey = + | 'live' + | 'futuresLiveAlternative' + | 'testnet' + | 'futuresTestnet'; ⋮---- -exchange?: string; // us | hk | jp +// interfaces ⋮---- -export interface GetStockOrdersReq { - symbol?: string; +export interface FromToPageLimit { + from: number; + to: number; + page: number; + limit: number; } ⋮---- -export interface CreateStockOrderReq { - volume: string; - symbol: string; - side: 1 | 2; - price_type: 'market' | 'limit'; - /** Limit: all only; market: regular only */ - trading_session: 'all' | 'regular'; - time_in_force: 'day'; - price?: string; - client_order_id?: string; +// Used for spot and flash swap +export interface CurrencyPair { + id?: string; + base?: string; + base_name?: string; + quote?: string; + quote_name?: string; + trade_quotes?: string[] | null; + fee?: string; + min_base_amount?: string; + min_quote_amount?: string; + max_base_amount?: string; + max_quote_amount?: string; + amount_precision?: number; + precision?: number; + trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; + sell_start?: number; + buy_start?: number; + type: string; + delisting_time?: number; + trade_url?: string; + up_rate?: string; // v4.106.4: Maximum price increase percentage + down_rate?: string; // v4.106.4: Maximum price decrease percentage + market_order_max_stock?: string | null; + market_order_max_money?: string | null; } ⋮---- -/** Limit: all only; market: regular only */ -⋮---- -export interface GetStockOrderHistoryReq { - symbol?: string; - order_ids?: string; - begin_time?: number; - end_time?: number; - side?: 1 | 2; - page?: number; - page_size?: number; -} +up_rate?: string; // v4.106.4: Maximum price increase percentage +down_rate?: string; // v4.106.4: Maximum price decrease percentage + +================ +File: examples/Rest/futures/testnet.ts +================ +import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. +// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) ⋮---- -export interface GetStockOrderDealsReq { - order_id: number; - /** Page number, defaults to 1 */ - page?: number; - /** Records per page, defaults to 10, maximum 100 */ - page_size?: number; -} +// Define the account object with API key and secret ⋮---- -/** Page number, defaults to 1 */ +key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key +secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret ⋮---- -/** Records per page, defaults to 10, maximum 100 */ +// Initialize the RestClient with the API credentials ⋮---- -export interface UpdateStockOrderReq { - volume: string; - price: string; -} +async function submitFuturesOrder() ⋮---- -export interface GetStockPositionsReq { - pnl_calc_type?: number; - pnl_calc_price?: number; - symbol?: string; - exchange?: string; // us | hk | jp -} +// Submit a market order for futures trading ⋮---- -exchange?: string; // us | hk | jp +settle: 'usdt', // Specify the settlement currency +contract: 'BTC_USDT', // Specify the contract +size: 20, // Order size: positive for long, negative for short +price: '0', // Market order, so price is set to '0' +tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) ⋮---- -export interface CloseStockPositionReq { - symbol: string; - close_type: 1 | 2; - close_volume?: string; -} +console.log('Response: ', result); // Log the response to the console ⋮---- -export interface GetStockTransactionsReq { - begin_time?: number; - end_time?: number; - ref_id?: string; - type?: string; - page?: number; - page_size?: number; -} +console.error('Error in execution: ', e); // Log any errors that occur ⋮---- -export interface CreateStockTransactionReq { - asset: string; - change: string; - type: 'deposit' | 'withdraw'; - ref_id: string; -} +// Execute the function to submit a futures order ================ -File: src/types/request/unified.ts +File: src/lib/BaseRestClient.ts ================ -export interface SubmitUnifiedBorrowOrRepayReq { - currency: string; - type: 'borrow' | 'repay'; - amount: string; - repaid_all?: boolean; - text?: string; -} +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'; ⋮---- -export interface GetUnifiedLoansReq { - currency?: string; - page?: number; - limit?: number; - type?: 'platform' | 'margin'; -} +import { neverGuard } from './misc-util.js'; +import { + CHANNEL_ID, + getRestBaseUrl, + RestClientOptions, + serializeParams, +} from './requestUtils.js'; +import { + checkWebCryptoAPISupported, + hashMessage, + SignAlgorithm, + SignEncodeMethod, + signMessage, +} from './webCryptoAPI.js'; ⋮---- -export interface GetUnifiedLoanRecordsReq { - type?: 'borrow' | 'repay'; - currency?: string; - page?: number; - limit?: number; -} -export interface GetUnifiedInterestRecordsReq { - currency?: string; - page?: number; - limit?: number; - from?: number; - to?: number; - type?: 'platform' | 'margin'; -} +/** + * Used to switch how authentication/requests work under the hood + */ ⋮---- -export interface SetUnifiedAccountModeReq { - mode: 'classic' | 'multi_currency' | 'portfolio' | 'single_currency'; - settings?: { - usdt_futures?: boolean; - spot_hedge?: boolean; - use_funding?: boolean; - options?: boolean; - }; -} +export type RestClientType = + (typeof REST_CLIENT_TYPE_ENUM)[keyof typeof REST_CLIENT_TYPE_ENUM]; ⋮---- -export interface PortfolioMarginCalculatorReq { - spot_balances?: { - currency: string; - equity: string; - }[]; - spot_orders?: { - currency_pairs: string; - order_price: string; - count?: string; - left: string; - type: 'sell' | 'buy'; - }[]; - futures_positions?: { - contract: string; - size: string; - }[]; - futures_orders?: { - contract: string; - size: string; - left: string; - }[]; - options_positions?: { - options_name: string; - size: string; - }[]; - options_orders?: { - options_name: string; - size: string; - left: string; - }[]; - spot_hedge?: boolean; +interface SignedRequest { + originalParams: T; + paramsWithSign?: T & { sign: string }; + serializedParams: string; + sign: string; + queryParamsWithSign: string; + timestamp: number; } ⋮---- -export interface GetUnifiedHistoryLendingRateReq { - currency: string; - tier?: string; - page?: number; - limit?: number; +interface UnsignedRequest { + originalParams: T; + paramsWithSign: T; } ⋮---- -export interface SubmitUnifiedLoanRepayReq { - currency: string; - amount: string; - currency_pair?: string; -} +type SignMethod = 'gateV4'; ⋮---- -export interface SetUnifiedCollateralCurrenciesReq { - collateral_type?: 0 | 1; - enable_list?: string[]; - disable_list?: string[]; -} +/** + * Some requests require some params to be in the query string and some in the body. Some even support passing params via headers. + * This type anticipates these are possible in any combination. + * + * The request builder will automatically handle where parameters should go. + */ +type ParamsInQueryBodyOrHeader = { + query?: object; + body?: object; + headers?: object; + /** multipart/form-data body; mutually exclusive with `body` */ + multipart?: FormData; +}; ⋮---- -export interface CreateQuickRepaymentReq { - debt_currencies: string[]; - available_currencies: string[]; -} +/** multipart/form-data body; mutually exclusive with `body` */ ⋮---- -/** POST /unified/delta_neutral — v4.106.97 */ -export interface SetUnifiedDeltaNeutralReq { - enabled: boolean; -} +/** + * Enables: + * - Detailed request/response logging + * - Full request dump in any exceptions thrown from API responses + */ ⋮---- -/** POST /unified/leverage/user_setting — set leverage for all borrowed currencies */ -export interface SetUserLeverageReq { - leverage?: string; -} - -================ -File: src/types/response/wallet.ts -================ -export interface CurrencyChain { - chain: string; - name_cn: string; - name_en: string; - contract_address: string; - is_disabled: number; - is_deposit_disabled: number; - is_withdraw_disabled: number; - decimal: string; -} +// request: { +// url: response.config.url, +// method: response.config.method, +// data: response.config.data, +// headers: response.config.headers, +// }, ⋮---- -/** GET /wallet/sub_account_balances item */ -export interface SubAccountBalance { - uid: string; - available: { [key: string]: string }; - /** Locked amount per currency */ - locking?: { [key: string]: string }; -} +/** + * Impure, mutates params to remove any values that have a key but are undefined. + */ +function deleteUndefinedValues(params?: any): void ⋮---- -/** Locked amount per currency */ +export abstract class BaseRestClient ⋮---- -export interface DepositRecord { - id: string; - txid: string; - timestamp: string; - amount: string; - currency: string; - address: string; - memo?: string; - status: - | 'BLOCKED' // Deposit Blocked - | 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock - | 'DONE' // Funds Credited to Spot Account - | 'INVALID' // Invalid Transaction - | 'MANUAL' // Manual Review Required - | 'PEND' // Processing - | 'REVIEW' // Under Compliance Review - | 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit - chain: string; - refund_status?: // v4.106.95: Blocked deposit refund status - 'REFUNDING' | 'REFUNDED' | 'REFUND_FAILED' | 'REJECTED'; -} +/** Defines the client type (affecting how requests & signatures behave) */ +abstract getClientType(): RestClientType; ⋮---- -| 'BLOCKED' // Deposit Blocked -| 'DEP_CREDITED' // Deposit Credited, Withdrawal Pending Unlock -| 'DONE' // Funds Credited to Spot Account -| 'INVALID' // Invalid Transaction -| 'MANUAL' // Manual Review Required -| 'PEND' // Processing -| 'REVIEW' // Under Compliance Review -| 'TRACK'; // Tracking Block Confirmations, Pending Spot Account Credit +/** + * 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 = {}, + ) ⋮---- -refund_status?: // v4.106.95: Blocked deposit refund status +/** Throw errors if any request params are empty */ ⋮---- -export interface CreateDepositAddressResp { - currency: string; - address: string; - multichain_addresses: { - chain: string; - address: string; - payment_id: string; - payment_name: string; - obtain_failed: number; - }[]; -} +/** in ms == 5 minutes by default */ ⋮---- -export interface SubAccountTransferRecord { - currency: string; - sub_account: string; - direction: 'to' | 'from'; - amount: string; - uid: string; - client_order_id: string; - timest: string; - source: string; - sub_account_type: 'spot' | 'futures' | 'cross_margin' | 'delivery'; -} +/** inject custom rquest options based on axios specs - see axios docs for more guidance on AxiosRequestConfig: https://github.com/axios/axios#request-config */ ⋮---- -export interface WithdrawalStatus { - currency: string; - name: string; - name_cn: string; - deposit: string; - withdraw_percent: string; - withdraw_fix: string; - withdraw_day_limit: string; - withdraw_amount_mini: string; - withdraw_day_limit_remain: string; - withdraw_eachtime_limit: string; - withdraw_fix_on_chains: { [key: string]: string }; - withdraw_percent_on_chains: { [key: string]: string }; -} +// 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. ⋮---- -export interface SubAccountMarginBalance { - currency_pair: string; - locked: boolean; - risk: string; - base: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; - quote: { - currency: string; - available: string; - locked: string; - borrowed: string; - interest: string; - }; -} +// Extract existing https agent parameters, if provided, to prevent the keepAlive flag from overwriting an existing https agent completely ⋮---- -export interface SubAccountFuturesBalancesResp { - uid: string; - available: { - [key: string]: { - total: string; - unrealised_pnl: string; - position_margin: string; - order_margin: string; - available: string; - point: string; - currency: string; - in_dual_mode: boolean; - enable_credit: boolean; - position_initial_margin: string; - maintenance_margin: string; - bonus: string; - enable_evolved_classic: boolean; - cross_order_margin: string; - cross_initial_margin: string; - cross_maintenance_margin: string; - cross_unrealised_pnl: string; - cross_available: string; - isolated_position_margin: string; - history: { - dnw: string; - pnl: string; - fee: string; - refr: string; - fund: string; - point_dnw: string; - point_fee: string; - point_refr: string; - bonus_dnw: string; - bonus_offset: string; - }; - }; - }; -} +// For more advanced configuration, raise an issue on GitHub or use the "networkOptions" +// parameter to define a custom httpsAgent with the desired properties ⋮---- -export interface SubAccountCrossMarginBalancesResp { - uid: string; - available: { - user_id: number; - locked: boolean; - balances: { - [key: string]: { - available: string; - freeze: string; - borrowed: string; - interest: string; - }; - }; - total: string; - borrowed: string; - borrowed_net: string; - net: string; - leverage: string; - interest: string; - risk: string; - total_initial_margin: string; - total_margin_balance: string; - total_maintenance_margin: string; - total_initial_margin_rate: string; - total_maintenance_margin_rate: string; - total_available_margin: string; - }; -} +// Check Web Crypto API support when credentials are provided and no custom sign function is used ⋮---- -export interface SavedAddress { - currency: string; - chain: string; - address: string; - name: string; - tag: string; - verified: string; -} +// Throw if one of the 3 values is missing, but at least one of them is set ⋮---- -export interface TradingFees { - user_id: number; - taker_fee: string; - maker_fee: string; - gt_discount: boolean; - gt_taker_fee: string; - gt_maker_fee: string; - loan_fee: string; - point_type: string; - futures_taker_fee: string; - futures_maker_fee: string; - delivery_taker_fee: string; - delivery_maker_fee: string; - debit_fee: number; -} +/** + * Timestamp used to sign the request. Override this method to implement your own timestamp/sync mechanism + */ +getSignTimestampMs(): number ⋮---- -export interface GetBalancesResp { - total: { - amount: string; - currency: string; - unrealised_pnl?: string; - borrowed?: string; - }; - details: { - [key: string]: { - amount: string; - currency: string; - unrealised_pnl?: string; - borrowed?: string; - }; - }; -} +protected get(endpoint: string, params?: object) +⋮---- +// GET only supports params in the query string +⋮---- +protected post(endpoint: string, params?: ParamsInQueryBodyOrHeader) +⋮---- +protected getPrivate(endpoint: string, params?: object) +⋮---- +// GET only supports params in the query string +⋮---- +protected postPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +⋮---- +/** POST private endpoint with multipart/form-data (empty body hash for signing) */ +protected postPrivateMultipart( + endpoint: string, + formData: FormData, + query?: object, + ) +⋮---- +protected deletePrivate( + endpoint: string, + params?: ParamsInQueryBodyOrHeader, + ) +⋮---- +protected putPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +⋮---- +// protected patchPrivate(endpoint: string, params?: any) { +protected patchPrivate(endpoint: string, params?: ParamsInQueryBodyOrHeader) +⋮---- +/** + * @private Make a HTTP request to a specific endpoint. Private endpoint API calls are automatically signed. + */ +private async _call( + method: Method, + endpoint: string, + params?: ParamsInQueryBodyOrHeader, + isPublicApi?: boolean, + ): Promise +⋮---- +// Sanity check to make sure it's only ever prefixed by one forward slash +⋮---- +// Build a request and handle signature process +⋮---- +// Dispatch request +⋮---- +// See: https://www.gate.io/docs/developers/apiv4/en/#return-format +⋮---- +// Throw API rejections by parsing the response code from the body +⋮---- +/** + * @private generic handler to parse request exceptions + */ +parseException(e: any, request: AxiosRequestConfig): 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 timestamp + */ +private async signRequest< + T extends ParamsInQueryBodyOrHeader | undefined = {}, + >( + data: T, + endpoint: string, + method: Method, + signMethod: SignMethod, + ): Promise> +⋮---- +const timestamp = +(this.getSignTimestampMs() / 1000).toFixed(0); // in seconds +⋮---- +// console.log('sign params: ', { +// requestBodyToHash, +// paramsStr: toSign, +// url: this.baseUrl, +// urlPath: this.baseUrlPath, +// }); ⋮---- -export interface SmallBalanceRecord { - currency: string; - available_balance: string; - estimated_as_btc: string; - convertible_to_gt: string; -} +private async signMessage( + paramsStr: string, + secret: string, + method: 'hex' | 'base64', + algorithm: SignAlgorithm, + ): Promise ⋮---- -export interface SmallBalanceHistoryRecord { - id: string; - currency: string; - amount: string; - gt_amount: string; - create_time: number; -} +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: true, + ): Promise>; ⋮---- -export interface PushOrder { - id: string; - push_uid: number; - receive_uid: number; - currency: string; - amount: string; - create_time: number; - status: - | 'CREATING' - | 'PENDING' - | 'CANCELLING' - | 'CANCELLED' - | 'REFUSING' - | 'REFUSED' - | 'RECEIVING' - | 'RECEIVED'; - message: string; -} +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + endpoint: string, + signMethod: SignMethod, + params?: TParams, + isPublicApi?: false | undefined, + ): Promise>; ⋮---- -/** GET /wallet/transfers — AccountTransferDetail */ -export interface AccountTransferDetail { - tx_id: string; - status: 'pending' | 'success' | 'fail'; - currency: string; - amount: string; - from_account: - | 'spot' - | 'margin' - | 'futures' - | 'delivery' - | 'options' - | 'unknown'; - to_account: - | 'spot' - | 'margin' - | 'futures' - | 'delivery' - | 'options' - | 'unknown'; - settle?: string | null; - currency_pair?: string | null; -} +private async prepareSignParams< + TParams extends ParamsInQueryBodyOrHeader | undefined, + >( + method: Method, + 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?: ParamsInQueryBodyOrHeader, + isPublicApi?: boolean, + ): Promise ================ -File: src/types/shared.ts +File: src/lib/requestUtils.ts ================ -export type GateBaseUrlKey = - | 'live' - | 'futuresLiveAlternative' - | 'testnet' - | 'futuresTestnet'; +import WebSocket from 'isomorphic-ws'; ⋮---- -// interfaces +import { GateBaseUrlKey } from '../types/shared.js'; ⋮---- -export interface FromToPageLimit { - from: number; - to: number; - page: number; - limit: number; +export interface RestClientOptions { + /** Your API key */ + apiKey?: string; + + /** Your API secret */ + apiSecret?: string; + + /** Use the Gate TestNet REST host. */ + useTestnet?: boolean; + + /** + * Ignored by REST clients. Gate REST has no recvWindow; it uses a Timestamp header + * with a fixed 60-second tolerance, so keep the system clock in sync. + * To offset WebSocket signature timestamps, set `recvWindow` in the WebsocketClient options. + * @deprecated Ignored by REST clients; retained for backwards compatibility. + */ + recvWindow?: 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.gate.io' + **/ + baseUrl?: string; + + // manually override with one of the known base URLs in the library + baseUrlKey?: GateBaseUrlKey; + + /** Default: true. whether to try and post-process request exceptions (and throw them). */ + parseExceptions?: 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; + + /** + * 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; } ⋮---- -// Used for spot and flash swap -export interface CurrencyPair { - id?: string; - base?: string; - base_name?: string; - quote?: string; - quote_name?: string; - trade_quotes?: string[] | null; - fee?: string; - min_base_amount?: string; - min_quote_amount?: string; - max_base_amount?: string; - max_quote_amount?: string; - amount_precision?: number; - precision?: number; - trade_status?: 'untradable' | 'buyable' | 'sellable' | 'tradable'; - sell_start?: number; - buy_start?: number; - type: string; - delisting_time?: number; - trade_url?: string; - up_rate?: string; // v4.106.4: Maximum price increase percentage - down_rate?: string; // v4.106.4: Maximum price decrease percentage - market_order_max_stock?: string | null; - market_order_max_money?: string | null; -} +/** Your API key */ ⋮---- -up_rate?: string; // v4.106.4: Maximum price increase percentage -down_rate?: string; // v4.106.4: Maximum price decrease percentage - -================ -File: examples/Rest/futures/testnet.ts -================ -import { RestClient } from '../../../src/index.js'; // For an easy demonstration, import from the src dir. Normally though, see below to import from the npm installed version instead. -// import { RestClient } from 'gateio-api'; // Import the RestClient from the published version of this SDK, installed via NPM (npm install gateio-api) +/** Your API secret */ ⋮---- -// Define the account object with API key and secret +/** Use the Gate TestNet REST host. */ ⋮---- -key: process.env.API_KEY || 'yourApiHere', // Replace 'yourApiHere' with your actual API key -secret: process.env.API_SECRET || 'yourSecretHere', // Replace 'yourSecretHere' with your actual API secret +/** + * Ignored by REST clients. Gate REST has no recvWindow; it uses a Timestamp header + * with a fixed 60-second tolerance, so keep the system clock in sync. + * To offset WebSocket signature timestamps, set `recvWindow` in the WebsocketClient options. + * @deprecated Ignored by REST clients; retained for backwards compatibility. + */ ⋮---- -// Initialize the RestClient with the API credentials +/** Default: false. If true, we'll throw errors if any params are undefined */ ⋮---- -async function submitFuturesOrder() +/** + * Optionally override API protocol + domain + * e.g baseUrl: 'https://api.gate.io' + **/ ⋮---- -// Submit a market order for futures trading +// manually override with one of the known base URLs in the library ⋮---- -settle: 'usdt', // Specify the settlement currency -contract: 'BTC_USDT', // Specify the contract -size: 20, // Order size: positive for long, negative for short -price: '0', // Market order, so price is set to '0' -tif: 'ioc', // Time in force: 'ioc' (Immediate Or Cancel) +/** Default: true. whether to try and post-process request exceptions (and throw them). */ ⋮---- -console.log('Response: ', result); // Log the response to the console +/** + * Enable keep alive for REST API requests (via axios). + * See: https://github.com/tiagosiebler/bybit-api/issues/368 + */ ⋮---- -console.error('Error in execution: ', e); // Log any errors that occur +/** + * 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) + */ ⋮---- -// Execute the function to submit a futures order +/** + * 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. + */ +⋮---- +export function serializeParams | undefined = {}>( + params: T, + strict_validation: boolean | undefined, + encodeValues: boolean, + prefixWith: string, +): string +⋮---- +// Only prefix if there's a value +⋮---- +/** Global TestNet REST host. Gate docs: spot and futures. */ +⋮---- +// Same host as testnet. The old fx-api-testnet.gateio.ws host returns 502. +⋮---- +export function getRestBaseUrl(restClientOptions: RestClientOptions): string +⋮---- +export interface MessageEventLike { + target: WebSocket; + type: 'message'; + data: string; +} +⋮---- +export function isMessageEvent(msg: unknown): msg is MessageEventLike ================ File: src/types/request/earn.ts @@ -20964,7 +20963,7 @@ File: package.json ================ { "name": "gateio-api", - "version": "1.6.8", + "version": "1.6.9", "description": "Complete & Robust Node.js SDK for Gate.com's REST APIs, WebSockets & WebSocket APIs, with TypeScript declarations.", "scripts": { "clean": "rm -rf dist/*",