@d8x/perpetuals-sdk 0.0.1 → 0.0.3

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.
@@ -2,8 +2,8 @@ import { ethers } from "ethers";
2
2
  import { NodeSDKConfig, Order, PerpetualStaticInfo } from "./nodeSDKTypes";
3
3
  import WriteAccessHandler from "./writeAccessHandler";
4
4
  /**
5
- * Account and Trade.
6
- * This class requires a private key and executes smart-contract interaction that
5
+ * Functions to create, submit and cancel orders on the exchange.
6
+ * This class requires a private key and executes smart-contract interactions that
7
7
  * require gas-payments.
8
8
  */
9
9
  export default class AccountTrade extends WriteAccessHandler {
@@ -25,6 +25,23 @@ export default class AccountTrade extends WriteAccessHandler {
25
25
  * @returns {string} Transaction hash.
26
26
  */
27
27
  order(order: Order): Promise<string | undefined>;
28
+ /**
29
+ * Fee charged by the exchange for trading any perpetual on a given pool.
30
+ * It accounts for the current trader's fee tier (based on the trader's D8X balance and trading volume).
31
+ * If trading with a broker, it also accounts for the selected broker's fee tier.
32
+ * Note that this result only includes exchange fees, additional broker fees are not included.
33
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
34
+ * @param {string=} brokerAddr Optional address of a broker this trader may use to trade under.
35
+ * @returns Exchange fee, in decimals (i.e. 0.1% is 0.001).
36
+ */
37
+ queryExchangeFee(poolSymbolName: string, brokerAddr?: string): Promise<number>;
38
+ /**
39
+ * Exponentially weighted EMA of the total trading volume of all trades performed by this trader.
40
+ * The weights are chosen so that in average this coincides with the 30 day volume.
41
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
42
+ * @returns {number} Current trading volume for this trader, in USD.
43
+ */
44
+ getCurrentTraderVolume(poolSymbolName: string): Promise<number>;
28
45
  /**
29
46
  * Static order function
30
47
  * @param order order type (not SmartContractOrder but Order)
@@ -13,12 +13,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
13
13
  };
14
14
  Object.defineProperty(exports, "__esModule", { value: true });
15
15
  const ethers_1 = require("ethers");
16
+ const d8XMath_1 = require("./d8XMath");
16
17
  const nodeSDKTypes_1 = require("./nodeSDKTypes");
17
18
  const writeAccessHandler_1 = __importDefault(require("./writeAccessHandler"));
18
- //import { abi, rawEncode } from "ethereumjs-abi";
19
19
  /**
20
- * Account and Trade.
21
- * This class requires a private key and executes smart-contract interaction that
20
+ * Functions to create, submit and cancel orders on the exchange.
21
+ * This class requires a private key and executes smart-contract interactions that
22
22
  * require gas-payments.
23
23
  */
24
24
  class AccountTrade extends writeAccessHandler_1.default {
@@ -67,6 +67,44 @@ class AccountTrade extends writeAccessHandler_1.default {
67
67
  return yield this._order(order, this.traderAddr, this.symbolToPerpStaticInfo, this.proxyContract, orderBookContract, this.chainId, this.signer, this.gasLimit);
68
68
  });
69
69
  }
70
+ /**
71
+ * Fee charged by the exchange for trading any perpetual on a given pool.
72
+ * It accounts for the current trader's fee tier (based on the trader's D8X balance and trading volume).
73
+ * If trading with a broker, it also accounts for the selected broker's fee tier.
74
+ * Note that this result only includes exchange fees, additional broker fees are not included.
75
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
76
+ * @param {string=} brokerAddr Optional address of a broker this trader may use to trade under.
77
+ * @returns Exchange fee, in decimals (i.e. 0.1% is 0.001).
78
+ */
79
+ queryExchangeFee(poolSymbolName, brokerAddr) {
80
+ return __awaiter(this, void 0, void 0, function* () {
81
+ if (this.proxyContract == null || this.signer == null) {
82
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
83
+ }
84
+ if (typeof brokerAddr == "undefined") {
85
+ brokerAddr = nodeSDKTypes_1.ZERO_ADDRESS;
86
+ }
87
+ let poolId = writeAccessHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
88
+ let feeTbps = yield this.proxyContract.queryExchangeFee(poolId, this.traderAddr, brokerAddr);
89
+ return feeTbps / 100000;
90
+ });
91
+ }
92
+ /**
93
+ * Exponentially weighted EMA of the total trading volume of all trades performed by this trader.
94
+ * The weights are chosen so that in average this coincides with the 30 day volume.
95
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
96
+ * @returns {number} Current trading volume for this trader, in USD.
97
+ */
98
+ getCurrentTraderVolume(poolSymbolName) {
99
+ return __awaiter(this, void 0, void 0, function* () {
100
+ if (this.proxyContract == null || this.signer == null) {
101
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
102
+ }
103
+ let poolId = writeAccessHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
104
+ let volume = yield this.proxyContract.getCurrentTraderVolume(poolId, this.traderAddr);
105
+ return (0, d8XMath_1.ABK64x64ToFloat)(volume);
106
+ });
107
+ }
70
108
  /**
71
109
  * Static order function
72
110
  * @param order order type (not SmartContractOrder but Order)
@@ -1,41 +1,114 @@
1
1
  import WriteAccessHandler from "./writeAccessHandler";
2
- import { NodeSDKConfig, Order } from "./nodeSDKTypes";
3
- import { ethers } from "ethers";
2
+ import { NodeSDKConfig, Order, PerpetualStaticInfo } from "./nodeSDKTypes";
3
+ import { BigNumber, ethers } from "ethers";
4
4
  /**
5
- * BrokerTool.
6
- * Signature method for brokers
5
+ * Functions for brokers to determine fees, deposit lots, and sign-up traders.
7
6
  */
8
7
  export default class BrokerTool extends WriteAccessHandler {
9
8
  /**
10
9
  * Constructor
11
- * @param config configuration
12
- * @param privateKey private key of account that trades
10
+ * @param {NodeSDKConfig} config Configuration object.
11
+ * @param {string} privateKey Private key of a broker.
13
12
  */
14
13
  constructor(config: NodeSDKConfig, privateKey: string);
15
14
  /**
16
- *
17
- * @param symbol symbol of the form "ETH-USD-MATIC" or just "MATIC"
18
- * @returns broker lot size in collateral currency, e.g. in MATIC for symbol ETH-USD-MATIC or MATIC
15
+ * Determine the exchange fee based on lots, traded volume, and D8X balance of this broker.
16
+ * This is the final exchange fee paid by the broker.
17
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
18
+ * @returns {number} Exchange fee for this broker, in decimals (i.e. 0.1% is 0.001)
19
19
  */
20
- getLotSize(symbol: string): Promise<number | undefined>;
21
- brokerDepositToDefaultFund(symbol: string, lots: number): Promise<ethers.providers.TransactionResponse>;
22
- getFeeForBrokerVolume(symbol: string): Promise<number | undefined>;
20
+ getBrokerInducedFee(poolSymbolName: string): Promise<number>;
23
21
  /**
24
- *
25
- * @param symbol symbol of the form "ETH-USD-MATIC" or just "MATIC"
26
- * @returns number of lots deposited by broker
22
+ * Determine the exchange fee based on lots purchased by this broker.
23
+ * The final exchange fee paid by the broker is equal to
24
+ * maximum(brokerTool.getFeeForBrokerDesignation(poolSymbolName), brokerTool.getFeeForBrokerVolume(poolSymbolName), brokerTool.getFeeForBrokerStake())
25
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
26
+ * @param {number=} lots Optional, designation to use if different from this broker's.
27
+ * @returns {number} Fee based solely on this broker's designation, in decimals (i.e. 0.1% is 0.001).
27
28
  */
28
- getBrokerDesignation(symbol: string): Promise<number>;
29
+ getFeeForBrokerDesignation(poolSymbolName: string, lots?: number): Promise<number>;
29
30
  /**
30
- * @param symbol symbol of the form "ETH-USD-MATIC" or just "MATIC"
31
- * @param lots number of lots for which to get the fee. Defaults to this broker's current deposit if not specified
32
- * @returns fee in decimals based on given number of lots
31
+ * Determine the exchange fee based on volume traded under this broker.
32
+ * The final exchange fee paid by the broker is equal to
33
+ * maximum(brokerTool.getFeeForBrokerDesignation(poolSymbolName), brokerTool.getFeeForBrokerVolume(poolSymbolName), brokerTool.getFeeForBrokerStake())
34
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
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).
33
36
  */
34
- getFeeForBrokerDesignation(symbol: string, newLots?: number): Promise<number | undefined>;
37
+ getFeeForBrokerVolume(poolSymbolName: string): Promise<number>;
35
38
  /**
36
- * @param order order for which to determine the trading fee
37
- * @param traderAddr address of the trader for whom to determine the fee, defaults to lowest tier
38
- * @returns fee in decimals (1% is 0.01)
39
+ * Determine the exchange fee based on the current D8X balance in a broker's wallet.
40
+ * The final exchange fee paid by the broker is equal to
41
+ * maximum(brokerTool.getFeeForBrokerDesignation(symbol, lots), brokerTool.getFeeForBrokerVolume(symbol), brokerTool.getFeeForBrokerStake)
42
+ * @param {string=} brokerAddr Address of the broker in question, if different from the one calling this function.
43
+ * @returns {number} Fee based solely on a broker's D8X balance, in decimals (i.e. 0.1% is 0.001).
39
44
  */
40
- determineExchangeFee(order: Order, traderAddr?: string): Promise<number | undefined>;
45
+ getFeeForBrokerStake(brokerAddr?: string): Promise<number>;
46
+ /**
47
+ * Determine exchange fee based on an order and a trader.
48
+ * This is the fee charged by the exchange only, excluding the broker fee,
49
+ * and it takes into account whether the order given here has been signed by a broker or not.
50
+ * Use this, for instance, to verify that the fee to be charged for a given order is as expected,
51
+ * before and after signing it with brokerTool.signOrder.
52
+ * This fee is equal or lower than the broker induced fee, provided the order is properly signed.
53
+ * @param {Order} order Order for which to determine the exchange fee. Not necessarily signed by this broker.
54
+ * @param {string} traderAddr Address of the trader for whom to determine the fee.
55
+ * @returns {number} Fee in decimals (i.e. 0.1% is 0.001).
56
+ */
57
+ determineExchangeFee(order: Order, traderAddr: string): Promise<number>;
58
+ /**
59
+ * Exponentially weighted EMA of the total trading volume of all trades performed under this broker.
60
+ * The weights are chosen so that in average this coincides with the 30 day volume.
61
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
62
+ * @returns {number} Current trading volume for this broker, in USD.
63
+ */
64
+ getCurrentBrokerVolume(poolSymbolName: string): Promise<number>;
65
+ /**
66
+ * Total amount of collateral currency a broker has to deposit into the default fund to purchase one lot.
67
+ * This is equivalent to the price of a lot expressed in a given pool's currency (e.g. MATIC, USDC, etc).
68
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
69
+ * @returns {number} Broker lot size in a given pool's currency, e.g. in MATIC for poolSymbolName MATIC.
70
+ */
71
+ getLotSize(poolSymbolName: string): Promise<number>;
72
+ /**
73
+ * Provides information on how many lots a broker purchased for a given pool.
74
+ * This is relevant to determine the broker's fee tier.
75
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
76
+ * @returns {number} Number of lots purchased by this broker.
77
+ */
78
+ getBrokerDesignation(poolSymbolName: string): Promise<number>;
79
+ /**
80
+ * Deposit lots to the default fund of a given pool.
81
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
82
+ * @param {number} lots Number of lots to deposit into this pool.
83
+ * @returns {ethers.providers.TransactionResponse} Transaction object.
84
+ */
85
+ brokerDepositToDefaultFund(poolSymbolName: string, lots: number): Promise<ethers.providers.TransactionResponse>;
86
+ /**
87
+ * Adds this broker's signature to an order so that it can be submitted by an approved trader.
88
+ * @param {Order} order Order to sign.
89
+ * @param {string} traderAddr Address of trader submitting the order.
90
+ * @param {number} feeDecimals Fee that this broker is approving for the trader.
91
+ * @param {number} deadline Deadline for the order to be executed.
92
+ * @returns {Order} An order signed by this broker, which can be submitted directly with AccountTrade.order.
93
+ */
94
+ signOrder(order: Order, traderAddr: string, brokerFee: number, deadline: number): Promise<Order>;
95
+ /**
96
+ * Creates a signature that a trader can use to place orders with this broker.
97
+ * This signature can be used to pass on to a trader who wishes to trade via this SDK or directly on the blockchain.
98
+ * @param {string} traderAddr Address of the trader signing up with this broker.
99
+ * @param {string} symbol Perpetual that this trader will be trading, of the form ETH-USD-MATIC.
100
+ * @param {number} brokerFee Broker fee for this trader, in decimals (i.e. 0.1% is 0.001).
101
+ * @param {number} deadline Deadline for the order to be executed.
102
+ * @returns {string} Broker signature approving this trader's fee, symbol, and deadline.
103
+ * @ignore
104
+ */
105
+ createSignatureForTrader(traderAddr: string, symbol: string, brokerFee: number, deadline: number): Promise<string>;
106
+ static _signOrder(symbol: string, brokerFeeTbps: number, traderAddr: string, iDeadline: BigNumber, signer: ethers.Wallet, chainId: number, proxyAddress: string, symbolToPerpStaticInfo: Map<string, PerpetualStaticInfo>): Promise<string>;
107
+ /**
108
+ * Transfer ownership of a broker's status to a new wallet.
109
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
110
+ * @param {string} newAddress The address this broker wants to use from now on.
111
+ * @returns {ethers.providers.TransactionResponse} ethers transaction object
112
+ */
113
+ transferOwnership(poolSymbolName: string, newAddress: string): Promise<ethers.providers.TransactionResponse>;
41
114
  }
@@ -13,116 +13,259 @@ 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 nodeSDKTypes_1 = require("./nodeSDKTypes");
17
16
  const perpetualDataHandler_1 = __importDefault(require("./perpetualDataHandler"));
18
17
  const d8XMath_1 = require("./d8XMath");
18
+ const ethers_1 = require("ethers");
19
19
  const accountTrade_1 = __importDefault(require("./accountTrade"));
20
20
  /**
21
- * BrokerTool.
22
- * Signature method for brokers
21
+ * Functions for brokers to determine fees, deposit lots, and sign-up traders.
23
22
  */
24
23
  class BrokerTool extends writeAccessHandler_1.default {
25
24
  /**
26
25
  * Constructor
27
- * @param config configuration
28
- * @param privateKey private key of account that trades
26
+ * @param {NodeSDKConfig} config Configuration object.
27
+ * @param {string} privateKey Private key of a broker.
29
28
  */
30
29
  constructor(config, privateKey) {
31
30
  super(config, privateKey);
32
31
  }
32
+ // Fee getters
33
33
  /**
34
- *
35
- * @param symbol symbol of the form "ETH-USD-MATIC" or just "MATIC"
36
- * @returns broker lot size in collateral currency, e.g. in MATIC for symbol ETH-USD-MATIC or MATIC
34
+ * Determine the exchange fee based on lots, traded volume, and D8X balance of this broker.
35
+ * This is the final exchange fee paid by the broker.
36
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
37
+ * @returns {number} Exchange fee for this broker, in decimals (i.e. 0.1% is 0.001)
37
38
  */
38
- getLotSize(symbol) {
39
+ getBrokerInducedFee(poolSymbolName) {
39
40
  return __awaiter(this, void 0, void 0, function* () {
40
- if (this.proxyContract == null) {
41
- throw Error("no proxy contract initialized. Use createProxyInstance().");
42
- }
43
- let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
44
- let pool = yield this.proxyContract.getLiquidityPool(poolId);
45
- let lot = pool === null || pool === void 0 ? void 0 : pool.fBrokerCollateralLotSize;
46
- if (lot != undefined) {
47
- lot = (0, d8XMath_1.ABK64x64ToFloat)(pool.fBrokerCollateralLotSize);
41
+ if (this.proxyContract == null || this.signer == null) {
42
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
48
43
  }
49
- return lot;
44
+ let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
45
+ let feeTbps = yield this.proxyContract.getBrokerInducedFee(poolId, this.traderAddr);
46
+ return feeTbps / 100000;
50
47
  });
51
48
  }
52
- brokerDepositToDefaultFund(symbol, lots) {
49
+ /**
50
+ * Determine the exchange fee based on lots purchased by this broker.
51
+ * The final exchange fee paid by the broker is equal to
52
+ * maximum(brokerTool.getFeeForBrokerDesignation(poolSymbolName), brokerTool.getFeeForBrokerVolume(poolSymbolName), brokerTool.getFeeForBrokerStake())
53
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
54
+ * @param {number=} lots Optional, designation to use if different from this broker's.
55
+ * @returns {number} Fee based solely on this broker's designation, in decimals (i.e. 0.1% is 0.001).
56
+ */
57
+ getFeeForBrokerDesignation(poolSymbolName, lots) {
53
58
  return __awaiter(this, void 0, void 0, function* () {
54
59
  if (this.proxyContract == null || this.signer == null) {
55
60
  throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
56
61
  }
57
- let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
58
- let tx = yield this.proxyContract.brokerDepositToDefaultFund(poolId, lots, { gasLimit: this.gasLimit });
59
- return tx;
62
+ // check if designation should be taken from the caller or as a parameter
63
+ let brokerDesignation;
64
+ if (typeof lots == "undefined") {
65
+ brokerDesignation = yield this.getBrokerDesignation(poolSymbolName);
66
+ }
67
+ else {
68
+ brokerDesignation = lots;
69
+ }
70
+ let feeTbps = yield this.proxyContract.getFeeForBrokerDesignation(brokerDesignation);
71
+ return feeTbps / 100000;
60
72
  });
61
73
  }
62
- getFeeForBrokerVolume(symbol) {
74
+ /**
75
+ * Determine the exchange fee based on volume traded under this broker.
76
+ * The final exchange fee paid by the broker is equal to
77
+ * maximum(brokerTool.getFeeForBrokerDesignation(poolSymbolName), brokerTool.getFeeForBrokerVolume(poolSymbolName), brokerTool.getFeeForBrokerStake())
78
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
79
+ * @returns {number} Fee based solely on a broker's traded volume in the corresponding pool, in decimals (i.e. 0.1% is 0.001).
80
+ */
81
+ getFeeForBrokerVolume(poolSymbolName) {
63
82
  return __awaiter(this, void 0, void 0, function* () {
64
- if (this.proxyContract == null) {
65
- throw Error("no proxy contract initialized.");
83
+ if (this.proxyContract == null || this.signer == null) {
84
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
66
85
  }
67
- let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
86
+ let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
68
87
  let feeTbps = yield this.proxyContract.getFeeForBrokerVolume(poolId, this.traderAddr);
69
88
  return feeTbps / 100000;
70
89
  });
71
90
  }
72
91
  /**
73
- *
74
- * @param symbol symbol of the form "ETH-USD-MATIC" or just "MATIC"
75
- * @returns number of lots deposited by broker
92
+ * Determine the exchange fee based on the current D8X balance in a broker's wallet.
93
+ * The final exchange fee paid by the broker is equal to
94
+ * maximum(brokerTool.getFeeForBrokerDesignation(symbol, lots), brokerTool.getFeeForBrokerVolume(symbol), brokerTool.getFeeForBrokerStake)
95
+ * @param {string=} brokerAddr Address of the broker in question, if different from the one calling this function.
96
+ * @returns {number} Fee based solely on a broker's D8X balance, in decimals (i.e. 0.1% is 0.001).
97
+ */
98
+ getFeeForBrokerStake(brokerAddr) {
99
+ return __awaiter(this, void 0, void 0, function* () {
100
+ if (this.proxyContract == null || this.signer == null) {
101
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
102
+ }
103
+ if (typeof brokerAddr == "undefined") {
104
+ brokerAddr = this.traderAddr;
105
+ }
106
+ let feeTbps = yield this.proxyContract.getFeeForBrokerStake(brokerAddr);
107
+ return feeTbps / 100000;
108
+ });
109
+ }
110
+ /**
111
+ * Determine exchange fee based on an order and a trader.
112
+ * This is the fee charged by the exchange only, excluding the broker fee,
113
+ * and it takes into account whether the order given here has been signed by a broker or not.
114
+ * Use this, for instance, to verify that the fee to be charged for a given order is as expected,
115
+ * before and after signing it with brokerTool.signOrder.
116
+ * This fee is equal or lower than the broker induced fee, provided the order is properly signed.
117
+ * @param {Order} order Order for which to determine the exchange fee. Not necessarily signed by this broker.
118
+ * @param {string} traderAddr Address of the trader for whom to determine the fee.
119
+ * @returns {number} Fee in decimals (i.e. 0.1% is 0.001).
120
+ */
121
+ determineExchangeFee(order, traderAddr) {
122
+ return __awaiter(this, void 0, void 0, function* () {
123
+ if (this.proxyContract == null || this.signer == null) {
124
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
125
+ }
126
+ let scOrder = accountTrade_1.default.toSmartContractOrder(order, traderAddr, this.symbolToPerpStaticInfo);
127
+ let feeTbps = yield this.proxyContract.determineExchangeFee(scOrder);
128
+ return feeTbps / 100000;
129
+ });
130
+ }
131
+ // Volume
132
+ /**
133
+ * Exponentially weighted EMA of the total trading volume of all trades performed under this broker.
134
+ * The weights are chosen so that in average this coincides with the 30 day volume.
135
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
136
+ * @returns {number} Current trading volume for this broker, in USD.
137
+ */
138
+ getCurrentBrokerVolume(poolSymbolName) {
139
+ return __awaiter(this, void 0, void 0, function* () {
140
+ if (this.proxyContract == null || this.signer == null) {
141
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
142
+ }
143
+ let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
144
+ let volume = yield this.proxyContract.getCurrentBrokerVolume(poolId, this.traderAddr);
145
+ return (0, d8XMath_1.ABK64x64ToFloat)(volume);
146
+ });
147
+ }
148
+ // Lots
149
+ /**
150
+ * Total amount of collateral currency a broker has to deposit into the default fund to purchase one lot.
151
+ * This is equivalent to the price of a lot expressed in a given pool's currency (e.g. MATIC, USDC, etc).
152
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
153
+ * @returns {number} Broker lot size in a given pool's currency, e.g. in MATIC for poolSymbolName MATIC.
76
154
  */
77
- getBrokerDesignation(symbol) {
155
+ getLotSize(poolSymbolName) {
78
156
  return __awaiter(this, void 0, void 0, function* () {
79
157
  if (this.proxyContract == null) {
80
- throw Error("no proxy contract initialized.");
158
+ throw Error("no proxy contract initialized. Use createProxyInstance().");
81
159
  }
82
- let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(symbol, this.poolStaticInfos);
160
+ let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
161
+ let pool = yield this.proxyContract.getLiquidityPool(poolId);
162
+ let lot = (0, d8XMath_1.ABK64x64ToFloat)(pool.fBrokerCollateralLotSize);
163
+ return lot;
164
+ });
165
+ }
166
+ /**
167
+ * Provides information on how many lots a broker purchased for a given pool.
168
+ * This is relevant to determine the broker's fee tier.
169
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
170
+ * @returns {number} Number of lots purchased by this broker.
171
+ */
172
+ getBrokerDesignation(poolSymbolName) {
173
+ return __awaiter(this, void 0, void 0, function* () {
174
+ if (this.proxyContract == null || this.signer == null) {
175
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
176
+ }
177
+ let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
83
178
  let designation = yield this.proxyContract.getBrokerDesignation(poolId, this.traderAddr);
84
179
  return designation;
85
180
  });
86
181
  }
87
182
  /**
88
- * @param symbol symbol of the form "ETH-USD-MATIC" or just "MATIC"
89
- * @param lots number of lots for which to get the fee. Defaults to this broker's current deposit if not specified
90
- * @returns fee in decimals based on given number of lots
183
+ * Deposit lots to the default fund of a given pool.
184
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
185
+ * @param {number} lots Number of lots to deposit into this pool.
186
+ * @returns {ethers.providers.TransactionResponse} Transaction object.
91
187
  */
92
- getFeeForBrokerDesignation(symbol, newLots = 0) {
188
+ brokerDepositToDefaultFund(poolSymbolName, lots) {
93
189
  return __awaiter(this, void 0, void 0, function* () {
94
- if (this.proxyContract == null) {
95
- throw Error("no proxy contract initialized.");
190
+ if (this.proxyContract == null || this.signer == null) {
191
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
96
192
  }
97
- if (newLots < 0) {
98
- throw Error("new lots must be a positive number.");
193
+ let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
194
+ let tx = yield this.proxyContract.brokerDepositToDefaultFund(poolId, lots, { gasLimit: this.gasLimit });
195
+ return tx;
196
+ });
197
+ }
198
+ // Signatures
199
+ /**
200
+ * Adds this broker's signature to an order so that it can be submitted by an approved trader.
201
+ * @param {Order} order Order to sign.
202
+ * @param {string} traderAddr Address of trader submitting the order.
203
+ * @param {number} feeDecimals Fee that this broker is approving for the trader.
204
+ * @param {number} deadline Deadline for the order to be executed.
205
+ * @returns {Order} An order signed by this broker, which can be submitted directly with AccountTrade.order.
206
+ */
207
+ signOrder(order, traderAddr, brokerFee, deadline) {
208
+ return __awaiter(this, void 0, void 0, function* () {
209
+ if (this.proxyContract == null || this.signer == null) {
210
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
99
211
  }
100
- let lots = yield this.getBrokerDesignation(symbol);
101
- lots += newLots;
102
- let feeTbps = yield this.proxyContract.getFeeForBrokerDesignation(lots);
103
- return feeTbps / 100000;
212
+ order.brokerAddr = this.traderAddr;
213
+ order.brokerFeeTbps = brokerFee * 100000;
214
+ order.deadline = deadline;
215
+ order.brokerSignature = yield BrokerTool._signOrder(order.symbol, order.brokerFeeTbps, traderAddr, ethers_1.BigNumber.from(deadline), this.signer, this.chainId, this.proxyAddr, this.symbolToPerpStaticInfo);
216
+ return order;
104
217
  });
105
218
  }
106
219
  /**
107
- * @param order order for which to determine the trading fee
108
- * @param traderAddr address of the trader for whom to determine the fee, defaults to lowest tier
109
- * @returns fee in decimals (1% is 0.01)
220
+ * Creates a signature that a trader can use to place orders with this broker.
221
+ * This signature can be used to pass on to a trader who wishes to trade via this SDK or directly on the blockchain.
222
+ * @param {string} traderAddr Address of the trader signing up with this broker.
223
+ * @param {string} symbol Perpetual that this trader will be trading, of the form ETH-USD-MATIC.
224
+ * @param {number} brokerFee Broker fee for this trader, in decimals (i.e. 0.1% is 0.001).
225
+ * @param {number} deadline Deadline for the order to be executed.
226
+ * @returns {string} Broker signature approving this trader's fee, symbol, and deadline.
227
+ * @ignore
110
228
  */
111
- determineExchangeFee(order, traderAddr = nodeSDKTypes_1.ZERO_ADDRESS) {
229
+ createSignatureForTrader(traderAddr, symbol, brokerFee, deadline) {
112
230
  return __awaiter(this, void 0, void 0, function* () {
113
- if (this.proxyContract == null) {
114
- throw Error("no proxy contract initialized.");
231
+ if (this.proxyContract == null || this.signer == null) {
232
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
115
233
  }
116
- // broker does not need to enter address in the order if he's signed in
117
- if (order.brokerAddr == undefined) {
118
- if (this.signer == null) {
119
- throw Error("no wallet initialized.");
120
- }
121
- order.brokerAddr = this.traderAddr;
234
+ let iDeadline = ethers_1.BigNumber.from(deadline);
235
+ let brokerFeeTbps = 100000 * brokerFee;
236
+ return yield BrokerTool._signOrder(symbol, brokerFeeTbps, traderAddr, iDeadline, this.signer, this.chainId, this.proxyAddr, this.symbolToPerpStaticInfo);
237
+ });
238
+ }
239
+ static _signOrder(symbol, brokerFeeTbps, traderAddr, iDeadline, signer, chainId, proxyAddress, symbolToPerpStaticInfo) {
240
+ return __awaiter(this, void 0, void 0, function* () {
241
+ const NAME = "Perpetual Trade Manager";
242
+ const DOMAIN_TYPEHASH = ethers_1.ethers.utils.keccak256(Buffer.from("EIP712Domain(string name,uint256 chainId,address verifyingContract)"));
243
+ let abiCoder = ethers_1.ethers.utils.defaultAbiCoder;
244
+ 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]));
245
+ //
246
+ const TRADE_BROKER_TYPEHASH = ethers_1.ethers.utils.keccak256(Buffer.from("Order(uint24 iPerpetualId,uint16 brokerFeeTbps,address traderAddr,uint256 iDeadline)"));
247
+ let iPerpetualId = perpetualDataHandler_1.default.symbolToPerpetualId(symbol, symbolToPerpStaticInfo);
248
+ let structHash = ethers_1.ethers.utils.keccak256(abiCoder.encode(["bytes32", "uint24", "uint16", "address", "uint256"], [TRADE_BROKER_TYPEHASH, iPerpetualId, brokerFeeTbps, traderAddr, iDeadline]));
249
+ let digest = ethers_1.ethers.utils.keccak256(abiCoder.encode(["bytes32", "bytes32"], [domainSeparator, structHash]));
250
+ let digestBuffer = Buffer.from(digest.substring(2, digest.length), "hex");
251
+ return yield signer.signMessage(digestBuffer);
252
+ });
253
+ }
254
+ // Transfer ownership
255
+ /**
256
+ * Transfer ownership of a broker's status to a new wallet.
257
+ * @param {string} poolSymbolName Pool symbol name (e.g. MATIC, USDC, etc).
258
+ * @param {string} newAddress The address this broker wants to use from now on.
259
+ * @returns {ethers.providers.TransactionResponse} ethers transaction object
260
+ */
261
+ transferOwnership(poolSymbolName, newAddress) {
262
+ return __awaiter(this, void 0, void 0, function* () {
263
+ if (this.proxyContract == null) {
264
+ throw Error("no proxy contract or wallet initialized. Use createProxyInstance().");
122
265
  }
123
- let scOrder = accountTrade_1.default.toSmartContractOrder(order, traderAddr, this.symbolToPerpStaticInfo);
124
- let feeTbps = yield this.proxyContract.determineExchangeFee(scOrder);
125
- return feeTbps / 100000;
266
+ let poolId = perpetualDataHandler_1.default._getPoolIdFromSymbol(poolSymbolName, this.poolStaticInfos);
267
+ let tx = yield this.proxyContract.transferOwnership(poolId, newAddress);
268
+ return tx;
126
269
  });
127
270
  }
128
271
  }
package/dist/d8XMath.d.ts CHANGED
@@ -1,41 +1,44 @@
1
1
  import { BigNumber } from "ethers";
2
+ /**
3
+ * @module d8xMath
4
+ */
2
5
  /**
3
6
  * Convert ABK64x64 bigint-format to float.
4
7
  * Result = x/2^64 if big number, x/2^29 if number
5
- * @param x number in ABDK-format or 2^29
6
- * @returns x/2^64 in number-format (float)
8
+ * @param {BigNumber|number} x number in ABDK-format or 2^29
9
+ * @returns {number} x/2^64 in number-format (float)
7
10
  */
8
11
  export declare function ABK64x64ToFloat(x: BigNumber | number): number;
9
12
  /**
10
13
  *
11
- * @param x BigNumber in Dec18 format
12
- * @returns x as a float (number)
14
+ * @param {BigNumber} x BigNumber in Dec18 format
15
+ * @returns {number} x as a float (number)
13
16
  */
14
17
  export declare function dec18ToFloat(x: BigNumber): number;
15
18
  /**
16
19
  * Converts x into ABDK64x64 format
17
- * @param x number (float)
18
- * @returns x^64 in big number format
20
+ * @param {number} x number (float)
21
+ * @returns {BigNumber} x^64 in big number format
19
22
  */
20
23
  export declare function floatToABK64x64(x: number): BigNumber;
21
24
  /**
22
25
  *
23
- * @param x number (float)
24
- * @returns x as a BigNumber in Dec18 format
26
+ * @param {number} x number (float)
27
+ * @returns {BigNumber} x as a BigNumber in Dec18 format
25
28
  */
26
29
  export declare function floatToDec18(x: number): BigNumber;
27
30
  /**
28
31
  *
29
- * @param x
30
- * @param y
31
- * @returns x * y
32
+ * @param {BigNumber} x
33
+ * @param {BigNumber} y
34
+ * @returns {BigNumber} x * y
32
35
  */
33
36
  export declare function mul64x64(x: BigNumber, y: BigNumber): BigNumber;
34
37
  /**
35
38
  *
36
- * @param x
37
- * @param y
38
- * @returns x / y
39
+ * @param {BigNumber} x
40
+ * @param {BigNumber} y
41
+ * @returns {BigNumber} x / y
39
42
  */
40
43
  export declare function div64x64(x: BigNumber, y: BigNumber): BigNumber;
41
44
  /**