@d8x/perpetuals-sdk 0.0.1 → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,38 @@
1
+ import WriteAccessHandler from "./writeAccessHandler";
2
+ import { NodeSDKConfig } from "./nodeSDKTypes";
3
+ /**
4
+ * Methods to liquidate traders.
5
+ */
6
+ export default class LiquidatorTool extends WriteAccessHandler {
7
+ /**
8
+ * Constructs a LiquidatorTool instance for a given configuration and private key.
9
+ * @param {NodeSDKConfig} config Configuration object.
10
+ * @param {string} privateKey Private key of account that liquidates.
11
+ */
12
+ constructor(config: NodeSDKConfig, privateKey: string);
13
+ /**
14
+ *
15
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
16
+ * @param {string} traderAddr Address of the trader to be liquidated.
17
+ * @param {string=} liquidatorAddr Address to be credited if the liquidation succeeds.
18
+ * Defaults to the wallet used to execute the liquidation.
19
+ * @returns {number} Liquidated amount.
20
+ */
21
+ liquidateTrader(symbol: string, traderAddr: string, liquidatorAddr?: string): Promise<number>;
22
+ /**
23
+ * Check if a trader is maintenance margin safe - if not, it can be liquidated.
24
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
25
+ * @param {string} traderAddr Address of the trader whose position we want to assess.
26
+ * @returns {boolean} True if the trader is maintenance margin safe in the perpetual.
27
+ */
28
+ isMaintenanceMarginSafe(symbol: string, traderAddr: string): Promise<boolean>;
29
+ /**
30
+ *
31
+ * @param perpetualId Perpetual id.
32
+ * @param liquidatorAddr Address to be credited for the liquidation.
33
+ * @param traderAddr Address of the trader to be liquidated.
34
+ * @param gasLimit Gas limit.
35
+ * @ignore
36
+ */
37
+ _liquidateByAMM(perpetualId: number, liquidatorAddr: string, traderAddr: string, gasLimit: number): Promise<number>;
38
+ }
@@ -0,0 +1,83 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
16
+ const d8XMath_1 = require("./d8XMath");
17
+ /**
18
+ * Methods to liquidate traders.
19
+ */
20
+ class LiquidatorTool extends writeAccessHandler_1.default {
21
+ /**
22
+ * Constructs a LiquidatorTool instance for a given configuration and private key.
23
+ * @param {NodeSDKConfig} config Configuration object.
24
+ * @param {string} privateKey Private key of account that liquidates.
25
+ */
26
+ constructor(config, privateKey) {
27
+ super(config, privateKey);
28
+ }
29
+ /**
30
+ *
31
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
32
+ * @param {string} traderAddr Address of the trader to be liquidated.
33
+ * @param {string=} liquidatorAddr Address to be credited if the liquidation succeeds.
34
+ * Defaults to the wallet used to execute the liquidation.
35
+ * @returns {number} Liquidated amount.
36
+ */
37
+ liquidateTrader(symbol, traderAddr, liquidatorAddr = "") {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ // this operation spends gas, so signer is required
40
+ if (this.proxyContract == null || this.signer == null) {
41
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
42
+ }
43
+ // liquidator is signer unless specified otherwise
44
+ if (liquidatorAddr == "") {
45
+ liquidatorAddr = this.traderAddr;
46
+ }
47
+ let perpID = LiquidatorTool.symbolToPerpetualId(symbol, this.symbolToPerpStaticInfo);
48
+ return yield this._liquidateByAMM(perpID, liquidatorAddr, traderAddr, this.gasLimit);
49
+ });
50
+ }
51
+ /**
52
+ * Check if a trader is maintenance margin safe - if not, it can be liquidated.
53
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
54
+ * @param {string} traderAddr Address of the trader whose position we want to assess.
55
+ * @returns {boolean} True if the trader is maintenance margin safe in the perpetual.
56
+ */
57
+ isMaintenanceMarginSafe(symbol, traderAddr) {
58
+ return __awaiter(this, void 0, void 0, function* () {
59
+ if (this.proxyContract == null) {
60
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
61
+ }
62
+ let perpID = LiquidatorTool.symbolToPerpetualId(symbol, this.symbolToPerpStaticInfo);
63
+ return yield this.proxyContract.isMaintenanceMarginSafe(perpID, traderAddr);
64
+ });
65
+ }
66
+ /**
67
+ *
68
+ * @param perpetualId Perpetual id.
69
+ * @param liquidatorAddr Address to be credited for the liquidation.
70
+ * @param traderAddr Address of the trader to be liquidated.
71
+ * @param gasLimit Gas limit.
72
+ * @ignore
73
+ */
74
+ _liquidateByAMM(perpetualId, liquidatorAddr, traderAddr, gasLimit) {
75
+ return __awaiter(this, void 0, void 0, function* () {
76
+ let fAmount = yield this.proxyContract.liquidateByAMM(perpetualId, liquidatorAddr, traderAddr, {
77
+ gasLimit: gasLimit,
78
+ });
79
+ return (0, d8XMath_1.ABK64x64ToFloat)(fAmount);
80
+ });
81
+ }
82
+ }
83
+ exports.default = LiquidatorTool;
@@ -2,7 +2,6 @@ import { ethers } from "ethers";
2
2
  import WriteAccessHandler from "./writeAccessHandler";
