@d8x/perpetuals-sdk 0.0.1
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/LICENSE +21 -0
- package/README.md +17 -0
- package/abi/ERC20.json +288 -0
- package/abi/IPerpetualManager.json +4674 -0
- package/abi/LimitOrderBook.json +865 -0
- package/abi/LimitOrderBookFactory.json +166 -0
- package/config/defaultConfig.json +9 -0
- package/config/oldConfig.json +9 -0
- package/dist/accountTrade.d.ts +54 -0
- package/dist/accountTrade.js +164 -0
- package/dist/brokerTool.d.ts +41 -0
- package/dist/brokerTool.js +129 -0
- package/dist/d8XMath.d.ts +71 -0
- package/dist/d8XMath.js +162 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +49 -0
- package/dist/liquiditatorTool.d.ts +14 -0
- package/dist/liquiditatorTool.js +21 -0
- package/dist/liquidityProviderTool.d.ts +39 -0
- package/dist/liquidityProviderTool.js +100 -0
- package/dist/marketData.d.ts +39 -0
- package/dist/marketData.js +160 -0
- package/dist/nodeSDKTypes.d.ts +130 -0
- package/dist/nodeSDKTypes.js +52 -0
- package/dist/orderReferrerTool.d.ts +14 -0
- package/dist/orderReferrerTool.js +21 -0
- package/dist/perpetualDataHandler.d.ts +85 -0
- package/dist/perpetualDataHandler.js +474 -0
- package/dist/utils.d.ts +37 -0
- package/dist/utils.js +84 -0
- package/dist/writeAccessHandler.d.ts +36 -0
- package/dist/writeAccessHandler.js +95 -0
- package/module.d.ts +1 -0
- package/package.json +63 -0
- package/src/accountTrade.ts +217 -0
- package/src/brokerTool.ts +155 -0
- package/src/d8XMath.ts +176 -0
- package/src/index.ts +32 -0
- package/src/liquiditatorTool.ts +21 -0
- package/src/liquidityProviderTool.ts +100 -0
- package/src/marketData.ts +149 -0
- package/src/nodeSDKTypes.ts +158 -0
- package/src/orderReferrerTool.ts +17 -0
- package/src/perpetualDataHandler.ts +549 -0
- package/src/utils.ts +83 -0
- package/src/writeAccessHandler.ts +83 -0
package/dist/d8XMath.js
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.calculateLiquidationPriceCollateralQuote = exports.calculateLiquidationPriceCollateralQuanto = exports.calculateLiquidationPriceCollateralBase = exports.div64x64 = exports.mul64x64 = exports.floatToDec18 = exports.floatToABK64x64 = exports.dec18ToFloat = exports.ABK64x64ToFloat = void 0;
|
|
4
|
+
const ethers_1 = require("ethers");
|
|
5
|
+
const nodeSDKTypes_1 = require("./nodeSDKTypes");
|
|
6
|
+
const BN = ethers_1.BigNumber;
|
|
7
|
+
/**
|
|
8
|
+
* Convert ABK64x64 bigint-format to float.
|
|
9
|
+
* Result = x/2^64 if big number, x/2^29 if number
|
|
10
|
+
* @param x number in ABDK-format or 2^29
|
|
11
|
+
* @returns x/2^64 in number-format (float)
|
|
12
|
+
*/
|
|
13
|
+
function ABK64x64ToFloat(x) {
|
|
14
|
+
if (typeof x == "number") {
|
|
15
|
+
return x / Math.pow(2, 29);
|
|
16
|
+
}
|
|
17
|
+
let s = x.lt(0) ? -1 : 1;
|
|
18
|
+
x = x.mul(s);
|
|
19
|
+
let xInt = x.div(nodeSDKTypes_1.ONE_64x64);
|
|
20
|
+
let dec18 = ethers_1.BigNumber.from(10).pow(ethers_1.BigNumber.from(18));
|
|
21
|
+
let xDec = x.sub(xInt.mul(nodeSDKTypes_1.ONE_64x64));
|
|
22
|
+
xDec = xDec.mul(dec18).div(nodeSDKTypes_1.ONE_64x64);
|
|
23
|
+
let k = 18 - xDec.toString().length;
|
|
24
|
+
// console.assert(k >= 0);
|
|
25
|
+
let sPad = "0".repeat(k);
|
|
26
|
+
let NumberStr = xInt.toString() + "." + sPad + xDec.toString();
|
|
27
|
+
return parseFloat(NumberStr) * s;
|
|
28
|
+
}
|
|
29
|
+
exports.ABK64x64ToFloat = ABK64x64ToFloat;
|
|
30
|
+
/**
|
|
31
|
+
*
|
|
32
|
+
* @param x BigNumber in Dec18 format
|
|
33
|
+
* @returns x as a float (number)
|
|
34
|
+
*/
|
|
35
|
+
function dec18ToFloat(x) {
|
|
36
|
+
//x: BigNumber in Dec18 format to float
|
|
37
|
+
let s = x.lt(0) ? -1 : 1;
|
|
38
|
+
x = x.mul(s);
|
|
39
|
+
let xInt = x.div(nodeSDKTypes_1.DECIMALS);
|
|
40
|
+
let xDec = x.sub(xInt.mul(nodeSDKTypes_1.DECIMALS));
|
|
41
|
+
let k = 18 - xDec.toString().length;
|
|
42
|
+
let sPad = "0".repeat(k);
|
|
43
|
+
let NumberStr = xInt.toString() + "." + sPad + xDec.toString();
|
|
44
|
+
return parseFloat(NumberStr) * s;
|
|
45
|
+
}
|
|
46
|
+
exports.dec18ToFloat = dec18ToFloat;
|
|
47
|
+
/**
|
|
48
|
+
* Converts x into ABDK64x64 format
|
|
49
|
+
* @param x number (float)
|
|
50
|
+
* @returns x^64 in big number format
|
|
51
|
+
*/
|
|
52
|
+
function floatToABK64x64(x) {
|
|
53
|
+
// convert float to ABK64x64 bigint-format
|
|
54
|
+
// Create string from number with 18 decimals
|
|
55
|
+
if (x === 0) {
|
|
56
|
+
return ethers_1.BigNumber.from(0);
|
|
57
|
+
}
|
|
58
|
+
let sg = Math.sign(x);
|
|
59
|
+
x = Math.abs(x);
|
|
60
|
+
let strX = Number(x).toFixed(18);
|
|
61
|
+
const arrX = strX.split(".");
|
|
62
|
+
let xInt = ethers_1.BigNumber.from(arrX[0]);
|
|
63
|
+
let xDec = ethers_1.BigNumber.from(arrX[1]);
|
|
64
|
+
let xIntBig = xInt.mul(nodeSDKTypes_1.ONE_64x64);
|
|
65
|
+
let dec18 = ethers_1.BigNumber.from(10).pow(ethers_1.BigNumber.from(18));
|
|
66
|
+
let xDecBig = xDec.mul(nodeSDKTypes_1.ONE_64x64).div(dec18);
|
|
67
|
+
return xIntBig.add(xDecBig).mul(sg);
|
|
68
|
+
}
|
|
69
|
+
exports.floatToABK64x64 = floatToABK64x64;
|
|
70
|
+
/**
|
|
71
|
+
*
|
|
72
|
+
* @param x number (float)
|
|
73
|
+
* @returns x as a BigNumber in Dec18 format
|
|
74
|
+
*/
|
|
75
|
+
function floatToDec18(x) {
|
|
76
|
+
// float number to dec 18
|
|
77
|
+
if (x === 0) {
|
|
78
|
+
return ethers_1.BigNumber.from(0);
|
|
79
|
+
}
|
|
80
|
+
let sg = Math.sign(x);
|
|
81
|
+
x = Math.abs(x);
|
|
82
|
+
let strX = x.toFixed(18);
|
|
83
|
+
const arrX = strX.split(".");
|
|
84
|
+
let xInt = ethers_1.BigNumber.from(arrX[0]);
|
|
85
|
+
let xDec = ethers_1.BigNumber.from(arrX[1]);
|
|
86
|
+
let xIntBig = xInt.mul(nodeSDKTypes_1.DECIMALS);
|
|
87
|
+
return xIntBig.add(xDec).mul(sg);
|
|
88
|
+
}
|
|
89
|
+
exports.floatToDec18 = floatToDec18;
|
|
90
|
+
/**
|
|
91
|
+
*
|
|
92
|
+
* @param x
|
|
93
|
+
* @param y
|
|
94
|
+
* @returns x * y
|
|
95
|
+
*/
|
|
96
|
+
function mul64x64(x, y) {
|
|
97
|
+
return x.mul(y).div(nodeSDKTypes_1.ONE_64x64);
|
|
98
|
+
}
|
|
99
|
+
exports.mul64x64 = mul64x64;
|
|
100
|
+
/**
|
|
101
|
+
*
|
|
102
|
+
* @param x
|
|
103
|
+
* @param y
|
|
104
|
+
* @returns x / y
|
|
105
|
+
*/
|
|
106
|
+
function div64x64(x, y) {
|
|
107
|
+
return x.mul(nodeSDKTypes_1.ONE_64x64).div(y);
|
|
108
|
+
}
|
|
109
|
+
exports.div64x64 = div64x64;
|
|
110
|
+
/**
|
|
111
|
+
* Determine the liquidation price
|
|
112
|
+
* @param {number} LockedInValueQC - trader locked in value in quote currency
|
|
113
|
+
* @param {number} position - trader position in base currency
|
|
114
|
+
* @param {number} cash_cc - trader available margin cash in collateral currency
|
|
115
|
+
* @param {number} maintenance_margin_rate - maintenance margin ratio
|
|
116
|
+
* @param {number} S3 - collateral to quote conversion (=S2 if base-collateral, =1 if quuote collateral, = index S3 if quanto)
|
|
117
|
+
* @returns {number} Amount to be deposited to have the given leverage when trading into position pos
|
|
118
|
+
*/
|
|
119
|
+
function calculateLiquidationPriceCollateralBase(LockedInValueQC, position, cash_cc, maintenance_margin_rate) {
|
|
120
|
+
// correct only if markprice = spot price
|
|
121
|
+
// m_r <= (Sm * Pi - L + cash * S3) / (Sm * |Pi|)
|
|
122
|
+
// -> Sm * (Pi + cash - m_r|Pi|) => L
|
|
123
|
+
return LockedInValueQC / (position - maintenance_margin_rate * Math.abs(position) + cash_cc);
|
|
124
|
+
}
|
|
125
|
+
exports.calculateLiquidationPriceCollateralBase = calculateLiquidationPriceCollateralBase;
|
|
126
|
+
/**
|
|
127
|
+
* Determine the liquidation price
|
|
128
|
+
* @param {number} LockedInValueQC - trader locked in value in quote currency
|
|
129
|
+
* @param {number} position - trader position in base currency
|
|
130
|
+
* @param {number} cash_cc - trader available margin cash in collateral currency
|
|
131
|
+
* @param {number} maintenance_margin_rate - maintenance margin ratio
|
|
132
|
+
* @param {number} S3 - collateral to quote conversion (=S2 if base-collateral, =1 if quuote collateral, = index S3 if quanto)
|
|
133
|
+
* @param {number} Sm - mark price
|
|
134
|
+
* @returns {number} Amount to be deposited to have the given leverage when trading into position pos
|
|
135
|
+
*/
|
|
136
|
+
function calculateLiquidationPriceCollateralQuanto(LockedInValueQC, position, cash_cc, maintenance_margin_rate, S3, Sm) {
|
|
137
|
+
// correct only if markprice = spot price and S3 co-moves with Sm
|
|
138
|
+
// m_r = (Sm * Pi - L + cash * S3) / (Sm * |Pi|)
|
|
139
|
+
// m_r = [Sm * Pi - L + cash * S3(0) * (1 + sign(Pi) (Sm / Sm(0) - 1)] / (Sm * |Pi|)
|
|
140
|
+
// -> Sm * (m_r |Pi| - Pi - cash * S3(0) * sign(Pi) / Sm(0)) = - L + cash * S3(0) * (1 - sign(Pi))
|
|
141
|
+
let numerator = -LockedInValueQC + cash_cc * S3 * (1 - Math.sign(position));
|
|
142
|
+
let denominator = maintenance_margin_rate * Math.abs(position) - position - (cash_cc * S3 * Math.sign(position)) / Sm;
|
|
143
|
+
return numerator / denominator;
|
|
144
|
+
}
|
|
145
|
+
exports.calculateLiquidationPriceCollateralQuanto = calculateLiquidationPriceCollateralQuanto;
|
|
146
|
+
/**
|
|
147
|
+
* Determine the liquidation price
|
|
148
|
+
* @param {number} LockedInValueQC - trader locked in value in quote currency
|
|
149
|
+
* @param {number} position - trader position in base currency
|
|
150
|
+
* @param {number} cash_cc - trader available margin cash in collateral currency
|
|
151
|
+
* @param {number} maintenance_margin_rate - maintenance margin ratio
|
|
152
|
+
* @param {number} S3 - collateral to quote conversion (=S2 if base-collateral, =1 if quuote collateral, = index S3 if quanto)
|
|
153
|
+
* @returns {number} Amount to be deposited to have the given leverage when trading into position pos
|
|
154
|
+
*/
|
|
155
|
+
function calculateLiquidationPriceCollateralQuote(LockedInValueQC, position, cash_cc, maintenance_margin_rate) {
|
|
156
|
+
// m_r = (Sm * Pi - L + cash ) / (Sm * |Pi|)
|
|
157
|
+
// -> Sm * (m_r |Pi| - Pi) = - L + cash
|
|
158
|
+
let numerator = -LockedInValueQC + cash_cc;
|
|
159
|
+
let denominator = maintenance_margin_rate * Math.abs(position) - position;
|
|
160
|
+
return numerator / denominator;
|
|
161
|
+
}
|
|
162
|
+
exports.calculateLiquidationPriceCollateralQuote = calculateLiquidationPriceCollateralQuote;
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import AccountTrade from "./accountTrade";
|
|
2
|
+
import BrokerTool from "./brokerTool";
|
|
3
|
+
import LiquidityProviderTool from "./liquidityProviderTool";
|
|
4
|
+
import MarketData from "./marketData";
|
|
5
|
+
import OrderReferrerTool from "./orderReferrerTool";
|
|
6
|
+
import PerpetualDataHandler from "./perpetualDataHandler";
|
|
7
|
+
import WriteAccessHandler from "./writeAccessHandler";
|
|
8
|
+
export * from "./nodeSDKTypes";
|
|
9
|
+
export * from "./utils";
|
|
10
|
+
export * from "./d8XMath";
|
|
11
|
+
export { AccountTrade, BrokerTool, LiquidityProviderTool, MarketData, OrderReferrerTool, PerpetualDataHandler, WriteAccessHandler, };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
17
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
18
|
+
};
|
|
19
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
20
|
+
exports.WriteAccessHandler = exports.PerpetualDataHandler = exports.OrderReferrerTool = exports.MarketData = exports.LiquidityProviderTool = exports.BrokerTool = exports.AccountTrade = void 0;
|
|
21
|
+
const accountTrade_1 = __importDefault(require("./accountTrade"));
|
|
22
|
+
exports.AccountTrade = accountTrade_1.default;
|
|
23
|
+
const brokerTool_1 = __importDefault(require("./brokerTool"));
|
|
24
|
+
exports.BrokerTool = brokerTool_1.default;
|
|
25
|
+
const liquidityProviderTool_1 = __importDefault(require("./liquidityProviderTool"));
|
|
26
|
+
exports.LiquidityProviderTool = liquidityProviderTool_1.default;
|
|
27
|
+
const marketData_1 = __importDefault(require("./marketData"));
|
|
28
|
+
exports.MarketData = marketData_1.default;
|
|
29
|
+
const orderReferrerTool_1 = __importDefault(require("./orderReferrerTool"));
|
|
30
|
+
exports.OrderReferrerTool = orderReferrerTool_1.default;
|
|
31
|
+
const perpetualDataHandler_1 = __importDefault(require("./perpetualDataHandler"));
|
|
32
|
+
exports.PerpetualDataHandler = perpetualDataHandler_1.default;
|
|
33
|
+
const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
|
|
34
|
+
exports.WriteAccessHandler = writeAccessHandler_1.default;
|
|
35
|
+
// import {
|
|
36
|
+
// NodeSDKConfig,
|
|
37
|
+
// MarginAccount,
|
|
38
|
+
// CollaterlCCY,
|
|
39
|
+
// PoolStaticInfo,
|
|
40
|
+
// PerpetualStaticInfo,
|
|
41
|
+
// ExchangeInfo,
|
|
42
|
+
// PoolState,
|
|
43
|
+
// PerpetualState,
|
|
44
|
+
// Order,
|
|
45
|
+
// SmartContractOrder,
|
|
46
|
+
// } from "./nodeSDKTypes";
|
|
47
|
+
__exportStar(require("./nodeSDKTypes"), exports);
|
|
48
|
+
__exportStar(require("./utils"), exports);
|
|
49
|
+
__exportStar(require("./d8XMath"), exports);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import WriteAccessHandler from "./writeAccessHandler";
|
|
2
|
+
import { NodeSDKConfig } from "./nodeSDKTypes";
|
|
3
|
+
/**
|
|
4
|
+
* LiquidatorTool
|
|
5
|
+
* Methods to liquidate traders
|
|
6
|
+
*/
|
|
7
|
+
export default class LiquidatorTool extends WriteAccessHandler {
|
|
8
|
+
/**
|
|
9
|
+
* Constructor
|
|
10
|
+
* @param config configuration
|
|
11
|
+
* @param privateKey private key of account that trades
|
|
12
|
+
*/
|
|
13
|
+
constructor(config: NodeSDKConfig, privateKey: string);
|
|
14
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
|
|
7
|
+
/**
|
|
8
|
+
* LiquidatorTool
|
|
9
|
+
* Methods to liquidate traders
|
|
10
|
+
*/
|
|
11
|
+
class LiquidatorTool extends writeAccessHandler_1.default {
|
|
12
|
+
/**
|
|
13
|
+
* Constructor
|
|
14
|
+
* @param config configuration
|
|
15
|
+
* @param privateKey private key of account that trades
|
|
16
|
+
*/
|
|
17
|
+
constructor(config, privateKey) {
|
|
18
|
+
super(config, privateKey);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.default = LiquidatorTool;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ethers } from "ethers";
|
|
2
|
+
import WriteAccessHandler from "./writeAccessHandler";
|
|
3
|
+
import { NodeSDKConfig } from "./nodeSDKTypes";
|
|
4
|
+
/**
|
|
5
|
+
* LiquidityProviderTool
|
|
6
|
+
* Methods to provide liquidity
|
|
7
|
+
*/
|
|
8
|
+
export default class LiquidityProviderTool extends WriteAccessHandler {
|
|
9
|
+
/**
|
|
10
|
+
* Constructor
|
|
11
|
+
* @param config configuration
|
|
12
|
+
* @param privateKey private key of account that trades
|
|
13
|
+
*/
|
|
14
|
+
constructor(config: NodeSDKConfig, privateKey: string);
|
|
15
|
+
/**
|
|
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)
|
|
19
|
+
*/
|
|
20
|
+
getParticipationValue(poolSymbolName: string): Promise<{
|
|
21
|
+
value: number;
|
|
22
|
+
shareTokenBalance: number;
|
|
23
|
+
poolShareToken: string;
|
|
24
|
+
}>;
|
|
25
|
+
/**
|
|
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
|
|
30
|
+
*/
|
|
31
|
+
addLiquidity(poolSymbolName: string, amountCC: number): Promise<ethers.providers.TransactionResponse>;
|
|
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
|
|
37
|
+
*/
|
|
38
|
+
removeLiquidity(poolSymbolName: string, amountPoolShares: number): Promise<ethers.providers.TransactionResponse>;
|
|
39
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
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 ethers_1 = require("ethers");
|
|
16
|
+
const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
|
|
17
|
+
const nodeSDKTypes_1 = require("./nodeSDKTypes");
|
|
18
|
+
const perpetualDataHandler_1 = __importDefault(require("./perpetualDataHandler"));
|
|
19
|
+
const d8XMath_1 = require("./d8XMath");
|
|
20
|
+
/**
|
|
21
|
+
* LiquidityProviderTool
|
|
22
|
+
* Methods to provide liquidity
|
|
23
|
+
*/
|
|
24
|
+
class LiquidityProviderTool extends writeAccessHandler_1.default {
|
|
25
|
+
/**
|
|
26
|
+
* Constructor
|
|
27
|
+
* @param config configuration
|
|
28
|
+
* @param privateKey private key of account that trades
|
|
29
|
+
*/
|
|
30
|
+
constructor(config, privateKey) {
|
|
31
|
+
super(config, privateKey);
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
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)
|
|
37
|
+
*/
|
|
38
|
+
getParticipationValue(poolSymbolName) {
|
|
39
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
40
|
+
if (this.proxyContract == null ||
|
|
41
|
+
this.signer == null ||
|
|
42
|
+
this.poolStaticInfos.length == 0 ||
|
|
43
|
+
this.provider == null) {
|
|
44
|
+
throw Error("no proxy contract or wallet or data initialized. Use createProxyInstance().");
|
|
45
|
+
}
|
|
46
|
+
let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
|
|
47
|
+
let shareTokenAddr = this.poolStaticInfos[poolId - 1].shareTokenAddr;
|
|
48
|
+
let shareToken = new ethers_1.ethers.Contract(shareTokenAddr, nodeSDKTypes_1.ERC20_ABI, this.signer);
|
|
49
|
+
let dShareTokenBalanceOfAddr = yield shareToken.balanceOf(this.traderAddr);
|
|
50
|
+
let shareTokenBalanceOfAddr = (0, d8XMath_1.dec18ToFloat)(dShareTokenBalanceOfAddr);
|
|
51
|
+
if (shareTokenBalanceOfAddr == 0) {
|
|
52
|
+
return { value: 0, shareTokenBalance: 0, poolShareToken: shareTokenAddr };
|
|
53
|
+
}
|
|
54
|
+
let pool = yield this.proxyContract.getLiquidityPool(poolId);
|
|
55
|
+
let fPnLParticipantFundCash = pool.fPnLparticipantsCashCC;
|
|
56
|
+
let pnlParticipantFundCash = (0, d8XMath_1.ABK64x64ToFloat)(fPnLParticipantFundCash);
|
|
57
|
+
let dTotalSupply = yield shareToken.totalSupply();
|
|
58
|
+
let totalSupply = (0, d8XMath_1.dec18ToFloat)(dTotalSupply);
|
|
59
|
+
let valueCC = (shareTokenBalanceOfAddr / totalSupply) * pnlParticipantFundCash;
|
|
60
|
+
return { value: valueCC, shareTokenBalance: shareTokenBalanceOfAddr, poolShareToken: shareTokenAddr };
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
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
|
|
68
|
+
*/
|
|
69
|
+
addLiquidity(poolSymbolName, amountCC) {
|
|
70
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
71
|
+
if (this.proxyContract == null || this.signer == null) {
|
|
72
|
+
throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
|
|
73
|
+
}
|
|
74
|
+
let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
|
|
75
|
+
let tx = yield this.proxyContract.addLiquidity(poolId, (0, d8XMath_1.floatToABK64x64)(amountCC), {
|
|
76
|
+
gasLimit: this.gasLimit,
|
|
77
|
+
});
|
|
78
|
+
return tx;
|
|
79
|
+
});
|
|
80
|
+
}
|
|
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
|
|
86
|
+
*/
|
|
87
|
+
removeLiquidity(poolSymbolName, amountPoolShares) {
|
|
88
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
89
|
+
if (this.proxyContract == null || this.signer == null) {
|
|
90
|
+
throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
|
|
91
|
+
}
|
|
92
|
+
let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
|
|
93
|
+
let tx = yield this.proxyContract.addLiquidity(poolId, (0, d8XMath_1.floatToABK64x64)(amountPoolShares), {
|
|
94
|
+
gasLimit: this.gasLimit,
|
|
95
|
+
});
|
|
96
|
+
return tx;
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
exports.default = LiquidityProviderTool;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { ExchangeInfo, NodeSDKConfig, MarginAccount } from "./nodeSDKTypes";
|
|
2
|
+
import { ethers } from "ethers";
|
|
3
|
+
import PerpetualDataHandler from "./perpetualDataHandler";
|
|
4
|
+
import { Order } from "./nodeSDKTypes";
|
|
5
|
+
/**
|
|
6
|
+
* This class requires no private key and is blockchain read-only.
|
|
7
|
+
* No gas required for the queries here.
|
|
8
|
+
*/
|
|
9
|
+
export default class MarketData extends PerpetualDataHandler {
|
|
10
|
+
constructor(config: NodeSDKConfig);
|
|
11
|
+
createProxyInstance(): Promise<void>;
|
|
12
|
+
exchangeInfo(): Promise<ExchangeInfo>;
|
|
13
|
+
/**
|
|
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
|
+
*/
|
|
19
|
+
openOrders(traderAddr: string, symbol: string): Promise<{
|
|
20
|
+
orders: Order[];
|
|
21
|
+
orderIds: string[];
|
|
22
|
+
}>;
|
|
23
|
+
positionRisk(traderAddr: string, symbol: string): Promise<MarginAccount>;
|
|
24
|
+
/**
|
|
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
|
|
29
|
+
*/
|
|
30
|
+
protected openOrdersOnOrderBook(traderAddr: string, orderBookContract: ethers.Contract): Promise<Order[]>;
|
|
31
|
+
/**
|
|
32
|
+
*
|
|
33
|
+
* @param traderAddr address of the trader
|
|
34
|
+
* @param orderBookContract instance of order book contract
|
|
35
|
+
* @returns array of order-id's
|
|
36
|
+
*/
|
|
37
|
+
protected orderIdsOfTrader(traderAddr: string, orderBookContract: ethers.Contract): Promise<string[]>;
|
|
38
|
+
static _exchangeInfo(_proxyContract: ethers.Contract): Promise<ExchangeInfo>;
|
|
39
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
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 nodeSDKTypes_1 = require("./nodeSDKTypes");
|
|
16
|
+
const ethers_1 = require("ethers");
|
|
17
|
+
const d8XMath_1 = require("./d8XMath");
|
|
18
|
+
const utils_1 = require("./utils");
|
|
19
|
+
const perpetualDataHandler_1 = __importDefault(require("./perpetualDataHandler"));
|
|
20
|
+
/**
|
|
21
|
+
* This class requires no private key and is blockchain read-only.
|
|
22
|
+
* No gas required for the queries here.
|
|
23
|
+
*/
|
|
24
|
+
class MarketData extends perpetualDataHandler_1.default {
|
|
25
|
+
constructor(config) {
|
|
26
|
+
super(config);
|
|
27
|
+
}
|
|
28
|
+
createProxyInstance() {
|
|
29
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
30
|
+
this.provider = new ethers_1.ethers.providers.JsonRpcProvider(this.nodeURL);
|
|
31
|
+
yield this.initContractsAndData(this.provider);
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
exchangeInfo() {
|
|
35
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
36
|
+
if (this.proxyContract == null) {
|
|
37
|
+
throw Error("no proxy contract initialized. Use createProxyInstance().");
|
|
38
|
+
}
|
|
39
|
+
return yield MarketData._exchangeInfo(this.proxyContract);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
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
|
+
*/
|
|
48
|
+
openOrders(traderAddr, symbol) {
|
|
49
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
50
|
+
// open orders requested only for given symbol
|
|
51
|
+
let orderBookContract = this.getOrderBookContract(symbol);
|
|
52
|
+
let [orders, digests] = yield Promise.all([
|
|
53
|
+
this.openOrdersOnOrderBook(traderAddr, orderBookContract),
|
|
54
|
+
this.orderIdsOfTrader(traderAddr, orderBookContract),
|
|
55
|
+
]);
|
|
56
|
+
return { orders: orders, orderIds: digests };
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
positionRisk(traderAddr, symbol) {
|
|
60
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
61
|
+
if (this.proxyContract == null) {
|
|
62
|
+
throw Error("no proxy contract initialized. Use createProxyInstance().");
|
|
63
|
+
}
|
|
64
|
+
let mgnAcct = yield perpetualDataHandler_1.default.getMarginAccount(traderAddr, symbol, this.symbolToPerpStaticInfo, this.proxyContract);
|
|
65
|
+
return mgnAcct;
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
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
|
|
73
|
+
*/
|
|
74
|
+
openOrdersOnOrderBook(traderAddr, orderBookContract) {
|
|
75
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
76
|
+
let orders = yield orderBookContract.getOrders(traderAddr, 0, 15);
|
|
77
|
+
//eliminate empty orders and map to user friendly orders
|
|
78
|
+
let userFriendlyOrders = new Array();
|
|
79
|
+
let k = 0;
|
|
80
|
+
while (k < orders.length && orders[k].traderAddr != nodeSDKTypes_1.ZERO_ADDRESS) {
|
|
81
|
+
userFriendlyOrders.push(perpetualDataHandler_1.default.fromSmartContractOrder(orders[k], this.symbolToPerpStaticInfo));
|
|
82
|
+
k++;
|
|
83
|
+
}
|
|
84
|
+
return userFriendlyOrders;
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
*
|
|
89
|
+
* @param traderAddr address of the trader
|
|
90
|
+
* @param orderBookContract instance of order book contract
|
|
91
|
+
* @returns array of order-id's
|
|
92
|
+
*/
|
|
93
|
+
orderIdsOfTrader(traderAddr, orderBookContract) {
|
|
94
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
95
|
+
let digestsRaw = yield orderBookContract.limitDigestsOfTrader(traderAddr, 0, 15);
|
|
96
|
+
let k = 0;
|
|
97
|
+
let digests = [];
|
|
98
|
+
while (k < digestsRaw.length && ethers_1.BigNumber.from(digestsRaw[k]).gt(0)) {
|
|
99
|
+
digests.push(digestsRaw[k]);
|
|
100
|
+
k++;
|
|
101
|
+
}
|
|
102
|
+
return digests;
|
|
103
|
+
});
|
|
104
|
+
}
|
|
105
|
+
static _exchangeInfo(_proxyContract) {
|
|
106
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
107
|
+
let nestedPerpetualIDs = yield perpetualDataHandler_1.default.getNestedPerpetualIds(_proxyContract);
|
|
108
|
+
let info = { pools: [] };
|
|
109
|
+
const numPools = nestedPerpetualIDs.length;
|
|
110
|
+
for (var j = 0; j < numPools; j++) {
|
|
111
|
+
let perpetualIDs = nestedPerpetualIDs[j];
|
|
112
|
+
let pool = yield _proxyContract.getLiquidityPool(j + 1);
|
|
113
|
+
let PoolState = {
|
|
114
|
+
isRunning: pool.isRunning,
|
|
115
|
+
marginTokenAddr: pool.marginTokenAddress,
|
|
116
|
+
poolShareTokenAddr: pool.shareTokenAddress,
|
|
117
|
+
defaultFundCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fDefaultFundCashCC),
|
|
118
|
+
pnlParticipantCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fPnLparticipantsCashCC),
|
|
119
|
+
totalAMMFundCashCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fAMMFundCashCC),
|
|
120
|
+
totalTargetAMMFundSizeCC: (0, d8XMath_1.ABK64x64ToFloat)(pool.fTargetAMMFundSize),
|
|
121
|
+
brokerCollateralLotSize: (0, d8XMath_1.ABK64x64ToFloat)(pool.fBrokerCollateralLotSize),
|
|
122
|
+
perpetuals: [],
|
|
123
|
+
};
|
|
124
|
+
for (var k = 0; k < perpetualIDs.length; k++) {
|
|
125
|
+
let perp = yield _proxyContract.getPerpetual(perpetualIDs[k]);
|
|
126
|
+
let fIndexS2 = yield _proxyContract.getOraclePrice([perp.S2BaseCCY, perp.S2QuoteCCY]);
|
|
127
|
+
let indexS2 = (0, d8XMath_1.ABK64x64ToFloat)(fIndexS2);
|
|
128
|
+
let indexS3 = 1;
|
|
129
|
+
if (perp.eCollateralCurrency == nodeSDKTypes_1.COLLATERAL_CURRENCY_BASE) {
|
|
130
|
+
indexS3 = indexS2;
|
|
131
|
+
}
|
|
132
|
+
else if (perp.eCollateralCurrency == nodeSDKTypes_1.COLLATERAL_CURRENCY_QUANTO) {
|
|
133
|
+
indexS3 = (0, d8XMath_1.ABK64x64ToFloat)(yield _proxyContract.getOraclePrice([perp.S3BaseCCY, perp.S3QuoteCCY]));
|
|
134
|
+
}
|
|
135
|
+
let markPremiumRate = (0, d8XMath_1.ABK64x64ToFloat)(perp.currentMarkPremiumRate.fPrice);
|
|
136
|
+
let currentFundingRateBps = 1e4 * (0, d8XMath_1.ABK64x64ToFloat)(perp.fCurrentFundingRate);
|
|
137
|
+
let state = nodeSDKTypes_1.PERP_STATE_STR[perp.state];
|
|
138
|
+
let PerpetualState = {
|
|
139
|
+
id: perp.id,
|
|
140
|
+
state: state,
|
|
141
|
+
baseCurrency: (0, utils_1.fromBytes4HexString)(perp.S2BaseCCY),
|
|
142
|
+
quoteCurrency: (0, utils_1.fromBytes4HexString)(perp.S2QuoteCCY),
|
|
143
|
+
indexPrice: indexS2,
|
|
144
|
+
collToQuoteIndexPrice: indexS3,
|
|
145
|
+
markPrice: indexS2 * (1 + markPremiumRate),
|
|
146
|
+
currentFundingRateBps: currentFundingRateBps,
|
|
147
|
+
initialMarginRate: (0, d8XMath_1.ABK64x64ToFloat)(perp.fInitialMarginRate),
|
|
148
|
+
maintenanceMarginRate: (0, d8XMath_1.ABK64x64ToFloat)(perp.fMaintenanceMarginRate),
|
|
149
|
+
openInterestBC: (0, d8XMath_1.ABK64x64ToFloat)(perp.fOpenInterest),
|
|
150
|
+
maxPositionBC: (0, d8XMath_1.ABK64x64ToFloat)(perp.fMaxPositionBC),
|
|
151
|
+
};
|
|
152
|
+
PoolState.perpetuals.push(PerpetualState);
|
|
153
|
+
}
|
|
154
|
+
info.pools.push(PoolState);
|
|
155
|
+
}
|
|
156
|
+
return info;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
exports.default = MarketData;
|