fix linter configuration & jest type dependency

This commit is contained in:
tiagosiebler
2023-02-17 13:51:40 +00:00
parent 7669c037c8
commit 8e54ecbaf5
34 changed files with 1600 additions and 1710 deletions

View File

@@ -1,36 +0,0 @@
module.exports = {
env: {
es6: true,
node: true,
},
extends: ['eslint:recommended'],
parserOptions: {
sourceType: 'module',
ecmaVersion: 9
},
plugins: [],
rules: {
'array-bracket-spacing': ['error', 'never'],
indent: ['warn', 2],
'linebreak-style': ['error', 'unix'],
'lines-between-class-members': ['warn', 'always'],
semi: ['error', 'always'],
'new-cap': 'off',
'no-console': 'off',
'no-debugger': 'off',
'no-mixed-spaces-and-tabs': 2,
'no-use-before-define': [2, 'nofunc'],
'no-unreachable': ['warn'],
'no-unused-vars': ['warn'],
'no-extra-parens': ['off'],
'no-mixed-operators': ['off'],
quotes: [2, 'single', 'avoid-escape'],
'block-scoped-var': 2,
'brace-style': [2, '1tbs', { allowSingleLine: true }],
'computed-property-spacing': [2, 'never'],
'keyword-spacing': 2,
'space-unary-ops': 2,
'max-len': ['warn', { 'code': 140 }]
}
};

86
.eslintrc.json Normal file
View File