3
3
  import { NodeSDKConfig } from "./nodeSDKTypes";
4
4
  /**
5
- * LiquidityProviderTool
6
5
  * Methods to provide liquidity
7
6
  */
8
7
  export default class LiquidityProviderTool extends WriteAccessHandler {
@@ -13,9 +12,10 @@ export default class LiquidityProviderTool extends WriteAccessHandler {
13
12
  */
14
13
  constructor(config: NodeSDKConfig, privateKey: string);
15
14
  /**
16
- * Returns the value of the share tokens for this liquidity provider
17
- * in poolSymbol-currency (e.g. MATIC, USDC)
18
- * @param poolSymbolName pool symbol name (e.g. MATIC)
15
+ * Value of the share tokens for this liquidity provider
16
+ * in poolSymbol-currency (e.g. MATIC, USDC).
17
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC).
18
+ * @return Value in poolSymbol-currency (e.g. MATIC, USDC), balabce of share tokens, and share token symbol.
19
19
  */
20
20
  getParticipationValue(poolSymbolName: string): Promise<{
21
21
  value: number;
@@ -24,16 +24,16 @@ export default class LiquidityProviderTool extends WriteAccessHandler {
24
24
  }>;
25
25
  /**
26
26
  * Add liquidity to the PnL participant fund. The address gets pool shares in return.
27
- * @param poolname name of pool symbol (e.g. MATIC)
28
- * @param amountCC amount in pool-collateral currency
29
- * @return transaction object
27
+ * @param {string} poolname Name of pool symbol (e.g. MATIC)
28
+ * @param {number} amountCC Amount in pool-collateral currency
29
+ * @return Transaction object
30
30
  */
31
31
  addLiquidity(poolSymbolName: string, amountCC: number): Promise<ethers.providers.TransactionResponse>;
32
32
  /**
33
- * Remove liquidity from the pool
34
- * @param poolSymbolName name of pool symbol (e.g. MATIC)
35
- * @param amountPoolShares amount in pool-tokens, removes everything if > available amount
36
- * @return transaction object
33
+ * Remove liquidity from the pool.
34
+ * @param {string} poolSymbolName Name of pool symbol (e.g. MATIC).
35
+ * @param {string} amountPoolShares Amount in pool-tokens, removes everything if > available amount.
36
+ * @return Transaction object.
37
37
  */
38
38
  removeLiquidity(poolSymbolName: string, amountPoolShares: number): Promise<ethers.providers.TransactionResponse>;
39
39
  }
@@ -18,7 +18,6 @@ const nodeSDKTypes_1 = require("./nodeSDKTypes");
18
18
  const perpetualDataHandler_1 = __importDefault(require("./perpetualDataHandler"));
19
19
  const d8XMath_1 = require("./d8XMath");
20
20
  /**
21
- * LiquidityProviderTool
22
21
  * Methods to provide liquidity
23
22
  */
24
23
  class LiquidityProviderTool extends writeAccessHandler_1.default {
@@ -31,9 +30,10 @@ class LiquidityProviderTool extends writeAccessHandler_1.default {
31
30
  super(config, privateKey);
32
31
  }
33
32
  /**
34
- * Returns the value of the share tokens for this liquidity provider
35
- * in poolSymbol-currency (e.g. MATIC, USDC)
36
- * @param poolSymbolName pool symbol name (e.g. MATIC)
33
+ * Value of the share tokens for this liquidity provider
34
+ * in poolSymbol-currency (e.g. MATIC, USDC).
35
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC).
36
+ * @return Value in poolSymbol-currency (e.g. MATIC, USDC), balabce of share tokens, and share token symbol.
37
37
  */
38
38
  getParticipationValue(poolSymbolName) {
39
39
  return __awaiter(this, void 0, void 0, function* () {
@@ -62,9 +62,9 @@ class LiquidityProviderTool extends writeAccessHandler_1.default {
62
62
  }
63
63
  /**
64
64
  * Add liquidity to the PnL participant fund. The address gets pool shares in return.
65
- * @param poolname name of pool symbol (e.g. MATIC)
66
- * @param amountCC amount in pool-collateral currency
67
- * @return transaction object
65
+ * @param {string} poolname Name of pool symbol (e.g. MATIC)
66
+ * @param {number} amountCC Amount in pool-collateral currency
67
+ * @return Transaction object
68
68
  */
69
69
  addLiquidity(poolSymbolName, amountCC) {
70
70
  return __awaiter(this, void 0, void 0, function* () {
@@ -79,10 +79,10 @@ class LiquidityProviderTool extends writeAccessHandler_1.default {
79
79
  });
80
80
  }
81
81
  /**
82
- * Remove liquidity from the pool
83
- * @param poolSymbolName name of pool symbol (e.g. MATIC)
84
- * @param amountPoolShares amount in pool-tokens, removes everything if > available amount
85
- * @return transaction object
82
+ * Remove liquidity from the pool.
83
+ * @param {string} poolSymbolName Name of pool symbol (e.g. MATIC).
84
+ * @param {string} amountPoolShares Amount in pool-tokens, removes everything if > available amount.
85
+ * @return Transaction object.
86
86
  */
87
87
  removeLiquidity(poolSymbolName, amountPoolShares) {
88
88
  return __awaiter(this, void 0, void 0, function* () {
@@ -9,23 +9,34 @@ import { Order } from "./nodeSDKTypes";
9
9
  export default class MarketData extends PerpetualDataHandler {
10
10
  constructor(config: NodeSDKConfig);
11
11
  createProxyInstance(): Promise<void>;
12
+ /**
13
+ * Information about the products traded in the exchange.
14
+ * @returns {ExchangeInfo} Array of static data for all the pools and perpetuals in the system.
15
+ */
12
16
  exchangeInfo(): Promise<ExchangeInfo>;
13
17
  /**
14
- * Get all open orders for a trader-address and a symbol
15
- * @param traderAddr address of the trader for which we get the open order
16
- * @param symbol symbol of the form ETH-USD-MATIC
17
- * @returns array of open orders and corresponding order-ids
18
+ * All open orders for a trader-address and a symbol.
19
+ * @param {string} traderAddr Address of the trader for which we get the open orders.
20
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
21
+ * @returns {Array<Array<Order>, Array<string>>} Array of open orders and corresponding order-ids.
18
22
  */
19
23
  openOrders(traderAddr: string, symbol: string): Promise<{
20
24
  orders: Order[];
21
25
  orderIds: string[];
22
26
  }>;
27
+ /**
28
+ * Information about the position open by a given trader in a given perpetual contract.
29
+ * @param {string} traderAddr Address of the trader for which we get the position risk.
30
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
31
+ * @returns {MarginAccount}
32
+ */
23
33
  positionRisk(traderAddr: string, symbol: string): Promise<MarginAccount>;
24
34
  /**
25
- * Query smart contract to get user orders and convert to user friendly order format
26
- * @param traderAddr address of trader
27
- * @param orderBookContract instance of order book
28
- * @returns array of user friendly order struct
35
+ * Query smart contract to get user orders and convert to user friendly order format.
36
+ * @param {string} traderAddr Address of trader.
37
+ * @param {ethers.Contract} orderBookContract Instance of order book.
38
+ * @returns {Order[]} Array of user friendly order struct.
39
+ * @ignore
29
40
  */
30
41
  protected openOrdersOnOrderBook(traderAddr: string, orderBookContract: ethers.Contract): Promise<Order[]>;
31
42
  /**
@@ -33,6 +44,7 @@ export default class MarketData extends PerpetualDataHandler {
33
44
  * @param traderAddr address of the trader
34
45
  * @param orderBookContract instance of order book contract
35
46
  * @returns array of order-id's
47
+ * @ignore
36
48
  */
37
49
  protected orderIdsOfTrader(traderAddr: string, orderBookContract: ethers.Contract): Promise<string[]>;
38
50
  static _exchangeInfo(_proxyContract: ethers.Contract): Promise<ExchangeInfo>;
@@ -31,6 +31,10 @@ class MarketData extends perpetualDataHandler_1.default {
31
31
  yield this.initContractsAndData(this.provider);
32
32
  });
33
33
  }
34
+ /**
35
+ * Information about the products traded in the exchange.
36
+ * @returns {ExchangeInfo} Array of static data for all the pools and perpetuals in the system.
37
+ */
34
38
  exchangeInfo() {
35
39
  return __awaiter(this, void 0, void 0, function* () {
36
40
  if (this.proxyContract == null) {
@@ -40,10 +44,10 @@ class MarketData extends perpetualDataHandler_1.default {
40
44
  });
41
45
  }
42
46
  /**
43
- * Get all open orders for a trader-address and a symbol
44
- * @param traderAddr address of the trader for which we get the open order
45
- * @param symbol symbol of the form ETH-USD-MATIC
46
- * @returns array of open orders and corresponding order-ids
47
+ * All open orders for a trader-address and a symbol.
48
+ * @param {string} traderAddr Address of the trader for which we get the open orders.
49
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
50
+ * @returns {Array<Array<Order>, Array<string>>} Array of open orders and corresponding order-ids.
47
51
  */
48
52
  openOrders(traderAddr, symbol) {
49
53
  return __awaiter(this, void 0, void 0, function* () {
@@ -56,6 +60,12 @@ class MarketData extends perpetualDataHandler_1.default {
56
60
  return { orders: orders, orderIds: digests };
57
61
  });
58
62
  }
63
+ /**
64
+ * Information about the position open by a given trader in a given perpetual contract.
65
+ * @param {string} traderAddr Address of the trader for which we get the position risk.
66
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
67
+ * @returns {MarginAccount}
68
+ */
59
69
  positionRisk(traderAddr, symbol) {
60
70
  return __awaiter(this, void 0, void 0, function* () {
61
71
  if (this.proxyContract == null) {
@@ -66,10 +76,11 @@ class MarketData extends perpetualDataHandler_1.default {
66
76
  });
67
77
  }
68
78
  /**
69
- * Query smart contract to get user orders and convert to user friendly order format
70
- * @param traderAddr address of trader
71
- * @param orderBookContract instance of order book
72
- * @returns array of user friendly order struct
79
+ * Query smart contract to get user orders and convert to user friendly order format.
80
+ * @param {string} traderAddr Address of trader.
81
+ * @param {ethers.Contract} orderBookContract Instance of order book.
82
+ * @returns {Order[]} Array of user friendly order struct.
83
+ * @ignore
73
84
  */
74
85
  openOrdersOnOrderBook(traderAddr, orderBookContract) {
75
86
  return __awaiter(this, void 0, void 0, function* () {
@@ -89,6 +100,7 @@ class MarketData extends perpetualDataHandler_1.default {
89
100
  * @param traderAddr address of the trader
90
101
  * @param orderBookContract instance of order book contract
91
102
  * @returns array of order-id's
103
+ * @ignore
92
104
  */
93
105
  orderIdsOfTrader(traderAddr, orderBookContract) {
94
106
  return __awaiter(this, void 0, void 0, function* () {
@@ -1,14 +1,33 @@
1
1
  import WriteAccessHandler from "./writeAccessHandler";
2
- import { NodeSDKConfig } from "./nodeSDKTypes";
2
+ import { NodeSDKConfig, Order } from "./nodeSDKTypes";
3
+ import { ethers } from "ethers";
3
4
  /**
4
- * OrderReferrerTool
5
- * Methods to refer orders from the limit order book
5
+ * Methods to execute existing orders from the limit order book.
6
6
  */
7
7
  export default class OrderReferrerTool extends WriteAccessHandler {
8
8
  /**
9
- * Constructor
10
- * @param config configuration
11
- * @param privateKey private key of account that trades
9
+ * Constructor.
10
+ * @param {NodeSDKConfig} config Configuration object.
11
+ * @param {string} privateKey Private key of the wallet that executes the conditional orders.
12
12
  */
13
13
  constructor(config: NodeSDKConfig, privateKey: string);
14
+ /**
15
+ * Executes an order by symbol and ID. This action interacts with the blockchain and incurs in gas costs.
16
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
17
+ * @param {string} orderId ID of the order to be executed.
18
+ * @param {string=} referrerAddr Address of the wallet to be credited for executing the order,
19
+ * if different from the one submitting this transaction.
20
+ * @returns Transaction object.
21
+ */
22
+ executeOrder(symbol: string, orderId: string, referrerAddr?: string): Promise<ethers.providers.TransactionResponse>;
23
+ /**
24
+ * Get a list of active conditional orders in the order book.
25
+ * This a read-only action and does not incur in gas costs.
26
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
27
+ * @param {number} numElements Maximum number of orders to poll.
28
+ * @param {string} startAfter Optional order ID from where to start polling. Defaults to the first order.
29
+ * @returns Array of orders and corresponding order IDs
30
+ */
31
+ pollLimitOrders(symbol: string, numElements: number, startAfter?: string): Promise<[Order[], string[]]>;
32
+ isTradeable(order: Order): Promise<boolean>;
14
33
  }
@@ -1,21 +1,110 @@
1
1
  "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
2
11
  var __importDefault = (this && this.__importDefault) || function (mod) {
3
12
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
13
  };
5
14
  Object.defineProperty(exports, "__esModule", { value: true });
6
15
  const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
16
+ const nodeSDKTypes_1 = require("./nodeSDKTypes");
7
17
  /**
8
- * OrderReferrerTool
9
- * Methods to refer orders from the limit order book
18
+ * Methods to execute existing orders from the limit order book.
10
19
  */
11
20
  class OrderReferrerTool extends writeAccessHandler_1.default {
12
21
  /**
13
- * Constructor
14
- * @param config configuration
15
- * @param privateKey private key of account that trades
22
+ * Constructor.
23
+ * @param {NodeSDKConfig} config Configuration object.
24
+ * @param {string} privateKey Private key of the wallet that executes the conditional orders.
16
25
  */
17
26
  constructor(config, privateKey) {
18
27
  super(config, privateKey);
19
28
  }
29
+ /**
30
+ * Executes an order by symbol and ID. This action interacts with the blockchain and incurs in gas costs.
31
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
32
+ * @param {string} orderId ID of the order to be executed.
33
+ * @param {string=} referrerAddr Address of the wallet to be credited for executing the order,
34
+ * if different from the one submitting this transaction.
35
+ * @returns Transaction object.
36
+ */
37
+ executeOrder(symbol, orderId, referrerAddr) {
38
+ return __awaiter(this, void 0, void 0, function* () {
39
+ if (this.proxyContract == null || this.signer == null) {
40
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
41
+ }
42
+ const orderBookSC = this.getOrderBookContract(symbol);
43
+ if (typeof referrerAddr == "undefined") {
44
+ referrerAddr = this.traderAddr;
45
+ }
46
+ return yield orderBookSC.executeLimitOrderByDigest(orderId, referrerAddr);
47
+ });
48
+ }
49
+ /**
50
+ * Get a list of active conditional orders in the order book.
51
+ * This a read-only action and does not incur in gas costs.
52
+ * @param {string} symbol Symbol of the form ETH-USD-MATIC.
53
+ * @param {number} numElements Maximum number of orders to poll.
54
+ * @param {string} startAfter Optional order ID from where to start polling. Defaults to the first order.
55
+ * @returns Array of orders and corresponding order IDs
56
+ */
57
+ pollLimitOrders(symbol, numElements, startAfter) {
58
+ return __awaiter(this, void 0, void 0, function* () {
59
+ if (this.proxyContract == null) {
60
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
61
+ }
62
+ if (typeof startAfter == "undefined") {
63
+ startAfter = nodeSDKTypes_1.ZERO_ADDRESS;
64
+ }
65
+ const orderBookSC = this.getOrderBookContract(symbol);
66
+ let [orders, orderIds] = yield orderBookSC.pollLimitOrders(startAfter, numElements);
67
+ let userFriendlyOrders = new Array();
68
+ let k = 0;
69
+ while (k < orders.length && orders[k].traderAddr != nodeSDKTypes_1.ZERO_ADDRESS) {
70
+ userFriendlyOrders.push(writeAccessHandler_1.default.fromSmartContractOrder(orders[k], this.symbolToPerpStaticInfo));
71
+ k++;
72
+ }
73
+ return [userFriendlyOrders, orderIds];
74
+ });
75
+ }
76
+ isTradeable(order) {
77
+ return __awaiter(this, void 0, void 0, function* () {
78
+ if (this.proxyContract == null) {
79
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
80
+ }
81
+ if (order.limitPrice == undefined) {
82
+ throw Error("order does not have a limit price");
83
+ }
84
+ // check expiration date
85
+ if (order.deadline != undefined && order.deadline < Date.now()) {
86
+ return false;
87
+ }
88
+ // check limit price
89
+ let orderPrice = yield writeAccessHandler_1.default._queryPerpetualPrice(order.symbol, order.quantity, this.symbolToPerpStaticInfo, this.proxyContract);
90
+ if ((order.side == nodeSDKTypes_1.BUY_SIDE && orderPrice > order.limitPrice) ||
91
+ (order.side == nodeSDKTypes_1.SELL_SIDE && orderPrice < order.limitPrice)) {
92
+ return false;
93
+ }
94
+ // do we need to check trigger/stop?
95
+ if (order.stopPrice == undefined) {
96
+ // nothing to check, order is tradeable
97
+ return true;
98
+ }
99
+ // we need the mark price to check
100
+ let markPrice = yield writeAccessHandler_1.default._queryPerpetualMarkPrice(order.symbol, this.symbolToPerpStaticInfo, this.proxyContract);
101
+ if ((order.side == nodeSDKTypes_1.BUY_SIDE && markPrice < order.stopPrice) ||
102
+ (order.side == nodeSDKTypes_1.SELL_SIDE && markPrice > order.stopPrice)) {
103
+ return false;
104
+ }
105
+ // all checks passed -> order is tradeable
106
+ return true;
107
+ });
108
+ }
20
109
  }
21
110
  exports.default = OrderReferrerTool;
@@ -39,6 +39,8 @@ export default class PerpetualDataHandler {
39
39
  protected static _getPoolIdFromSymbol(symbol: string, staticInfos: PoolStaticInfo[]): number;
40
40
  static getNestedPerpetualIds(_proxyContract: ethers.Contract): Promise<number[][]>;
41
41
  static getMarginAccount(traderAddr: string, symbol: string, symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>, _proxyContract: ethers.Contract): Promise<MarginAccount>;
42
+ protected static _queryPerpetualPrice(symbol: string, tradeAmount: number, symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>, _proxyContract: ethers.Contract): Promise<number>;
43
+ protected static _queryPerpetualMarkPrice(symbol: string, symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>, _proxyContract: ethers.Contract): Promise<number>;
42
44
  /**
43
45
  * Liquidation price
44
46
  * @param cleanSymbol symbol after calling symbolToBytes4Symbol
@@ -218,6 +218,20 @@ class PerpetualDataHandler {
218
218
  return mgn;
219
219
  });
220
220
  }
221
+ static _queryPerpetualPrice(symbol, tradeAmount, symbolToPerpStaticInfo, _proxyContract) {
222
+ return __awaiter(this, void 0, void 0, function* () {
223
+ let perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
224
+ let fPrice = yield _proxyContract.queryPerpetualPrice(perpId, (0, d8XMath_1.floatToABK64x64)(tradeAmount));
225
+ return (0, d8XMath_1.ABK64x64ToFloat)(fPrice);
226
+ });
227
+ }
228
+ static _queryPerpetualMarkPrice(symbol, symbolToPerpStaticInfo, _proxyContract) {
229
+ return __awaiter(this, void 0, void 0, function* () {
230
+ let perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
231
+ let ammState = yield _proxyContract.getAMMState(perpId);
232
+ return (0, d8XMath_1.ABK64x64ToFloat)(ammState[6].mul(nodeSDKTypes_1.ONE_64x64.add(ammState[8])));
233
+ });
234
+ }
221
235
  /**
222
236
  * Liquidation price
223
237
  * @param cleanSymbol symbol after calling symbolToBytes4Symbol
package/dist/utils.d.ts CHANGED
@@ -2,8 +2,8 @@
2
2
  import { BigNumber } from "ethers";
3
3
  /**
4
4
  *
5
- * @param s string to shorten/extend to 4 characters
6
- * @returns string with 4 characters (or characters + null chars)
5
+ * @param {string} s String to shorten/extend to 4 characters
6
+ * @returns {string} String with 4 characters (or characters + null chars)
7
7
  */
8
8
  export declare function to4Chars(s: string): string;
9
9
  /**
@@ -12,23 +12,23 @@ export declare function to4Chars(s: string): string;
12
12
  * 4 characters.
13
13
  * Resulting buffer can be used with smart contract to
14
14
  * identify tokens (BTC, USDC, MATIC etc.)
15
- * @param s string to encode into bytes4
16
- * @returns buffer
15
+ * @param {string} s String to encode into bytes4
16
+ * @returns {Buffer} 4-character bytes4.
17
17
  */
18
18
  export declare function toBytes4(s: string): Buffer;
19
19
  /**
20
20
  * Decodes a buffer encoded with toBytes4 into
21
21
  * a string. The string is the result of to4Chars of the
22
22
  * originally encoded string stripped from null-chars
23
- * @param b correctly encoded bytes4 buffer using toBytes4
24
- * @returns string decoded into to4Chars-type string without null characters
23
+ * @param {Buffer} b Correctly encoded bytes4 buffer using toBytes4
24
+ * @returns {string} String decoded into to4Chars-type string without null characters
25
25
  */
26
26
  export declare function fromBytes4(b: Buffer): string;
27
27
  /**
28
28
  * Decodes the bytes4 encoded string received from the
29
29
  * smart contract as a hex-number in string-format
30
- * @param s string representing a hex-number ("0x...")
31
- * @returns x of to4Chars(x) stripped from null-chars,
30
+ * @param {string} s string representing a hex-number ("0x...")
31
+ * @returns {string} x of to4Chars(x) stripped from null-chars,
32
32
  * where x was originally encoded and
33
33
  * returned by the smart contract as bytes4
34
34
  */
package/dist/utils.js CHANGED
@@ -2,15 +2,17 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.containsFlag = exports.combineFlags = exports.fromBytes4HexString = exports.fromBytes4 = exports.toBytes4 = exports.to4Chars = void 0;
4
4
  const ethers_1 = require("ethers");
5
- const ethers = require("ethers");
5
+ /**
6
+ * @module utils
7
+ */
6
8
  function _isVocal(char) {
7
9
  char = char.toLowerCase();
8
10
  return char == "a" || char == "e" || char == "i" || char == "o" || char == "u";
9
11
  }
10
12
  /**
11
13
  *
12
- * @param s string to shorten/extend to 4 characters
13
- * @returns string with 4 characters (or characters + null chars)
14
+ * @param {string} s String to shorten/extend to 4 characters
15
+ * @returns {string} String with 4 characters (or characters + null chars)
14
16
  */
15
17
  function to4Chars(s) {
16
18
  while (s.length < 4) {
@@ -35,8 +37,8 @@ exports.to4Chars = to4Chars;
35
37
  * 4 characters.
36
38
  * Resulting buffer can be used with smart contract to
37
39
  * identify tokens (BTC, USDC, MATIC etc.)
38
- * @param s string to encode into bytes4
39
- * @returns buffer
40
+ * @param {string} s String to encode into bytes4
41
+ * @returns {Buffer} 4-character bytes4.
40
42
  */
41
43
  function toBytes4(s) {
42
44
  s = to4Chars(s);
@@ -48,8 +50,8 @@ exports.toBytes4 = toBytes4;
48
50
  * Decodes a buffer encoded with toBytes4 into
49
51
  * a string. The string is the result of to4Chars of the
50
52
  * originally encoded string stripped from null-chars
51
- * @param b correctly encoded bytes4 buffer using toBytes4
52
- * @returns string decoded into to4Chars-type string without null characters
53
+ * @param {Buffer} b Correctly encoded bytes4 buffer using toBytes4
54
+ * @returns {string} String decoded into to4Chars-type string without null characters
53
55
  */
54
56
  function fromBytes4(b) {
55
57
  let val = b.toString("ascii");
@@ -60,8 +62,8 @@ exports.fromBytes4 = fromBytes4;
60
62
  /**
61
63
  * Decodes the bytes4 encoded string received from the
62
64
  * smart contract as a hex-number in string-format
63
- * @param s string representing a hex-number ("0x...")
64
- * @returns x of to4Chars(x) stripped from null-chars,
65
+ * @param {string} s string representing a hex-number ("0x...")
66
+ * @returns {string} x of to4Chars(x) stripped from null-chars,
65
67
  * where x was originally encoded and
66
68
  * returned by the smart contract as bytes4
67
69
  */
package/package.json CHANGED
@@ -12,7 +12,7 @@
12
12
  },
13
13
  "scripts": {
14
14
  "build": "tsc",
15
- "build:doc": "jsdoc2md --files ./src/accountTrade.ts --configure ./jsdoc2md.json > ./doc/accountTrade.md",
15
+ "build:doc": "jsdoc2md --files ./src/accountTrade.ts --configure ./jsdoc2md.json > ./doc/accountTrade.md && jsdoc2md --files ./src/marketData.ts --configure ./jsdoc2md.json > ./doc/marketData.md && jsdoc2md --files ./src/liquidatorTool.ts --configure ./jsdoc2md.json > ./doc/liquidatorTool.md && jsdoc2md --files ./src/liquidityProviderTool.ts --configure ./jsdoc2md.json > ./doc/liquidityProviderTool.md && jsdoc2md --files ./src/brokerTool.ts --configure ./jsdoc2md.json > ./doc/brokerTool.md && jsdoc2md --files ./src/orderReferrerTool.ts --configure ./jsdoc2md.json > ./doc/orderReferrerTool.md",
16
16
  "test": "jest",
17
17
  "coverage": "nyc -r lcov -e .ts -x \"*.test.ts\" npm run test"
18
18
  },
@@ -27,7 +27,7 @@
27
27
  },
28
28
  "name": "@d8x/perpetuals-sdk",
29
29
  "description": "Node TypeScript SDK for D8X Perpetual Futures",
30
- "version": "0.0.1",
30
+ "version": "0.0.2",
31
31
  "main": "./dist/index.js",
32
32
  "types": "./dist/index.d.ts",
33
33
  "directories": {