@drift-labs/sdk 0.1.36-master.7 → 0.2.0-master.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/accounts/bulkAccountLoader.d.ts +6 -6
- package/lib/accounts/bulkAccountLoader.js +81 -95
- package/lib/accounts/bulkUserSubscription.js +13 -57
- package/lib/accounts/fetch.d.ts +4 -0
- package/lib/accounts/fetch.js +18 -0
- package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +34 -38
- package/lib/accounts/pollingClearingHouseAccountSubscriber.js +224 -224
- package/lib/accounts/pollingOracleSubscriber.d.ts +3 -3
- package/lib/accounts/pollingOracleSubscriber.js +37 -49
- package/lib/accounts/pollingTokenAccountSubscriber.d.ts +3 -3
- package/lib/accounts/pollingTokenAccountSubscriber.js +35 -50
- package/lib/accounts/pollingUserAccountSubscriber.d.ts +7 -13
- package/lib/accounts/pollingUserAccountSubscriber.js +71 -134
- package/lib/accounts/types.d.ts +34 -41
- package/lib/accounts/webSocketAccountSubscriber.d.ts +6 -4
- package/lib/accounts/webSocketAccountSubscriber.js +39 -35
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +33 -28
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +153 -185
- package/lib/accounts/webSocketUserAccountSubscriber.d.ts +5 -11
- package/lib/accounts/webSocketUserAccountSubscriber.js +22 -67
- package/lib/addresses/marketAddresses.d.ts +4 -0
- package/lib/addresses/marketAddresses.js +15 -0
- package/lib/addresses/pda.d.ts +12 -0
- package/lib/addresses/pda.js +83 -0
- package/lib/admin.d.ts +9 -17
- package/lib/admin.js +375 -558
- package/lib/clearingHouse.d.ts +86 -109
- package/lib/clearingHouse.js +828 -895
- package/lib/clearingHouseConfig.d.ts +34 -0
- package/lib/clearingHouseConfig.js +2 -0
- package/lib/clearingHouseUser.d.ts +19 -22
- package/lib/clearingHouseUser.js +155 -141
- package/lib/clearingHouseUserConfig.d.ts +14 -0
- package/lib/clearingHouseUserConfig.js +2 -0
- package/lib/config.d.ts +12 -0
- package/lib/config.js +35 -4
- package/lib/constants/banks.d.ts +16 -0
- package/lib/constants/banks.js +34 -0
- package/lib/constants/markets.d.ts +8 -3
- package/lib/constants/markets.js +13 -206
- package/lib/constants/numericConstants.d.ts +17 -0
- package/lib/constants/numericConstants.js +23 -6
- package/lib/events/eventList.d.ts +22 -0
- package/lib/events/eventList.js +77 -0
- package/lib/events/eventSubscriber.d.ts +34 -0
- package/lib/events/eventSubscriber.js +126 -0
- package/lib/events/fetchLogs.d.ts +13 -0
- package/lib/events/fetchLogs.js +39 -0
- package/lib/events/pollingLogProvider.d.ts +15 -0
- package/lib/events/pollingLogProvider.js +53 -0
- package/lib/events/sort.d.ts +2 -0
- package/lib/events/sort.js +44 -0
- package/lib/events/txEventCache.d.ts +24 -0
- package/lib/events/txEventCache.js +71 -0
- package/lib/events/types.d.ts +49 -0
- package/lib/events/types.js +20 -0
- package/lib/events/webSocketLogProvider.d.ts +12 -0
- package/lib/events/webSocketLogProvider.js +30 -0
- package/lib/examples/makeTradeExample.js +26 -27
- package/lib/factory/bigNum.d.ts +118 -0
- package/lib/factory/bigNum.js +364 -0
- package/lib/factory/oracleClient.d.ts +1 -2
- package/lib/factory/oracleClient.js +6 -2
- package/lib/idl/clearing_house.json +2287 -2938
- package/lib/index.d.ts +12 -4
- package/lib/index.js +12 -4
- package/lib/math/amm.d.ts +24 -29
- package/lib/math/amm.js +239 -178
- package/lib/math/auction.d.ts +5 -0
- package/lib/math/auction.js +39 -0
- package/lib/math/bankBalance.d.ts +9 -0
- package/lib/math/bankBalance.js +75 -0
- package/lib/math/conversion.d.ts +0 -1
- package/lib/math/conversion.js +1 -5
- package/lib/math/funding.d.ts +6 -6
- package/lib/math/funding.js +158 -175
- package/lib/math/market.d.ts +6 -6
- package/lib/math/market.js +10 -9
- package/lib/math/orders.d.ts +5 -0
- package/lib/math/orders.js +31 -1
- package/lib/math/position.d.ts +7 -5
- package/lib/math/position.js +27 -27
- package/lib/math/repeg.d.ts +22 -0
- package/lib/math/repeg.js +128 -0
- package/lib/math/trade.d.ts +5 -4
- package/lib/math/trade.js +29 -21
- package/lib/mockUSDCFaucet.js +87 -116
- package/lib/oracles/oracleClientCache.d.ts +8 -0
- package/lib/oracles/oracleClientCache.js +19 -0
- package/lib/oracles/pythClient.d.ts +3 -5
- package/lib/oracles/pythClient.js +12 -31
- package/lib/oracles/quoteAssetOracleClient.d.ts +9 -0
- package/lib/oracles/quoteAssetOracleClient.js +21 -0
- package/lib/oracles/switchboardClient.d.ts +3 -5
- package/lib/oracles/switchboardClient.js +29 -50
- package/lib/oracles/types.d.ts +6 -1
- package/lib/orders.d.ts +6 -7
- package/lib/orders.js +10 -80
- package/lib/slot/SlotSubscriber.d.ts +12 -0
- package/lib/slot/SlotSubscriber.js +23 -0
- package/lib/tx/retryTxSender.d.ts +2 -2
- package/lib/tx/retryTxSender.js +108 -123
- package/lib/tx/types.d.ts +5 -1
- package/lib/tx/utils.d.ts +1 -1
- package/lib/tx/utils.js +11 -2
- package/lib/types.d.ts +110 -109
- package/lib/types.js +14 -1
- package/lib/userName.d.ts +4 -0
- package/lib/userName.js +20 -0
- package/lib/util/computeUnits.js +10 -21
- package/lib/util/tps.js +11 -22
- package/lib/wallet.js +7 -20
- package/package.json +11 -4
- package/src/accounts/bulkAccountLoader.ts +21 -15
- package/src/accounts/bulkUserSubscription.ts +1 -45
- package/src/accounts/fetch.ts +33 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.ts +249 -214
- package/src/accounts/pollingOracleSubscriber.ts +16 -8
- package/src/accounts/pollingTokenAccountSubscriber.ts +11 -8
- package/src/accounts/pollingUserAccountSubscriber.ts +21 -86
- package/src/accounts/types.ts +41 -70
- package/src/accounts/webSocketAccountSubscriber.ts +33 -16
- package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +190 -240
- package/src/accounts/webSocketUserAccountSubscriber.ts +11 -71
- package/src/addresses/marketAddresses.ts +18 -0
- package/src/addresses/pda.ts +118 -0
- package/src/admin.ts +218 -346
- package/src/clearingHouse.ts +983 -952
- package/src/clearingHouseConfig.ts +37 -0
- package/src/clearingHouseUser.ts +275 -185
- package/src/clearingHouseUserConfig.ts +18 -0
- package/src/config.ts +54 -1
- package/src/constants/banks.ts +43 -0
- package/src/constants/markets.ts +16 -207
- package/src/constants/numericConstants.ts +34 -5
- package/src/events/eventList.ts +94 -0
- package/src/events/eventSubscriber.ts +194 -0
- package/src/events/fetchLogs.ts +80 -0
- package/src/events/pollingLogProvider.ts +79 -0
- package/src/events/sort.ts +65 -0
- package/src/events/txEventCache.ts +74 -0
- package/src/events/types.ts +98 -0
- package/src/events/webSocketLogProvider.ts +38 -0
- package/src/examples/makeTradeExample.ts +20 -11
- package/src/factory/bigNum.ts +524 -0
- package/src/factory/oracleClient.ts +7 -4
- package/src/idl/clearing_house.json +2287 -2938
- package/src/index.ts +12 -4
- package/src/math/amm.ts +414 -245
- package/src/math/auction.ts +39 -0
- package/src/math/bankBalance.ts +112 -0
- package/src/math/conversion.ts +1 -11
- package/src/math/funding.ts +12 -9
- package/src/math/market.ts +37 -30
- package/src/math/orders.ts +38 -0
- package/src/math/position.ts +48 -35
- package/src/math/repeg.ts +176 -0
- package/src/math/trade.ts +45 -35
- package/src/math/utils.js +27 -0
- package/src/math/utils.js.map +1 -0
- package/src/oracles/oracleClientCache.ts +20 -0
- package/src/oracles/pythClient.ts +4 -11
- package/src/oracles/quoteAssetOracleClient.ts +25 -0
- package/src/oracles/switchboardClient.ts +11 -24
- package/src/oracles/types.ts +7 -1
- package/src/orders.ts +24 -126
- package/src/slot/SlotSubscriber.ts +32 -0
- package/src/tx/retryTxSender.ts +6 -4
- package/src/tx/types.ts +6 -1
- package/src/tx/utils.ts +22 -3
- package/src/types.ts +111 -122
- package/src/userName.ts +20 -0
- package/src/util/computeUnits.js +17 -0
- package/src/util/computeUnits.js.map +1 -0
- package/tests/bn/test.ts +255 -0
- package/tsconfig.json +12 -12
- package/lib/addresses.d.ts +0 -10
- package/lib/addresses.js +0 -93
- package/lib/constants/accounts.d.ts +0 -15
- package/lib/constants/accounts.js +0 -18
- package/lib/factory/clearingHouse.d.ts +0 -35
- package/lib/factory/clearingHouse.js +0 -81
- package/lib/factory/clearingHouseUser.d.ts +0 -19
- package/lib/factory/clearingHouseUser.js +0 -34
- package/lib/math/insuranceFund.d.ts +0 -15
- package/lib/math/insuranceFund.js +0 -33
- package/lib/settlement.d.ts +0 -4
- package/lib/settlement.js +0 -10
- package/lib/tx/defaultTxSender.d.ts +0 -8
- package/lib/tx/defaultTxSender.js +0 -12
- package/src/addresses.ts +0 -82
- package/src/constants/accounts.ts +0 -26
- package/src/factory/clearingHouse.ts +0 -173
- package/src/factory/clearingHouseUser.ts +0 -73
- package/src/math/insuranceFund.ts +0 -29
- package/src/settlement.ts +0 -9
- package/src/tx/defaultTxSender.ts +0 -24
package/lib/clearingHouse.js
CHANGED
|
@@ -22,15 +22,6 @@ var __importStar = (this && this.__importStar) || function (mod) {
|
|
|
22
22
|
__setModuleDefault(result, mod);
|
|
23
23
|
return result;
|
|
24
24
|
};
|
|
25
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
26
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
27
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
28
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
29
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
30
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
31
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
32
|
-
});
|
|
33
|
-
};
|
|
34
25
|
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
35
26
|
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
36
27
|
};
|
|
@@ -41,30 +32,62 @@ const spl_token_1 = require("@solana/spl-token");
|
|
|
41
32
|
const anchor = __importStar(require("@project-serum/anchor"));
|
|
42
33
|
const clearing_house_json_1 = __importDefault(require("./idl/clearing_house.json"));
|
|
43
34
|
const web3_js_1 = require("@solana/web3.js");
|
|
44
|
-
const
|
|
35
|
+
const pda_1 = require("./addresses/pda");
|
|
45
36
|
const utils_1 = require("./tx/utils");
|
|
46
|
-
const clearingHouse_1 = require("./factory/clearingHouse");
|
|
47
37
|
const numericConstants_1 = require("./constants/numericConstants");
|
|
48
|
-
const
|
|
49
|
-
const
|
|
50
|
-
const
|
|
38
|
+
const position_1 = require("./math/position");
|
|
39
|
+
const bankBalance_1 = require("./math/bankBalance");
|
|
40
|
+
const userName_1 = require("./userName");
|
|
41
|
+
const pollingClearingHouseAccountSubscriber_1 = require("./accounts/pollingClearingHouseAccountSubscriber");
|
|
42
|
+
const webSocketClearingHouseAccountSubscriber_1 = require("./accounts/webSocketClearingHouseAccountSubscriber");
|
|
43
|
+
const retryTxSender_1 = require("./tx/retryTxSender");
|
|
44
|
+
const clearingHouseUser_1 = require("./clearingHouseUser");
|
|
45
|
+
const orderParams_1 = require("./orderParams");
|
|
46
|
+
const config_1 = require("./config");
|
|
51
47
|
/**
|
|
52
48
|
* # ClearingHouse
|
|
53
49
|
* This class is the main way to interact with Drift Protocol. It allows you to subscribe to the various accounts where the Market's state is stored, as well as: opening positions, liquidating, settling funding, depositing & withdrawing, and more.
|
|
54
|
-
*
|
|
55
|
-
* The default way to construct a ClearingHouse instance is using the {@link from} method. This will create an instance using the static {@link WebSocketClearingHouseAccountSubscriber}, which will use a websocket for each state account subscription.
|
|
56
|
-
* Alternatively, if you want to implement your own method of subscribing to the state accounts on the blockchain, you can implement a {@link ClearingHouseAccountSubscriber} and use it in the {@link ClearingHouse.constructor}
|
|
57
50
|
*/
|
|
58
51
|
class ClearingHouse {
|
|
59
|
-
constructor(
|
|
52
|
+
constructor(config) {
|
|
53
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k;
|
|
54
|
+
this.users = new Map();
|
|
60
55
|
this._isSubscribed = false;
|
|
61
|
-
this.
|
|
62
|
-
this.
|
|
63
|
-
this.
|
|
64
|
-
this.
|
|
65
|
-
this.
|
|
56
|
+
this.marketLastSlotCache = new Map();
|
|
57
|
+
this.connection = config.connection;
|
|
58
|
+
this.wallet = config.wallet;
|
|
59
|
+
this.opts = config.opts || anchor_1.AnchorProvider.defaultOptions();
|
|
60
|
+
this.provider = new anchor_1.AnchorProvider(config.connection, config.wallet, this.opts);
|
|
61
|
+
this.program = new anchor_1.Program(clearing_house_json_1.default, config.programID, this.provider);
|
|
62
|
+
const userIds = (_a = config.userIds) !== null && _a !== void 0 ? _a : [0];
|
|
63
|
+
this.activeUserId = (_b = config.activeUserId) !== null && _b !== void 0 ? _b : userIds[0];
|
|
64
|
+
this.userAccountSubscriptionConfig =
|
|
65
|
+
((_c = config.accountSubscription) === null || _c === void 0 ? void 0 : _c.type) === 'polling'
|
|
66
|
+
? {
|
|
67
|
+
type: 'polling',
|
|
68
|
+
accountLoader: config.accountSubscription.accountLoader,
|
|
69
|
+
}
|
|
70
|
+
: {
|
|
71
|
+
type: 'websocket',
|
|
72
|
+
};
|
|
73
|
+
this.createUsers(userIds, this.userAccountSubscriptionConfig);
|
|
74
|
+
let marketIndexes = config.marketIndexes;
|
|
75
|
+
let bankIndexes = config.bankIndexes;
|
|
76
|
+
let oracleInfos = config.oracleInfos;
|
|
77
|
+
if (config.env) {
|
|
78
|
+
const { marketIndexes: envMarketIndexes, bankIndexes: envBankIndexes, oracleInfos: envOralceInfos, } = (0, config_1.getMarketsBanksAndOraclesForSubscription)(config.env);
|
|
79
|
+
marketIndexes = marketIndexes ? marketIndexes : envMarketIndexes;
|
|
80
|
+
bankIndexes = bankIndexes ? bankIndexes : envBankIndexes;
|
|
81
|
+
oracleInfos = oracleInfos ? oracleInfos : envOralceInfos;
|
|
82
|
+
}
|
|
83
|
+
if (((_d = config.accountSubscription) === null || _d === void 0 ? void 0 : _d.type) === 'polling') {
|
|
84
|
+
this.accountSubscriber = new pollingClearingHouseAccountSubscriber_1.PollingClearingHouseAccountSubscriber(this.program, config.accountSubscription.accountLoader, marketIndexes !== null && marketIndexes !== void 0 ? marketIndexes : [], bankIndexes !== null && bankIndexes !== void 0 ? bankIndexes : [], oracleInfos !== null && oracleInfos !== void 0 ? oracleInfos : []);
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
this.accountSubscriber = new webSocketClearingHouseAccountSubscriber_1.WebSocketClearingHouseAccountSubscriber(this.program, (_e = config.marketIndexes) !== null && _e !== void 0 ? _e : [], (_f = config.bankIndexes) !== null && _f !== void 0 ? _f : [], (_g = config.oracleInfos) !== null && _g !== void 0 ? _g : []);
|
|
88
|
+
}
|
|
66
89
|
this.eventEmitter = this.accountSubscriber.eventEmitter;
|
|
67
|
-
this.txSender =
|
|
90
|
+
this.txSender = new retryTxSender_1.RetryTxSender(this.provider, (_h = config.txSenderConfig) === null || _h === void 0 ? void 0 : _h.timeout, (_j = config.txSenderConfig) === null || _j === void 0 ? void 0 : _j.retrySleep, (_k = config.txSenderConfig) === null || _k === void 0 ? void 0 : _k.additionalConnections);
|
|
68
91
|
}
|
|
69
92
|
get isSubscribed() {
|
|
70
93
|
return this._isSubscribed && this.accountSubscriber.isSubscribed;
|
|
@@ -72,128 +95,82 @@ class ClearingHouse {
|
|
|
72
95
|
set isSubscribed(val) {
|
|
73
96
|
this._isSubscribed = val;
|
|
74
97
|
}
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
* @param opts
|
|
81
|
-
* @returns
|
|
82
|
-
*/
|
|
83
|
-
static from(connection, wallet, clearingHouseProgramId, opts = anchor_1.AnchorProvider.defaultOptions()) {
|
|
84
|
-
const config = (0, clearingHouse_1.getWebSocketClearingHouseConfig)(connection, wallet, clearingHouseProgramId, opts);
|
|
85
|
-
return (0, clearingHouse_1.getClearingHouse)(config);
|
|
98
|
+
createUsers(userIds, accountSubscriptionConfig) {
|
|
99
|
+
for (const userId of userIds) {
|
|
100
|
+
const user = this.createUser(userId, accountSubscriptionConfig);
|
|
101
|
+
this.users.set(userId, user);
|
|
102
|
+
}
|
|
86
103
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
94
|
-
this.isSubscribed = yield this.accountSubscriber.subscribe(optionalSubscriptions);
|
|
95
|
-
return this.isSubscribed;
|
|
104
|
+
createUser(userId, accountSubscriptionConfig) {
|
|
105
|
+
const userAccountPublicKey = (0, pda_1.getUserAccountPublicKeySync)(this.program.programId, this.wallet.publicKey, userId);
|
|
106
|
+
return new clearingHouseUser_1.ClearingHouseUser({
|
|
107
|
+
clearingHouse: this,
|
|
108
|
+
userAccountPublicKey,
|
|
109
|
+
accountSubscription: accountSubscriptionConfig,
|
|
96
110
|
});
|
|
97
111
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
subscribeToAll() {
|
|
103
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
104
|
-
return this.subscribe([
|
|
105
|
-
'curveHistoryAccount',
|
|
106
|
-
'depositHistoryAccount',
|
|
107
|
-
'fundingPaymentHistoryAccount',
|
|
108
|
-
'fundingRateHistoryAccount',
|
|
109
|
-
'liquidationHistoryAccount',
|
|
110
|
-
'tradeHistoryAccount',
|
|
111
|
-
'orderHistoryAccount',
|
|
112
|
-
]);
|
|
113
|
-
});
|
|
112
|
+
async subscribe() {
|
|
113
|
+
const subscribePromises = this.subscribeUsers().concat(this.accountSubscriber.subscribe());
|
|
114
|
+
this.isSubscribed = (await Promise.all(subscribePromises)).reduce((success, prevSuccess) => success && prevSuccess);
|
|
115
|
+
return this.isSubscribed;
|
|
114
116
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
*/
|
|
118
|
-
fetchAccounts() {
|
|
119
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
120
|
-
yield this.accountSubscriber.fetch();
|
|
121
|
-
});
|
|
117
|
+
subscribeUsers() {
|
|
118
|
+
return [...this.users.values()].map((user) => user.subscribe());
|
|
122
119
|
}
|
|
123
120
|
/**
|
|
124
|
-
*
|
|
121
|
+
* Forces the accountSubscriber to fetch account updates from rpc
|
|
125
122
|
*/
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
this.
|
|
130
|
-
});
|
|
123
|
+
async fetchAccounts() {
|
|
124
|
+
await Promise.all([...this.users.values()]
|
|
125
|
+
.map((user) => user.fetchAccounts())
|
|
126
|
+
.concat(this.accountSubscriber.fetch()));
|
|
131
127
|
}
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
}
|
|
137
|
-
this.statePublicKey = yield (0, addresses_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
|
|
138
|
-
return this.statePublicKey;
|
|
139
|
-
});
|
|
140
|
-
}
|
|
141
|
-
getStateAccount() {
|
|
142
|
-
return this.accountSubscriber.getStateAccount();
|
|
143
|
-
}
|
|
144
|
-
getSettlementAccount() {
|
|
145
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
146
|
-
// @ts-ignore
|
|
147
|
-
return yield this.program.account.settlementState.fetch(yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId));
|
|
148
|
-
});
|
|
128
|
+
async unsubscribe() {
|
|
129
|
+
const unsubscribePromises = this.unsubscribeUsers().concat(this.accountSubscriber.unsubscribe());
|
|
130
|
+
await Promise.all(unsubscribePromises);
|
|
131
|
+
this.isSubscribed = false;
|
|
149
132
|
}
|
|
150
|
-
|
|
151
|
-
return this.
|
|
133
|
+
unsubscribeUsers() {
|
|
134
|
+
return [...this.users.values()].map((user) => user.unsubscribe());
|
|
152
135
|
}
|
|
153
|
-
|
|
154
|
-
if (
|
|
155
|
-
|
|
136
|
+
async getStatePublicKey() {
|
|
137
|
+
if (this.statePublicKey) {
|
|
138
|
+
return this.statePublicKey;
|
|
156
139
|
}
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
getFundingPaymentHistoryAccount() {
|
|
160
|
-
return this.accountSubscriber.getFundingPaymentHistoryAccount();
|
|
161
|
-
}
|
|
162
|
-
getFundingRateHistoryAccount() {
|
|
163
|
-
return this.accountSubscriber.getFundingRateHistoryAccount();
|
|
164
|
-
}
|
|
165
|
-
getTradeHistoryAccount() {
|
|
166
|
-
return this.accountSubscriber.getTradeHistoryAccount();
|
|
140
|
+
this.statePublicKey = await (0, pda_1.getClearingHouseStateAccountPublicKey)(this.program.programId);
|
|
141
|
+
return this.statePublicKey;
|
|
167
142
|
}
|
|
168
|
-
|
|
169
|
-
return this.accountSubscriber.
|
|
143
|
+
getStateAccount() {
|
|
144
|
+
return this.accountSubscriber.getStateAccountAndSlot().data;
|
|
170
145
|
}
|
|
171
|
-
|
|
172
|
-
|
|
146
|
+
getMarketAccount(marketIndex) {
|
|
147
|
+
var _a;
|
|
148
|
+
marketIndex = marketIndex instanceof anchor_1.BN ? marketIndex : new anchor_1.BN(marketIndex);
|
|
149
|
+
return (_a = this.accountSubscriber.getMarketAccountAndSlot(marketIndex)) === null || _a === void 0 ? void 0 : _a.data;
|
|
173
150
|
}
|
|
174
|
-
|
|
175
|
-
return this.accountSubscriber
|
|
151
|
+
getMarketAccounts() {
|
|
152
|
+
return this.accountSubscriber
|
|
153
|
+
.getMarketAccountsAndSlots()
|
|
154
|
+
.map((value) => value.data);
|
|
176
155
|
}
|
|
177
|
-
|
|
178
|
-
|
|
156
|
+
getBankAccount(bankIndex) {
|
|
157
|
+
bankIndex = bankIndex instanceof anchor_1.BN ? bankIndex : new anchor_1.BN(bankIndex);
|
|
158
|
+
return this.accountSubscriber.getBankAccountAndSlot(bankIndex).data;
|
|
179
159
|
}
|
|
180
|
-
|
|
181
|
-
return
|
|
182
|
-
|
|
183
|
-
return this.orderStatePublicKey;
|
|
184
|
-
}
|
|
185
|
-
this.orderStatePublicKey = yield (0, addresses_1.getOrderStateAccountPublicKey)(this.program.programId);
|
|
186
|
-
return this.orderStatePublicKey;
|
|
187
|
-
});
|
|
160
|
+
getQuoteAssetBankAccount() {
|
|
161
|
+
return this.accountSubscriber.getBankAccountAndSlot(numericConstants_1.QUOTE_ASSET_BANK_INDEX)
|
|
162
|
+
.data;
|
|
188
163
|
}
|
|
189
|
-
|
|
190
|
-
return this.accountSubscriber.
|
|
164
|
+
getOraclePriceDataAndSlot(oraclePublicKey) {
|
|
165
|
+
return this.accountSubscriber.getOraclePriceDataAndSlot(oraclePublicKey);
|
|
191
166
|
}
|
|
192
167
|
/**
|
|
193
168
|
* Update the wallet to use for clearing house transactions and linked user account
|
|
194
169
|
* @param newWallet
|
|
170
|
+
* @param userIds
|
|
171
|
+
* @param activeUserId
|
|
195
172
|
*/
|
|
196
|
-
updateWallet(newWallet) {
|
|
173
|
+
async updateWallet(newWallet, userIds = [0], activeUserId = 0) {
|
|
197
174
|
const newProvider = new anchor_1.AnchorProvider(this.connection, newWallet, this.opts);
|
|
198
175
|
const newProgram = new anchor_1.Program(clearing_house_json_1.default, this.program.programId, newProvider);
|
|
199
176
|
// Update provider for txSender with new wallet details
|
|
@@ -201,852 +178,808 @@ class ClearingHouse {
|
|
|
201
178
|
this.wallet = newWallet;
|
|
202
179
|
this.provider = newProvider;
|
|
203
180
|
this.program = newProgram;
|
|
204
|
-
this.
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
this.
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
.add(initializeUserAccountIx)
|
|
214
|
-
.add(initializeUserOrdersAccountIx);
|
|
215
|
-
const txSig = yield this.txSender.send(tx, [userPositionsAccount], this.opts);
|
|
216
|
-
return [txSig, userAccountPublicKey];
|
|
217
|
-
});
|
|
218
|
-
}
|
|
219
|
-
getInitializeUserInstructions() {
|
|
220
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
221
|
-
const [userAccountPublicKey, userAccountNonce] = yield (0, addresses_1.getUserAccountPublicKeyAndNonce)(this.program.programId, this.wallet.publicKey);
|
|
222
|
-
const remainingAccounts = [];
|
|
223
|
-
const optionalAccounts = {
|
|
224
|
-
whitelistToken: false,
|
|
225
|
-
};
|
|
226
|
-
const state = this.getStateAccount();
|
|
227
|
-
if (state.whitelistMint) {
|
|
228
|
-
optionalAccounts.whitelistToken = true;
|
|
229
|
-
const associatedTokenPublicKey = yield spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.whitelistMint, this.wallet.publicKey);
|
|
230
|
-
remainingAccounts.push({
|
|
231
|
-
pubkey: associatedTokenPublicKey,
|
|
232
|
-
isWritable: false,
|
|
233
|
-
isSigner: false,
|
|
234
|
-
});
|
|
235
|
-
}
|
|
236
|
-
const userPositions = new web3_js_1.Keypair();
|
|
237
|
-
const initializeUserAccountIx = yield this.program.instruction.initializeUser(userAccountNonce, optionalAccounts, {
|
|
238
|
-
accounts: {
|
|
239
|
-
user: userAccountPublicKey,
|
|
240
|
-
authority: this.wallet.publicKey,
|
|
241
|
-
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
242
|
-
systemProgram: anchor.web3.SystemProgram.programId,
|
|
243
|
-
userPositions: userPositions.publicKey,
|
|
244
|
-
state: yield this.getStatePublicKey(),
|
|
245
|
-
},
|
|
246
|
-
remainingAccounts: remainingAccounts,
|
|
247
|
-
});
|
|
248
|
-
const initializeUserOrdersAccountIx = yield this.getInitializeUserOrdersInstruction(userAccountPublicKey);
|
|
249
|
-
return [
|
|
250
|
-
userPositions,
|
|
251
|
-
userAccountPublicKey,
|
|
252
|
-
initializeUserAccountIx,
|
|
253
|
-
initializeUserOrdersAccountIx,
|
|
254
|
-
];
|
|
255
|
-
});
|
|
256
|
-
}
|
|
257
|
-
getInitializeUserOrdersInstruction(userAccountPublicKey) {
|
|
258
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
259
|
-
if (!userAccountPublicKey) {
|
|
260
|
-
userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
261
|
-
}
|
|
262
|
-
const [userOrdersAccountPublicKey, userOrdersAccountNonce] = yield (0, addresses_1.getUserOrdersAccountPublicKeyAndNonce)(this.program.programId, userAccountPublicKey);
|
|
263
|
-
return yield this.program.instruction.initializeUserOrders(userOrdersAccountNonce, {
|
|
264
|
-
accounts: {
|
|
265
|
-
user: userAccountPublicKey,
|
|
266
|
-
authority: this.wallet.publicKey,
|
|
267
|
-
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
268
|
-
systemProgram: anchor.web3.SystemProgram.programId,
|
|
269
|
-
userOrders: userOrdersAccountPublicKey,
|
|
270
|
-
state: yield this.getStatePublicKey(),
|
|
271
|
-
},
|
|
272
|
-
});
|
|
273
|
-
});
|
|
274
|
-
}
|
|
275
|
-
/**
|
|
276
|
-
* Get the address for the Clearing House User's account. NOT the user's wallet address.
|
|
277
|
-
* @returns
|
|
278
|
-
*/
|
|
279
|
-
getUserAccountPublicKey() {
|
|
280
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
281
|
-
if (this.userAccountPublicKey) {
|
|
282
|
-
return this.userAccountPublicKey;
|
|
283
|
-
}
|
|
284
|
-
this.userAccountPublicKey = yield (0, addresses_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey);
|
|
285
|
-
return this.userAccountPublicKey;
|
|
286
|
-
});
|
|
287
|
-
}
|
|
288
|
-
getUserAccount() {
|
|
289
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
290
|
-
if (this.userAccount) {
|
|
291
|
-
return this.userAccount;
|
|
292
|
-
}
|
|
293
|
-
this.userAccount = (yield this.program.account.user.fetch(yield this.getUserAccountPublicKey()));
|
|
294
|
-
return this.userAccount;
|
|
295
|
-
});
|
|
296
|
-
}
|
|
297
|
-
/**
|
|
298
|
-
* Get the address for the Clearing House User Order's account. NOT the user's wallet address.
|
|
299
|
-
* @returns
|
|
300
|
-
*/
|
|
301
|
-
getUserOrdersAccountPublicKey() {
|
|
302
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
303
|
-
if (this.userOrdersAccountPublicKey) {
|
|
304
|
-
return this.userOrdersAccountPublicKey;
|
|
305
|
-
}
|
|
306
|
-
this.userOrdersAccountPublicKey = yield (0, addresses_1.getUserOrdersAccountPublicKey)(this.program.programId, yield this.getUserAccountPublicKey());
|
|
307
|
-
return this.userOrdersAccountPublicKey;
|
|
308
|
-
});
|
|
181
|
+
if (this.isSubscribed) {
|
|
182
|
+
await Promise.all(this.unsubscribeUsers());
|
|
183
|
+
}
|
|
184
|
+
this.users.clear();
|
|
185
|
+
this.createUsers(userIds, this.userAccountSubscriptionConfig);
|
|
186
|
+
if (this.isSubscribed) {
|
|
187
|
+
await Promise.all(this.subscribeUsers());
|
|
188
|
+
}
|
|
189
|
+
this.activeUserId = activeUserId;
|
|
309
190
|
}
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
if (this.userOrdersExist) {
|
|
313
|
-
return this.userOrdersExist;
|
|
314
|
-
}
|
|
315
|
-
const userOrdersAccountRPCResponse = yield this.connection.getParsedAccountInfo(yield this.getUserOrdersAccountPublicKey());
|
|
316
|
-
this.userOrdersExist = userOrdersAccountRPCResponse.value !== null;
|
|
317
|
-
return this.userOrdersExist;
|
|
318
|
-
});
|
|
191
|
+
async switchActiveUser(userId) {
|
|
192
|
+
this.activeUserId = userId;
|
|
319
193
|
}
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
194
|
+
async addUser(userId) {
|
|
195
|
+
if (this.users.has(userId)) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
const user = this.createUser(userId, this.userAccountSubscriptionConfig);
|
|
199
|
+
await user.subscribe();
|
|
200
|
+
this.users.set(userId, user);
|
|
201
|
+
}
|
|
202
|
+
async initializeUserAccount(userId = 0, name = userName_1.DEFAULT_USER_NAME) {
|
|
203
|
+
const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name);
|
|
204
|
+
const tx = new web3_js_1.Transaction().add(initializeUserAccountIx);
|
|
205
|
+
const { txSig } = await this.txSender.send(tx, [], this.opts);
|
|
206
|
+
return [txSig, userAccountPublicKey];
|
|
207
|
+
}
|
|
208
|
+
async getInitializeUserInstructions(userId = 0, name = userName_1.DEFAULT_USER_NAME) {
|
|
209
|
+
const userAccountPublicKey = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, userId);
|
|
210
|
+
const nameBuffer = (0, userName_1.encodeName)(name);
|
|
211
|
+
const initializeUserAccountIx = await this.program.instruction.initializeUser(userId, nameBuffer, {
|
|
212
|
+
accounts: {
|
|
213
|
+
user: userAccountPublicKey,
|
|
214
|
+
authority: this.wallet.publicKey,
|
|
215
|
+
payer: this.wallet.publicKey,
|
|
216
|
+
rent: anchor.web3.SYSVAR_RENT_PUBKEY,
|
|
217
|
+
systemProgram: anchor.web3.SystemProgram.programId,
|
|
218
|
+
state: await this.getStatePublicKey(),
|
|
219
|
+
},
|
|
220
|
+
});
|
|
221
|
+
return [userAccountPublicKey, initializeUserAccountIx];
|
|
222
|
+
}
|
|
223
|
+
getUser(userId) {
|
|
224
|
+
userId = userId !== null && userId !== void 0 ? userId : this.activeUserId;
|
|
225
|
+
if (!this.users.has(userId)) {
|
|
226
|
+
throw new Error(`Clearing House has no user for user id ${userId}`);
|
|
227
|
+
}
|
|
228
|
+
return this.users.get(userId);
|
|
326
229
|
}
|
|
327
|
-
|
|
328
|
-
return
|
|
329
|
-
const userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
330
|
-
if (!userPositionsAccountPublicKey) {
|
|
331
|
-
userPositionsAccountPublicKey = (yield this.getUserAccount()).positions;
|
|
332
|
-
}
|
|
333
|
-
const state = this.getStateAccount();
|
|
334
|
-
return yield this.program.instruction.depositCollateral(amount, {
|
|
335
|
-
accounts: {
|
|
336
|
-
state: yield this.getStatePublicKey(),
|
|
337
|
-
user: userAccountPublicKey,
|
|
338
|
-
collateralVault: state.collateralVault,
|
|
339
|
-
userCollateralAccount: collateralAccountPublicKey,
|
|
340
|
-
authority: this.wallet.publicKey,
|
|
341
|
-
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
342
|
-
markets: state.markets,
|
|
343
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
344
|
-
depositHistory: state.depositHistory,
|
|
345
|
-
userPositions: userPositionsAccountPublicKey,
|
|
346
|
-
},
|
|
347
|
-
});
|
|
348
|
-
});
|
|
230
|
+
getUsers() {
|
|
231
|
+
return [...this.users.values()];
|
|
349
232
|
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
* @param amount
|
|
353
|
-
* @param collateralAccountPublicKey
|
|
354
|
-
* @returns
|
|
355
|
-
*/
|
|
356
|
-
initializeUserAccountAndDepositCollateral(amount, collateralAccountPublicKey) {
|
|
357
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
358
|
-
const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx, initializeUserOrdersAccountIx,] = yield this.getInitializeUserInstructions();
|
|
359
|
-
const depositCollateralIx = yield this.getDepositCollateralInstruction(amount, collateralAccountPublicKey, userPositionsAccount.publicKey);
|
|
360
|
-
const tx = new web3_js_1.Transaction()
|
|
361
|
-
.add(initializeUserAccountIx)
|
|
362
|
-
.add(initializeUserOrdersAccountIx)
|
|
363
|
-
.add(depositCollateralIx);
|
|
364
|
-
const txSig = yield this.txSender.send(tx, [userPositionsAccount]);
|
|
365
|
-
return [txSig, userAccountPublicKey];
|
|
366
|
-
});
|
|
233
|
+
async getUserAccountPublicKey() {
|
|
234
|
+
return this.getUser().userAccountPublicKey;
|
|
367
235
|
}
|
|
368
|
-
|
|
369
|
-
return
|
|
370
|
-
const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = yield mockUSDCFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
|
|
371
|
-
const [userPositionsAccount, userAccountPublicKey, initializeUserAccountIx, initializeUserOrdersAccountIx,] = yield this.getInitializeUserInstructions();
|
|
372
|
-
const depositCollateralIx = yield this.getDepositCollateralInstruction(amount, associateTokenPublicKey, userPositionsAccount.publicKey);
|
|
373
|
-
const tx = new web3_js_1.Transaction()
|
|
374
|
-
.add(createAssociatedAccountIx)
|
|
375
|
-
.add(mintToIx)
|
|
376
|
-
.add(initializeUserAccountIx)
|
|
377
|
-
.add(initializeUserOrdersAccountIx)
|
|
378
|
-
.add(depositCollateralIx);
|
|
379
|
-
const txSig = yield this.program.provider.sendAndConfirm(tx, [
|
|
380
|
-
userPositionsAccount,
|
|
381
|
-
]);
|
|
382
|
-
return [txSig, userAccountPublicKey];
|
|
383
|
-
});
|
|
236
|
+
getUserAccount(userId) {
|
|
237
|
+
return this.getUser(userId).getUserAccount();
|
|
384
238
|
}
|
|
385
|
-
|
|
386
|
-
return
|
|
387
|
-
return this.txSender.send((0, utils_1.wrapInTx)(yield this.getWithdrawCollateralIx(amount, collateralAccountPublicKey)), [], this.opts);
|
|
388
|
-
});
|
|
239
|
+
getUserAccountAndSlot(userId) {
|
|
240
|
+
return this.getUser(userId).getUserAccountAndSlot();
|
|
389
241
|
}
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
const user = yield this.program.account.user.fetch(userAccountPublicKey);
|
|
394
|
-
const state = this.getStateAccount();
|
|
395
|
-
return yield this.program.instruction.withdrawCollateral(amount, {
|
|
396
|
-
accounts: {
|
|
397
|
-
state: yield this.getStatePublicKey(),
|
|
398
|
-
user: userAccountPublicKey,
|
|
399
|
-
collateralVault: state.collateralVault,
|
|
400
|
-
collateralVaultAuthority: state.collateralVaultAuthority,
|
|
401
|
-
insuranceVault: state.insuranceVault,
|
|
402
|
-
insuranceVaultAuthority: state.insuranceVaultAuthority,
|
|
403
|
-
userCollateralAccount: collateralAccountPublicKey,
|
|
404
|
-
authority: this.wallet.publicKey,
|
|
405
|
-
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
406
|
-
markets: state.markets,
|
|
407
|
-
userPositions: user.positions,
|
|
408
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
409
|
-
depositHistory: state.depositHistory,
|
|
410
|
-
},
|
|
411
|
-
});
|
|
412
|
-
});
|
|
242
|
+
getUserBankBalance(bankIndex) {
|
|
243
|
+
const bankIndexBN = bankIndex instanceof anchor_1.BN ? bankIndex : new anchor_1.BN(bankIndex);
|
|
244
|
+
return this.getUserAccount().bankBalances.find((bankBalance) => bankBalance.bankIndex.eq(bankIndexBN));
|
|
413
245
|
}
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
246
|
+
getQuoteAssetTokenAmount() {
|
|
247
|
+
const bank = this.getBankAccount(numericConstants_1.QUOTE_ASSET_BANK_INDEX);
|
|
248
|
+
const userBankBalance = this.getUserBankBalance(numericConstants_1.QUOTE_ASSET_BANK_INDEX);
|
|
249
|
+
return (0, bankBalance_1.getTokenAmount)(userBankBalance.balance, bank, userBankBalance.balanceType);
|
|
418
250
|
}
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
if (
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
pubkey:
|
|
435
|
-
isWritable: false,
|
|
251
|
+
getRemainingAccounts(params) {
|
|
252
|
+
const userAccountAndSlot = this.getUserAccountAndSlot();
|
|
253
|
+
if (!userAccountAndSlot) {
|
|
254
|
+
throw Error('No user account found. Most likely user account does not exist or failed to fetch account');
|
|
255
|
+
}
|
|
256
|
+
const { data: userAccount, slot: lastUserPositionsSlot } = userAccountAndSlot;
|
|
257
|
+
const oracleAccountMap = new Map();
|
|
258
|
+
const bankAccountMap = new Map();
|
|
259
|
+
const marketAccountMap = new Map();
|
|
260
|
+
for (const [marketIndexNum, slot] of this.marketLastSlotCache.entries()) {
|
|
261
|
+
// if cache has more recent slot than user positions account slot, add market to remaining accounts
|
|
262
|
+
// otherwise remove from slot
|
|
263
|
+
if (slot > lastUserPositionsSlot) {
|
|
264
|
+
const marketAccount = this.getMarketAccount(marketIndexNum);
|
|
265
|
+
marketAccountMap.set(marketIndexNum, {
|
|
266
|
+
pubkey: marketAccount.pubkey,
|
|
436
267
|
isSigner: false,
|
|
268
|
+
isWritable: false,
|
|
437
269
|
});
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
optionalAccounts.referrer = true;
|
|
441
|
-
remainingAccounts.push({
|
|
442
|
-
pubkey: referrer,
|
|
443
|
-
isWritable: true,
|
|
270
|
+
oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
|
|
271
|
+
pubkey: marketAccount.amm.oracle,
|
|
444
272
|
isSigner: false,
|
|
273
|
+
isWritable: false,
|
|
445
274
|
});
|
|
446
275
|
}
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
return yield this.program.instruction.openPosition(direction, amount, marketIndex, limitPrice, optionalAccounts, {
|
|
450
|
-
accounts: {
|
|
451
|
-
state: yield this.getStatePublicKey(),
|
|
452
|
-
user: userAccountPublicKey,
|
|
453
|
-
authority: this.wallet.publicKey,
|
|
454
|
-
markets: state.markets,
|
|
455
|
-
userPositions: userAccount.positions,
|
|
456
|
-
tradeHistory: state.tradeHistory,
|
|
457
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
458
|
-
fundingRateHistory: state.fundingRateHistory,
|
|
459
|
-
oracle: priceOracle,
|
|
460
|
-
},
|
|
461
|
-
remainingAccounts: remainingAccounts,
|
|
462
|
-
});
|
|
463
|
-
});
|
|
464
|
-
}
|
|
465
|
-
initializeUserOrdersThenPlaceOrder(orderParams, discountToken, referrer) {
|
|
466
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
467
|
-
const instructions = [];
|
|
468
|
-
const userOrdersAccountExists = yield this.userOrdersAccountExists();
|
|
469
|
-
if (!userOrdersAccountExists) {
|
|
470
|
-
instructions.push(yield this.getInitializeUserOrdersInstruction());
|
|
276
|
+
else {
|
|
277
|
+
this.marketLastSlotCache.delete(marketIndexNum);
|
|
471
278
|
}
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
}
|
|
480
|
-
placeOrder(orderParams, discountToken, referrer) {
|
|
481
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
482
|
-
return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getPlaceOrderIx(orderParams, discountToken, referrer)), [], this.opts);
|
|
483
|
-
});
|
|
484
|
-
}
|
|
485
|
-
getPlaceOrderIx(orderParams, discountToken, referrer) {
|
|
486
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
487
|
-
const userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
488
|
-
const userAccount = yield this.getUserAccount();
|
|
489
|
-
const priceOracle = this.getMarketsAccount().markets[orderParams.marketIndex.toNumber()].amm
|
|
490
|
-
.oracle;
|
|
491
|
-
const remainingAccounts = [];
|
|
492
|
-
if (orderParams.optionalAccounts.discountToken) {
|
|
493
|
-
if (!discountToken) {
|
|
494
|
-
throw Error('Optional accounts specified discount token but no discount token present');
|
|
495
|
-
}
|
|
496
|
-
remainingAccounts.push({
|
|
497
|
-
pubkey: discountToken,
|
|
498
|
-
isWritable: false,
|
|
279
|
+
}
|
|
280
|
+
for (const position of userAccount.positions) {
|
|
281
|
+
if (!(0, position_1.positionIsAvailable)(position)) {
|
|
282
|
+
const marketIndexNum = position.marketIndex.toNumber();
|
|
283
|
+
const marketAccount = this.getMarketAccount(marketIndexNum);
|
|
284
|
+
marketAccountMap.set(marketIndexNum, {
|
|
285
|
+
pubkey: marketAccount.pubkey,
|
|
499
286
|
isSigner: false,
|
|
287
|
+
// isWritable: false, // TODO
|
|
288
|
+
isWritable: true,
|
|
500
289
|
});
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
if (!referrer) {
|
|
504
|
-
throw Error('Optional accounts specified referrer but no referrer present');
|
|
505
|
-
}
|
|
506
|
-
remainingAccounts.push({
|
|
507
|
-
pubkey: referrer,
|
|
508
|
-
isWritable: false,
|
|
290
|
+
oracleAccountMap.set(marketAccount.pubkey.toString(), {
|
|
291
|
+
pubkey: marketAccount.amm.oracle,
|
|
509
292
|
isSigner: false,
|
|
510
|
-
});
|
|
511
|
-
}
|
|
512
|
-
if (!orderParams.oraclePriceOffset.eq(numericConstants_1.ZERO)) {
|
|
513
|
-
remainingAccounts.push({
|
|
514
|
-
pubkey: priceOracle,
|
|
515
293
|
isWritable: false,
|
|
516
|
-
isSigner: false,
|
|
517
294
|
});
|
|
518
295
|
}
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
markets: state.markets,
|
|
527
|
-
userOrders: yield this.getUserOrdersAccountPublicKey(),
|
|
528
|
-
userPositions: userAccount.positions,
|
|
529
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
530
|
-
fundingRateHistory: state.fundingRateHistory,
|
|
531
|
-
orderState: yield this.getOrderStatePublicKey(),
|
|
532
|
-
orderHistory: orderState.orderHistory,
|
|
533
|
-
},
|
|
534
|
-
remainingAccounts,
|
|
296
|
+
}
|
|
297
|
+
if (params.writableMarketIndex) {
|
|
298
|
+
const marketAccount = this.getMarketAccount(params.writableMarketIndex.toNumber());
|
|
299
|
+
marketAccountMap.set(params.writableMarketIndex.toNumber(), {
|
|
300
|
+
pubkey: marketAccount.pubkey,
|
|
301
|
+
isSigner: false,
|
|
302
|
+
isWritable: true,
|
|
535
303
|
});
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getExpireOrdersIx(userAccountPublicKey, userOrdersAccountPublicKey)), [], this.opts);
|
|
541
|
-
});
|
|
542
|
-
}
|
|
543
|
-
getExpireOrdersIx(userAccountPublicKey, userOrdersAccountPublicKey) {
|
|
544
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
545
|
-
const fillerPublicKey = yield this.getUserAccountPublicKey();
|
|
546
|
-
const userAccount = yield this.program.account.user.fetch(userAccountPublicKey);
|
|
547
|
-
const orderState = this.getOrderStateAccount();
|
|
548
|
-
return yield this.program.instruction.expireOrders({
|
|
549
|
-
accounts: {
|
|
550
|
-
state: yield this.getStatePublicKey(),
|
|
551
|
-
filler: fillerPublicKey,
|
|
552
|
-
user: userAccountPublicKey,
|
|
553
|
-
authority: this.wallet.publicKey,
|
|
554
|
-
userPositions: userAccount.positions,
|
|
555
|
-
userOrders: userOrdersAccountPublicKey,
|
|
556
|
-
orderState: yield this.getOrderStatePublicKey(),
|
|
557
|
-
orderHistory: orderState.orderHistory,
|
|
558
|
-
},
|
|
304
|
+
oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
|
|
305
|
+
pubkey: marketAccount.amm.oracle,
|
|
306
|
+
isSigner: false,
|
|
307
|
+
isWritable: false,
|
|
559
308
|
});
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
}
|
|
567
|
-
getCancelOrderIx(orderId, oracle) {
|
|
568
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
569
|
-
const userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
570
|
-
const userAccount = yield this.getUserAccount();
|
|
571
|
-
const state = this.getStateAccount();
|
|
572
|
-
const orderState = this.getOrderStateAccount();
|
|
573
|
-
const remainingAccounts = [];
|
|
574
|
-
if (oracle) {
|
|
575
|
-
remainingAccounts.push({
|
|
576
|
-
pubkey: oracle,
|
|
577
|
-
isWritable: false,
|
|
309
|
+
}
|
|
310
|
+
for (const userBankBalance of userAccount.bankBalances) {
|
|
311
|
+
if (!userBankBalance.balance.eq(numericConstants_1.ZERO)) {
|
|
312
|
+
const bankAccount = this.getBankAccount(userBankBalance.bankIndex);
|
|
313
|
+
bankAccountMap.set(userBankBalance.bankIndex.toNumber(), {
|
|
314
|
+
pubkey: bankAccount.pubkey,
|
|
578
315
|
isSigner: false,
|
|
316
|
+
isWritable: false,
|
|
579
317
|
});
|
|
318
|
+
if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
|
|
319
|
+
oracleAccountMap.set(bankAccount.oracle.toString(), {
|
|
320
|
+
pubkey: bankAccount.oracle,
|
|
321
|
+
isSigner: false,
|
|
322
|
+
isWritable: false,
|
|
323
|
+
});
|
|
324
|
+
}
|
|
580
325
|
}
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
userPositions: userAccount.positions,
|
|
589
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
590
|
-
fundingRateHistory: state.fundingRateHistory,
|
|
591
|
-
orderState: yield this.getOrderStatePublicKey(),
|
|
592
|
-
orderHistory: orderState.orderHistory,
|
|
593
|
-
},
|
|
594
|
-
remainingAccounts,
|
|
326
|
+
}
|
|
327
|
+
if (params.writableBankIndex) {
|
|
328
|
+
const bankAccount = this.getBankAccount(params.writableBankIndex);
|
|
329
|
+
bankAccountMap.set(params.writableBankIndex.toNumber(), {
|
|
330
|
+
pubkey: bankAccount.pubkey,
|
|
331
|
+
isSigner: false,
|
|
332
|
+
isWritable: true,
|
|
595
333
|
});
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
600
|
-
return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getCancelOrderByUserIdIx(userOrderId, oracle)), [], this.opts);
|
|
601
|
-
});
|
|
602
|
-
}
|
|
603
|
-
getCancelOrderByUserIdIx(userOrderId, oracle) {
|
|
604
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
605
|
-
const userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
606
|
-
const userAccount = yield this.getUserAccount();
|
|
607
|
-
const state = this.getStateAccount();
|
|
608
|
-
const orderState = this.getOrderStateAccount();
|
|
609
|
-
const remainingAccounts = [];
|
|
610
|
-
if (oracle) {
|
|
611
|
-
remainingAccounts.push({
|
|
612
|
-
pubkey: oracle,
|
|
613
|
-
isWritable: false,
|
|
334
|
+
if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
|
|
335
|
+
oracleAccountMap.set(bankAccount.oracle.toString(), {
|
|
336
|
+
pubkey: bankAccount.oracle,
|
|
614
337
|
isSigner: false,
|
|
338
|
+
isWritable: false,
|
|
615
339
|
});
|
|
616
340
|
}
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
341
|
+
}
|
|
342
|
+
return [
|
|
343
|
+
...oracleAccountMap.values(),
|
|
344
|
+
...bankAccountMap.values(),
|
|
345
|
+
...marketAccountMap.values(),
|
|
346
|
+
];
|
|
347
|
+
}
|
|
348
|
+
getOrder(orderId) {
|
|
349
|
+
var _a;
|
|
350
|
+
const orderIdBN = orderId instanceof anchor_1.BN ? orderId : new anchor_1.BN(orderId);
|
|
351
|
+
return (_a = this.getUserAccount()) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.orderId.eq(orderIdBN));
|
|
352
|
+
}
|
|
353
|
+
getOrderByUserId(userOrderId) {
|
|
354
|
+
var _a;
|
|
355
|
+
return (_a = this.getUserAccount()) === null || _a === void 0 ? void 0 : _a.orders.find((order) => order.userOrderId === userOrderId);
|
|
356
|
+
}
|
|
357
|
+
async deposit(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly = false) {
|
|
358
|
+
const depositCollateralIx = await this.getDepositInstruction(amount, bankIndex, collateralAccountPublicKey, userId, reduceOnly, true);
|
|
359
|
+
const tx = new web3_js_1.Transaction().add(depositCollateralIx);
|
|
360
|
+
const { txSig } = await this.txSender.send(tx);
|
|
361
|
+
return txSig;
|
|
362
|
+
}
|
|
363
|
+
async getDepositInstruction(amount, bankIndex, userTokenAccount, userId, reduceOnly = false, userInitialized = true) {
|
|
364
|
+
const userAccountPublicKey = userId
|
|
365
|
+
? await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, userId)
|
|
366
|
+
: await this.getUserAccountPublicKey();
|
|
367
|
+
let remainingAccounts = [];
|
|
368
|
+
if (userInitialized) {
|
|
369
|
+
remainingAccounts = this.getRemainingAccounts({
|
|
370
|
+
writableBankIndex: bankIndex,
|
|
631
371
|
});
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
remainingAccounts = [
|
|
375
|
+
{
|
|
376
|
+
pubkey: this.getBankAccount(bankIndex).pubkey,
|
|
377
|
+
isSigner: false,
|
|
378
|
+
isWritable: true,
|
|
379
|
+
},
|
|
380
|
+
];
|
|
381
|
+
}
|
|
382
|
+
const bank = this.getBankAccount(bankIndex);
|
|
383
|
+
return await this.program.instruction.deposit(bankIndex, amount, reduceOnly, {
|
|
384
|
+
accounts: {
|
|
385
|
+
state: await this.getStatePublicKey(),
|
|
386
|
+
bank: bank.pubkey,
|
|
387
|
+
bankVault: bank.vault,
|
|
388
|
+
user: userAccountPublicKey,
|
|
389
|
+
userTokenAccount: userTokenAccount,
|
|
390
|
+
authority: this.wallet.publicKey,
|
|
391
|
+
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
392
|
+
},
|
|
393
|
+
remainingAccounts,
|
|
632
394
|
});
|
|
633
395
|
}
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
396
|
+
/**
|
|
397
|
+
* Creates the Clearing House User account for a user, and deposits some initial collateral
|
|
398
|
+
* @param userId
|
|
399
|
+
* @param name
|
|
400
|
+
* @param amount
|
|
401
|
+
* @param userTokenAccount
|
|
402
|
+
* @param fromUserId
|
|
403
|
+
* @returns
|
|
404
|
+
*/
|
|
405
|
+
async initializeUserAccountAndDepositCollateral(amount, userTokenAccount, bankIndex = new anchor_1.BN(0), userId = 0, name = userName_1.DEFAULT_USER_NAME, fromUserId) {
|
|
406
|
+
const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name);
|
|
407
|
+
const depositCollateralIx = fromUserId != null
|
|
408
|
+
? await this.getTransferDepositIx(amount, bankIndex, fromUserId, userId)
|
|
409
|
+
: await this.getDepositInstruction(amount, bankIndex, userTokenAccount, userId, false, false);
|
|
410
|
+
const tx = new web3_js_1.Transaction()
|
|
411
|
+
.add(initializeUserAccountIx)
|
|
412
|
+
.add(depositCollateralIx);
|
|
413
|
+
const { txSig } = await this.txSender.send(tx, []);
|
|
414
|
+
return [txSig, userAccountPublicKey];
|
|
415
|
+
}
|
|
416
|
+
async initializeUserAccountForDevnet(userId = 0, name = userName_1.DEFAULT_USER_NAME, mockUSDCFaucet, amount) {
|
|
417
|
+
const [associateTokenPublicKey, createAssociatedAccountIx, mintToIx] = await mockUSDCFaucet.createAssociatedTokenAccountAndMintToInstructions(this.wallet.publicKey, amount);
|
|
418
|
+
const [userAccountPublicKey, initializeUserAccountIx] = await this.getInitializeUserInstructions(userId, name);
|
|
419
|
+
const depositCollateralIx = await this.getDepositInstruction(amount, new anchor_1.BN(0), associateTokenPublicKey, userId, false, false);
|
|
420
|
+
const tx = new web3_js_1.Transaction()
|
|
421
|
+
.add(createAssociatedAccountIx)
|
|
422
|
+
.add(mintToIx)
|
|
423
|
+
.add(initializeUserAccountIx)
|
|
424
|
+
.add(depositCollateralIx);
|
|
425
|
+
const txSig = await this.program.provider.sendAndConfirm(tx, []);
|
|
426
|
+
return [txSig, userAccountPublicKey];
|
|
427
|
+
}
|
|
428
|
+
async withdraw(amount, bankIndex, userTokenAccount, reduceOnly = false) {
|
|
429
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getWithdrawIx(amount, bankIndex, userTokenAccount, reduceOnly)), [], this.opts);
|
|
430
|
+
return txSig;
|
|
431
|
+
}
|
|
432
|
+
async getWithdrawIx(amount, bankIndex, userTokenAccount, reduceOnly = false) {
|
|
433
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey();
|
|
434
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
435
|
+
writableBankIndex: bankIndex,
|
|
436
|
+
});
|
|
437
|
+
const bank = this.getBankAccount(bankIndex);
|
|
438
|
+
return await this.program.instruction.withdraw(bankIndex, amount, reduceOnly, {
|
|
439
|
+
accounts: {
|
|
440
|
+
state: await this.getStatePublicKey(),
|
|
441
|
+
bank: bank.pubkey,
|
|
442
|
+
bankVault: bank.vault,
|
|
443
|
+
bankVaultAuthority: bank.vaultAuthority,
|
|
444
|
+
user: userAccountPublicKey,
|
|
445
|
+
userTokenAccount: userTokenAccount,
|
|
446
|
+
authority: this.wallet.publicKey,
|
|
447
|
+
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
448
|
+
},
|
|
449
|
+
remainingAccounts,
|
|
450
|
+
});
|
|
451
|
+
}
|
|
452
|
+
async transferDeposit(amount, bankIndex, fromUserId, toUserId) {
|
|
453
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTransferDepositIx(amount, bankIndex, fromUserId, toUserId)), [], this.opts);
|
|
454
|
+
return txSig;
|
|
455
|
+
}
|
|
456
|
+
async getTransferDepositIx(amount, bankIndex, fromUserId, toUserId) {
|
|
457
|
+
const fromUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, fromUserId);
|
|
458
|
+
const toUser = await (0, pda_1.getUserAccountPublicKey)(this.program.programId, this.wallet.publicKey, toUserId);
|
|
459
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
460
|
+
writableBankIndex: bankIndex,
|
|
461
|
+
});
|
|
462
|
+
return await this.program.instruction.transferDeposit(bankIndex, amount, {
|
|
463
|
+
accounts: {
|
|
464
|
+
authority: this.wallet.publicKey,
|
|
465
|
+
fromUser,
|
|
466
|
+
toUser,
|
|
467
|
+
state: await this.getStatePublicKey(),
|
|
468
|
+
},
|
|
469
|
+
remainingAccounts,
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
async updateBankCumulativeInterest(bankIndex) {
|
|
473
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.updateBankCumulativeInterestIx(bankIndex)), [], this.opts);
|
|
474
|
+
return txSig;
|
|
475
|
+
}
|
|
476
|
+
async updateBankCumulativeInterestIx(bankIndex) {
|
|
477
|
+
const bank = this.getBankAccount(bankIndex);
|
|
478
|
+
return await this.program.instruction.updateBankCumulativeInterest({
|
|
479
|
+
accounts: {
|
|
480
|
+
bank: bank.pubkey,
|
|
481
|
+
},
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
async openPosition(direction, amount, marketIndex, limitPrice) {
|
|
485
|
+
return await this.placeAndTake((0, orderParams_1.getMarketOrderParams)(marketIndex, direction, numericConstants_1.ZERO, amount, false, limitPrice));
|
|
486
|
+
}
|
|
487
|
+
async placeOrder(orderParams) {
|
|
488
|
+
const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceOrderIx(orderParams)), [], this.opts);
|
|
489
|
+
this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
|
|
490
|
+
return txSig;
|
|
491
|
+
}
|
|
492
|
+
async getPlaceOrderIx(orderParams) {
|
|
493
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey();
|
|
494
|
+
const priceOracle = this.getMarketAccount(orderParams.marketIndex).amm
|
|
495
|
+
.oracle;
|
|
496
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
497
|
+
writableMarketIndex: orderParams.marketIndex,
|
|
498
|
+
});
|
|
499
|
+
return await this.program.instruction.placeOrder(orderParams, {
|
|
500
|
+
accounts: {
|
|
501
|
+
state: await this.getStatePublicKey(),
|
|
502
|
+
user: userAccountPublicKey,
|
|
503
|
+
authority: this.wallet.publicKey,
|
|
504
|
+
oracle: priceOracle,
|
|
505
|
+
},
|
|
506
|
+
remainingAccounts,
|
|
507
|
+
});
|
|
508
|
+
}
|
|
509
|
+
async expireOrders(userAccountPublicKey) {
|
|
510
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getExpireOrdersIx(userAccountPublicKey)), [], this.opts);
|
|
511
|
+
return txSig;
|
|
512
|
+
}
|
|
513
|
+
async getExpireOrdersIx(userAccountPublicKey) {
|
|
514
|
+
const fillerPublicKey = await this.getUserAccountPublicKey();
|
|
515
|
+
return await this.program.instruction.expireOrders({
|
|
516
|
+
accounts: {
|
|
517
|
+
state: await this.getStatePublicKey(),
|
|
518
|
+
filler: fillerPublicKey,
|
|
519
|
+
user: userAccountPublicKey,
|
|
520
|
+
authority: this.wallet.publicKey,
|
|
521
|
+
},
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
async updateAMMs(marketIndexes) {
|
|
525
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getUpdateAMMsIx(marketIndexes)), [], this.opts);
|
|
526
|
+
return txSig;
|
|
527
|
+
}
|
|
528
|
+
async getUpdateAMMsIx(marketIndexes) {
|
|
529
|
+
for (let i = marketIndexes.length; i < 5; i++) {
|
|
530
|
+
marketIndexes.push(new anchor_1.BN(100));
|
|
531
|
+
}
|
|
532
|
+
const marketAccountInfos = [];
|
|
533
|
+
const oracleAccountInfos = [];
|
|
534
|
+
for (const marketIndex of marketIndexes) {
|
|
535
|
+
if (!marketIndex.eq(new anchor_1.BN(100))) {
|
|
536
|
+
const market = this.getMarketAccount(marketIndex);
|
|
537
|
+
marketAccountInfos.push({
|
|
538
|
+
pubkey: market.pubkey,
|
|
539
|
+
isWritable: true,
|
|
540
|
+
isSigner: false,
|
|
541
|
+
});
|
|
542
|
+
oracleAccountInfos.push({
|
|
543
|
+
pubkey: market.amm.oracle,
|
|
649
544
|
isWritable: false,
|
|
650
545
|
isSigner: false,
|
|
651
546
|
});
|
|
652
547
|
}
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
548
|
+
}
|
|
549
|
+
const remainingAccounts = oracleAccountInfos.concat(marketAccountInfos);
|
|
550
|
+
return await this.program.instruction.updateAmms(marketIndexes, {
|
|
551
|
+
accounts: {
|
|
552
|
+
state: await this.getStatePublicKey(),
|
|
553
|
+
authority: this.wallet.publicKey,
|
|
554
|
+
},
|
|
555
|
+
remainingAccounts,
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
async cancelOrder(orderId) {
|
|
559
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelOrderIx(orderId)), [], this.opts);
|
|
560
|
+
return txSig;
|
|
561
|
+
}
|
|
562
|
+
async getCancelOrderIx(orderId) {
|
|
563
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey();
|
|
564
|
+
const remainingAccounts = this.getRemainingAccounts({});
|
|
565
|
+
return await this.program.instruction.cancelOrder(orderId !== null && orderId !== void 0 ? orderId : null, {
|
|
566
|
+
accounts: {
|
|
567
|
+
state: await this.getStatePublicKey(),
|
|
568
|
+
user: userAccountPublicKey,
|
|
569
|
+
authority: this.wallet.publicKey,
|
|
570
|
+
},
|
|
571
|
+
remainingAccounts,
|
|
572
|
+
});
|
|
573
|
+
}
|
|
574
|
+
async cancelOrderByUserId(userOrderId) {
|
|
575
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelOrderByUserIdIx(userOrderId)), [], this.opts);
|
|
576
|
+
return txSig;
|
|
577
|
+
}
|
|
578
|
+
async getCancelOrderByUserIdIx(userOrderId) {
|
|
579
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey();
|
|
580
|
+
const order = this.getOrderByUserId(userOrderId);
|
|
581
|
+
const oracle = this.getMarketAccount(order.marketIndex).amm.oracle;
|
|
582
|
+
const remainingAccounts = this.getRemainingAccounts({});
|
|
583
|
+
return await this.program.instruction.cancelOrderByUserId(userOrderId, {
|
|
584
|
+
accounts: {
|
|
585
|
+
state: await this.getStatePublicKey(),
|
|
586
|
+
user: userAccountPublicKey,
|
|
587
|
+
authority: this.wallet.publicKey,
|
|
588
|
+
oracle,
|
|
589
|
+
},
|
|
590
|
+
remainingAccounts,
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
async cancelAllOrders(bestEffort) {
|
|
594
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelAllOrdersIx(bestEffort)), [], this.opts);
|
|
595
|
+
return txSig;
|
|
596
|
+
}
|
|
597
|
+
async getCancelAllOrdersIx(bestEffort) {
|
|
598
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey();
|
|
599
|
+
const remainingAccounts = this.getRemainingAccounts({});
|
|
600
|
+
for (const order of this.getUserAccount().orders) {
|
|
601
|
+
const oracle = this.getMarketAccount(order.marketIndex).amm.oracle;
|
|
602
|
+
remainingAccounts.push({
|
|
603
|
+
pubkey: oracle,
|
|
604
|
+
isWritable: false,
|
|
605
|
+
isSigner: false,
|
|
667
606
|
});
|
|
668
|
-
}
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
607
|
+
}
|
|
608
|
+
return await this.program.instruction.cancelAllOrders(bestEffort, {
|
|
609
|
+
accounts: {
|
|
610
|
+
state: await this.getStatePublicKey(),
|
|
611
|
+
user: userAccountPublicKey,
|
|
612
|
+
authority: this.wallet.publicKey,
|
|
613
|
+
},
|
|
614
|
+
remainingAccounts,
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
async cancelOrdersByMarketAndSide(bestEffort, marketIndexOnly, directionOnly) {
|
|
618
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getCancelOrdersByMarketAndSideIx(bestEffort, marketIndexOnly, directionOnly)), [], this.opts);
|
|
619
|
+
return txSig;
|
|
620
|
+
}
|
|
621
|
+
async getCancelOrdersByMarketAndSideIx(bestEffort, marketIndexOnly, directionOnly) {
|
|
622
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey();
|
|
623
|
+
const remainingAccounts = this.getRemainingAccounts({});
|
|
624
|
+
for (const order of this.getUserAccount().orders) {
|
|
625
|
+
const oracle = this.getMarketAccount(order.marketIndex).amm.oracle;
|
|
626
|
+
remainingAccounts.push({
|
|
627
|
+
pubkey: oracle,
|
|
628
|
+
isWritable: false,
|
|
629
|
+
isSigner: false,
|
|
630
|
+
});
|
|
631
|
+
}
|
|
632
|
+
return await this.program.instruction.cancelOrdersByMarketAndSide(bestEffort, marketIndexOnly, directionOnly, {
|
|
633
|
+
accounts: {
|
|
634
|
+
state: await this.getStatePublicKey(),
|
|
635
|
+
user: userAccountPublicKey,
|
|
636
|
+
authority: this.wallet.publicKey,
|
|
637
|
+
},
|
|
638
|
+
remainingAccounts,
|
|
639
|
+
});
|
|
640
|
+
}
|
|
641
|
+
async fillOrder(userAccountPublicKey, user, order, makerInfo) {
|
|
642
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getFillOrderIx(userAccountPublicKey, user, order, makerInfo)), [], this.opts);
|
|
643
|
+
return txSig;
|
|
644
|
+
}
|
|
645
|
+
async getFillOrderIx(userAccountPublicKey, userAccount, order, makerInfo) {
|
|
646
|
+
const fillerPublicKey = await this.getUserAccountPublicKey();
|
|
647
|
+
const marketIndex = order.marketIndex;
|
|
648
|
+
const marketAccount = this.getMarketAccount(marketIndex);
|
|
649
|
+
const oracle = marketAccount.amm.oracle;
|
|
650
|
+
const bankAccountInfos = [
|
|
651
|
+
{
|
|
652
|
+
pubkey: this.getQuoteAssetBankAccount().pubkey,
|
|
653
|
+
isSigner: false,
|
|
654
|
+
isWritable: true,
|
|
655
|
+
},
|
|
656
|
+
];
|
|
657
|
+
const marketAccountInfos = [
|
|
658
|
+
{
|
|
659
|
+
pubkey: marketAccount.pubkey,
|
|
660
|
+
isWritable: true,
|
|
661
|
+
isSigner: false,
|
|
662
|
+
},
|
|
663
|
+
];
|
|
664
|
+
const oracleAccountInfos = [
|
|
665
|
+
{
|
|
666
|
+
pubkey: marketAccount.amm.oracle,
|
|
667
|
+
isWritable: false,
|
|
668
|
+
isSigner: false,
|
|
669
|
+
},
|
|
670
|
+
];
|
|
671
|
+
for (const position of userAccount.positions) {
|
|
672
|
+
if (!(0, position_1.positionIsAvailable)(position) &&
|
|
673
|
+
!position.marketIndex.eq(order.marketIndex)) {
|
|
674
|
+
const market = this.getMarketAccount(position.marketIndex);
|
|
675
|
+
marketAccountInfos.push({
|
|
676
|
+
pubkey: market.pubkey,
|
|
685
677
|
isWritable: false,
|
|
686
678
|
isSigner: false,
|
|
687
679
|
});
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
state: yield this.getStatePublicKey(),
|
|
692
|
-
user: userAccountPublicKey,
|
|
693
|
-
authority: this.wallet.publicKey,
|
|
694
|
-
markets: state.markets,
|
|
695
|
-
userOrders: yield this.getUserOrdersAccountPublicKey(),
|
|
696
|
-
userPositions: userAccount.positions,
|
|
697
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
698
|
-
fundingRateHistory: state.fundingRateHistory,
|
|
699
|
-
orderState: yield this.getOrderStatePublicKey(),
|
|
700
|
-
orderHistory: orderState.orderHistory,
|
|
701
|
-
},
|
|
702
|
-
remainingAccounts,
|
|
703
|
-
});
|
|
704
|
-
});
|
|
705
|
-
}
|
|
706
|
-
fillOrder(userAccountPublicKey, userOrdersAccountPublicKey, order) {
|
|
707
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
708
|
-
return yield this.txSender.send((0, utils_1.wrapInTx)(yield this.getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order)), [], this.opts);
|
|
709
|
-
});
|
|
710
|
-
}
|
|
711
|
-
getFillOrderIx(userAccountPublicKey, userOrdersAccountPublicKey, order) {
|
|
712
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
713
|
-
const fillerPublicKey = yield this.getUserAccountPublicKey();
|
|
714
|
-
const userAccount = yield this.program.account.user.fetch(userAccountPublicKey);
|
|
715
|
-
const marketIndex = order.marketIndex;
|
|
716
|
-
const oracle = this.getMarket(marketIndex).amm.oracle;
|
|
717
|
-
const state = this.getStateAccount();
|
|
718
|
-
const orderState = this.getOrderStateAccount();
|
|
719
|
-
const remainingAccounts = [];
|
|
720
|
-
if (!order.referrer.equals(web3_js_1.PublicKey.default)) {
|
|
721
|
-
remainingAccounts.push({
|
|
722
|
-
pubkey: order.referrer,
|
|
723
|
-
isWritable: true,
|
|
680
|
+
oracleAccountInfos.push({
|
|
681
|
+
pubkey: market.amm.oracle,
|
|
682
|
+
isWritable: false,
|
|
724
683
|
isSigner: false,
|
|
725
684
|
});
|
|
726
685
|
}
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
markets: state.markets,
|
|
735
|
-
userPositions: userAccount.positions,
|
|
736
|
-
userOrders: userOrdersAccountPublicKey,
|
|
737
|
-
tradeHistory: state.tradeHistory,
|
|
738
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
739
|
-
fundingRateHistory: state.fundingRateHistory,
|
|
740
|
-
orderState: yield this.getOrderStatePublicKey(),
|
|
741
|
-
orderHistory: orderState.orderHistory,
|
|
742
|
-
extendedCurveHistory: state.extendedCurveHistory,
|
|
743
|
-
oracle: oracle,
|
|
744
|
-
},
|
|
745
|
-
remainingAccounts,
|
|
686
|
+
}
|
|
687
|
+
const remainingAccounts = oracleAccountInfos.concat(bankAccountInfos.concat(marketAccountInfos));
|
|
688
|
+
if (makerInfo) {
|
|
689
|
+
remainingAccounts.push({
|
|
690
|
+
pubkey: makerInfo.maker,
|
|
691
|
+
isWritable: true,
|
|
692
|
+
isSigner: false,
|
|
746
693
|
});
|
|
747
|
-
}
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
return
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
});
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
694
|
+
}
|
|
695
|
+
const orderId = order.orderId;
|
|
696
|
+
const makerOrderId = makerInfo ? makerInfo.order.orderId : null;
|
|
697
|
+
return await this.program.instruction.fillOrder(orderId, makerOrderId, {
|
|
698
|
+
accounts: {
|
|
699
|
+
state: await this.getStatePublicKey(),
|
|
700
|
+
filler: fillerPublicKey,
|
|
701
|
+
user: userAccountPublicKey,
|
|
702
|
+
authority: this.wallet.publicKey,
|
|
703
|
+
oracle: oracle,
|
|
704
|
+
},
|
|
705
|
+
remainingAccounts,
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
async triggerOrder(userAccountPublicKey, user, order) {
|
|
709
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getTriggerOrderIx(userAccountPublicKey, user, order)), [], this.opts);
|
|
710
|
+
return txSig;
|
|
711
|
+
}
|
|
712
|
+
async getTriggerOrderIx(userAccountPublicKey, userAccount, order) {
|
|
713
|
+
const fillerPublicKey = await this.getUserAccountPublicKey();
|
|
714
|
+
const marketIndex = order.marketIndex;
|
|
715
|
+
const marketAccount = this.getMarketAccount(marketIndex);
|
|
716
|
+
const bankAccountInfos = [
|
|
717
|
+
{
|
|
718
|
+
pubkey: this.getQuoteAssetBankAccount().pubkey,
|
|
719
|
+
isSigner: false,
|
|
720
|
+
isWritable: true,
|
|
721
|
+
},
|
|
722
|
+
];
|
|
723
|
+
const marketAccountInfos = [
|
|
724
|
+
{
|
|
725
|
+
pubkey: marketAccount.pubkey,
|
|
726
|
+
isWritable: true,
|
|
727
|
+
isSigner: false,
|
|
728
|
+
},
|
|
729
|
+
];
|
|
730
|
+
const oracleAccountInfos = [
|
|
731
|
+
{
|
|
732
|
+
pubkey: marketAccount.amm.oracle,
|
|
733
|
+
isWritable: false,
|
|
734
|
+
isSigner: false,
|
|
735
|
+
},
|
|
736
|
+
];
|
|
737
|
+
for (const position of userAccount.positions) {
|
|
738
|
+
if (!(0, position_1.positionIsAvailable)(position) &&
|
|
739
|
+
!position.marketIndex.eq(order.marketIndex)) {
|
|
740
|
+
const market = this.getMarketAccount(position.marketIndex);
|
|
741
|
+
marketAccountInfos.push({
|
|
742
|
+
pubkey: market.pubkey,
|
|
782
743
|
isWritable: false,
|
|
783
744
|
isSigner: false,
|
|
784
745
|
});
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
throw Error('Optional accounts specified referrer but no referrer present');
|
|
789
|
-
}
|
|
790
|
-
remainingAccounts.push({
|
|
791
|
-
pubkey: referrer,
|
|
792
|
-
isWritable: true,
|
|
746
|
+
oracleAccountInfos.push({
|
|
747
|
+
pubkey: market.amm.oracle,
|
|
748
|
+
isWritable: false,
|
|
793
749
|
isSigner: false,
|
|
794
750
|
});
|
|
795
751
|
}
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
752
|
+
}
|
|
753
|
+
const remainingAccounts = oracleAccountInfos.concat(bankAccountInfos.concat(marketAccountInfos));
|
|
754
|
+
const orderId = order.orderId;
|
|
755
|
+
return await this.program.instruction.triggerOrder(orderId, {
|
|
756
|
+
accounts: {
|
|
757
|
+
state: await this.getStatePublicKey(),
|
|
758
|
+
filler: fillerPublicKey,
|
|
759
|
+
user: userAccountPublicKey,
|
|
760
|
+
authority: this.wallet.publicKey,
|
|
761
|
+
},
|
|
762
|
+
remainingAccounts,
|
|
763
|
+
});
|
|
764
|
+
}
|
|
765
|
+
async placeAndTake(orderParams, makerInfo) {
|
|
766
|
+
const { txSig, slot } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getPlaceAndTakeIx(orderParams, makerInfo)), [], this.opts);
|
|
767
|
+
this.marketLastSlotCache.set(orderParams.marketIndex.toNumber(), slot);
|
|
768
|
+
return txSig;
|
|
769
|
+
}
|
|
770
|
+
async getPlaceAndTakeIx(orderParams, makerInfo) {
|
|
771
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey();
|
|
772
|
+
const priceOracle = this.getMarketAccount(orderParams.marketIndex).amm
|
|
773
|
+
.oracle;
|
|
774
|
+
const remainingAccounts = this.getRemainingAccounts({
|
|
775
|
+
writableMarketIndex: orderParams.marketIndex,
|
|
776
|
+
writableBankIndex: numericConstants_1.QUOTE_ASSET_BANK_INDEX,
|
|
777
|
+
});
|
|
778
|
+
let makerOrderId = null;
|
|
779
|
+
if (makerInfo) {
|
|
780
|
+
makerOrderId = makerInfo.order.orderId;
|
|
781
|
+
remainingAccounts.push({
|
|
782
|
+
pubkey: makerInfo.maker,
|
|
783
|
+
isSigner: false,
|
|
784
|
+
isWritable: true,
|
|
815
785
|
});
|
|
786
|
+
}
|
|
787
|
+
return await this.program.instruction.placeAndTake(orderParams, makerOrderId, {
|
|
788
|
+
accounts: {
|
|
789
|
+
state: await this.getStatePublicKey(),
|
|
790
|
+
user: userAccountPublicKey,
|
|
791
|
+
authority: this.wallet.publicKey,
|
|
792
|
+
oracle: priceOracle,
|
|
793
|
+
},
|
|
794
|
+
remainingAccounts,
|
|
816
795
|
});
|
|
817
796
|
}
|
|
818
797
|
/**
|
|
819
798
|
* Close an entire position. If you want to reduce a position, use the {@link openPosition} method in the opposite direction of the current position.
|
|
820
799
|
* @param marketIndex
|
|
821
|
-
* @param discountToken
|
|
822
|
-
* @param referrer
|
|
823
800
|
* @returns
|
|
824
801
|
*/
|
|
825
|
-
closePosition(marketIndex
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
802
|
+
async closePosition(marketIndex) {
|
|
803
|
+
const userPosition = this.getUser().getUserPosition(marketIndex);
|
|
804
|
+
if (!userPosition) {
|
|
805
|
+
throw Error(`No position in market ${marketIndex.toString()}`);
|
|
806
|
+
}
|
|
807
|
+
return await this.placeAndTake((0, orderParams_1.getMarketOrderParams)(marketIndex, (0, position_1.findDirectionToClose)(userPosition), numericConstants_1.ZERO, userPosition.baseAssetAmount, true, undefined));
|
|
829
808
|
}
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
809
|
+
async settlePNLs(users, marketIndex) {
|
|
810
|
+
const ixs = [];
|
|
811
|
+
for (const { settleeUserAccountPublicKey, settleeUserAccount } of users) {
|
|
812
|
+
ixs.push(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex));
|
|
813
|
+
}
|
|
814
|
+
const tx = new web3_js_1.Transaction().add(...ixs);
|
|
815
|
+
const { txSig } = await this.txSender.send(tx, [], this.opts);
|
|
816
|
+
return txSig;
|
|
817
|
+
}
|
|
818
|
+
async settlePNL(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
|
|
819
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex)), [], this.opts);
|
|
820
|
+
return txSig;
|
|
821
|
+
}
|
|
822
|
+
async settlePNLIx(settleeUserAccountPublicKey, settleeUserAccount, marketIndex) {
|
|
823
|
+
const marketAccountMap = new Map();
|
|
824
|
+
const oracleAccountMap = new Map();
|
|
825
|
+
const bankAccountMap = new Map();
|
|
826
|
+
for (const position of settleeUserAccount.positions) {
|
|
827
|
+
if (!(0, position_1.positionIsAvailable)(position)) {
|
|
828
|
+
const market = this.getMarketAccount(position.marketIndex);
|
|
829
|
+
marketAccountMap.set(position.marketIndex.toNumber(), {
|
|
830
|
+
pubkey: market.pubkey,
|
|
831
|
+
isWritable: true,
|
|
832
|
+
isSigner: false,
|
|
833
|
+
});
|
|
834
|
+
oracleAccountMap.set(market.amm.oracle.toString(), {
|
|
835
|
+
pubkey: market.amm.oracle,
|
|
844
836
|
isWritable: false,
|
|
845
837
|
isSigner: false,
|
|
846
838
|
});
|
|
847
839
|
}
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
840
|
+
}
|
|
841
|
+
for (const userBankBalance of settleeUserAccount.bankBalances) {
|
|
842
|
+
if (!userBankBalance.balance.eq(numericConstants_1.QUOTE_ASSET_BANK_INDEX)) {
|
|
843
|
+
const bankAccount = this.getBankAccount(userBankBalance.bankIndex);
|
|
844
|
+
bankAccountMap.set(userBankBalance.bankIndex.toNumber(), {
|
|
845
|
+
pubkey: bankAccount.pubkey,
|
|
853
846
|
isSigner: false,
|
|
847
|
+
isWritable: false,
|
|
854
848
|
});
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
accounts: {
|
|
859
|
-
state: yield this.getStatePublicKey(),
|
|
860
|
-
user: userAccountPublicKey,
|
|
861
|
-
authority: this.wallet.publicKey,
|
|
862
|
-
markets: state.markets,
|
|
863
|
-
userPositions: userAccount.positions,
|
|
864
|
-
tradeHistory: state.tradeHistory,
|
|
865
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
866
|
-
fundingRateHistory: state.fundingRateHistory,
|
|
867
|
-
oracle: priceOracle,
|
|
868
|
-
},
|
|
869
|
-
remainingAccounts: remainingAccounts,
|
|
870
|
-
});
|
|
871
|
-
});
|
|
872
|
-
}
|
|
873
|
-
closeAllPositions(userPositionsAccount, discountToken, referrer) {
|
|
874
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
875
|
-
const ixs = [];
|
|
876
|
-
for (const userPosition of userPositionsAccount.positions) {
|
|
877
|
-
if (userPosition.baseAssetAmount.eq(numericConstants_1.ZERO)) {
|
|
878
|
-
continue;
|
|
879
|
-
}
|
|
880
|
-
ixs.push(yield this.getClosePositionIx(userPosition.marketIndex, discountToken, referrer));
|
|
881
|
-
}
|
|
882
|
-
const tx = new web3_js_1.Transaction().add(...ixs);
|
|
883
|
-
return this.txSender.send(tx, [], this.opts);
|
|
884
|
-
});
|
|
885
|
-
}
|
|
886
|
-
liquidate(liquidateeUserAccountPublicKey) {
|
|
887
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
888
|
-
return this.txSender.send((0, utils_1.wrapInTx)(yield this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
|
|
889
|
-
});
|
|
890
|
-
}
|
|
891
|
-
getLiquidateIx(liquidateeUserAccountPublicKey) {
|
|
892
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
893
|
-
const userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
894
|
-
const liquidateeUserAccount = yield this.program.account.user.fetch(liquidateeUserAccountPublicKey);
|
|
895
|
-
const liquidateePositions = yield this.program.account.userPositions.fetch(liquidateeUserAccount.positions);
|
|
896
|
-
const markets = this.getMarketsAccount();
|
|
897
|
-
const remainingAccounts = [];
|
|
898
|
-
for (const position of liquidateePositions.positions) {
|
|
899
|
-
if (!position.baseAssetAmount.eq(new anchor_1.BN(0))) {
|
|
900
|
-
const market = markets.markets[position.marketIndex.toNumber()];
|
|
901
|
-
remainingAccounts.push({
|
|
902
|
-
pubkey: market.amm.oracle,
|
|
903
|
-
isWritable: false,
|
|
849
|
+
if (!bankAccount.bankIndex.eq(numericConstants_1.ZERO)) {
|
|
850
|
+
oracleAccountMap.set(bankAccount.oracle.toString(), {
|
|
851
|
+
pubkey: bankAccount.oracle,
|
|
904
852
|
isSigner: false,
|
|
853
|
+
isWritable: false,
|
|
905
854
|
});
|
|
906
855
|
}
|
|
907
856
|
}
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
}
|
|
964
|
-
|
|
857
|
+
}
|
|
858
|
+
const marketAccount = this.getMarketAccount(marketIndex.toNumber());
|
|
859
|
+
marketAccountMap.set(marketIndex.toNumber(), {
|
|
860
|
+
pubkey: marketAccount.pubkey,
|
|
861
|
+
isSigner: false,
|
|
862
|
+
isWritable: true,
|
|
863
|
+
});
|
|
864
|
+
oracleAccountMap.set(marketAccount.amm.oracle.toString(), {
|
|
865
|
+
pubkey: marketAccount.amm.oracle,
|
|
866
|
+
isSigner: false,
|
|
867
|
+
isWritable: false,
|
|
868
|
+
});
|
|
869
|
+
bankAccountMap.set(numericConstants_1.QUOTE_ASSET_BANK_INDEX.toNumber(), {
|
|
870
|
+
pubkey: this.getBankAccount(numericConstants_1.QUOTE_ASSET_BANK_INDEX).pubkey,
|
|
871
|
+
isSigner: false,
|
|
872
|
+
isWritable: true,
|
|
873
|
+
});
|
|
874
|
+
const remainingAccounts = [
|
|
875
|
+
...oracleAccountMap.values(),
|
|
876
|
+
...bankAccountMap.values(),
|
|
877
|
+
...marketAccountMap.values(),
|
|
878
|
+
];
|
|
879
|
+
return await this.program.instruction.settlePnl(marketIndex, {
|
|
880
|
+
accounts: {
|
|
881
|
+
state: await this.getStatePublicKey(),
|
|
882
|
+
authority: this.wallet.publicKey,
|
|
883
|
+
user: settleeUserAccountPublicKey,
|
|
884
|
+
},
|
|
885
|
+
remainingAccounts: remainingAccounts,
|
|
886
|
+
});
|
|
887
|
+
}
|
|
888
|
+
async liquidate(liquidateeUserAccountPublicKey) {
|
|
889
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getLiquidateIx(liquidateeUserAccountPublicKey)), [], this.opts);
|
|
890
|
+
return txSig;
|
|
891
|
+
}
|
|
892
|
+
async getLiquidateIx(liquidateeUserAccountPublicKey) {
|
|
893
|
+
const userAccountPublicKey = await this.getUserAccountPublicKey();
|
|
894
|
+
const liquidateeUserAccount = (await this.program.account.user.fetch(liquidateeUserAccountPublicKey));
|
|
895
|
+
const bankAccountInfos = [
|
|
896
|
+
{
|
|
897
|
+
pubkey: this.getQuoteAssetBankAccount().pubkey,
|
|
898
|
+
isSigner: false,
|
|
899
|
+
isWritable: true,
|
|
900
|
+
},
|
|
901
|
+
];
|
|
902
|
+
const marketAccountInfos = [];
|
|
903
|
+
const oracleAccountInfos = [];
|
|
904
|
+
for (const position of liquidateeUserAccount.positions) {
|
|
905
|
+
if (!(0, position_1.positionIsAvailable)(position)) {
|
|
906
|
+
const market = this.getMarketAccount(position.marketIndex);
|
|
907
|
+
const marketPublicKey = await (0, pda_1.getMarketPublicKey)(this.program.programId, position.marketIndex);
|
|
908
|
+
marketAccountInfos.push({
|
|
909
|
+
pubkey: marketPublicKey,
|
|
910
|
+
isWritable: true,
|
|
911
|
+
isSigner: false,
|
|
912
|
+
});
|
|
913
|
+
oracleAccountInfos.push({
|
|
914
|
+
pubkey: market.amm.oracle,
|
|
915
|
+
isWritable: false,
|
|
916
|
+
isSigner: false,
|
|
917
|
+
});
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
const remainingAccounts = oracleAccountInfos.concat(bankAccountInfos.concat(marketAccountInfos));
|
|
921
|
+
const state = this.getStateAccount();
|
|
922
|
+
const quoteAssetBankAccount = this.getQuoteAssetBankAccount();
|
|
923
|
+
return await this.program.instruction.liquidate({
|
|
924
|
+
accounts: {
|
|
925
|
+
state: await this.getStatePublicKey(),
|
|
926
|
+
authority: this.wallet.publicKey,
|
|
927
|
+
user: liquidateeUserAccountPublicKey,
|
|
928
|
+
liquidator: userAccountPublicKey,
|
|
929
|
+
bankVault: quoteAssetBankAccount.vault,
|
|
930
|
+
bankVaultAuthority: quoteAssetBankAccount.vaultAuthority,
|
|
931
|
+
insuranceVault: state.insuranceVault,
|
|
932
|
+
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
933
|
+
},
|
|
934
|
+
remainingAccounts: remainingAccounts,
|
|
935
|
+
});
|
|
936
|
+
}
|
|
937
|
+
async updateFundingRate(oracle, marketIndex) {
|
|
938
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getUpdateFundingRateIx(oracle, marketIndex)), [], this.opts);
|
|
939
|
+
return txSig;
|
|
940
|
+
}
|
|
941
|
+
async getUpdateFundingRateIx(oracle, marketIndex) {
|
|
942
|
+
return await this.program.instruction.updateFundingRate(marketIndex, {
|
|
943
|
+
accounts: {
|
|
944
|
+
state: await this.getStatePublicKey(),
|
|
945
|
+
market: await (0, pda_1.getMarketPublicKey)(this.program.programId, marketIndex),
|
|
946
|
+
oracle: oracle,
|
|
947
|
+
},
|
|
948
|
+
});
|
|
949
|
+
}
|
|
950
|
+
async settleFundingPayment(userAccount) {
|
|
951
|
+
const { txSig } = await this.txSender.send((0, utils_1.wrapInTx)(await this.getSettleFundingPaymentIx(userAccount)), [], this.opts);
|
|
952
|
+
return txSig;
|
|
953
|
+
}
|
|
954
|
+
async getSettleFundingPaymentIx(userAccount) {
|
|
955
|
+
const user = (await this.program.account.user.fetch(userAccount));
|
|
956
|
+
const userPositions = user.positions;
|
|
957
|
+
const remainingAccounts = [];
|
|
958
|
+
for (const position of userPositions) {
|
|
959
|
+
if (!(0, position_1.positionIsAvailable)(position)) {
|
|
960
|
+
const marketPublicKey = await (0, pda_1.getMarketPublicKey)(this.program.programId, position.marketIndex);
|
|
961
|
+
remainingAccounts.push({
|
|
962
|
+
pubkey: marketPublicKey,
|
|
963
|
+
isWritable: false,
|
|
964
|
+
isSigner: false,
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
}
|
|
968
|
+
return await this.program.instruction.settleFundingPayment({
|
|
969
|
+
accounts: {
|
|
970
|
+
state: await this.getStatePublicKey(),
|
|
971
|
+
user: userAccount,
|
|
972
|
+
},
|
|
973
|
+
remainingAccounts,
|
|
965
974
|
});
|
|
966
975
|
}
|
|
967
976
|
triggerEvent(eventName, data) {
|
|
968
977
|
this.eventEmitter.emit(eventName, data);
|
|
969
978
|
}
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
const tx = new web3_js_1.Transaction().add(settlePositionIx).add(claimCollateralIx);
|
|
975
|
-
return this.txSender.send(tx, [], this.opts);
|
|
976
|
-
});
|
|
977
|
-
}
|
|
978
|
-
getSettlePositionIx() {
|
|
979
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
980
|
-
const userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
981
|
-
const user = yield this.program.account.user.fetch(userAccountPublicKey);
|
|
982
|
-
const state = this.getStateAccount();
|
|
983
|
-
const settlementState = yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId);
|
|
984
|
-
return yield this.program.instruction.settlePosition({
|
|
985
|
-
accounts: {
|
|
986
|
-
state: yield this.getStatePublicKey(),
|
|
987
|
-
user: userAccountPublicKey,
|
|
988
|
-
markets: state.markets,
|
|
989
|
-
authority: this.wallet.publicKey,
|
|
990
|
-
userPositions: user.positions,
|
|
991
|
-
settlementState,
|
|
992
|
-
fundingPaymentHistory: state.fundingPaymentHistory,
|
|
993
|
-
},
|
|
994
|
-
});
|
|
995
|
-
});
|
|
996
|
-
}
|
|
997
|
-
getClaimCollateralIx(collateralAccountPublicKey) {
|
|
998
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
999
|
-
const userAccountPublicKey = yield this.getUserAccountPublicKey();
|
|
1000
|
-
const state = this.getStateAccount();
|
|
1001
|
-
const settlementState = yield (0, addresses_1.getSettlementStatePublicKey)(this.program.programId);
|
|
1002
|
-
return yield this.program.instruction.claimCollateral({
|
|
1003
|
-
accounts: {
|
|
1004
|
-
state: yield this.getStatePublicKey(),
|
|
1005
|
-
user: userAccountPublicKey,
|
|
1006
|
-
collateralVault: state.collateralVault,
|
|
1007
|
-
collateralVaultAuthority: state.collateralVaultAuthority,
|
|
1008
|
-
userCollateralAccount: collateralAccountPublicKey,
|
|
1009
|
-
authority: this.wallet.publicKey,
|
|
1010
|
-
tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
|
|
1011
|
-
settlementState,
|
|
1012
|
-
},
|
|
1013
|
-
});
|
|
1014
|
-
});
|
|
1015
|
-
}
|
|
1016
|
-
getTotalSettlementSize() {
|
|
1017
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
1018
|
-
const accountLoader = new bulkAccountLoader_1.BulkAccountLoader(this.connection, 'processed', 50000);
|
|
1019
|
-
const clearingHouse = (0, clearingHouse_1.getClearingHouse)((0, clearingHouse_1.getPollingClearingHouseConfig)(this.connection, this.wallet, this.program.programId, accountLoader));
|
|
1020
|
-
console.log('loading all users');
|
|
1021
|
-
const programUserAccounts = (yield this.program.account.user.all());
|
|
1022
|
-
const userArray = [];
|
|
1023
|
-
for (const programUserAccount of programUserAccounts) {
|
|
1024
|
-
const user = (0, clearingHouseUser_1.getClearingHouseUser)((0, clearingHouseUser_1.getPollingClearingHouseUserConfig)(clearingHouse, programUserAccount.account.authority, accountLoader));
|
|
1025
|
-
userArray.push(user);
|
|
1026
|
-
}
|
|
1027
|
-
console.log('subscribing all users');
|
|
1028
|
-
yield (0, bulkUserSubscription_1.bulkPollingUserSubscribe)(userArray, accountLoader);
|
|
1029
|
-
console.log('calculating settlement size');
|
|
1030
|
-
const settlementSize = userArray.reduce((collateralToBeSettled, user) => {
|
|
1031
|
-
return collateralToBeSettled.add(user.getUserAccount().forgoPositionSettlement === 0
|
|
1032
|
-
? user.getSettledPositionValue()
|
|
1033
|
-
: numericConstants_1.ZERO);
|
|
1034
|
-
}, numericConstants_1.ZERO);
|
|
1035
|
-
for (const user of userArray) {
|
|
1036
|
-
yield user.unsubscribe();
|
|
1037
|
-
}
|
|
1038
|
-
return settlementSize;
|
|
1039
|
-
});
|
|
1040
|
-
}
|
|
1041
|
-
updateUserForgoSettlement() {
|
|
1042
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
1043
|
-
return yield this.program.rpc.updateUserForgoSettlement({
|
|
1044
|
-
accounts: {
|
|
1045
|
-
authority: this.wallet.publicKey,
|
|
1046
|
-
user: yield this.getUserAccountPublicKey(),
|
|
1047
|
-
},
|
|
1048
|
-
});
|
|
1049
|
-
});
|
|
979
|
+
getOracleDataForMarket(marketIndex) {
|
|
980
|
+
const oracleKey = this.getMarketAccount(marketIndex).amm.oracle;
|
|
981
|
+
const oracleData = this.getOraclePriceDataAndSlot(oracleKey).data;
|
|
982
|
+
return oracleData;
|
|
1050
983
|
}
|
|
1051
984
|
}
|
|
1052
985
|
exports.ClearingHouse = ClearingHouse;
|