@d8x/perpetuals-sdk 0.0.7 → 0.0.8

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.
@@ -22,9 +22,9 @@ export default class AccountTrade extends WriteAccessHandler {
22
22
  /**
23
23
  * Submits an order to the exchange.
24
24
  * @param {Order} order Order struct.
25
- * @returns {string} Transaction hash.
25
+ * @returns {ContractTransaction} Contract Transaction (containing events).
26
26
  */
27
- order(order: Order): Promise<string | undefined>;
27
+ order(order: Order): Promise<ethers.ContractTransaction>;
28
28
  /**
29
29
  * Fee charged by the exchange for trading any perpetual on a given pool.
30
30
  * It accounts for the current trader's fee tier (based on the trader's D8X balance and trading volume).
@@ -55,7 +55,7 @@ export default class AccountTrade extends WriteAccessHandler {
55
55
  * @returns transaction hash
56
56
  * @ignore
57
57
  */
58
- _order(order: Order, traderAddr: string, symbolToPerpetualMap: Map<string, PerpetualStaticInfo>, proxyContract: ethers.Contract, orderBookContract: ethers.Contract | null, chainId: number, signer: ethers.Wallet, gasLimit: number): Promise<string | undefined>;
58
+ _order(order: Order, traderAddr: string, symbolToPerpetualMap: Map<string, PerpetualStaticInfo>, proxyContract: ethers.Contract, orderBookContract: ethers.Contract | null, chainId: number, signer: ethers.Wallet, gasLimit: number): Promise<ethers.ContractTransaction>;
59
59
  protected _cancelOrder(symbol: string, orderId: string, orderBookContract: ethers.Contract | null): Promise<string | undefined>;
60
60
  /**
61
61
  * Creates a signature
@@ -53,7 +53,7 @@ class AccountTrade extends writeAccessHandler_1.default {
53
53
  /**
54
54
  * Submits an order to the exchange.
55
55
  * @param {Order} order Order struct.
56
- * @returns {string} Transaction hash.
56
+ * @returns {ContractTransaction} Contract Transaction (containing events).
57
57
  */
58
58
  order(order) {
59
59
  return __awaiter(this, void 0, void 0, function* () {
@@ -136,7 +136,7 @@ class AccountTrade extends writeAccessHandler_1.default {
136
136
  let signature = yield this._createSignature(scOrder, chainId, true, signer, proxyContract.address);
137
137
  tx = yield orderBookContract.createLimitOrder(scOrder, signature, { gasLimit: gasLimit });
138
138
  }
139
- return tx.hash;
139
+ return tx;
140
140
  });
141
141
  }
142
142
  _cancelOrder(symbol, orderId, orderBookContract) {
@@ -34,7 +34,7 @@ export default class BrokerTool extends WriteAccessHandler {
34
34
  * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
35
35
  * @returns {number} Fee based solely on a broker's traded volume in the corresponding pool, in decimals (i.e. 0.1% is 0.001).
36
36
  */
37
- getFeeForBrokerVolume(poolSymbolName: string): Promise<number | undefined>;
37
+ getFeeForBrokerVolume(poolSymbolName: string): Promise<number>;
38
38
  /**
39
39
  * Determine the exchange fee based on the current D8X balance in a broker's wallet.
40
40
  * The final exchange fee paid by the broker is equal to
@@ -80,9 +80,9 @@ export default class BrokerTool extends WriteAccessHandler {
80
80
  * Deposit lots to the default fund of a given pool.
81
81
  * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
82
82
  * @param {number} lots Number of lots to deposit into this pool.
83
- * @returns {ethers.providers.TransactionResponse} Transaction object.
83
+ * @returns {ethers.ContractTransaction} ContractTransaction object.
84
84
  */
85
- brokerDepositToDefaultFund(poolSymbolName: string, lots: number): Promise<ethers.providers.TransactionResponse>;
85
+ brokerDepositToDefaultFund(poolSymbolName: string, lots: number): Promise<ethers.ContractTransaction>;
86
86
  /**
87
87
  * Adds this broker's signature to an order so that it can be submitted by an approved trader.
88
88
  * @param {Order} order Order to sign.
@@ -183,7 +183,7 @@ class BrokerTool extends writeAccessHandler_1.default {
183
183
  * Deposit lots to the default fund of a given pool.
184
184
  * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
185
185
  * @param {number} lots Number of lots to deposit into this pool.
186
- * @returns {ethers.providers.TransactionResponse} Transaction object.
186
+ * @returns {ethers.ContractTransaction} ContractTransaction object.
187
187
  */
188
188
  brokerDepositToDefaultFund(poolSymbolName, lots) {
189
189
  return __awaiter(this, void 0, void 0, function* () {
package/dist/index.d.ts CHANGED
@@ -5,7 +5,8 @@ import MarketData from "./marketData";
5
5
  import OrderReferrerTool from "./orderReferrerTool";
6
6
  import PerpetualDataHandler from "./perpetualDataHandler";
7
7
  import WriteAccessHandler from "./writeAccessHandler";
8
+ import LiquidatorTool from "./liquidatorTool";
8
9
  export * from "./nodeSDKTypes";
9
10
  export * from "./utils";
10
11
  export * from "./d8XMath";
11
- export { AccountTrade, BrokerTool, LiquidityProviderTool, MarketData, OrderReferrerTool, PerpetualDataHandler, WriteAccessHandler, };
12
+ export { AccountTrade, BrokerTool, LiquidityProviderTool, MarketData, OrderReferrerTool, PerpetualDataHandler, WriteAccessHandler, LiquidatorTool, };
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
17
17
  return (mod && mod.__esModule) ? mod : { "default": mod };
18
18
  };
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.WriteAccessHandler = exports.PerpetualDataHandler = exports.OrderReferrerTool = exports.MarketData = exports.LiquidityProviderTool = exports.BrokerTool = exports.AccountTrade = void 0;
20
+ exports.LiquidatorTool = exports.WriteAccessHandler = exports.PerpetualDataHandler = exports.OrderReferrerTool = exports.MarketData = exports.LiquidityProviderTool = exports.BrokerTool = exports.AccountTrade = void 0;
21
21
  const accountTrade_1 = __importDefault(require("./accountTrade"));
22
22
  exports.AccountTrade = accountTrade_1.default;
23
23
  const brokerTool_1 = __importDefault(require("./brokerTool"));
@@ -32,6 +32,8 @@ const perpetualDataHandler_1 = __importDefault(require("./perpetualDataHandler")
32
32
  exports.PerpetualDataHandler = perpetualDataHandler_1.default;
33
33
  const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
34
34
  exports.WriteAccessHandler = writeAccessHandler_1.default;
35
+ const liquidatorTool_1 = __importDefault(require("./liquidatorTool"));
36
+ exports.LiquidatorTool = liquidatorTool_1.default;
35
37
  // import {
36
38
  // NodeSDKConfig,
37
39
  // MarginAccount,
@@ -45,8 +45,8 @@ export default class LiquidatorTool extends WriteAccessHandler {
45
45
  * Get addresses of active accounts by chunks.
46
46
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
47
47
  * @param {number} from From which account we start counting (0-indexed).
48
- * @param {number} to Until which account we count.
49
- * @returns {string[]} Array of addresses.
48
+ * @param {number} to Until which account we count, non inclusive.
49
+ * @returns {string[]} Array of addresses at locations 'from', 'from'+1 ,..., 'to'-1.
50
50
  */
51
51
  getActiveAccountsByChunks(symbol: string, from: number, to: number): Promise<string[]>;
52
52
  /**
@@ -60,7 +60,7 @@ class LiquidatorTool extends writeAccessHandler_1.default {
60
60
  throw Error("no proxy contract initialized. Use createProxyInstance().");
61
61
  }
62
62
  let perpID = LiquidatorTool.symbolToPerpetualId(symbol, this.symbolToPerpStaticInfo);
63
- return yield this.proxyContract.isMaintenanceMarginSafe(perpID, traderAddr);
63
+ return yield this.proxyContract.isTraderMaintenanceMarginSafe(perpID, traderAddr);
64
64
  });
65
65
  }
66
66
  /**
@@ -97,8 +97,8 @@ class LiquidatorTool extends writeAccessHandler_1.default {
97
97
  * Get addresses of active accounts by chunks.
98
98
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
99
99
  * @param {number} from From which account we start counting (0-indexed).
100
- * @param {number} to Until which account we count.
101
- * @returns {string[]} Array of addresses.
100
+ * @param {number} to Until which account we count, non inclusive.
101
+ * @returns {string[]} Array of addresses at locations 'from', 'from'+1 ,..., 'to'-1.
102
102
  */
103
103
  getActiveAccountsByChunks(symbol, from, to) {
104
104
  return __awaiter(this, void 0, void 0, function* () {
@@ -117,8 +117,8 @@ class LiquidatorTool extends writeAccessHandler_1.default {
117
117
  getAllActiveAccounts(symbol) {
118
118
  return __awaiter(this, void 0, void 0, function* () {
119
119
  // checks are done inside the intermediate functions
120
- let totalAccoutns = yield this.countActivePerpAccounts(symbol);
121
- return yield this.getActiveAccountsByChunks(symbol, 0, totalAccoutns - 1);
120
+ let totalAccounts = yield this.countActivePerpAccounts(symbol);
121
+ return yield this.getActiveAccountsByChunks(symbol, 0, totalAccounts);
122
122
  });
123
123
  }
124
124
  }
@@ -28,7 +28,7 @@ export default class LiquidityProviderTool extends WriteAccessHandler {
28
28
  * @param {number} amountCC Amount in pool-collateral currency
29
29
  * @return Transaction object
30
30
  */
31
- addLiquidity(poolSymbolName: string, amountCC: number): Promise<ethers.providers.TransactionResponse>;
31
+ addLiquidity(poolSymbolName: string, amountCC: number): Promise<ethers.ContractTransaction>;
32
32
  /**
33
33
  * Remove liquidity from the pool.
34
34
  * @param {string} poolSymbolName Name of pool symbol (e.g. MATIC).
@@ -9,6 +9,11 @@ import { Order } from "./nodeSDKTypes";
9
9
  export default class MarketData extends PerpetualDataHandler {
10
10
  constructor(config: NodeSDKConfig);
11
11
  createProxyInstance(): Promise<void>;
12
+ /**
13
+ * Get contract instance. Useful for event listening.
14
+ * @returns read-only proxy instance
15
+ */
16
+ getReadOnlyProxyInstance(): ethers.Contract;
12
17
  /**
13
18
  * Information about the products traded in the exchange.
14
19
  * @returns {ExchangeInfo} Array of static data for all the pools and perpetuals in the system.
@@ -31,6 +36,26 @@ export default class MarketData extends PerpetualDataHandler {
31
36
  * @returns {MarginAccount}
32
37
  */
33
38
  positionRisk(traderAddr: string, symbol: string): Promise<MarginAccount>;
39
+ /**
40
+ * Uses the Oracle(s) in the exchange to get the latest price of a given index in a given currency, if a route exists.
41
+ * @param {string} base Index name, e.g. ETH.
42
+ * @param {string} quote Quote currency, e.g. USD.
43
+ * @returns {number} Price of index in given currency.
44
+ */
45
+ getOraclePrice(base: string, quote: string): Promise<number | undefined>;
46
+ /**
47
+ * Get the current mark price
48
+ * @param symbol symbol of the form ETH-USD-MATIC
49
+ * @returns mark price
50
+ */
51
+ getMarkPrice(symbol: string): Promise<number>;
52
+ /**
53
+ * get the current price for a given quantity
54
+ * @param symbol symbol of the form ETH-USD-MATIC
55
+ * @param quantity quantity to be traded, negative if short
56
+ * @returns price (number)
57
+ */
58
+ getPerpetualPrice(symbol: string, quantity: number): Promise<number>;
34
59
  /**
35
60
  * Query smart contract to get user orders and convert to user friendly order format.
36
61
  * @param {string} traderAddr Address of trader.
@@ -31,6 +31,16 @@ class MarketData extends perpetualDataHandler_1.default {
31
31
  yield this.initContractsAndData(this.provider);
32
32
  });
33
33
  }
34
+ /**
35
+ * Get contract instance. Useful for event listening.
36
+ * @returns read-only proxy instance
37
+ */
38
+ getReadOnlyProxyInstance() {
39
+ if (this.proxyContract == null) {
40
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
41
+ }
42
+ return this.proxyContract;
43
+ }
34
44
  /**
35
45
  * Information about the products traded in the exchange.
36
46
  * @returns {ExchangeInfo} Array of static data for all the pools and perpetuals in the system.
@@ -75,6 +85,48 @@ class MarketData extends perpetualDataHandler_1.default {
75
85
  return mgnAcct;
76
86
  });
77
87
  }
88
+ /**
89
+ * Uses the Oracle(s) in the exchange to get the latest price of a given index in a given currency, if a route exists.
90
+ * @param {string} base Index name, e.g. ETH.
91
+ * @param {string} quote Quote currency, e.g. USD.
92
+ * @returns {number} Price of index in given currency.
93
+ */
94
+ getOraclePrice(base, quote) {
95
+ return __awaiter(this, void 0, void 0, function* () {
96
+ if (this.proxyContract == null) {
97
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
98
+ }
99
+ let px = yield this.proxyContract.getOraclePrice([(0, utils_1.toBytes4)(base), (0, utils_1.toBytes4)(quote)]);
100
+ return px == undefined ? undefined : (0, d8XMath_1.ABK64x64ToFloat)(px);
101
+ });
102
+ }
103
+ /**
104
+ * Get the current mark price
105
+ * @param symbol symbol of the form ETH-USD-MATIC
106
+ * @returns mark price
107
+ */
108
+ getMarkPrice(symbol) {
109
+ return __awaiter(this, void 0, void 0, function* () {
110
+ if (this.proxyContract == null) {
111
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
112
+ }
113
+ return yield perpetualDataHandler_1.default._queryPerpetualMarkPrice(symbol, this.symbolToPerpStaticInfo, this.proxyContract);
114
+ });
115
+ }
116
+ /**
117
+ * get the current price for a given quantity
118
+ * @param symbol symbol of the form ETH-USD-MATIC
119
+ * @param quantity quantity to be traded, negative if short
120
+ * @returns price (number)
121
+ */
122
+ getPerpetualPrice(symbol, quantity) {
123
+ return __awaiter(this, void 0, void 0, function* () {
124
+ if (this.proxyContract == null) {
125
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
126
+ }
127
+ return yield perpetualDataHandler_1.default._queryPerpetualPrice(symbol, quantity, this.symbolToPerpStaticInfo, this.proxyContract);
128
+ });
129
+ }
78
130
  /**
79
131
  * Query smart contract to get user orders and convert to user friendly order format.
80
132
  * @param {string} traderAddr Address of trader.
@@ -9,6 +9,7 @@ export declare const COLLATERAL_CURRENCY_BASE = 1;
9
9
  export declare const COLLATERAL_CURRENCY_QUANTO = 2;
10
10
  export declare const PERP_STATE_STR: string[];
11
11
  export declare const ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
12
+ export declare const ZERO_ORDER_ID = "0x0000000000000000000000000000000000000000000000000000000000000000";
12
13
  export declare const ONE_64x64: BigNumber;
13
14
  export declare const MAX_64x64: BigNumber;
14
15
  export declare const MAX_UINT_256: BigNumber;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.CollaterlCCY = exports.CLOSED_SIDE = exports.SELL_SIDE = exports.BUY_SIDE = exports.ORDER_TYPE_STOP_LIMIT = exports.ORDER_TYPE_STOP_MARKET = exports.ORDER_TYPE_MARKET = exports.ORDER_TYPE_LIMIT = exports.MASK_KEEP_POS_LEVERAGE = exports.MASK_STOP_ORDER = exports.MASK_MARKET_ORDER = exports.MASK_LIMIT_ORDER = exports.MASK_CLOSE_ONLY = exports.ORDER_MAX_DURATION_SEC = exports.DECIMALS = exports.MAX_UINT_256 = exports.MAX_64x64 = exports.ONE_64x64 = exports.ZERO_ADDRESS = exports.PERP_STATE_STR = exports.COLLATERAL_CURRENCY_QUANTO = exports.COLLATERAL_CURRENCY_BASE = exports.COLLATERAL_CURRENCY_QUOTE = exports.ERC20_ABI = exports.DEFAULT_CONFIG_MAINNET_NAME = exports.DEFAULT_CONFIG_TESTNET_NAME = exports.DEFAULT_CONFIG_MAINNET = exports.DEFAULT_CONFIG_TESTNET = void 0;
3
+ exports.CollaterlCCY = exports.CLOSED_SIDE = exports.SELL_SIDE = exports.BUY_SIDE = exports.ORDER_TYPE_STOP_LIMIT = exports.ORDER_TYPE_STOP_MARKET = exports.ORDER_TYPE_MARKET = exports.ORDER_TYPE_LIMIT = exports.MASK_KEEP_POS_LEVERAGE = exports.MASK_STOP_ORDER = exports.MASK_MARKET_ORDER = exports.MASK_LIMIT_ORDER = exports.MASK_CLOSE_ONLY = exports.ORDER_MAX_DURATION_SEC = exports.DECIMALS = exports.MAX_UINT_256 = exports.MAX_64x64 = exports.ONE_64x64 = exports.ZERO_ORDER_ID = exports.ZERO_ADDRESS = exports.PERP_STATE_STR = exports.COLLATERAL_CURRENCY_QUANTO = exports.COLLATERAL_CURRENCY_BASE = exports.COLLATERAL_CURRENCY_QUOTE = exports.ERC20_ABI = exports.DEFAULT_CONFIG_MAINNET_NAME = exports.DEFAULT_CONFIG_TESTNET_NAME = exports.DEFAULT_CONFIG_MAINNET = exports.DEFAULT_CONFIG_TESTNET = void 0;
4
4
  const ethers_1 = require("ethers");
5
5
  exports.DEFAULT_CONFIG_TESTNET = "../config/defaultConfig.json";
6
6
  exports.DEFAULT_CONFIG_MAINNET = "notthereyet";
@@ -11,7 +11,8 @@ exports.COLLATERAL_CURRENCY_QUOTE = 0;
11
11
  exports.COLLATERAL_CURRENCY_BASE = 1;
12
12
  exports.COLLATERAL_CURRENCY_QUANTO = 2;
13
13
  exports.PERP_STATE_STR = ["INVALID", "INITIALIZING", "NORMAL", "EMERGENCY", "CLEARED"];
14
- exports.ZERO_ADDRESS = "0x0000000000000000000000000000000000000000";
14
+ exports.ZERO_ADDRESS = ethers_1.constants.AddressZero;
15
+ exports.ZERO_ORDER_ID = ethers_1.constants.HashZero;
15
16
  exports.ONE_64x64 = ethers_1.BigNumber.from("0x010000000000000000");
16
17
  exports.MAX_64x64 = ethers_1.BigNumber.from("0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
17
18
  exports.MAX_UINT_256 = ethers_1.BigNumber.from(2).pow(256).sub(ethers_1.BigNumber.from(1));
@@ -19,7 +19,7 @@ export default class OrderReferrerTool extends WriteAccessHandler {
19
19
  * if different from the one submitting this transaction.
20
20
  * @returns Transaction object.
21
21
  */
22
- executeOrder(symbol: string, orderId: string, referrerAddr?: string): Promise<ethers.providers.TransactionResponse>;
22
+ executeOrder(symbol: string, orderId: string, referrerAddr?: string): Promise<ethers.ContractTransaction>;
23
23
  /**
24
24
  * All the orders in the order book for a given symbol that are currently open.
25
25
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
@@ -32,14 +32,26 @@ export default class OrderReferrerTool extends WriteAccessHandler {
32
32
  * @returns {number} Number of open orders.
33
33
  */
34
34
  numberOfOpenOrders(symbol: string): Promise<number>;
35
+ /**
36
+ * Get order from the digest (=id)
37
+ * @param symbol symbol of order book, e.g. ETH-USD-MATIC
38
+ * @param digest digest of the order (=order ID)
39
+ * @returns order or undefined
40
+ */
41
+ getOrderById(symbol: string, id: string): Promise<Order | undefined>;
35
42
  /**
36
43
  * Get a list of active conditional orders in the order book.
37
44
  * This a read-only action and does not incur in gas costs.
38
45
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
39
46
  * @param {number} numElements Maximum number of orders to poll.
40
47
  * @param {string=} startAfter Optional order ID from where to start polling. Defaults to the first order.
41
- * @returns {[Order[], string[]]} Array of orders and corresponding order IDs
48
+ * @returns Array of orders and corresponding order IDs
42
49
  */
43
50
  pollLimitOrders(symbol: string, numElements: number, startAfter?: string): Promise<[Order[], string[]]>;
51
+ /**
52
+ * Check if a conditional order can be executed
53
+ * @param order order structure
54
+ * @returns true if order can be executed for the current state of the perpetuals
55
+ */
44
56
  isTradeable(order: Order): Promise<boolean>;
45
57
  }
@@ -71,13 +71,30 @@ class OrderReferrerTool extends writeAccessHandler_1.default {
71
71
  return yield orderBookSC.numberOfOrderBookDigests();
72
72
  });
73
73
  }
74
+ /**
75
+ * Get order from the digest (=id)
76
+ * @param symbol symbol of order book, e.g. ETH-USD-MATIC
77
+ * @param digest digest of the order (=order ID)
78
+ * @returns order or undefined
79
+ */
80
+ getOrderById(symbol, id) {
81
+ return __awaiter(this, void 0, void 0, function* () {
82
+ let ob = yield this.getOrderBookContract(symbol);
83
+ let smartContractOrder = yield ob.orderOfDigest(id);
84
+ if (smartContractOrder.traderAddr == nodeSDKTypes_1.ZERO_ADDRESS) {
85
+ return undefined;
86
+ }
87
+ let order = OrderReferrerTool.fromSmartContractOrder(smartContractOrder, this.symbolToPerpStaticInfo);
88
+ return order;
89
+ });
90
+ }
74
91
  /**
75
92
  * Get a list of active conditional orders in the order book.
76
93
  * This a read-only action and does not incur in gas costs.
77
94
  * @param {string} symbol Symbol of the form ETH-USD-MATIC.
78
95
  * @param {number} numElements Maximum number of orders to poll.
79
96
  * @param {string=} startAfter Optional order ID from where to start polling. Defaults to the first order.
80
- * @returns {[Order[], string[]]} Array of orders and corresponding order IDs
97
+ * @returns Array of orders and corresponding order IDs
81
98
  */
82
99
  pollLimitOrders(symbol, numElements, startAfter) {
83
100
  return __awaiter(this, void 0, void 0, function* () {
@@ -85,7 +102,7 @@ class OrderReferrerTool extends writeAccessHandler_1.default {
85
102
  throw Error("no proxy contract initialized. Use createProxyInstance().");
86
103
  }
87
104
  if (typeof startAfter == "undefined") {
88
- startAfter = nodeSDKTypes_1.ZERO_ADDRESS;
105
+ startAfter = nodeSDKTypes_1.ZERO_ORDER_ID;
89
106
  }
90
107
  const orderBookSC = this.getOrderBookContract(symbol);
91
108
  let [orders, orderIds] = yield orderBookSC.pollLimitOrders(startAfter, numElements);
@@ -98,6 +115,11 @@ class OrderReferrerTool extends writeAccessHandler_1.default {
98
115
  return [userFriendlyOrders, orderIds];
99
116
  });
100
117
  }
118
+ /**
119
+ * Check if a conditional order can be executed
120
+ * @param order order structure
121
+ * @returns true if order can be executed for the current state of the perpetuals
122
+ */
101
123
  isTradeable(order) {
102
124
  return __awaiter(this, void 0, void 0, function* () {
103
125
  if (this.proxyContract == null) {
@@ -107,7 +129,7 @@ class OrderReferrerTool extends writeAccessHandler_1.default {
107
129
  throw Error("order does not have a limit price");
108
130
  }
109
131
  // check expiration date
110
- if (order.deadline != undefined && order.deadline < Date.now()) {
132
+ if (order.deadline != undefined && order.deadline < Date.now() / 1000) {
111
133
  return false;
112
134
  }
113
135
  // check limit price
@@ -229,7 +229,7 @@ class PerpetualDataHandler {
229
229
  return __awaiter(this, void 0, void 0, function* () {
230
230
  let perpId = PerpetualDataHandler.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
231
231
  let ammState = yield _proxyContract.getAMMState(perpId);
232
- return (0, d8XMath_1.ABK64x64ToFloat)(ammState[6].mul(nodeSDKTypes_1.ONE_64x64.add(ammState[8])));
232
+ return (0, d8XMath_1.ABK64x64ToFloat)(ammState[6].mul(nodeSDKTypes_1.ONE_64x64.add(ammState[8])).div(nodeSDKTypes_1.ONE_64x64));
233
233
  });
234
234
  }
235
235
  /**
@@ -310,16 +310,20 @@ class PerpetualDataHandler {
310
310
  // concatenate and find perpetual Id in map
311
311
  return symbols[0] + "-" + symbols[1] + "-" + symbols[2];
312
312
  }
313
- static _getByValue(map, searchValue) {
313
+ static _getByValue(map, searchValue, valueField) {
314
314
  for (let [key, value] of map.entries()) {
315
- if (value === searchValue) {
315
+ if (value[valueField] === searchValue) {
316
316
  return key;
317
317
  }
318
318
  }
319
+ return undefined;
319
320
  }
320
321
  static fromSmartContractOrder(order, symbolToPerpInfoMap) {
321
322
  // find symbol of perpetual id
322
- let symbol = PerpetualDataHandler._getByValue(symbolToPerpInfoMap, order.iPerpetualId);
323
+ let symbol = PerpetualDataHandler._getByValue(symbolToPerpInfoMap, order.iPerpetualId, "id");
324
+ if (symbol == undefined) {
325
+ throw Error(`Perpetual id ${order.iPerpetualId} not found. Check with marketData.exchangeInfo().`);
326
+ }
323
327
  let side = order.fAmount > 0 ? nodeSDKTypes_1.BUY_SIDE : nodeSDKTypes_1.SELL_SIDE;
324
328
  let limitPrice, stopPrice;
325
329
  let fLimitPrice = ethers_1.BigNumber.from(order.fLimitPrice);
@@ -344,9 +348,9 @@ class PerpetualDataHandler {
344
348
  reduceOnly: (0, utils_1.containsFlag)(ethers_1.BigNumber.from(order.flags), nodeSDKTypes_1.MASK_CLOSE_ONLY),
345
349
  limitPrice: limitPrice,
346
350
  keepPositionLvg: (0, utils_1.containsFlag)(ethers_1.BigNumber.from(order.flags), nodeSDKTypes_1.MASK_KEEP_POS_LEVERAGE),
347
- brokerFeeTbps: Number(order.brokerFeeTbps),
348
- brokerAddr: order.brokerAddr,
349
- brokerSignature: order.brokerSignature,
351
+ brokerFeeTbps: order.brokerFeeTbps == 0 ? undefined : Number(order.brokerFeeTbps),
352
+ brokerAddr: order.brokerAddr == nodeSDKTypes_1.ZERO_ADDRESS ? undefined : order.brokerAddr,
353
+ brokerSignature: order.brokerSignature == "0x" ? undefined : order.brokerSignature,
350
354
  stopPrice: stopPrice,
351
355
  leverage: (0, d8XMath_1.ABK64x64ToFloat)(ethers_1.BigNumber.from(order.fLeverage)),
352
356
  deadline: Number(order.iDeadline),
@@ -29,8 +29,8 @@ export default class WriteAccessHandler extends PerpetualDataHandler {
29
29
  * Set allowance for ar margin token (e.g., MATIC, ETH, USDC)
30
30
  * @param symbol token in 'long-form' such as MATIC, symbol also fine (ETH-USD-MATIC)
31
31
  * @param amount optional, amount to approve if not 'infinity'
32
- * @returns transaction hash
32
+ * @returns ContractTransaction
33
33
  */
34
- setAllowance(symbol: string, amount?: number | undefined): Promise<string>;
35
- protected static _setAllowance(tokenAddr: string, proxyAddr: string, signer: ethers.Wallet, amount: BigNumber): Promise<string>;
34
+ setAllowance(symbol: string, amount?: number | undefined): Promise<ethers.ContractTransaction>;
35
+ protected static _setAllowance(tokenAddr: string, proxyAddr: string, signer: ethers.Wallet, amount: BigNumber): Promise<ethers.ContractTransaction>;
36
36
  }
@@ -59,7 +59,7 @@ class WriteAccessHandler extends perpetualDataHandler_1.default {
59
59
  * Set allowance for ar margin token (e.g., MATIC, ETH, USDC)
60
60
  * @param symbol token in 'long-form' such as MATIC, symbol also fine (ETH-USD-MATIC)
61
61
  * @param amount optional, amount to approve if not 'infinity'
62
- * @returns transaction hash
62
+ * @returns ContractTransaction
63
63
  */
64
64
  setAllowance(symbol, amount = undefined) {
65
65
  return __awaiter(this, void 0, void 0, function* () {
@@ -87,8 +87,7 @@ class WriteAccessHandler extends perpetualDataHandler_1.default {
87
87
  return __awaiter(this, void 0, void 0, function* () {
88
88
  const marginToken = new ethers_1.ethers.Contract(tokenAddr, nodeSDKTypes_1.ERC20_ABI, signer);
89
89
  let tx = yield marginToken.approve(proxyAddr, amount);
90
- yield tx.wait();
91
- return tx.hash;
90
+ return tx;
92
91
  });
93
92
  }
94
93
  }
package/package.json CHANGED
@@ -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.7",
30
+ "version": "0.0.8",
31
31
  "main": "./dist/index.js",
32
32
  "types": "./dist/index.d.ts",
33
33
  "directories": {