UNPKG

@bcswaper/apis

Version:

bcswaper apis

1 lines 7.24 kB
import{IndexerConfig,ValidatorConfig,Network,IndexerClient,SocketClient,ValidatorClient,CompositeClient,LocalWallet,BECH32_PREFIX,SubaccountInfo,Order_TimeInForce,OrderExecution,OrderFlags,OrderSide,OrderTimeInForce,OrderType}from"@dydxprotocol/v4-client-js";import{CandlesResolution,IncomingMessageTypes}from"@dydxprotocol/v4-client-js/build/src/clients/socket-client";import{SubTypes}from"../clientContext";import{MarketsHandler}from"./marketsHandler";import{AccountHandler}from"./accountHandler";import{OrderbookHandler}from"./orderbookHandler";import{CandleResolution}from"../../swapContext";import{CandlesHandler}from"./candlesHandler";import{TradesHandler}from"./tradesHandler";import{clientCallBackFuncs,clientCandleMap,convertResolution,resetContext}from"./dydxContext";export class dydxClient{constructor(e){this.running=!1,this.mainnetIndexerConfig=new IndexerConfig("https://indexer.dydx.trade/","wss://indexer.dydx.trade/v4/ws"),this.mainnetValidatorConfig=new ValidatorConfig("https://dydx-dao-archive-rpc.polkachu.com","dydx-mainnet-1",{USDC_DENOM:"ibc/8E27BA2D5493AF5636760E354E46004562C46AB7EC0CC4C1CA14E9E20E2545B5",USDC_DECIMALS:6,USDC_GAS_DENOM:"uusdc",CHAINTOKEN_DENOM:"adydx",CHAINTOKEN_DECIMALS:18}),this.mainnetNetwork=new Network("mainnet",this.mainnetIndexerConfig,this.mainnetValidatorConfig),this.clientParams=e,this.accountHandler=new AccountHandler(this.clientParams.symbol,"USDC"),this.candlesHandler=new CandlesHandler(this.clientParams.symbol),this.marketsHandler=new MarketsHandler(this.clientParams.symbol),this.orderbookHandler=new OrderbookHandler(this.clientParams.symbol),this.tradesHandler=new TradesHandler(this.clientParams.symbol)}async initialize(){console.log("initializing ..."),this.indexerClient=new IndexerClient(this.mainnetNetwork.indexerConfig),this.validatorClient=await ValidatorClient.connect(this.mainnetNetwork.validatorConfig),this.compositeClient=await CompositeClient.connect(this.mainnetNetwork),this.localWallet=await LocalWallet.fromMnemonic(this.clientParams.mnemonic,BECH32_PREFIX),this.subaccount=new SubaccountInfo(this.localWallet,0),this.createSocketClient(),this.running=!0,console.log("done.")}createSocketClient(){this.socketClient=new SocketClient(this.mainnetNetwork.indexerConfig,(()=>{console.log("socket client opened."),console.log("subscribed to dydx account ..."),console.log("clientCallBackFuncs ...",clientCallBackFuncs),this.socketClient?.subscribeToSubaccount(this.clientParams.address,0),clientCallBackFuncs.tickFunc&&this.socketClient?.subscribeToCandles(this.clientParams.symbol,CandlesResolution.ONE_DAY),clientCallBackFuncs.orderBookFunc&&(console.log("subscribed to dydx orderbook ..."),this.socketClient?.subscribeToOrderbook(this.clientParams.symbol)),clientCallBackFuncs.tradesFunc&&(console.log("subscribe to trade ... "),this.socketClient?.subscribeToTrades(this.clientParams.symbol)),console.log("clientCandleMap ...",clientCandleMap),clientCandleMap?.forEach(((e,n)=>{if(n==CandleResolution.DAY1)return;const t=convertResolution(n);t&&(console.log("subscribed candle: ",n),this.socketClient?.subscribeToCandles(this.clientParams.symbol,t))}))}),(()=>{console.log("socket client closed."),this.running&&(console.log("reconnecting ..."),this.socketClient?.connect())}),(e=>{if("string"!=typeof e.data)return void console.error("error data received ",e);const n=e.data;try{const e=JSON.parse(n),t=e.channel;switch(console.log(`========== type : ${e.type}, channel: ${t}, data: \n ${n}`),e.type){case IncomingMessageTypes.CONNECTED:console.log("socket client connected.");break;case IncomingMessageTypes.SUBSCRIBED:switch(t){case ChannelTypes.Subaccounts:this.accountHandler.initialize(e);break;case ChannelTypes.Markets:this.marketsHandler.initialize(e);break;case ChannelTypes.Orderbook:this.orderbookHandler.initialize(e);break;case ChannelTypes.Candles:this.candlesHandler.initialize(e);break;case ChannelTypes.Trades:this.tradesHandler.initialize(e);break;default:console.error("unexpected channel: ",t)}break;case IncomingMessageTypes.CHANNEL_DATA:break;case IncomingMessageTypes.CHANNEL_BATCH_DATA:switch(t){case ChannelTypes.Subaccounts:this.accountHandler.update(e);break;case ChannelTypes.Markets:this.marketsHandler.update(e);break;case ChannelTypes.Orderbook:this.orderbookHandler.update(e);break;case ChannelTypes.Candles:this.candlesHandler.update(e);break;case ChannelTypes.Trades:this.tradesHandler.update(e);break;default:console.log("unexpected channel: ",t)}break;default:console.log("received unknown message",e)}}catch(e){console.error("error resolving websocket message:",e)}}),(e=>{console.error("socket client error:",e)})),this.socketClient.connect()}subscribe(e,n){switch(e){case SubTypes.Account:clientCallBackFuncs.accountFunc=n;break;case SubTypes.Position:clientCallBackFuncs.positionFunc=n;break;case SubTypes.Order:clientCallBackFuncs.orderFunc=n;break;case SubTypes.Deal:clientCallBackFuncs.dealFunc=n;break;case SubTypes.Tick:clientCallBackFuncs.tickFunc=n;break;case SubTypes.Orderbook:clientCallBackFuncs.orderBookFunc=n;break;case SubTypes.Trades:clientCallBackFuncs.tradesFunc=n;break;default:console.error("error subscribing: ",e)}}subscribeCandle(e,n){clientCallBackFuncs.candleFunc=n,clientCandleMap.set(e,1)}getClientId(){return Date.now()}async calculateGoodTilBlock(){return this.validatorClient?this.validatorClient.get.latestBlockHeight().then((e=>e+20)).catch((e=>{throw console.error("error fetching block height:",e),e})):0}getPrice(){return this.candlesHandler.getPrice()||0}getOrderbook(){return this.orderbookHandler.getOrderbook()}getPosition(){return this.accountHandler.getPosition()}async marketOrder(e,n,t){const o=this.getClientId(),r=n*(e==OrderSide.BUY?1.0005:.9995);console.log(`market order: side : ${e}, price: ${n}/${r}, dasizeta: ${t}`),this.calculateGoodTilBlock().then((n=>{this.compositeClient?.placeShortTermOrder(this.subaccount,this.clientParams.symbol,e,r,t,o,n,Order_TimeInForce.TIME_IN_FORCE_UNSPECIFIED,!1).catch((e=>console.error("Error placing short term market order:",e)))})).catch((e=>console.error("Error calculating good til block on market order:",e)))}async limitOrder(e,n,t,o){console.log(`limit order: side : ${e}, price: ${n}, dasizeta: ${t}, goodTillTime: ${o}`);const r=this.getClientId(),s=OrderType.LIMIT,a=OrderTimeInForce.GTT,l=OrderExecution.POST_ONLY;this.compositeClient?.placeOrder(this.subaccount,this.clientParams.symbol,s,e,n,t,r,a,o,l,!0,!1).catch((e=>console.error("error placing long term post-only order:",e)))}async cancelOrderLongTerm(e,n){console.log(`cancel order: id : ${e}, goodTillTime: ${n}`);const t=OrderFlags.LONG_TERM,o=n-Date.now()/1e3;this.compositeClient?.cancelOrder(this.subaccount,e,t,this.clientParams.symbol,0,o).catch((e=>console.error("error cancelling long term order:",e)))}destroy(){console.log("dydx client release ..."),this.running=!1,delete this.indexerClient,delete this.validatorClient,delete this.compositeClient,delete this.localWallet,this.socketClient?.close(),resetContext(),console.log("dydx client released.")}}export var ChannelTypes;!function(e){e.Subaccounts="v4_subaccounts",e.Markets="v4_markets",e.Orderbook="v4_orderbook",e.Candles="v4_candles",e.Trades="v4_trades"}(ChannelTypes||(ChannelTypes={}));