@@ -0,0 +1,86 @@
{
"env": {
"es6": true,
"node": true
},
"extends": ["eslint:recommended"],
"parser": "@typescript-eslint/parser",
"root": true,
"plugins": ["@typescript-eslint"],
"overrides": [
{
"files": ["**/*.ts", "**/*.tsx"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"parserOptions": {
"projecasdft": true,
"project": ["./tsconfig.json", "examples/tsconfig.examples.json"]
},
"rules": {
"@typescript-eslint/await-thenable": "error",
"@typescript-eslint/dot-notation": "off",
"@typescript-eslint/no-unused-vars": "warn",
"@typescript-eslint/no-unused-expressions": "error",
"@typescript-eslint/no-var-requires": "error",
"@typescript-eslint/prefer-namespace-keyword": "error",
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-floating-promises": "off",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/promise-function-async": "off",
"@typescript-eslint/no-use-before-define": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/explicit-module-boundary-types": "off",
"no-dupe-class-members": "off",
"no-param-reassign": ["error"],
"array-bracket-spacing": ["error", "never"],
"indent": [
"warn",
2,
{
"SwitchCase": 1
}
],
"linebreak-style": ["error", "unix"],
"lines-between-class-members": ["warn", "always"],
"semi": "off",
"@typescript-eslint/semi": ["error"],
"new-cap": "off",
"no-console": "off",
"no-debugger": "off",
"no-mixed-spaces-and-tabs": 2,
"no-use-before-define": [2, "nofunc"],
"no-unreachable": ["warn"],
"no-unused-vars": ["warn"],
"no-extra-parens": ["off"],
"no-mixed-operators": ["off"],
"quotes": [2, "single", "avoid-escape"],
"block-scoped-var": 2,
"brace-style": [2, "1tbs", { "allowSingleLine": true }],
"computed-property-spacing": [2, "never"],
"keyword-spacing": 2,
"space-unary-ops": 2,
"sort-imports": [
"error",
{
"ignoreCase": false,
"ignoreDeclarationSort": true,
"ignoreMemberSort": false,
"memberSyntaxSortOrder": ["none", "all", "multiple", "single"],
"allowSeparatedGroups": false
}
],
"max-len": ["warn", { "code": 140 }]
}
},
{
"files": ["examples/*.js"],
"extends": ["eslint:recommended"]
}
]
}

View File

@@ -15,8 +15,10 @@ const client = new ContractClient({
(async () => { (async () => {
try { try {
/** /**
* You can make raw HTTP requests without the per-endpoint abstraction, * You can make raw HTTP requests without the per-endpoint abstraction.
* The REST ContractClient uses bybit's v3 signature mechanism, so it can be used for raw calls to any v3-supporting endpoints (incl the V5 APIs). *
* The REST ContractClient uses bybit's v3 signature mechanism,
* so it can be used for raw calls to any v3-supporting endpoints (incl the V5 APIs).
* e.g. if an endpoint is missing and you desperately need it (but please raise an issue or PR if you're missing an endpoint) * e.g. if an endpoint is missing and you desperately need it (but please raise an issue or PR if you're missing an endpoint)
*/ */
const rawCall = await client.getPrivate('/v5/order/realtime', { const rawCall = await client.getPrivate('/v5/order/realtime', {

View File

@@ -0,0 +1,12 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"outDir": "distExamples",
"allowJs": true
},
"include": [
"**/*.ts",
// if you have a mixed JS/TS codebase, don't forget to include your JS files
"**/*.js"
]
}

2644
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -29,12 +29,14 @@
"ws": "^7.4.0" "ws": "^7.4.0"
}, },
"devDependencies": { "devDependencies": {
"@types/jest": "^26.0.23", "@types/jest": "^27.0.4",
"@types/node": "^14.14.7", "@types/node": "^14.14.7",
"eslint": "^7.10.0", "@typescript-eslint/eslint-plugin": "^5.46.0",
"@typescript-eslint/parser": "^5.46.0",
"eslint": "^8.29.0",
"jest": "^27.0.4", "jest": "^27.0.4",
"source-map-loader": "^2.0.0", "source-map-loader": "^2.0.0",
"ts-jest": "^27.0.3", "ts-jest": "^27.0.4",
"ts-loader": "^8.0.11", "ts-loader": "^8.0.11",
"typescript": "^4.0.5", "typescript": "^4.0.5",
"webpack": "^5.4.0", "webpack": "^5.4.0",

View File

@@ -1,10 +1,11 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
AccountCoinBalanceResponseV3,
AccountCoinBalancesRequestV3,
AccountCoinBalancesResponseV3,
APIKeyInfoV3, APIKeyInfoV3,
APIResponseV3WithTime, APIResponseV3WithTime,
APIResponseWithTime, APIResponseWithTime,
AccountCoinBalanceResponseV3,
AccountCoinBalancesRequestV3,
AccountCoinBalancesResponseV3,
AssetInfoRequestV3, AssetInfoRequestV3,
AssetInfoResponseV3, AssetInfoResponseV3,
CoinInfoQueryResponseV3, CoinInfoQueryResponseV3,
@@ -18,8 +19,8 @@ import {
InternalTransferRequestV3, InternalTransferRequestV3,
ModifyAPIKeyRequestV3, ModifyAPIKeyRequestV3,
QueryDepositAddressRequestV3, QueryDepositAddressRequestV3,
QueryInternalTransfersRequestV3,
QueryInternalTransferSResponseV3, QueryInternalTransferSResponseV3,
QueryInternalTransfersRequestV3,
QuerySubAccountDepositAddressRequestV3, QuerySubAccountDepositAddressRequestV3,
SingleAccountCoinBalanceRequestV3, SingleAccountCoinBalanceRequestV3,
SubAccountTransferRequestV3, SubAccountTransferRequestV3,

View File

@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
AccountAssetInformationRequest,
APIResponseWithTime, APIResponseWithTime,
AccountAssetInformationRequest,
DepositRecordsRequest, DepositRecordsRequest,
EnableUniversalTransferRequest, EnableUniversalTransferRequest,
InternalTransferRequest, InternalTransferRequest,

View File

@@ -1,6 +1,24 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
APIResponseWithTime,
APIResponseV3, APIResponseV3,
APIResponseWithTime,
ContractActiveOrdersRequest,
ContractCancelOrderRequest,
ContractClosedPNLRequest,
ContractHistoricOrder,
ContractHistoricOrdersRequest,
ContractListResult,
ContractModifyOrderRequest,
ContractOrderRequest,
ContractPositionsRequest,
ContractSetAutoAddMarginRequest,
ContractSetMarginSwitchRequest,
ContractSetPositionModeRequest,
ContractSetTPSLRequest,
ContractSymbolTicker,
ContractUserExecutionHistoryRequest,
ContractWalletFundRecordRequest,
PaginatedResult,
UMCandlesRequest, UMCandlesRequest,
UMCategory, UMCategory,
UMFundingRateHistoryRequest, UMFundingRateHistoryRequest,
@@ -8,23 +26,6 @@ import {
UMOpenInterestRequest, UMOpenInterestRequest,
UMOptionDeliveryPriceRequest, UMOptionDeliveryPriceRequest,
UMPublicTradesRequest, UMPublicTradesRequest,
ContractOrderRequest,
ContractHistoricOrdersRequest,
ContractCancelOrderRequest,
ContractModifyOrderRequest,
ContractActiveOrdersRequest,
ContractPositionsRequest,
ContractSetAutoAddMarginRequest,
ContractSetMarginSwitchRequest,
ContractSetPositionModeRequest,
ContractSetTPSLRequest,
ContractUserExecutionHistoryRequest,
ContractClosedPNLRequest,
ContractWalletFundRecordRequest,
PaginatedResult,
ContractHistoricOrder,
ContractSymbolTicker,
ContractListResult,
} from './types'; } from './types';
import { REST_CLIENT_TYPE_ENUM } from './util'; import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient'; import BaseRestClient from './util/BaseRestClient';

View File

@@ -1,4 +1,6 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
APIResponseV3,
APIResponseWithTime, APIResponseWithTime,
CopyTradingCancelOrderRequest, CopyTradingCancelOrderRequest,
CopyTradingCloseOrderRequest, CopyTradingCloseOrderRequest,
@@ -6,7 +8,6 @@ import {
CopyTradingOrderRequest, CopyTradingOrderRequest,
CopyTradingTradingStopRequest, CopyTradingTradingStopRequest,
CopyTradingTransferRequest, CopyTradingTransferRequest,
APIResponseV3,
} from './types'; } from './types';
import { REST_CLIENT_TYPE_ENUM } from './util'; import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient'; import BaseRestClient from './util/BaseRestClient';

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { REST_CLIENT_TYPE_ENUM } from './util'; import { REST_CLIENT_TYPE_ENUM } from './util';
import { import {
APIResponseWithTime, APIResponseWithTime,

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils'; import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils';
import { import {
APIResponseWithTime, APIResponseWithTime,

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils'; import { REST_CLIENT_TYPE_ENUM } from './util/requestUtils';
import { import {
APIResponse, APIResponse,
@@ -273,6 +274,7 @@ export class LinearClient extends BaseRestClient {
*/ */
getPosition(): Promise<APIResponseWithTime<PerpPositionRoot[]>>; getPosition(): Promise<APIResponseWithTime<PerpPositionRoot[]>>;
getPosition( getPosition(
params: Partial<SymbolParam> params: Partial<SymbolParam>
): Promise<APIResponseWithTime<PerpPosition[]>>; ): Promise<APIResponseWithTime<PerpPosition[]>>;
@@ -344,7 +346,10 @@ export class LinearClient extends BaseRestClient {
getHistoryTradeRecords( getHistoryTradeRecords(
params: LinearGetHistoryTradeRecordsRequest params: LinearGetHistoryTradeRecordsRequest
): Promise<APIResponseWithTime<any>> { ): Promise<APIResponseWithTime<any>> {
return this.getPrivate('/private/linear/trade/execution/history-list', params); return this.getPrivate(
'/private/linear/trade/execution/history-list',
params
);
} }
getClosedPnl( getClosedPnl(

View File

@@ -1,13 +1,63 @@
import { import {
APIResponseV3,
APIResponseV3WithTime, APIResponseV3WithTime,
AccountCoinBalanceV5,
AccountInfoV5,
AccountMarginModeV5,
AccountOrderV5,
AccountTypeV5,
AllCoinsBalanceV5,
AllowedDepositCoinInfoV5,
AmendOrderParamsV5,
ApiKeyInfoV5,
AssetInfoV5,
BatchAmendOrderParamsV5,
BatchAmendOrderResult,
BatchCancelOrderParamsV5,
BatchCancelOrderResult,
BatchOrderParamsV5,
BatchOrderResult,
BatchOrdersResult,
BorrowHistoryRecordV5,
CancelAllOrdersParamsV5,
CancelOrderParamsV5,
CategoryCursorListV5,
CategoryListV5, CategoryListV5,
CategorySymbolListV5,
CategoryV5, CategoryV5,
ClosedPnLV5,
CoinExchangeRecordV5,
CoinGreeksV5,
CoinInfoV5,
CollateralInfoV5,
CreateSubApiKeyParamsV5,
CreateSubApiKeyResultV5,
CreateSubMemberParamsV5,
CreateSubMemberResultV5,
CursorListV5,
DeliveryRecordV5,
DepositAddressResultV5,
DepositRecordV5,
ExecutionV5,
FeeRateV5,
FundingRateHistoryResponseV5, FundingRateHistoryResponseV5,
GetAccountCoinBalanceParamsV5,
GetAccountOrdersParams,
GetAllCoinsBalanceParamsV5,
GetAllowedDepositCoinInfoParamsV5,
GetAssetInfoParamsV5,
GetBorrowHistoryParamsV5,
GetClosedPnLParamsV5,
GetCoinExchangeRecordParamsV5,
GetDeliveryRecordParamsV5,
GetDepositRecordParamsV5,
GetExecutionListParamsV5,
GetFundingRateHistoryParamsV5, GetFundingRateHistoryParamsV5,
GetHistoricalVolatilityParamsV5, GetHistoricalVolatilityParamsV5,
GetIndexPriceKlineParamsV5, GetIndexPriceKlineParamsV5,
GetInstrumentsInfoParamsV5, GetInstrumentsInfoParamsV5,
GetInsuranceParamsV5, GetInsuranceParamsV5,
GetInternalTransferParamsV5,
GetKlineParamsV5, GetKlineParamsV5,
GetMarkPriceKlineParamsV5, GetMarkPriceKlineParamsV5,
GetOpenInterestParamsV5, GetOpenInterestParamsV5,
@@ -16,113 +66,63 @@ import {
GetPremiumIndexPriceKlineParams, GetPremiumIndexPriceKlineParams,
GetPublicTradingHistoryParamsV5, GetPublicTradingHistoryParamsV5,
GetRiskLimitParamsV5, GetRiskLimitParamsV5,
GetTickersParamsV5,
HistoricalVolatilityV5,
InsuranceResponseV5,
OpenInterestResponseV5,
OrderbookResponseV5,
OrderParamsV5,
CursorListV5,
PublicTradeV5,
RiskLimitV5,
AmendOrderParamsV5,
CancelOrderParamsV5,
GetAccountOrdersParams,
OrderResultV5,
CancelAllOrdersParamsV5,
BatchOrderParamsV5,
BatchAmendOrderParamsV5,
BatchOrderResult,
BatchOrdersResult,
BatchAmendOrderResult,
BatchCancelOrderParamsV5,
BatchCancelOrderResult,
OrderSideV5,
SpotBorrowCheckResult,
APIResponseV3,
PositionInfoParamsV5,
CategoryCursorListV5,
PositionV5,
AccountOrderV5,
OptionDeliveryPriceV5,
CategorySymbolListV5,
OHLCKlineV5,
OHLCVKlineV5,
TickerSpotV5,
TickerOptionV5,
TickerLinearInverseV5,
SetLeverageParamsV5,
SwitchIsolatedMarginParamsV5,
SetTPSLModeParamsV5,
TPSLModeV5,
SwitchPositionModeParamsV5,
SetRiskLimitParamsV5,
SetRiskLimitResultV5,
SetTradingStopParamsV5,
SetAutoAddMarginParamsV5,
GetExecutionListParamsV5,
ExecutionV5,
GetClosedPnLParamsV5,
ClosedPnLV5,
GetWalletBalanceParamsV5,
WalletBalanceV5,
UnifiedAccountUpgradeResultV5,
GetBorrowHistoryParamsV5,
BorrowHistoryRecordV5,
CollateralInfoV5,
CoinGreeksV5,
FeeRateV5,
AccountInfoV5,
GetTransactionLogParamsV5,
TransactionLogV5,
AccountMarginModeV5,
MMPModifyParamsV5,
MMPStateV5,
GetCoinExchangeRecordParamsV5,
CoinExchangeRecordV5,
GetDeliveryRecordParamsV5,
DeliveryRecordV5,
GetSettlementRecordParamsV5, GetSettlementRecordParamsV5,
SettlementRecordV5, GetSpotLeveragedTokenOrderHistoryParamsV5,
GetAssetInfoParamsV5,
AssetInfoV5,
GetAllCoinsBalanceParamsV5,
AllCoinsBalanceV5,
GetAccountCoinBalanceParamsV5,
AccountCoinBalanceV5,
AccountTypeV5,
GetInternalTransferParamsV5,
InternalTransferRecordV5,
UniversalTransferParamsV5,
GetUniversalTransferRecordsParamsV5,
UniversalTransferRecordV5,
GetAllowedDepositCoinInfoParamsV5,
AllowedDepositCoinInfoV5,
GetDepositRecordParamsV5,
DepositRecordV5,
GetSubAccountDepositRecordParamsV5, GetSubAccountDepositRecordParamsV5,
DepositAddressResultV5, GetTickersParamsV5,
CoinInfoV5, GetTransactionLogParamsV5,
GetUniversalTransferRecordsParamsV5,
GetWalletBalanceParamsV5,
GetWithdrawalRecordsParamsV5, GetWithdrawalRecordsParamsV5,
WithdrawalRecordV5, HistoricalVolatilityV5,
WithdrawParamsV5, InstrumentInfoResponseV5,
CreateSubMemberParamsV5, InsuranceResponseV5,
CreateSubMemberResultV5, InternalTransferRecordV5,
CreateSubApiKeyParamsV5,
CreateSubApiKeyResultV5,
SubMemberV5,
ApiKeyInfoV5,
UpdateApiKeyResultV5,
UpdateApiKeyParamsV5,
LeverageTokenInfoV5, LeverageTokenInfoV5,
LeveragedTokenMarketResultV5, LeveragedTokenMarketResultV5,
MMPModifyParamsV5,
MMPStateV5,
OHLCKlineV5,
OHLCVKlineV5,
OpenInterestResponseV5,
OptionDeliveryPriceV5,
OrderParamsV5,
OrderResultV5,
OrderSideV5,
OrderbookResponseV5,
PositionInfoParamsV5,
PositionV5,
PublicTradeV5,
PurchaseSpotLeveragedTokenParamsV5, PurchaseSpotLeveragedTokenParamsV5,
PurchaseSpotLeveragedTokenResultV5, PurchaseSpotLeveragedTokenResultV5,
RedeemSpotLeveragedTokenParamsV5, RedeemSpotLeveragedTokenParamsV5,
RedeemSpotLeveragedTokenResultV5, RedeemSpotLeveragedTokenResultV5,
GetSpotLeveragedTokenOrderHistoryParamsV5, RiskLimitV5,
SetAutoAddMarginParamsV5,
SetLeverageParamsV5,
SetRiskLimitParamsV5,
SetRiskLimitResultV5,
SetTPSLModeParamsV5,
SetTradingStopParamsV5,
SettlementRecordV5,
SpotBorrowCheckResult,
SpotLeveragedTokenOrderHistoryV5, SpotLeveragedTokenOrderHistoryV5,
InstrumentInfoResponseV5, SubMemberV5,
SwitchIsolatedMarginParamsV5,
SwitchPositionModeParamsV5,
TPSLModeV5,
TickerLinearInverseV5,
TickerOptionV5,
TickerSpotV5,
TransactionLogV5,
UnifiedAccountUpgradeResultV5,
UniversalTransferParamsV5,
UniversalTransferRecordV5,
UpdateApiKeyParamsV5,
UpdateApiKeyResultV5,
WalletBalanceV5,
WithdrawParamsV5,
WithdrawalRecordV5,
} from './types'; } from './types';
import { REST_CLIENT_TYPE_ENUM } from './util'; import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient'; import BaseRestClient from './util/BaseRestClient';
@@ -166,7 +166,7 @@ export class RestClientV5 extends BaseRestClient {
CategorySymbolListV5<OHLCVKlineV5[], 'spot' | 'linear' | 'inverse'> CategorySymbolListV5<OHLCVKlineV5[], 'spot' | 'linear' | 'inverse'>
> >
> { > {
return this.get(`/v5/market/kline`, params); return this.get('/v5/market/kline', params);
} }
/** /**
@@ -181,7 +181,7 @@ export class RestClientV5 extends BaseRestClient {
CategorySymbolListV5<OHLCKlineV5[], 'linear' | 'inverse'> CategorySymbolListV5<OHLCKlineV5[], 'linear' | 'inverse'>
> >
> { > {
return this.get(`/v5/market/mark-price-kline`, params); return this.get('/v5/market/mark-price-kline', params);
} }
/** /**
@@ -196,7 +196,7 @@ export class RestClientV5 extends BaseRestClient {
CategorySymbolListV5<OHLCKlineV5[], 'linear' | 'inverse'> CategorySymbolListV5<OHLCKlineV5[], 'linear' | 'inverse'>
> >
> { > {
return this.get(`/v5/market/index-price-kline`, params); return this.get('/v5/market/index-price-kline', params);
} }
/** /**
@@ -209,7 +209,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise< ): Promise<
APIResponseV3WithTime<CategorySymbolListV5<OHLCKlineV5[], 'linear'>> APIResponseV3WithTime<CategorySymbolListV5<OHLCKlineV5[], 'linear'>>
> { > {
return this.get(`/v5/market/premium-index-price-kline`, params); return this.get('/v5/market/premium-index-price-kline', params);
} }
/** /**
@@ -222,7 +222,7 @@ export class RestClientV5 extends BaseRestClient {
getInstrumentsInfo( getInstrumentsInfo(
params: GetInstrumentsInfoParamsV5 params: GetInstrumentsInfoParamsV5
): Promise<APIResponseV3WithTime<InstrumentInfoResponseV5>> { ): Promise<APIResponseV3WithTime<InstrumentInfoResponseV5>> {
return this.get(`/v5/market/instruments-info`, params); return this.get('/v5/market/instruments-info', params);
} }
/** /**
@@ -233,7 +233,7 @@ export class RestClientV5 extends BaseRestClient {
getOrderbook( getOrderbook(
params: GetOrderbookParamsV5 params: GetOrderbookParamsV5
): Promise<APIResponseV3WithTime<OrderbookResponseV5>> { ): Promise<APIResponseV3WithTime<OrderbookResponseV5>> {
return this.get(`/v5/market/orderbook`, params); return this.get('/v5/market/orderbook', params);
} }
/** /**
@@ -250,7 +250,7 @@ export class RestClientV5 extends BaseRestClient {
| CategoryListV5<TickerSpotV5[], 'spot'> | CategoryListV5<TickerSpotV5[], 'spot'>
> >
> { > {
return this.get(`/v5/market/tickers`, params); return this.get('/v5/market/tickers', params);
} }
/** /**
@@ -265,7 +265,7 @@ export class RestClientV5 extends BaseRestClient {
CategoryListV5<FundingRateHistoryResponseV5[], 'linear' | 'inverse'> CategoryListV5<FundingRateHistoryResponseV5[], 'linear' | 'inverse'>
> >
> { > {
return this.get(`/v5/market/funding/history`, params); return this.get('/v5/market/funding/history', params);
} }
/** /**
@@ -278,7 +278,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise< ): Promise<
APIResponseV3WithTime<CategoryListV5<PublicTradeV5[], CategoryV5>> APIResponseV3WithTime<CategoryListV5<PublicTradeV5[], CategoryV5>>
> { > {
return this.get(`/v5/market/recent-trade`, params); return this.get('/v5/market/recent-trade', params);
} }
/** /**
@@ -289,7 +289,7 @@ export class RestClientV5 extends BaseRestClient {
getOpenInterest( getOpenInterest(
params: GetOpenInterestParamsV5 params: GetOpenInterestParamsV5
): Promise<APIResponseV3WithTime<OpenInterestResponseV5>> { ): Promise<APIResponseV3WithTime<OpenInterestResponseV5>> {
return this.get(`/v5/market/open-interest`, params); return this.get('/v5/market/open-interest', params);
} }
/** /**
@@ -301,7 +301,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise< ): Promise<
APIResponseV3WithTime<CategoryListV5<HistoricalVolatilityV5[], 'option'>> APIResponseV3WithTime<CategoryListV5<HistoricalVolatilityV5[], 'option'>>
> { > {
return this.get(`/v5/market/historical-volatility`, params); return this.get('/v5/market/historical-volatility', params);
} }
/** /**
@@ -310,7 +310,7 @@ export class RestClientV5 extends BaseRestClient {
getInsurance( getInsurance(
params?: GetInsuranceParamsV5 params?: GetInsuranceParamsV5
): Promise<APIResponseV3WithTime<InsuranceResponseV5>> { ): Promise<APIResponseV3WithTime<InsuranceResponseV5>> {
return this.get(`/v5/market/insurance`, params); return this.get('/v5/market/insurance', params);
} }
/** /**
@@ -323,7 +323,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise< ): Promise<
APIResponseV3WithTime<CategoryListV5<RiskLimitV5[], 'inverse' | 'linear'>> APIResponseV3WithTime<CategoryListV5<RiskLimitV5[], 'inverse' | 'linear'>>
> { > {
return this.get(`/v5/market/risk-limit`, params); return this.get('/v5/market/risk-limit', params);
} }
/** /**
@@ -336,7 +336,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise< ): Promise<
APIResponseV3WithTime<CategoryCursorListV5<OptionDeliveryPriceV5[]>> APIResponseV3WithTime<CategoryCursorListV5<OptionDeliveryPriceV5[]>>
> { > {
return this.get(`/v5/market/delivery-price`, params); return this.get('/v5/market/delivery-price', params);
} }
/** /**
@@ -348,7 +348,7 @@ export class RestClientV5 extends BaseRestClient {
submitOrder( submitOrder(
params: OrderParamsV5 params: OrderParamsV5
): Promise<APIResponseV3WithTime<OrderResultV5>> { ): Promise<APIResponseV3WithTime<OrderResultV5>> {
return this.postPrivate(`/v5/order/create`, params); return this.postPrivate('/v5/order/create', params);
} }
amendOrder( amendOrder(
@@ -386,7 +386,7 @@ export class RestClientV5 extends BaseRestClient {
getHistoricOrders( getHistoricOrders(
params: GetAccountOrdersParams params: GetAccountOrdersParams
): Promise<APIResponseV3WithTime<CategoryCursorListV5<AccountOrderV5[]>>> { ): Promise<APIResponseV3WithTime<CategoryCursorListV5<AccountOrderV5[]>>> {
return this.getPrivate(`/v5/order/history`, params); return this.getPrivate('/v5/order/history', params);
} }
/** /**
@@ -573,6 +573,7 @@ export class RestClientV5 extends BaseRestClient {
): Promise<APIResponseV3WithTime<{}>> { ): Promise<APIResponseV3WithTime<{}>> {
return this.postPrivate('/v5/position/trading-stop', params); return this.postPrivate('/v5/position/trading-stop', params);
} }
/** /**
* This endpoint allows you to turn on/off auto-add-margin for an isolated margin position. * This endpoint allows you to turn on/off auto-add-margin for an isolated margin position.
* *
@@ -1175,7 +1176,7 @@ export class RestClientV5 extends BaseRestClient {
getLeveragedTokenMarket( getLeveragedTokenMarket(
ltCoin: string ltCoin: string
): Promise<APIResponseV3WithTime<LeveragedTokenMarketResultV5>> { ): Promise<APIResponseV3WithTime<LeveragedTokenMarketResultV5>> {
return this.get(`/v5/spot-lever-token/reference`, { ltCoin }); return this.get('/v5/spot-lever-token/reference', { ltCoin });
} }
/** /**

View File

@@ -1,17 +1,16 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
APIResponseWithTime,
APIResponseV3, APIResponseV3,
SpotOrderQueryById, APIResponseWithTime,
OrderSide,
OrderTypeSpot,
SpotBalances,
KlineInterval, KlineInterval,
NewSpotOrderV3, NewSpotOrderV3,
SpotMyTradesRequest, SpotBalances,
SpotLeveragedTokenPRHistoryRequest, SpotCancelOrderBatchRequest,
SpotCrossMarginBorrowingInfoRequest, SpotCrossMarginBorrowingInfoRequest,
SpotCrossMarginRepaymentHistoryRequest, SpotCrossMarginRepaymentHistoryRequest,
SpotCancelOrderBatchRequest, SpotLeveragedTokenPRHistoryRequest,
SpotMyTradesRequest,
SpotOrderQueryById,
} from './types'; } from './types';
import { REST_CLIENT_TYPE_ENUM } from './util'; import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient'; import BaseRestClient from './util/BaseRestClient';

View File

@@ -1,7 +1,8 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
NewSpotOrder,
APIResponse, APIResponse,
KlineInterval, KlineInterval,
NewSpotOrder,
OrderSide, OrderSide,
OrderTypeSpot, OrderTypeSpot,
SpotBalances, SpotBalances,
@@ -87,7 +88,9 @@ export class SpotClient extends BaseRestClient {
} }
getLastTradedPrice(): Promise<APIResponse<SpotLastPrice[]>>; getLastTradedPrice(): Promise<APIResponse<SpotLastPrice[]>>;
getLastTradedPrice(symbol: string): Promise<APIResponse<SpotLastPrice>>; getLastTradedPrice(symbol: string): Promise<APIResponse<SpotLastPrice>>;
getLastTradedPrice( getLastTradedPrice(
symbol?: string symbol?: string
): Promise<APIResponse<SpotLastPrice | SpotLastPrice[]>> { ): Promise<APIResponse<SpotLastPrice | SpotLastPrice[]>> {

View File

@@ -1,4 +1,4 @@
import { numberInString, OrderSide } from '../shared'; import { OrderSide, numberInString } from '../shared';
export type OrderTypeSpot = 'LIMIT' | 'MARKET' | 'LIMIT_MAKER'; export type OrderTypeSpot = 'LIMIT' | 'MARKET' | 'LIMIT_MAKER';
export type OrderTimeInForce = 'GTC' | 'FOK' | 'IOC'; export type OrderTimeInForce = 'GTC' | 'FOK' | 'IOC';

View File

@@ -1,3 +1,4 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
export interface PaginatedResult<TList = any> { export interface PaginatedResult<TList = any> {
nextPageCursor: string; nextPageCursor: string;
list: TList[]; list: TList[];

View File

@@ -1,3 +1,4 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface UMPaginatedResult<List = any> { export interface UMPaginatedResult<List = any> {
nextPageCursor: string; nextPageCursor: string;
category: string; category: string;

View File

@@ -251,6 +251,7 @@ export interface RiskLimitV5 {
riskLimitValue: string; riskLimitValue: string;
maintenanceMargin: number; maintenanceMargin: number;
initialMargin: number; initialMargin: number;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
section: any; section: any;
isLowestRisk: 0 | 1; isLowestRisk: 0 | 1;
maxLeverage: string; maxLeverage: string;

View File

@@ -1,7 +1,7 @@
import { import {
LeverageTokenStatusV5,
LTOrderStatusV5, LTOrderStatusV5,
LTOrderTypeV5, LTOrderTypeV5,
LeverageTokenStatusV5,
} from '../v5-shared'; } from '../v5-shared';
export interface LeverageTokenInfoV5 { export interface LeverageTokenInfoV5 {

View File

@@ -71,9 +71,9 @@ export type StopOrderTypeV5 =
/** /**
* Position index. Used to identify positions in different position modes. * Position index. Used to identify positions in different position modes.
* *
* - 0one-way mode position * - 0 one-way mode position
* - 1Buy side of hedge-mode position * - 1 Buy side of hedge-mode position
* - 2Sell side of hedge-mode position * - 2 Sell side of hedge-mode position
*/ */
export type PositionIdx = 0 | 1 | 2; export type PositionIdx = 0 | 1 | 2;
@@ -124,15 +124,11 @@ export type PermissionTypeV5 =
/** /**
* Leveraged token status: * Leveraged token status:
* *
* 1LT can be purchased and redeemed * - '1' LT can be purchased and redeemed
* * - '2' LT can be purchased, but not redeemed
* 2LT can be purchased, but not redeemed * - '3' LT can be redeemed, but not purchased
* * - '4' LT cannot be purchased nor redeemed
* 3LT can be redeemed, but not purchased * - '5' Adjusting position
*
* 4LT cannot be purchased nor redeemed
*
* 5Adjusting position
*/ */
export type LeverageTokenStatusV5 = '1' | '2' | '3' | '4' | '5'; export type LeverageTokenStatusV5 = '1' | '2' | '3' | '4' | '5';

View File

@@ -98,6 +98,7 @@ export interface WSClientConfigurableOptions {
pingInterval?: number; pingInterval?: number;
reconnectTimeout?: number; reconnectTimeout?: number;
restOptions?: RestClientOptions; restOptions?: RestClientOptions;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
requestOptions?: any; requestOptions?: any;
wsUrl?: string; wsUrl?: string;
/** If true, fetch server time before trying to authenticate (disabled by default) */ /** If true, fetch server time before trying to authenticate (disabled by default) */

View File

@@ -1,34 +1,35 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
APIResponseWithTime,
APIResponseV3, APIResponseV3,
UMCategory, APIResponseWithTime,
UMCandlesRequest,
UMInstrumentInfoRequest,
UMFundingRateHistoryRequest,
UMOptionDeliveryPriceRequest,
UMPublicTradesRequest,
UMOpenInterestRequest,
UMOrderRequest,
UMModifyOrderRequest,
UMCancelOrderRequest,
UMActiveOrdersRequest,
UMHistoricOrdersRequest,
UMBatchOrder,
UMBatchOrderReplace,
UMBatchOrderCancel,
UMCancelAllOrdersRequest,
UMPositionsRequest,
UMSetTPSLRequest,
UM7DayTradingHistoryRequest,
UMOptionsSettlementHistoryRequest,
UMPerpSettlementHistoryRequest,
UMTransactionLogRequest,
InternalTransferRequest, InternalTransferRequest,
UMExchangeCoinsRequest, UM7DayTradingHistoryRequest,
UMActiveOrdersRequest,
UMBatchOrder,
UMBatchOrderCancel,
UMBatchOrderReplace,
UMBorrowHistoryRequest, UMBorrowHistoryRequest,
UMPaginatedResult, UMCancelAllOrdersRequest,
UMCancelOrderRequest,
UMCandlesRequest,
UMCategory,
UMExchangeCoinsRequest,
UMFundingRateHistoryRequest,
UMHistoricOrder, UMHistoricOrder,
UMHistoricOrdersRequest,
UMInstrumentInfo, UMInstrumentInfo,
UMInstrumentInfoRequest,
UMModifyOrderRequest,
UMOpenInterestRequest,
UMOptionDeliveryPriceRequest,
UMOptionsSettlementHistoryRequest,
UMOrderRequest,
UMPaginatedResult,
UMPerpSettlementHistoryRequest,
UMPositionsRequest,
UMPublicTradesRequest,
UMSetTPSLRequest,
UMTransactionLogRequest,
} from './types'; } from './types';
import { REST_CLIENT_TYPE_ENUM } from './util'; import { REST_CLIENT_TYPE_ENUM } from './util';
import BaseRestClient from './util/BaseRestClient'; import BaseRestClient from './util/BaseRestClient';

View File

@@ -1,6 +1,7 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
APIResponseWithTime,
APIResponseV3, APIResponseV3,
APIResponseWithTime,
USDCOptionsActiveOrdersRealtimeRequest, USDCOptionsActiveOrdersRealtimeRequest,
USDCOptionsActiveOrdersRequest, USDCOptionsActiveOrdersRequest,
USDCOptionsCancelAllOrdersRequest, USDCOptionsCancelAllOrdersRequest,
@@ -8,8 +9,8 @@ import {
USDCOptionsContractInfoRequest, USDCOptionsContractInfoRequest,
USDCOptionsDeliveryHistoryRequest, USDCOptionsDeliveryHistoryRequest,
USDCOptionsDeliveryPriceRequest, USDCOptionsDeliveryPriceRequest,
USDCOptionsHistoricalVolatilityRequest,
USDCOptionsHistoricOrdersRequest, USDCOptionsHistoricOrdersRequest,
USDCOptionsHistoricalVolatilityRequest,
USDCOptionsModifyMMPRequest, USDCOptionsModifyMMPRequest,
USDCOptionsModifyOrderRequest, USDCOptionsModifyOrderRequest,
USDCOptionsOrderExecutionRequest, USDCOptionsOrderExecutionRequest,
@@ -203,7 +204,11 @@ export class USDCOptionClient extends BaseRestClient {
); );
} }
/** Query trade history. The endpoint only supports up to 30 days of queried records. An error will be returned if startTime is more than 30 days. */ /**
* Query trade history.
* The endpoint only supports up to 30 days of queried records.
* An error will be returned if startTime is more than 30 days.
*/
getOrderExecutionHistory( getOrderExecutionHistory(
params: USDCOptionsOrderExecutionRequest params: USDCOptionsOrderExecutionRequest
): Promise<APIResponseV3<any>> { ): Promise<APIResponseV3<any>> {
@@ -241,7 +246,9 @@ export class USDCOptionClient extends BaseRestClient {
} }
/** /**
* If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN, and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN. X and Y will be adjusted according to operational requirements. * If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN,
* and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN.
* X and Y will be adjusted according to operational requirements.
* Rest API returns the result of checking prerequisites. You could get the real status of margin mode change by subscribing margin mode. * Rest API returns the result of checking prerequisites. You could get the real status of margin mode change by subscribing margin mode.
*/ */
setMarginMode( setMarginMode(

View File

@@ -1,8 +1,9 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { import {
APIResponseV3,
APIResponseWithTime, APIResponseWithTime,
SymbolLimitParam, SymbolLimitParam,
SymbolPeriodLimitParam, SymbolPeriodLimitParam,
APIResponseV3,
USDCKlineRequest, USDCKlineRequest,
USDCLast500TradesRequest, USDCLast500TradesRequest,
USDCOpenInterestRequest, USDCOpenInterestRequest,
@@ -213,7 +214,9 @@ export class USDCPerpetualClient extends BaseRestClient {
} }
/** /**
* If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN, and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN. X and Y will be adjusted according to operational requirements. * If USDC derivatives account balance is greater than X, you can open PORTFOLIO_MARGIN,
* and if it is less than Y, it will automatically close PORTFOLIO_MARGIN and change back to REGULAR_MARGIN.
* X and Y will be adjusted according to operational requirements.
* Rest API returns the result of checking prerequisites. You could get the real status of margin mode change by subscribing margin mode. * Rest API returns the result of checking prerequisites. You could get the real status of margin mode change by subscribing margin mode.
*/ */
setMarginMode( setMarginMode(

View File

@@ -1,14 +1,15 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios'; import axios, { AxiosRequestConfig, AxiosResponse, Method } from 'axios';
import { signMessage } from './node-support';
import { import {
RestClientOptions,
serializeParams,
RestClientType,
REST_CLIENT_TYPE_ENUM,
APIID, APIID,
REST_CLIENT_TYPE_ENUM,
RestClientOptions,
RestClientType,
getRestBaseUrl, getRestBaseUrl,
serializeParams,
} from './requestUtils'; } from './requestUtils';
import { signMessage } from './node-support';
// axios.interceptors.request.use((request) => { // axios.interceptors.request.use((request) => {
// console.log(new Date(), 'Starting Request', JSON.stringify(request, null, 2)); // console.log(new Date(), 'Starting Request', JSON.stringify(request, null, 2));
@@ -48,7 +49,7 @@ interface SignedRequestContext {
} }
interface SignedRequest<T> { interface SignedRequest<T> {
originalParams: T & SignedRequestContext; originalParams: (T & SignedRequestContext) | SignedRequestContext;
paramsWithSign?: T & SignedRequestContext & { sign: string }; paramsWithSign?: T & SignedRequestContext & { sign: string };
serializedParams: string; serializedParams: string;
sign: string; sign: string;
@@ -65,12 +66,19 @@ type SignMethod = 'keyInBody' | 'usdc';
export default abstract class BaseRestClient { export default abstract class BaseRestClient {
private timeOffset: number | null = null; private timeOffset: number | null = null;
private syncTimePromise: null | Promise<any> = null; private syncTimePromise: null | Promise<any> = null;
private options: RestClientOptions; private options: RestClientOptions;
private baseUrl: string; private baseUrl: string;
private globalRequestOptions: AxiosRequestConfig; private globalRequestOptions: AxiosRequestConfig;
private key: string | undefined; private key: string | undefined;
private secret: string | undefined; private secret: string | undefined;
private clientType: RestClientType; private clientType: RestClientType;
/** Function that calls exchange API to query & resolve server time, used by time sync, disabled by default */ /** Function that calls exchange API to query & resolve server time, used by time sync, disabled by default */
@@ -159,13 +167,15 @@ export default abstract class BaseRestClient {
params?: TParams, params?: TParams,
isPublicApi?: true isPublicApi?: true
): Promise<UnsignedRequest<TParams>>; ): Promise<UnsignedRequest<TParams>>;
private async prepareSignParams<TParams = any>( private async prepareSignParams<TParams = any>(
method: Method, method: Method,
signMethod: SignMethod, signMethod: SignMethod,
params?: TParams, params?: TParams,
isPublicApi?: false | undefined isPublicApi?: false | undefined
): Promise<SignedRequest<TParams>>; ): Promise<SignedRequest<TParams>>;
private async prepareSignParams<TParams = any>(
private async prepareSignParams<TParams extends SignedRequestContext = any>(
method: Method, method: Method,
signMethod: SignMethod, signMethod: SignMethod,
params?: TParams, params?: TParams,
@@ -186,7 +196,7 @@ export default abstract class BaseRestClient {
await this.syncTime(); await this.syncTime();
} }
return this.signRequest(params, method, signMethod); return this.signRequest(params || {}, method, signMethod);
} }
/** Returns an axios request object. Handles signing process automatically if this is a private API call */ /** Returns an axios request object. Handles signing process automatically if this is a private API call */
@@ -336,7 +346,7 @@ export default abstract class BaseRestClient {
/** /**
* @private sign request and set recv window * @private sign request and set recv window
*/ */
private async signRequest<T = {}>( private async signRequest<T extends SignedRequestContext | {} = {}>(
data: T, data: T,
method: Method, method: Method,
signMethod: SignMethod signMethod: SignMethod
@@ -409,10 +419,13 @@ export default abstract class BaseRestClient {
encodeValues encodeValues
); );
res.sign = await signMessage(res.serializedParams, this.secret); res.sign = await signMessage(res.serializedParams, this.secret);
// @ts-ignore
res.paramsWithSign = { res.paramsWithSign = {
...res.originalParams, ...res.originalParams,
sign: res.sign, sign: res.sign,
}; };
return res; return res;
} }

View File

@@ -16,7 +16,8 @@ type WsTopic = string;
/** /**
* A "Set" is used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to) * A "Set" is used to ensure we only subscribe to a topic once (tracking a list of unique topics we're expected to be connected to)
* Note: Accurate duplicate tracking only works for plaintext topics. E.g. JSON objects may not be seen as duplicates if keys are in different orders. If that's needed, check the FTX implementation. * Note: Accurate duplicate tracking only works for plaintext topics.
* E.g. JSON objects may not be seen as duplicates if keys are in different orders. If that's needed, check the FTX implementation.
*/ */
type WsTopicList = Set<WsTopic>; type WsTopicList = Set<WsTopic>;
@@ -39,6 +40,7 @@ interface WsStoredState {
export default class WsStore { export default class WsStore {
private wsState: Record<string, WsStoredState>; private wsState: Record<string, WsStoredState>;
private logger: typeof DefaultLogger; private logger: typeof DefaultLogger;
constructor(logger: typeof DefaultLogger) { constructor(logger: typeof DefaultLogger) {
@@ -48,7 +50,9 @@ export default class WsStore {
/** Get WS stored state for key, optionally create if missing */ /** Get WS stored state for key, optionally create if missing */
get(key: WsKey, createIfMissing?: true): WsStoredState; get(key: WsKey, createIfMissing?: true): WsStoredState;
get(key: WsKey, createIfMissing?: false): WsStoredState | undefined; get(key: WsKey, createIfMissing?: false): WsStoredState | undefined;
get(key: WsKey, createIfMissing?: boolean): WsStoredState | undefined { get(key: WsKey, createIfMissing?: boolean): WsStoredState | undefined {
if (this.wsState[key]) { if (this.wsState[key]) {
return this.wsState[key]; return this.wsState[key];

View File

@@ -3,6 +3,7 @@ export async function signMessage(
secret: string secret: string
): Promise<string> { ): Promise<string> {
const encoder = new TextEncoder(); const encoder = new TextEncoder();
// eslint-disable-next-line no-undef
const key = await window.crypto.subtle.importKey( const key = await window.crypto.subtle.importKey(
'raw', 'raw',
encoder.encode(secret), encoder.encode(secret),
@@ -11,6 +12,7 @@ export async function signMessage(
['sign'] ['sign']
); );
// eslint-disable-next-line no-undef
const signature = await window.crypto.subtle.sign( const signature = await window.crypto.subtle.sign(
'HMAC', 'HMAC',
key, key,
@@ -18,7 +20,9 @@ export async function signMessage(
); );
return Array.prototype.map return Array.prototype.map
.call(new Uint8Array(signature), (x: any) => .call(
new Uint8Array(signature),
(x: { toString: (arg0: number) => string }) =>
('00' + x.toString(16)).slice(-2) ('00' + x.toString(16)).slice(-2)
) )
.join(''); .join('');

View File

@@ -1,3 +1,4 @@
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type LogParams = null | any; export type LogParams = null | any;
export const DefaultLogger = { export const DefaultLogger = {

View File

@@ -91,6 +91,7 @@ export function getRestBaseUrl(
return exchangeBaseUrls.livenet; return exchangeBaseUrls.livenet;
} }
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isWsPong(msg: any): boolean { export function isWsPong(msg: any): boolean {
if (!msg) { if (!msg) {
return false; return false;

View File

@@ -298,7 +298,7 @@ export function getWsKeyForTopic(
: WS_KEY_MAP.contractUSDTPublic; : WS_KEY_MAP.contractUSDTPublic;
} }
default: { default: {
throw neverGuard(market, `getWsKeyForTopic(): Unhandled market`); throw neverGuard(market, 'getWsKeyForTopic(): Unhandled market');
} }
} }
} }
@@ -322,7 +322,7 @@ export function getMaxTopicsPerSubscribeEvent(
return 10; return 10;
} }
default: { default: {
throw neverGuard(market, `getWsKeyForTopic(): Unhandled market`); throw neverGuard(market, 'getWsKeyForTopic(): Unhandled market');
} }
} }
} }

View File

@@ -1,3 +1,5 @@
/* eslint-disable max-len */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { EventEmitter } from 'events'; import { EventEmitter } from 'events';
import WebSocket from 'isomorphic-ws'; import WebSocket from 'isomorphic-ws';
@@ -17,24 +19,24 @@ import {
APIMarket, APIMarket,
KlineInterval, KlineInterval,
RESTClient, RESTClient,
WebsocketClientOptions,
WSClientConfigurableOptions, WSClientConfigurableOptions,
WebsocketClientOptions,
WsKey, WsKey,
WsTopic, WsTopic,
} from './types'; } from './types';
import { import {
serializeParams, DefaultLogger,
isWsPong,
WsConnectionStateEnum,
PUBLIC_WS_KEYS, PUBLIC_WS_KEYS,
WS_AUTH_ON_CONNECT_KEYS, WS_AUTH_ON_CONNECT_KEYS,
WS_KEY_MAP,
DefaultLogger,
WS_BASE_URL_MAP, WS_BASE_URL_MAP,
getWsKeyForTopic, WS_KEY_MAP,
neverGuard, WsConnectionStateEnum,
getMaxTopicsPerSubscribeEvent, getMaxTopicsPerSubscribeEvent,
getWsKeyForTopic,
isWsPong,
neverGuard,
serializeParams,
} from './util'; } from './util';
const loggerCategory = { category: 'bybit-ws' }; const loggerCategory = { category: 'bybit-ws' };
@@ -78,10 +80,14 @@ export declare interface WebsocketClient {
): boolean; ): boolean;
} }
// eslint-disable-next-line no-redeclare
export class WebsocketClient extends EventEmitter { export class WebsocketClient extends EventEmitter {
private logger: typeof DefaultLogger; private logger: typeof DefaultLogger;
private restClient?: RESTClient; private restClient?: RESTClient;
private options: WebsocketClientOptions; private options: WebsocketClientOptions;
private wsStore: WsStore; private wsStore: WsStore;
constructor( constructor(
@@ -109,6 +115,7 @@ export class WebsocketClient extends EventEmitter {
this.prepareRESTClient(); this.prepareRESTClient();
// add default error handling so this doesn't crash node (if the user didn't set a handler) // add default error handling so this doesn't crash node (if the user didn't set a handler)
// eslint-disable-next-line @typescript-eslint/no-empty-function
this.on('error', () => {}); this.on('error', () => {});
} }
@@ -247,7 +254,7 @@ export class WebsocketClient extends EventEmitter {
default: { default: {
throw neverGuard( throw neverGuard(
this.options.market, this.options.market,
`prepareRESTClient(): Unhandled market` 'prepareRESTClient(): Unhandled market'
); );
} }
} }
@@ -304,7 +311,7 @@ export class WebsocketClient extends EventEmitter {
return [...this.connectPublic(), this.connectPrivate()]; return [...this.connectPublic(), this.connectPrivate()];
} }
default: { default: {
throw neverGuard(this.options.market, `connectAll(): Unhandled market`); throw neverGuard(this.options.market, 'connectAll(): Unhandled market');
} }
} }
} }
@@ -345,7 +352,7 @@ export class WebsocketClient extends EventEmitter {
default: { default: {
throw neverGuard( throw neverGuard(
this.options.market, this.options.market,
`connectPublic(): Unhandled market` 'connectPublic(): Unhandled market'
); );
} }
} }
@@ -382,7 +389,7 @@ export class WebsocketClient extends EventEmitter {
default: { default: {
throw neverGuard( throw neverGuard(
this.options.market, this.options.market,
`connectPrivate(): Unhandled market` 'connectPrivate(): Unhandled market'
); );
} }
} }
@@ -517,7 +524,7 @@ export class WebsocketClient extends EventEmitter {
'Cannot authenticate websocket, either api or private keys missing.', 'Cannot authenticate websocket, either api or private keys missing.',
{ ...loggerCategory, wsKey } { ...loggerCategory, wsKey }
); );
throw new Error(`Cannot auth - missing api or secret in config`); throw new Error('Cannot auth - missing api or secret in config');
} }
this.logger.debug("Getting auth'd request params", { this.logger.debug("Getting auth'd request params", {
@@ -660,7 +667,7 @@ export class WebsocketClient extends EventEmitter {
this.logger.silly( this.logger.silly(
`Subscribing to topics in batches of ${maxTopicsPerEvent}` `Subscribing to topics in batches of ${maxTopicsPerEvent}`
); );
for (var i = 0; i < topics.length; i += maxTopicsPerEvent) { for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
const batch = topics.slice(i, i + maxTopicsPerEvent); const batch = topics.slice(i, i + maxTopicsPerEvent);
this.logger.silly(`Subscribing to batch of ${batch.length}`); this.logger.silly(`Subscribing to batch of ${batch.length}`);
this.requestSubscribeTopics(wsKey, batch); this.requestSubscribeTopics(wsKey, batch);
@@ -695,7 +702,7 @@ export class WebsocketClient extends EventEmitter {
this.logger.silly( this.logger.silly(
`Unsubscribing to topics in batches of ${maxTopicsPerEvent}` `Unsubscribing to topics in batches of ${maxTopicsPerEvent}`
); );
for (var i = 0; i < topics.length; i += maxTopicsPerEvent) { for (let i = 0; i < topics.length; i += maxTopicsPerEvent) {
const batch = topics.slice(i, i + maxTopicsPerEvent); const batch = topics.slice(i, i + maxTopicsPerEvent);
this.logger.silly(`Unsubscribing to batch of ${batch.length}`); this.logger.silly(`Unsubscribing to batch of ${batch.length}`);
this.requestUnsubscribeTopics(wsKey, batch); this.requestUnsubscribeTopics(wsKey, batch);
@@ -716,7 +723,7 @@ export class WebsocketClient extends EventEmitter {
public tryWsSend(wsKey: WsKey, wsMessage: string) { public tryWsSend(wsKey: WsKey, wsMessage: string) {
try { try {
this.logger.silly(`Sending upstream ws message: `, { this.logger.silly('Sending upstream ws message: ', {
...loggerCategory, ...loggerCategory,
wsMessage, wsMessage,
wsKey, wsKey,
@@ -734,7 +741,7 @@ export class WebsocketClient extends EventEmitter {
} }
ws.send(wsMessage); ws.send(wsMessage);
} catch (e) { } catch (e) {
this.logger.error(`Failed to send WS message`, { this.logger.error('Failed to send WS message', {
...loggerCategory, ...loggerCategory,
wsMessage, wsMessage,
wsKey, wsKey,
@@ -782,7 +789,7 @@ export class WebsocketClient extends EventEmitter {
// Some websockets require an auth packet to be sent after opening the connection // Some websockets require an auth packet to be sent after opening the connection
if (WS_AUTH_ON_CONNECT_KEYS.includes(wsKey)) { if (WS_AUTH_ON_CONNECT_KEYS.includes(wsKey)) {
this.logger.info(`Sending auth request...`); this.logger.info('Sending auth request...');
await this.sendAuthRequest(wsKey); await this.sendAuthRequest(wsKey);
} }
@@ -955,7 +962,7 @@ export class WebsocketClient extends EventEmitter {
...loggerCategory, ...loggerCategory,
wsKey, wsKey,
}); });
throw neverGuard(wsKey, `getWsUrl(): Unhandled wsKey`); throw neverGuard(wsKey, 'getWsUrl(): Unhandled wsKey');
} }
} }
} }
@@ -1051,7 +1058,7 @@ export class WebsocketClient extends EventEmitter {
case 'merge': { case 'merge': {
topic = 'mergedDepth'; topic = 'mergedDepth';
if (!dumpScale) { if (!dumpScale) {
throw new Error(`Dumpscale must be provided for merged orderbooks`); throw new Error('Dumpscale must be provided for merged orderbooks');
} }
break; break;
} }

View File

@@ -13,14 +13,9 @@
"skipLibCheck": true, "skipLibCheck": true,
"sourceMap": true, "sourceMap": true,
"esModuleInterop": true, "esModuleInterop": true,
"lib": ["es2017","dom"], "lib": ["es2017", "dom"],
"outDir": "lib" "outDir": "lib"
}, },
"include": ["src/**/*"], "include": ["src/**/*"],
"exclude": [ "exclude": ["node_modules", "**/node_modules/*", "coverage", "doc"]
"node_modules",
"**/node_modules/*",
"coverage",
"doc"
]
} }