@d8x/perpetuals-sdk 0.0.23 → 0.0.25
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.
- package/config/symbolList.json +13 -9
- package/dist/accountTrade.d.ts +2 -18
- package/dist/accountTrade.js +4 -70
- package/dist/apiInterface.d.ts +40 -0
- package/dist/apiInterface.js +92 -0
- package/dist/brokerTool.d.ts +2 -5
- package/dist/brokerTool.js +3 -8
- package/dist/d8XMath.d.ts +1 -1
- package/dist/d8XMath.js +1 -1
- package/dist/liquidatorTool.d.ts +4 -3
- package/dist/liquidatorTool.js +2 -5
- package/dist/marketData.d.ts +2 -3
- package/dist/marketData.js +11 -0
- package/dist/orderReferrerTool.d.ts +2 -1
- package/dist/orderReferrerTool.js +11 -2
- package/dist/perpetualDataHandler.d.ts +1 -3
- package/dist/perpetualDataHandler.js +18 -16
- package/dist/perpetualEventHandler.d.ts +2 -1
- package/dist/perpetualEventHandler.js +10 -5
- package/dist/traderDigests.d.ts +21 -0
- package/dist/traderDigests.js +80 -0
- package/dist/utils.d.ts +12 -9
- package/dist/utils.js +30 -16
- package/package.json +1 -1
- package/src/accountTrade.ts +7 -90
- package/src/apiInterface.ts +79 -0
- package/src/brokerTool.ts +4 -9
- package/src/d8XMath.ts +1 -1
- package/src/liquidatorTool.ts +8 -5
- package/src/marketData.ts +11 -1
- package/src/orderReferrerTool.ts +10 -10
- package/src/perpetualDataHandler.ts +17 -15
- package/src/perpetualEventHandler.ts +23 -5
- package/src/traderDigests.ts +90 -0
- package/src/utils.ts +28 -16
package/config/symbolList.json
CHANGED
|
@@ -1,9 +1,13 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
1
|
+
{
|
|
2
|
+
"MATC": "MATIC",
|
|
3
|
+
"ETH": "ETH",
|
|
4
|
+
"BTC": "BTC",
|
|
5
|
+
"USDC": "USDC",
|
|
6
|
+
"XAU": "XAU",
|
|
7
|
+
"XAG": "XAG",
|
|
8
|
+
"USD": "USD",
|
|
9
|
+
"GBP": "GBP",
|
|
10
|
+
"CHF": "CHF",
|
|
11
|
+
"EUR": "EUR",
|
|
12
|
+
"JPY": "JPY"
|
|
13
|
+
}
|
package/dist/accountTrade.d.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { ethers } from "ethers";
|
|
2
2
|
import { NodeSDKConfig, Order, PerpetualStaticInfo, OrderResponse } from "./nodeSDKTypes";
|
|
3
3
|
import WriteAccessHandler from "./writeAccessHandler";
|
|
4
|
+
import TraderDigests from "./traderDigests";
|
|
4
5
|
/**
|
|
5
6
|
* Functions to create, submit and cancel orders on the exchange.
|
|
6
7
|
* This class requires a private key and executes smart-contract interactions that
|
|
@@ -8,6 +9,7 @@ import WriteAccessHandler from "./writeAccessHandler";
|
|
|
8
9
|
* @extends WriteAccessHandler
|
|
9
10
|
*/
|
|
10
11
|
export default class AccountTrade extends WriteAccessHandler {
|
|
12
|
+
protected digestTool: TraderDigests;
|
|
11
13
|
/**
|
|
12
14
|
* Constructor
|
|
13
15
|
* @param {NodeSDKConfig} config Configuration object, see PerpetualDataHandler.
|
|
@@ -204,22 +206,4 @@ export default class AccountTrade extends WriteAccessHandler {
|
|
|
204
206
|
* @ignore
|
|
205
207
|
*/
|
|
206
208
|
private _createSignature;
|
|
207
|
-
/**
|
|
208
|
-
* Creates an order-id from the digest. Order-id is the 'digest' used in the smart contract.
|
|
209
|
-
* @param digest created with _createDigest
|
|
210
|
-
* @returns orderId string
|
|
211
|
-
* @ignore
|
|
212
|
-
*/
|
|
213
|
-
private createOrderId;
|
|
214
|
-
/**
|
|
215
|
-
* Creates a digest (order-id)
|
|
216
|
-
* @param order smart-contract-type order
|
|
217
|
-
* @param chainId chainId of network
|
|
218
|
-
* @param isNewOrder true unless we cancel
|
|
219
|
-
* @param signer ethereum-type wallet
|
|
220
|
-
* @param proxyAddress address of the contract
|
|
221
|
-
* @returns digest
|
|
222
|
-
* @ignore
|
|
223
|
-
*/
|
|
224
|
-
private _createDigest;
|
|
225
209
|
}
|
package/dist/accountTrade.js
CHANGED
|
@@ -12,14 +12,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
12
12
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
13
|
};
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
const ethers_1 = require("ethers");
|
|
16
|
-
const strings_1 = require("@ethersproject/strings");
|
|
17
|
-
const bytes_1 = require("@ethersproject/bytes");
|
|
18
15
|
const d8XMath_1 = require("./d8XMath");
|
|
19
16
|
const marketData_1 = __importDefault(require("./marketData"));
|
|
20
17
|
const nodeSDKTypes_1 = require("./nodeSDKTypes");
|
|
21
18
|
const perpetualDataHandler_1 = __importDefault(require("./perpetualDataHandler"));
|
|
22
19
|
const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
|
|
20
|
+
const traderDigests_1 = __importDefault(require("./traderDigests"));
|
|
23
21
|
/**
|
|
24
22
|
* Functions to create, submit and cancel orders on the exchange.
|
|
25
23
|
* This class requires a private key and executes smart-contract interactions that
|
|
@@ -49,6 +47,7 @@ class AccountTrade extends writeAccessHandler_1.default {
|
|
|
49
47
|
*/
|
|
50
48
|
constructor(config, privateKey) {
|
|
51
49
|
super(config, privateKey);
|
|
50
|
+
this.digestTool = new traderDigests_1.default();
|
|
52
51
|
}
|
|
53
52
|
/**
|
|
54
53
|
* Cancels an existing order on the exchange.
|
|
@@ -154,8 +153,6 @@ class AccountTrade extends writeAccessHandler_1.default {
|
|
|
154
153
|
throw Error("order size too small");
|
|
155
154
|
}
|
|
156
155
|
let orderBookContract = this.getOrderBookContract(order.symbol);
|
|
157
|
-
let tx;
|
|
158
|
-
let orderId;
|
|
159
156
|
let res = yield this._order(order, this.traderAddr, this.symbolToPerpStaticInfo, this.proxyContract, orderBookContract, this.chainId, this.signer, this.gasLimit);
|
|
160
157
|
return res;
|
|
161
158
|
});
|
|
@@ -279,7 +276,7 @@ class AccountTrade extends writeAccessHandler_1.default {
|
|
|
279
276
|
// all orders are sent to the order-book
|
|
280
277
|
let [signature, digest] = yield this._createSignature(scOrder, chainId, true, signer, proxyContract.address);
|
|
281
278
|
tx = yield orderBookContract.postOrder(scOrder, signature, { gasLimit: gasLimit });
|
|
282
|
-
let id = yield this.createOrderId(digest);
|
|
279
|
+
let id = yield this.digestTool.createOrderId(digest);
|
|
283
280
|
return { tx: tx, orderId: id };
|
|
284
281
|
});
|
|
285
282
|
}
|
|
@@ -305,74 +302,11 @@ class AccountTrade extends writeAccessHandler_1.default {
|
|
|
305
302
|
*/
|
|
306
303
|
_createSignature(order, chainId, isNewOrder, signer, proxyAddress) {
|
|
307
304
|
return __awaiter(this, void 0, void 0, function* () {
|
|
308
|
-
let digest = yield this.
|
|
305
|
+
let digest = yield this.digestTool.createDigest(order, chainId, isNewOrder, proxyAddress);
|
|
309
306
|
let digestBuffer = Buffer.from(digest.substring(2, digest.length), "hex");
|
|
310
307
|
let signature = yield signer.signMessage(digestBuffer);
|
|
311
308
|
return [signature, digest];
|
|
312
309
|
});
|
|
313
310
|
}
|
|
314
|
-
/**
|
|
315
|
-
* Creates an order-id from the digest. Order-id is the 'digest' used in the smart contract.
|
|
316
|
-
* @param digest created with _createDigest
|
|
317
|
-
* @returns orderId string
|
|
318
|
-
* @ignore
|
|
319
|
-
*/
|
|
320
|
-
createOrderId(digest) {
|
|
321
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
322
|
-
let digestBuffer = Buffer.from(digest.substring(2, digest.length), "hex");
|
|
323
|
-
const messagePrefix = "\x19Ethereum Signed Message:\n";
|
|
324
|
-
let tmp = (0, bytes_1.concat)([(0, strings_1.toUtf8Bytes)(messagePrefix), (0, strings_1.toUtf8Bytes)(String(digestBuffer.length)), digestBuffer]);
|
|
325
|
-
// see: https://github.com/ethers-io/ethers.js/blob/c80fcddf50a9023486e9f9acb1848aba4c19f7b6/packages/hash/src.ts/message.ts#L7
|
|
326
|
-
return ethers_1.ethers.utils.keccak256(tmp);
|
|
327
|
-
});
|
|
328
|
-
}
|
|
329
|
-
/**
|
|
330
|
-
* Creates a digest (order-id)
|
|
331
|
-
* @param order smart-contract-type order
|
|
332
|
-
* @param chainId chainId of network
|
|
333
|
-
* @param isNewOrder true unless we cancel
|
|
334
|
-
* @param signer ethereum-type wallet
|
|
335
|
-
* @param proxyAddress address of the contract
|
|
336
|
-
* @returns digest
|
|
337
|
-
* @ignore
|
|
338
|
-
*/
|
|
339
|
-
_createDigest(order, chainId, isNewOrder, proxyAddress) {
|
|
340
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
341
|
-
const NAME = "Perpetual Trade Manager";
|
|
342
|
-
const DOMAIN_TYPEHASH = ethers_1.ethers.utils.keccak256(Buffer.from("EIP712Domain(string name,uint256 chainId,address verifyingContract)"));
|
|
343
|
-
let abiCoder = ethers_1.ethers.utils.defaultAbiCoder;
|
|
344
|
-
let domainSeparator = ethers_1.ethers.utils.keccak256(abiCoder.encode(["bytes32", "bytes32", "uint256", "address"], [DOMAIN_TYPEHASH, ethers_1.ethers.utils.keccak256(Buffer.from(NAME)), chainId, proxyAddress]));
|
|
345
|
-
const TRADE_ORDER_TYPEHASH = ethers_1.ethers.utils.keccak256(Buffer.from("Order(uint24 iPerpetualId,uint16 brokerFeeTbps,address traderAddr,address brokerAddr,int128 fAmount,int128 fLimitPrice,int128 fTriggerPrice,uint64 iDeadline,uint32 flags,int128 fLeverage,uint64 createdTimestamp)"));
|
|
346
|
-
let structHash = ethers_1.ethers.utils.keccak256(abiCoder.encode([
|
|
347
|
-
"bytes32",
|
|
348
|
-
"uint24",
|
|
349
|
-
"uint16",
|
|
350
|
-
"address",
|
|
351
|
-
"address",
|
|
352
|
-
"int128",
|
|
353
|
-
"int128",
|
|
354
|
-
"int128",
|
|
355
|
-
"uint64",
|
|
356
|
-
"uint32",
|
|
357
|
-
"int128",
|
|
358
|
-
"uint64",
|
|
359
|
-
], [
|
|
360
|
-
TRADE_ORDER_TYPEHASH,
|
|
361
|
-
order.iPerpetualId,
|
|
362
|
-
order.brokerFeeTbps,
|
|
363
|
-
order.traderAddr,
|
|
364
|
-
order.brokerAddr,
|
|
365
|
-
order.fAmount,
|
|
366
|
-
order.fLimitPrice,
|
|
367
|
-
order.fTriggerPrice,
|
|
368
|
-
order.iDeadline,
|
|
369
|
-
order.flags,
|
|
370
|
-
order.fLeverage,
|
|
371
|
-
order.createdTimestamp,
|
|
372
|
-
]));
|
|
373
|
-
let digest = ethers_1.ethers.utils.keccak256(abiCoder.encode(["bytes32", "bytes32", "bool"], [domainSeparator, structHash, isNewOrder]));
|
|
374
|
-
return digest;
|
|
375
|
-
});
|
|
376
|
-
}
|
|
377
311
|
}
|
|
378
312
|
exports.default = AccountTrade;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { ethers } from "ethers";
|
|
2
|
+
import MarketData from "./marketData";
|
|
3
|
+
import { NodeSDKConfig, SmartContractOrder, Order } from "./nodeSDKTypes";
|
|
4
|
+
import TraderDigests from "./traderDigests";
|
|
5
|
+
export default class APIInterface extends MarketData {
|
|
6
|
+
protected chainId: number;
|
|
7
|
+
protected digestTool: TraderDigests;
|
|
8
|
+
constructor(config: NodeSDKConfig);
|
|
9
|
+
/**
|
|
10
|
+
* Initialize the marketData-Class with this function
|
|
11
|
+
* to create instance of D8X perpetual contract and gather information
|
|
12
|
+
* about perpetual currencies
|
|
13
|
+
* @param provider optional provider
|
|
14
|
+
*/
|
|
15
|
+
createProxyInstance(provider?: ethers.providers.JsonRpcProvider): Promise<void>;
|
|
16
|
+
/**
|
|
17
|
+
* Get digest to cancel an order. Digest needs to be signed and submitted via
|
|
18
|
+
* orderBookContract.cancelOrder(orderId, signature);
|
|
19
|
+
* @param symbol
|
|
20
|
+
* @param orderId
|
|
21
|
+
* @returns tuple of digest which the trader needs to sign and address of order book contract
|
|
22
|
+
*/
|
|
23
|
+
cancelOrderDigest(symbol: string, orderId: string): Promise<{
|
|
24
|
+
digest: string;
|
|
25
|
+
OBContractAddr: string;
|
|
26
|
+
}>;
|
|
27
|
+
/**
|
|
28
|
+
* Create smart contract order and digest that the trader signs.
|
|
29
|
+
* await orderBookContract.postOrder(scOrder, signature, { gasLimit: gasLimit });
|
|
30
|
+
* Order must contain broker fee and broker address if there is supposed to be a broker.
|
|
31
|
+
* @param order order struct
|
|
32
|
+
* @param traderAddr address of the trader
|
|
33
|
+
* @returns tuple of digest that the trader has to sign, order book address, and smart contract order
|
|
34
|
+
*/
|
|
35
|
+
orderDigest(order: Order, traderAddr: string): Promise<{
|
|
36
|
+
digest: string;
|
|
37
|
+
OBAddr: string;
|
|
38
|
+
SCOrder: SmartContractOrder;
|
|
39
|
+
}>;
|
|
40
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
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 marketData_1 = __importDefault(require("./marketData"));
|
|
16
|
+
const perpetualDataHandler_1 = __importDefault(require("./perpetualDataHandler"));
|
|
17
|
+
const traderDigests_1 = __importDefault(require("./traderDigests"));
|
|
18
|
+
/*
|
|
19
|
+
interface that can be used by front-end that wraps all private functions
|
|
20
|
+
so that signatures can be handled in frontend via wallet
|
|
21
|
+
|
|
22
|
+
*/
|
|
23
|
+
class APIInterface extends marketData_1.default {
|
|
24
|
+
// accTrade.order(order)
|
|
25
|
+
// cancelOrder(symbol: string, orderId: string)
|
|
26
|
+
// accTrade.setAllowance
|
|
27
|
+
// accTrade.queryExchangeFee("MATIC")
|
|
28
|
+
// accTrade.getCurrentTraderVolume("MATIC")
|
|
29
|
+
// accTrade.getOrderIds("MATIC-USD-MATIC")
|
|
30
|
+
constructor(config) {
|
|
31
|
+
super(config);
|
|
32
|
+
this.chainId = 0;
|
|
33
|
+
this.digestTool = new traderDigests_1.default();
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Initialize the marketData-Class with this function
|
|
37
|
+
* to create instance of D8X perpetual contract and gather information
|
|
38
|
+
* about perpetual currencies
|
|
39
|
+
* @param provider optional provider
|
|
40
|
+
*/
|
|
41
|
+
createProxyInstance(provider) {
|
|
42
|
+
const _super = Object.create(null, {
|
|
43
|
+
createProxyInstance: { get: () => super.createProxyInstance }
|
|
44
|
+
});
|
|
45
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
46
|
+
yield _super.createProxyInstance.call(this, provider);
|
|
47
|
+
this.chainId = (yield this.provider.getNetwork()).chainId;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Get digest to cancel an order. Digest needs to be signed and submitted via
|
|
52
|
+
* orderBookContract.cancelOrder(orderId, signature);
|
|
53
|
+
* @param symbol
|
|
54
|
+
* @param orderId
|
|
55
|
+
* @returns tuple of digest which the trader needs to sign and address of order book contract
|
|
56
|
+
*/
|
|
57
|
+
cancelOrderDigest(symbol, orderId) {
|
|
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 orderBookContract = this.getOrderBookContract(symbol);
|
|
63
|
+
let scOrder = yield orderBookContract.orderOfDigest(orderId);
|
|
64
|
+
let digest = yield this.digestTool.createDigest(scOrder, this.chainId, false, this.proxyAddr);
|
|
65
|
+
return { digest: digest, OBContractAddr: orderBookContract.address };
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Create smart contract order and digest that the trader signs.
|
|
70
|
+
* await orderBookContract.postOrder(scOrder, signature, { gasLimit: gasLimit });
|
|
71
|
+
* Order must contain broker fee and broker address if there is supposed to be a broker.
|
|
72
|
+
* @param order order struct
|
|
73
|
+
* @param traderAddr address of the trader
|
|
74
|
+
* @returns tuple of digest that the trader has to sign, order book address, and smart contract order
|
|
75
|
+
*/
|
|
76
|
+
orderDigest(order, traderAddr) {
|
|
77
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
78
|
+
if (this.proxyContract == null) {
|
|
79
|
+
throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
|
|
80
|
+
}
|
|
81
|
+
let minSize = perpetualDataHandler_1.default._getMinimalPositionSize(order.symbol, this.symbolToPerpStaticInfo);
|
|
82
|
+
if (Math.abs(order.quantity) < minSize) {
|
|
83
|
+
throw Error("order size too small");
|
|
84
|
+
}
|
|
85
|
+
let orderBookContract = this.getOrderBookContract(order.symbol);
|
|
86
|
+
let scOrder = APIInterface.toSmartContractOrder(order, traderAddr, this.symbolToPerpStaticInfo);
|
|
87
|
+
let digest = yield this.digestTool.createDigest(scOrder, this.chainId, true, this.proxyContract.address);
|
|
88
|
+
return { digest: digest, OBAddr: orderBookContract.address, SCOrder: scOrder };
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
exports.default = APIInterface;
|
package/dist/brokerTool.d.ts
CHANGED
|
@@ -249,11 +249,8 @@ export default class BrokerTool extends WriteAccessHandler {
|
|
|
249
249
|
/**
|
|
250
250
|
* Adds this broker's signature to an order. An order signed by a broker is considered
|
|
251
251
|
* to be routed through this broker and benefits from the broker's fee conditions.
|
|
252
|
-
* @param {Order} order Order to sign.
|
|
252
|
+
* @param {Order} order Order to sign. It must contain valid broker fee, broker address, and order deadline.
|
|
253
253
|
* @param {string} traderAddr Address of trader submitting the order.
|
|
254
|
-
* @param {number} feeDecimals Fee that this broker imposes on this order.
|
|
255
|
-
* The fee is sent to the broker's wallet. Fee should be specified in decimals, e.g., 0.0001 equals 1bps.
|
|
256
|
-
* @param {number} deadline Deadline for the order to be executed. Specify deadline as a unix timestamp
|
|
257
254
|
* @example
|
|
258
255
|
* import { BrokerTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
|
|
259
256
|
* async function main() {
|
|
@@ -281,7 +278,7 @@ export default class BrokerTool extends WriteAccessHandler {
|
|
|
281
278
|
*
|
|
282
279
|
* @returns {Order} An order signed by this broker, which can be submitted directly with AccountTrade.order.
|
|
283
280
|
*/
|
|
284
|
-
signOrder(order: Order, traderAddr: string
|
|
281
|
+
signOrder(order: Order, traderAddr: string): Promise<Order>;
|
|
285
282
|
/**
|
|
286
283
|
* Creates a signature that a trader can use to place orders with this broker.
|
|
287
284
|
* This signature can be used to pass on to a trader who wishes to trade via this SDK or directly on the blockchain.
|
package/dist/brokerTool.js
CHANGED
|
@@ -367,11 +367,8 @@ class BrokerTool extends writeAccessHandler_1.default {
|
|
|
367
367
|
/**
|
|
368
368
|
* Adds this broker's signature to an order. An order signed by a broker is considered
|
|
369
369
|
* to be routed through this broker and benefits from the broker's fee conditions.
|
|
370
|
-
* @param {Order} order Order to sign.
|
|
370
|
+
* @param {Order} order Order to sign. It must contain valid broker fee, broker address, and order deadline.
|
|
371
371
|
* @param {string} traderAddr Address of trader submitting the order.
|
|
372
|
-
* @param {number} feeDecimals Fee that this broker imposes on this order.
|
|
373
|
-
* The fee is sent to the broker's wallet. Fee should be specified in decimals, e.g., 0.0001 equals 1bps.
|
|
374
|
-
* @param {number} deadline Deadline for the order to be executed. Specify deadline as a unix timestamp
|
|
375
372
|
* @example
|
|
376
373
|
* import { BrokerTool, PerpetualDataHandler } from '@d8x/perpetuals-sdk';
|
|
377
374
|
* async function main() {
|
|
@@ -399,15 +396,13 @@ class BrokerTool extends writeAccessHandler_1.default {
|
|
|
399
396
|
*
|
|
400
397
|
* @returns {Order} An order signed by this broker, which can be submitted directly with AccountTrade.order.
|
|
401
398
|
*/
|
|
402
|
-
signOrder(order, traderAddr
|
|
399
|
+
signOrder(order, traderAddr) {
|
|
403
400
|
return __awaiter(this, void 0, void 0, function* () {
|
|
404
401
|
if (this.proxyContract == null || this.signer == null) {
|
|
405
402
|
throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
|
|
406
403
|
}
|
|
407
404
|
order.brokerAddr = this.traderAddr;
|
|
408
|
-
order.
|
|
409
|
-
order.deadline = Math.round(deadline);
|
|
410
|
-
order.brokerSignature = yield BrokerTool._signOrder(order.symbol, order.brokerFeeTbps, traderAddr, ethers_1.BigNumber.from(Math.round(deadline)), this.signer, this.chainId, this.proxyAddr, this.symbolToPerpStaticInfo);
|
|
405
|
+
order.brokerSignature = yield BrokerTool._signOrder(order.symbol, order.brokerFeeTbps, traderAddr, ethers_1.BigNumber.from(order.deadline), this.signer, this.chainId, this.proxyAddr, this.symbolToPerpStaticInfo);
|
|
411
406
|
return order;
|
|
412
407
|
});
|
|
413
408
|
}
|
package/dist/d8XMath.d.ts
CHANGED
|
@@ -83,7 +83,7 @@ export declare function calculateLiquidationPriceCollateralQuote(LockedInValueQC
|
|
|
83
83
|
* @param indexPriceS3 Collateral index price, positive.
|
|
84
84
|
* @param tradePrice Expected price to trade tradeAmount.
|
|
85
85
|
* @param feeRate
|
|
86
|
-
* @returns
|
|
86
|
+
* @returns Total collateral amount needed for the new position to have he desired leverage.
|
|
87
87
|
*/
|
|
88
88
|
export declare function getMarginRequiredForLeveragedTrade(targetLeverage: number | undefined, currentPosition: number, currentLockedInValue: number, tradeAmount: number, markPrice: number, indexPriceS2: number, indexPriceS3: number, tradePrice: number, feeRate: number): number;
|
|
89
89
|
export declare function getMaxSignedPositionSize(marginCollateral: number, currentPosition: number, currentLockedInValue: number, direction: number, limitPrice: number, initialMarginRate: number, feeRate: number, markPrice: number, indexPriceS2: number, indexPriceS3: number): number;
|
package/dist/d8XMath.js
CHANGED
|
@@ -173,7 +173,7 @@ exports.calculateLiquidationPriceCollateralQuote = calculateLiquidationPriceColl
|
|
|
173
173
|
* @param indexPriceS3 Collateral index price, positive.
|
|
174
174
|
* @param tradePrice Expected price to trade tradeAmount.
|
|
175
175
|
* @param feeRate
|
|
176
|
-
* @returns
|
|
176
|
+
* @returns Total collateral amount needed for the new position to have he desired leverage.
|
|
177
177
|
*/
|
|
178
178
|
function getMarginRequiredForLeveragedTrade(targetLeverage, currentPosition, currentLockedInValue, tradeAmount, markPrice, indexPriceS2, indexPriceS3, tradePrice, feeRate) {
|
|
179
179
|
// we solve for margin in:
|
package/dist/liquidatorTool.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import WriteAccessHandler from "./writeAccessHandler";
|
|
2
2
|
import { NodeSDKConfig } from "./nodeSDKTypes";
|
|
3
|
+
import { ethers } from "ethers";
|
|
3
4
|
/**
|
|
4
5
|
* Functions to liquidate traders. This class requires a private key
|
|
5
6
|
* and executes smart-contract interactions that require gas-payments.
|
|
@@ -49,9 +50,9 @@ export default class LiquidatorTool extends WriteAccessHandler {
|
|
|
49
50
|
* }
|
|
50
51
|
* main();
|
|
51
52
|
*
|
|
52
|
-
* @returns
|
|
53
|
+
* @returns Transaction object.
|
|
53
54
|
*/
|
|
54
|
-
liquidateTrader(symbol: string, traderAddr: string, liquidatorAddr?: string): Promise<
|
|
55
|
+
liquidateTrader(symbol: string, traderAddr: string, liquidatorAddr?: string): Promise<ethers.ContractTransaction>;
|
|
55
56
|
/**
|
|
56
57
|
* Check if the collateral of a trader is above the maintenance margin ("maintenance margin safe").
|
|
57
58
|
* If not, the position can be liquidated.
|
|
@@ -85,7 +86,7 @@ export default class LiquidatorTool extends WriteAccessHandler {
|
|
|
85
86
|
* @param gasLimit Gas limit.
|
|
86
87
|
* @ignore
|
|
87
88
|
*/
|
|
88
|
-
_liquidateByAMM(perpetualId: number, liquidatorAddr: string, traderAddr: string, gasLimit: number): Promise<
|
|
89
|
+
_liquidateByAMM(perpetualId: number, liquidatorAddr: string, traderAddr: string, gasLimit: number): Promise<any>;
|
|
89
90
|
/**
|
|
90
91
|
* Total number of active accounts for this symbol, i.e. accounts with positions that are currently open.
|
|
91
92
|
* @param {string} symbol Symbol of the form ETH-USD-MATIC.
|
package/dist/liquidatorTool.js
CHANGED
|
@@ -13,7 +13,6 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
|
13
13
|
};
|
|
14
14
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
15
|
const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
|
|
16
|
-
const d8XMath_1 = require("./d8XMath");
|
|
17
16
|
/**
|
|
18
17
|
* Functions to liquidate traders. This class requires a private key
|
|
19
18
|
* and executes smart-contract interactions that require gas-payments.
|
|
@@ -65,7 +64,7 @@ class LiquidatorTool extends writeAccessHandler_1.default {
|
|
|
65
64
|
* }
|
|
66
65
|
* main();
|
|
67
66
|
*
|
|
68
|
-
* @returns
|
|
67
|
+
* @returns Transaction object.
|
|
69
68
|
*/
|
|
70
69
|
liquidateTrader(symbol, traderAddr, liquidatorAddr = "") {
|
|
71
70
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -129,12 +128,10 @@ class LiquidatorTool extends writeAccessHandler_1.default {
|
|
|
129
128
|
* @ignore
|
|
130
129
|
*/
|
|
131
130
|
_liquidateByAMM(perpetualId, liquidatorAddr, traderAddr, gasLimit) {
|
|
132
|
-
var _a;
|
|
133
131
|
return __awaiter(this, void 0, void 0, function* () {
|
|
134
|
-
|
|
132
|
+
return yield this.proxyContract.liquidateByAMM(perpetualId, liquidatorAddr, traderAddr, {
|
|
135
133
|
gasLimit: gasLimit,
|
|
136
134
|
});
|
|
137
|
-
return (0, d8XMath_1.ABK64x64ToFloat)((_a = tx.value) !== null && _a !== void 0 ? _a : 0);
|
|
138
135
|
});
|
|
139
136
|
}
|
|
140
137
|
/**
|
package/dist/marketData.d.ts
CHANGED
|
@@ -150,6 +150,7 @@ export default class MarketData extends PerpetualDataHandler {
|
|
|
150
150
|
* @returns {number} Price of index in given currency.
|
|
151
151
|
*/
|
|
152
152
|
getOraclePrice(base: string, quote: string): Promise<number | undefined>;
|
|
153
|
+
getOrderStatus(symbol: string, orderId: string): Promise<string>;
|
|
153
154
|
/**
|
|
154
155
|
* Get the current mark price
|
|
155
156
|
* @param symbol symbol of the form ETH-USD-MATIC
|
|
@@ -233,7 +234,5 @@ export default class MarketData extends PerpetualDataHandler {
|
|
|
233
234
|
* @ignore
|
|
234
235
|
*/
|
|
235
236
|
static orderIdsOfTrader(traderAddr: string, orderBookContract: ethers.Contract): Promise<string[]>;
|
|
236
|
-
static _exchangeInfo(_proxyContract: ethers.Contract, _poolStaticInfos: Array<PoolStaticInfo>, _symbolList:
|
|
237
|
-
[key: string]: string;
|
|
238
|
-
}>): Promise<ExchangeInfo>;
|
|
237
|
+
static _exchangeInfo(_proxyContract: ethers.Contract, _poolStaticInfos: Array<PoolStaticInfo>, _symbolList: Map<string, string>): Promise<ExchangeInfo>;
|
|
239
238
|
}
|
package/dist/marketData.js
CHANGED
|
@@ -293,6 +293,17 @@ class MarketData extends perpetualDataHandler_1.default {
|
|
|
293
293
|
return px == undefined ? undefined : (0, d8XMath_1.ABK64x64ToFloat)(px);
|
|
294
294
|
});
|
|
295
295
|
}
|
|
296
|
+
getOrderStatus(symbol, orderId) {
|
|
297
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
298
|
+
if (this.proxyContract == null) {
|
|
299
|
+
throw Error("no proxy contract initialized. Use createProxyInstance().");
|
|
300
|
+
}
|
|
301
|
+
let orderBookContract = null;
|
|
302
|
+
orderBookContract = this.getOrderBookContract(symbol);
|
|
303
|
+
let status = yield orderBookContract.getOrderStatus(orderId);
|
|
304
|
+
return status;
|
|
305
|
+
});
|
|
306
|
+
}
|
|
296
307
|
/**
|
|
297
308
|
* Get the current mark price
|
|
298
309
|
* @param symbol symbol of the form ETH-USD-MATIC
|
|
@@ -61,7 +61,7 @@ export default class OrderReferrerTool extends WriteAccessHandler {
|
|
|
61
61
|
* main();
|
|
62
62
|
* @returns Transaction object.
|
|
63
63
|
*/
|
|
64
|
-
executeOrder(symbol: string, orderId: string, referrerAddr?: string): Promise<ethers.ContractTransaction>;
|
|
64
|
+
executeOrder(symbol: string, orderId: string, referrerAddr?: string, nonce?: number): Promise<ethers.ContractTransaction>;
|
|
65
65
|
/**
|
|
66
66
|
* All the orders in the order book for a given symbol that are currently open.
|
|
67
67
|
* @param {string} symbol Symbol of the form ETH-USD-MATIC.
|
|
@@ -172,4 +172,5 @@ export default class OrderReferrerTool extends WriteAccessHandler {
|
|
|
172
172
|
* @returns true if order can be executed for the current state of the perpetuals
|
|
173
173
|
*/
|
|
174
174
|
isTradeable(order: Order): Promise<boolean>;
|
|
175
|
+
getTransactionCount(blockTag?: ethers.providers.BlockTag): Promise<number>;
|
|
175
176
|
}
|
|
@@ -78,7 +78,7 @@ class OrderReferrerTool extends writeAccessHandler_1.default {
|
|
|
78
78
|
* main();
|
|
79
79
|
* @returns Transaction object.
|
|
80
80
|
*/
|
|
81
|
-
executeOrder(symbol, orderId, referrerAddr) {
|
|
81
|
+
executeOrder(symbol, orderId, referrerAddr, nonce) {
|
|
82
82
|
return __awaiter(this, void 0, void 0, function* () {
|
|
83
83
|
if (this.proxyContract == null || this.signer == null) {
|
|
84
84
|
throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
|
|
@@ -87,7 +87,8 @@ class OrderReferrerTool extends writeAccessHandler_1.default {
|
|
|
87
87
|
if (typeof referrerAddr == "undefined") {
|
|
88
88
|
referrerAddr = this.traderAddr;
|
|
89
89
|
}
|
|
90
|
-
|
|
90
|
+
const options = { gasLimit: this.gasLimit, nonce: nonce };
|
|
91
|
+
return yield orderBookSC.executeOrder(orderId, referrerAddr, options);
|
|
91
92
|
});
|
|
92
93
|
}
|
|
93
94
|
/**
|
|
@@ -280,5 +281,13 @@ class OrderReferrerTool extends writeAccessHandler_1.default {
|
|
|
280
281
|
return true;
|
|
281
282
|
});
|
|
282
283
|
}
|
|
284
|
+
getTransactionCount(blockTag) {
|
|
285
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
286
|
+
if (this.signer == null) {
|
|
287
|
+
throw Error("no wallet initialized. Use createProxyInstance().");
|
|
288
|
+
}
|
|
289
|
+
return yield this.signer.getTransactionCount(blockTag);
|
|
290
|
+
});
|
|
291
|
+
}
|
|
283
292
|
}
|
|
284
293
|
exports.default = OrderReferrerTool;
|
|
@@ -7,9 +7,7 @@ import { NodeSDKConfig, Order, SmartContractOrder, PerpetualStaticInfo, MarginAc
|
|
|
7
7
|
export default class PerpetualDataHandler {
|
|
8
8
|
protected symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>;
|
|
9
9
|
protected poolStaticInfos: Array<PoolStaticInfo>;
|
|
10
|
-
protected symbolList:
|
|
11
|
-
[key: string]: string;
|
|
12
|
-
}>;
|
|
10
|
+
protected symbolList: Map<string, string>;
|
|
13
11
|
protected symbolToTokenAddrMap: Map<string, string>;
|
|
14
12
|
protected proxyContract: ethers.Contract | null;
|
|
15
13
|
protected proxyABI: ethers.ContractInterface;
|
|
@@ -34,7 +34,7 @@ class PerpetualDataHandler {
|
|
|
34
34
|
this.proxyABI = require(config.proxyABILocation);
|
|
35
35
|
this.lobFactoryABI = require(config.limitOrderBookFactoryABILocation);
|
|
36
36
|
this.lobABI = require(config.limitOrderBookABILocation);
|
|
37
|
-
this.symbolList = require(config.symbolListLocation);
|
|
37
|
+
this.symbolList = new Map(Object.entries(require(config.symbolListLocation)));
|
|
38
38
|
}
|
|
39
39
|
initContractsAndData(signerOrProvider) {
|
|
40
40
|
return __awaiter(this, void 0, void 0, function* () {
|
|
@@ -95,21 +95,23 @@ class PerpetualDataHandler {
|
|
|
95
95
|
// try to find a limit order book
|
|
96
96
|
let lobAddr = yield this.lobFactoryContract.getOrderBookAddress(perpetualIDs[k]);
|
|
97
97
|
currentLimitOrderBookAddr.push(lobAddr);
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
98
|
+
if (poolCCY == undefined) {
|
|
99
|
+
// we find out the pool currency by looking at all perpetuals
|
|
100
|
+
// unless for quanto perpetuals, we know the pool currency
|
|
101
|
+
// from the perpetual. This fails if we have a pool with only
|
|
102
|
+
// quanto perpetuals
|
|
103
|
+
if (perp.eCollateralCurrency == nodeSDKTypes_1.COLLATERAL_CURRENCY_BASE) {
|
|
104
|
+
poolCCY = base;
|
|
105
|
+
ccy.push(nodeSDKTypes_1.CollaterlCCY.BASE);
|
|
106
|
+
}
|
|
107
|
+
else if (perp.eCollateralCurrency == nodeSDKTypes_1.COLLATERAL_CURRENCY_QUOTE) {
|
|
108
|
+
poolCCY = quote;
|
|
109
|
+
ccy.push(nodeSDKTypes_1.CollaterlCCY.QUOTE);
|
|
110
|
+
}
|
|
111
|
+
else {
|
|
112
|
+
poolCCY = base3;
|
|
113
|
+
ccy.push(nodeSDKTypes_1.CollaterlCCY.QUANTO);
|
|
114
|
+
}
|
|
113
115
|
}
|
|
114
116
|
}
|
|
115
117
|
if (perpetualIDs.length == 0) {
|
|
@@ -35,6 +35,7 @@ export default class PerpetualEventHandler {
|
|
|
35
35
|
private traderAddr;
|
|
36
36
|
private ordersInPerpetual;
|
|
37
37
|
private positionInPerpetual;
|
|
38
|
+
private poolIndexForPerpetual;
|
|
38
39
|
private exchangeInfo;
|
|
39
40
|
constructor(mktData: MarketData, traderAddr: string);
|
|
40
41
|
/**
|
|
@@ -85,7 +86,7 @@ export default class PerpetualEventHandler {
|
|
|
85
86
|
* @param fSpotIndexPrice spot index price in ABDK format
|
|
86
87
|
* @returns void
|
|
87
88
|
*/
|
|
88
|
-
onUpdateMarkPrice(perpetualId: number, fMarkPricePremium: BigNumber, fSpotIndexPrice: BigNumber): void;
|
|
89
|
+
onUpdateMarkPrice(perpetualId: number, fMidPricePremium: BigNumber, fMarkPricePremium: BigNumber, fSpotIndexPrice: BigNumber): void;
|
|
89
90
|
/**
|
|
90
91
|
* Handle the event UpdateFundingRate and update relevant
|
|
91
92
|
* data
|