@drift-labs/sdk 0.2.0-master.0 → 0.2.0-master.11
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/admin.d.ts +8 -5
- package/lib/admin.js +43 -11
- package/lib/clearingHouse.d.ts +28 -18
- package/lib/clearingHouse.js +366 -143
- package/lib/clearingHouseUser.d.ts +2 -2
- package/lib/clearingHouseUser.js +8 -17
- package/lib/config.js +1 -1
- package/lib/constants/banks.js +9 -2
- package/lib/constants/numericConstants.d.ts +2 -0
- package/lib/constants/numericConstants.js +3 -1
- package/lib/factory/bigNum.d.ts +8 -2
- package/lib/factory/bigNum.js +14 -6
- package/lib/idl/clearing_house.json +805 -202
- package/lib/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/lib/index.d.ts +3 -2
- package/lib/index.js +7 -2
- package/lib/math/amm.d.ts +6 -1
- package/lib/math/amm.js +124 -41
- package/lib/math/auction.js +4 -1
- package/lib/math/orders.d.ts +2 -2
- package/lib/math/orders.js +18 -11
- package/lib/math/position.js +3 -1
- package/lib/math/repeg.js +1 -1
- package/lib/math/trade.d.ts +1 -1
- package/lib/math/trade.js +7 -10
- package/lib/orderParams.d.ts +14 -5
- package/lib/orderParams.js +8 -96
- package/lib/orders.d.ts +1 -2
- package/lib/orders.js +6 -85
- package/lib/slot/SlotSubscriber.d.ts +7 -0
- package/lib/slot/SlotSubscriber.js +3 -0
- package/lib/{mockUSDCFaucet.d.ts → tokenFaucet.d.ts} +7 -5
- package/lib/{mockUSDCFaucet.js → tokenFaucet.js} +41 -40
- package/lib/tx/utils.js +1 -1
- package/lib/types.d.ts +137 -14
- package/lib/types.js +53 -1
- package/lib/util/computeUnits.js +1 -1
- package/package.json +3 -3
- package/src/accounts/bulkAccountLoader.js +197 -0
- package/src/accounts/bulkUserSubscription.js +33 -0
- package/src/accounts/fetch.js +29 -0
- package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
- package/src/accounts/pollingOracleSubscriber.js +93 -0
- package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
- package/src/accounts/pollingUserAccountSubscriber.js +132 -0
- package/src/accounts/types.js +10 -0
- package/src/accounts/utils.js +7 -0
- package/src/accounts/webSocketAccountSubscriber.js +93 -0
- package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
- package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
- package/src/addresses/marketAddresses.js +26 -0
- package/src/addresses/pda.js +104 -0
- package/src/admin.ts +66 -14
- package/src/assert/assert.js +9 -0
- package/src/clearingHouse.ts +558 -230
- package/src/clearingHouseUser.ts +12 -23
- package/src/config.ts +1 -1
- package/src/constants/banks.ts +9 -2
- package/src/constants/numericConstants.ts +2 -0
- package/src/events/eventList.js +77 -0
- package/src/events/eventSubscriber.js +139 -0
- package/src/events/fetchLogs.js +50 -0
- package/src/events/pollingLogProvider.js +64 -0
- package/src/events/sort.js +44 -0
- package/src/events/txEventCache.js +71 -0
- package/src/events/types.js +20 -0
- package/src/events/webSocketLogProvider.js +41 -0
- package/src/examples/makeTradeExample.js +80 -0
- package/src/factory/bigNum.js +364 -0
- package/src/factory/bigNum.ts +26 -9
- package/src/factory/oracleClient.js +20 -0
- package/src/idl/clearing_house.json +805 -202
- package/src/idl/{mock_usdc_faucet.json → token_faucet.json} +46 -23
- package/src/index.js +100 -0
- package/src/index.ts +3 -2
- package/src/math/amm.js +369 -0
- package/src/math/amm.ts +207 -52
- package/src/math/auction.js +42 -0
- package/src/math/auction.ts +5 -1
- package/src/math/bankBalance.js +75 -0
- package/src/math/conversion.js +11 -0
- package/src/math/funding.js +248 -0
- package/src/math/market.js +57 -0
- package/src/math/oracles.js +26 -0
- package/src/math/orders.js +110 -0
- package/src/math/orders.ts +17 -13
- package/src/math/position.js +140 -0
- package/src/math/position.ts +5 -1
- package/src/math/repeg.js +128 -0
- package/src/math/repeg.ts +2 -1
- package/src/math/state.js +15 -0
- package/src/math/trade.js +253 -0
- package/src/math/trade.ts +23 -25
- package/src/math/utils.js +0 -1
- package/src/mockUSDCFaucet.js +280 -0
- package/src/oracles/oracleClientCache.js +19 -0
- package/src/oracles/pythClient.js +46 -0
- package/src/oracles/quoteAssetOracleClient.js +32 -0
- package/src/oracles/switchboardClient.js +69 -0
- package/src/oracles/types.js +2 -0
- package/src/orderParams.js +20 -0
- package/src/orderParams.ts +20 -141
- package/src/orders.js +134 -0
- package/src/orders.ts +7 -131
- package/src/slot/SlotSubscriber.js +39 -0
- package/src/slot/SlotSubscriber.ts +11 -1
- package/src/token/index.js +38 -0
- package/src/{mockUSDCFaucet.ts → tokenFaucet.ts} +48 -59
- package/src/tx/retryTxSender.js +188 -0
- package/src/tx/types.js +2 -0
- package/src/tx/utils.js +17 -0
- package/src/tx/utils.ts +1 -1
- package/src/types.js +114 -0
- package/src/types.ts +132 -16
- package/src/userName.js +20 -0
- package/src/util/computeUnits.ts +1 -1
- package/src/util/promiseTimeout.js +14 -0
- package/src/util/tps.js +27 -0
- package/src/wallet.js +35 -0
- package/src/util/computeUnits.js +0 -17
- package/src/util/computeUnits.js.map +0 -1
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.RetryTxSender = void 0;
|
|
16
|
+
const assert_1 = __importDefault(require("assert"));
|
|
17
|
+
const bs58_1 = __importDefault(require("bs58"));
|
|
18
|
+
const DEFAULT_TIMEOUT = 35000;
|
|
19
|
+
const DEFAULT_RETRY = 8000;
|
|
20
|
+
class RetryTxSender {
|
|
21
|
+
constructor(provider, timeout, retrySleep, additionalConnections = new Array()) {
|
|
22
|
+
this.provider = provider;
|
|
23
|
+
this.timeout = timeout !== null && timeout !== void 0 ? timeout : DEFAULT_TIMEOUT;
|
|
24
|
+
this.retrySleep = retrySleep !== null && retrySleep !== void 0 ? retrySleep : DEFAULT_RETRY;
|
|
25
|
+
this.additionalConnections = additionalConnections;
|
|
26
|
+
}
|
|
27
|
+
send(tx, additionalSigners, opts) {
|
|
28
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
29
|
+
if (additionalSigners === undefined) {
|
|
30
|
+
additionalSigners = [];
|
|
31
|
+
}
|
|
32
|
+
if (opts === undefined) {
|
|
33
|
+
opts = this.provider.opts;
|
|
34
|
+
}
|
|
35
|
+
yield this.prepareTx(tx, additionalSigners, opts);
|
|
36
|
+
const rawTransaction = tx.serialize();
|
|
37
|
+
const startTime = this.getTimestamp();
|
|
38
|
+
const txid = yield this.provider.connection.sendRawTransaction(rawTransaction, opts);
|
|
39
|
+
this.sendToAdditionalConnections(rawTransaction, opts);
|
|
40
|
+
let done = false;
|
|
41
|
+
const resolveReference = {
|
|
42
|
+
resolve: undefined,
|
|
43
|
+
};
|
|
44
|
+
const stopWaiting = () => {
|
|
45
|
+
done = true;
|
|
46
|
+
if (resolveReference.resolve) {
|
|
47
|
+
resolveReference.resolve();
|
|
48
|
+
}
|
|
49
|
+
};
|
|
50
|
+
(() => __awaiter(this, void 0, void 0, function* () {
|
|
51
|
+
while (!done && this.getTimestamp() - startTime < this.timeout) {
|
|
52
|
+
yield this.sleep(resolveReference);
|
|
53
|
+
if (!done) {
|
|
54
|
+
this.provider.connection
|
|
55
|
+
.sendRawTransaction(rawTransaction, opts)
|
|
56
|
+
.catch((e) => {
|
|
57
|
+
console.error(e);
|
|
58
|
+
stopWaiting();
|
|
59
|
+
});
|
|
60
|
+
this.sendToAdditionalConnections(rawTransaction, opts);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}))();
|
|
64
|
+
let slot;
|
|
65
|
+
try {
|
|
66
|
+
const result = yield this.confirmTransaction(txid, opts.commitment);
|
|
67
|
+
slot = result.context.slot;
|
|
68
|
+
}
|
|
69
|
+
catch (e) {
|
|
70
|
+
console.error(e);
|
|
71
|
+
throw e;
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
stopWaiting();
|
|
75
|
+
}
|
|
76
|
+
return { txSig: txid, slot };
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
prepareTx(tx, additionalSigners, opts) {
|
|
80
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
81
|
+
tx.feePayer = this.provider.wallet.publicKey;
|
|
82
|
+
tx.recentBlockhash = (yield this.provider.connection.getRecentBlockhash(opts.preflightCommitment)).blockhash;
|
|
83
|
+
yield this.provider.wallet.signTransaction(tx);
|
|
84
|
+
additionalSigners
|
|
85
|
+
.filter((s) => s !== undefined)
|
|
86
|
+
.forEach((kp) => {
|
|
87
|
+
tx.partialSign(kp);
|
|
88
|
+
});
|
|
89
|
+
return tx;
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
confirmTransaction(signature, commitment) {
|
|
93
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
94
|
+
let decodedSignature;
|
|
95
|
+
try {
|
|
96
|
+
decodedSignature = bs58_1.default.decode(signature);
|
|
97
|
+
}
|
|
98
|
+
catch (err) {
|
|
99
|
+
throw new Error('signature must be base58 encoded: ' + signature);
|
|
100
|
+
}
|
|
101
|
+
assert_1.default(decodedSignature.length === 64, 'signature has invalid length');
|
|
102
|
+
const start = Date.now();
|
|
103
|
+
const subscriptionCommitment = commitment || this.provider.opts.commitment;
|
|
104
|
+
const subscriptionIds = new Array();
|
|
105
|
+
const connections = [
|
|
106
|
+
this.provider.connection,
|
|
107
|
+
...this.additionalConnections,
|
|
108
|
+
];
|
|
109
|
+
let response = null;
|
|
110
|
+
const promises = connections.map((connection, i) => {
|
|
111
|
+
let subscriptionId;
|
|
112
|
+
const confirmPromise = new Promise((resolve, reject) => {
|
|
113
|
+
try {
|
|
114
|
+
subscriptionId = connection.onSignature(signature, (result, context) => {
|
|
115
|
+
subscriptionIds[i] = undefined;
|
|
116
|
+
response = {
|
|
117
|
+
context,
|
|
118
|
+
value: result,
|
|
119
|
+
};
|
|
120
|
+
resolve(null);
|
|
121
|
+
}, subscriptionCommitment);
|
|
122
|
+
}
|
|
123
|
+
catch (err) {
|
|
124
|
+
reject(err);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
subscriptionIds.push(subscriptionId);
|
|
128
|
+
return confirmPromise;
|
|
129
|
+
});
|
|
130
|
+
try {
|
|
131
|
+
yield this.promiseTimeout(promises, this.timeout);
|
|
132
|
+
}
|
|
133
|
+
finally {
|
|
134
|
+
for (const [i, subscriptionId] of subscriptionIds.entries()) {
|
|
135
|
+
if (subscriptionId) {
|
|
136
|
+
connections[i].removeSignatureListener(subscriptionId);
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
if (response === null) {
|
|
141
|
+
const duration = (Date.now() - start) / 1000;
|
|
142
|
+
throw new Error(`Transaction was not confirmed in ${duration.toFixed(2)} seconds. It is unknown if it succeeded or failed. Check signature ${signature} using the Solana Explorer or CLI tools.`);
|
|
143
|
+
}
|
|
144
|
+
return response;
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
getTimestamp() {
|
|
148
|
+
return new Date().getTime();
|
|
149
|
+
}
|
|
150
|
+
sleep(reference) {
|
|
151
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
152
|
+
return new Promise((resolve) => {
|
|
153
|
+
reference.resolve = resolve;
|
|
154
|
+
setTimeout(resolve, this.retrySleep);
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
promiseTimeout(promises, timeoutMs) {
|
|
159
|
+
let timeoutId;
|
|
160
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
161
|
+
timeoutId = setTimeout(() => resolve(null), timeoutMs);
|
|
162
|
+
});
|
|
163
|
+
return Promise.race([...promises, timeoutPromise]).then((result) => {
|
|
164
|
+
clearTimeout(timeoutId);
|
|
165
|
+
return result;
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
sendToAdditionalConnections(rawTx, opts) {
|
|
169
|
+
this.additionalConnections.map((connection) => {
|
|
170
|
+
connection.sendRawTransaction(rawTx, opts).catch((e) => {
|
|
171
|
+
console.error(
|
|
172
|
+
// @ts-ignore
|
|
173
|
+
`error sending tx to additional connection ${connection._rpcEndpoint}`);
|
|
174
|
+
console.error(e);
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
addAdditionalConnection(newConnection) {
|
|
179
|
+
const alreadyUsingConnection = this.additionalConnections.filter((connection) => {
|
|
180
|
+
// @ts-ignore
|
|
181
|
+
return connection._rpcEndpoint === newConnection.rpcEndpoint;
|
|
182
|
+
}).length > 0;
|
|
183
|
+
if (!alreadyUsingConnection) {
|
|
184
|
+
this.additionalConnections.push(newConnection);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
exports.RetryTxSender = RetryTxSender;
|
package/src/tx/types.js
ADDED
package/src/tx/utils.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.wrapInTx = void 0;
|
|
4
|
+
const web3_js_1 = require("@solana/web3.js");
|
|
5
|
+
const COMPUTE_UNITS_DEFAULT = 200000;
|
|
6
|
+
function wrapInTx(instruction, computeUnits = 600000 // TODO, requires less code change
|
|
7
|
+
) {
|
|
8
|
+
const tx = new web3_js_1.Transaction();
|
|
9
|
+
if (computeUnits != COMPUTE_UNITS_DEFAULT) {
|
|
10
|
+
tx.add(web3_js_1.ComputeBudgetProgram.requestUnits({
|
|
11
|
+
units: computeUnits,
|
|
12
|
+
additionalFee: 0,
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
return tx.add(instruction);
|
|
16
|
+
}
|
|
17
|
+
exports.wrapInTx = wrapInTx;
|
package/src/tx/utils.ts
CHANGED
|
@@ -8,7 +8,7 @@ const COMPUTE_UNITS_DEFAULT = 200_000;
|
|
|
8
8
|
|
|
9
9
|
export function wrapInTx(
|
|
10
10
|
instruction: TransactionInstruction,
|
|
11
|
-
computeUnits =
|
|
11
|
+
computeUnits = 600_000 // TODO, requires less code change
|
|
12
12
|
): Transaction {
|
|
13
13
|
const tx = new Transaction();
|
|
14
14
|
if (computeUnits != COMPUTE_UNITS_DEFAULT) {
|
package/src/types.js
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DefaultOrderParams = exports.TradeSide = exports.isOneOfVariant = exports.isVariant = exports.OrderTriggerCondition = exports.OrderActionExplanation = exports.OrderAction = exports.OrderDiscountTier = exports.OrderStatus = exports.OrderType = exports.OracleSource = exports.DepositDirection = exports.PositionDirection = exports.BankBalanceType = exports.SwapDirection = void 0;
|
|
4
|
+
const _1 = require(".");
|
|
5
|
+
// # Utility Types / Enums / Constants
|
|
6
|
+
class SwapDirection {
|
|
7
|
+
}
|
|
8
|
+
exports.SwapDirection = SwapDirection;
|
|
9
|
+
SwapDirection.ADD = { add: {} };
|
|
10
|
+
SwapDirection.REMOVE = { remove: {} };
|
|
11
|
+
class BankBalanceType {
|
|
12
|
+
}
|
|
13
|
+
exports.BankBalanceType = BankBalanceType;
|
|
14
|
+
BankBalanceType.DEPOSIT = { deposit: {} };
|
|
15
|
+
BankBalanceType.BORROW = { borrow: {} };
|
|
16
|
+
class PositionDirection {
|
|
17
|
+
}
|
|
18
|
+
exports.PositionDirection = PositionDirection;
|
|
19
|
+
PositionDirection.LONG = { long: {} };
|
|
20
|
+
PositionDirection.SHORT = { short: {} };
|
|
21
|
+
class DepositDirection {
|
|
22
|
+
}
|
|
23
|
+
exports.DepositDirection = DepositDirection;
|
|
24
|
+
DepositDirection.DEPOSIT = { deposit: {} };
|
|
25
|
+
DepositDirection.WITHDRAW = { withdraw: {} };
|
|
26
|
+
class OracleSource {
|
|
27
|
+
}
|
|
28
|
+
exports.OracleSource = OracleSource;
|
|
29
|
+
OracleSource.PYTH = { pyth: {} };
|
|
30
|
+
OracleSource.SWITCHBOARD = { switchboard: {} };
|
|
31
|
+
OracleSource.QUOTE_ASSET = { quoteAsset: {} };
|
|
32
|
+
class OrderType {
|
|
33
|
+
}
|
|
34
|
+
exports.OrderType = OrderType;
|
|
35
|
+
OrderType.LIMIT = { limit: {} };
|
|
36
|
+
OrderType.TRIGGER_MARKET = { triggerMarket: {} };
|
|
37
|
+
OrderType.TRIGGER_LIMIT = { triggerLimit: {} };
|
|
38
|
+
OrderType.MARKET = { market: {} };
|
|
39
|
+
class OrderStatus {
|
|
40
|
+
}
|
|
41
|
+
exports.OrderStatus = OrderStatus;
|
|
42
|
+
OrderStatus.INIT = { init: {} };
|
|
43
|
+
OrderStatus.OPEN = { open: {} };
|
|
44
|
+
class OrderDiscountTier {
|
|
45
|
+
}
|
|
46
|
+
exports.OrderDiscountTier = OrderDiscountTier;
|
|
47
|
+
OrderDiscountTier.NONE = { none: {} };
|
|
48
|
+
OrderDiscountTier.FIRST = { first: {} };
|
|
49
|
+
OrderDiscountTier.SECOND = { second: {} };
|
|
50
|
+
OrderDiscountTier.THIRD = { third: {} };
|
|
51
|
+
OrderDiscountTier.FOURTH = { fourth: {} };
|
|
52
|
+
class OrderAction {
|
|
53
|
+
}
|
|
54
|
+
exports.OrderAction = OrderAction;
|
|
55
|
+
OrderAction.PLACE = { place: {} };
|
|
56
|
+
OrderAction.CANCEL = { cancel: {} };
|
|
57
|
+
OrderAction.EXPIRE = { expire: {} };
|
|
58
|
+
OrderAction.FILL = { fill: {} };
|
|
59
|
+
OrderAction.TRIGGER = { trigger: {} };
|
|
60
|
+
class OrderActionExplanation {
|
|
61
|
+
}
|
|
62
|
+
exports.OrderActionExplanation = OrderActionExplanation;
|
|
63
|
+
OrderActionExplanation.NONE = { none: {} };
|
|
64
|
+
OrderActionExplanation.BREACHED_MARGIN_REQUIREMENT = {
|
|
65
|
+
breachedMarginRequirement: {},
|
|
66
|
+
};
|
|
67
|
+
OrderActionExplanation.ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
|
|
68
|
+
oraclePriceBreachedLimitPrice: {},
|
|
69
|
+
};
|
|
70
|
+
OrderActionExplanation.MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
|
|
71
|
+
marketOrderFilledToLimitPrice: {},
|
|
72
|
+
};
|
|
73
|
+
class OrderTriggerCondition {
|
|
74
|
+
}
|
|
75
|
+
exports.OrderTriggerCondition = OrderTriggerCondition;
|
|
76
|
+
OrderTriggerCondition.ABOVE = { above: {} };
|
|
77
|
+
OrderTriggerCondition.BELOW = { below: {} };
|
|
78
|
+
function isVariant(object, type) {
|
|
79
|
+
return object.hasOwnProperty(type);
|
|
80
|
+
}
|
|
81
|
+
exports.isVariant = isVariant;
|
|
82
|
+
function isOneOfVariant(object, types) {
|
|
83
|
+
return types.reduce((result, type) => {
|
|
84
|
+
return result || object.hasOwnProperty(type);
|
|
85
|
+
}, false);
|
|
86
|
+
}
|
|
87
|
+
exports.isOneOfVariant = isOneOfVariant;
|
|
88
|
+
var TradeSide;
|
|
89
|
+
(function (TradeSide) {
|
|
90
|
+
TradeSide[TradeSide["None"] = 0] = "None";
|
|
91
|
+
TradeSide[TradeSide["Buy"] = 1] = "Buy";
|
|
92
|
+
TradeSide[TradeSide["Sell"] = 2] = "Sell";
|
|
93
|
+
})(TradeSide = exports.TradeSide || (exports.TradeSide = {}));
|
|
94
|
+
exports.DefaultOrderParams = {
|
|
95
|
+
orderType: OrderType.MARKET,
|
|
96
|
+
userOrderId: 0,
|
|
97
|
+
direction: PositionDirection.LONG,
|
|
98
|
+
baseAssetAmount: _1.ZERO,
|
|
99
|
+
price: _1.ZERO,
|
|
100
|
+
marketIndex: _1.ZERO,
|
|
101
|
+
reduceOnly: false,
|
|
102
|
+
postOnly: false,
|
|
103
|
+
immediateOrCancel: false,
|
|
104
|
+
triggerPrice: _1.ZERO,
|
|
105
|
+
triggerCondition: OrderTriggerCondition.ABOVE,
|
|
106
|
+
positionLimit: _1.ZERO,
|
|
107
|
+
oraclePriceOffset: _1.ZERO,
|
|
108
|
+
padding0: _1.ZERO,
|
|
109
|
+
padding1: _1.ZERO,
|
|
110
|
+
optionalAccounts: {
|
|
111
|
+
discountToken: false,
|
|
112
|
+
referrer: false,
|
|
113
|
+
},
|
|
114
|
+
};
|
package/src/types.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { PublicKey, Transaction } from '@solana/web3.js';
|
|
2
|
-
import { BN } from '.';
|
|
2
|
+
import { BN, ZERO } from '.';
|
|
3
3
|
|
|
4
4
|
// # Utility Types / Enums / Constants
|
|
5
5
|
export class SwapDirection {
|
|
@@ -17,6 +17,11 @@ export class PositionDirection {
|
|
|
17
17
|
static readonly SHORT = { short: {} };
|
|
18
18
|
}
|
|
19
19
|
|
|
20
|
+
export class DepositDirection {
|
|
21
|
+
static readonly DEPOSIT = { deposit: {} };
|
|
22
|
+
static readonly WITHDRAW = { withdraw: {} };
|
|
23
|
+
}
|
|
24
|
+
|
|
20
25
|
export class OracleSource {
|
|
21
26
|
static readonly PYTH = { pyth: {} };
|
|
22
27
|
static readonly SWITCHBOARD = { switchboard: {} };
|
|
@@ -48,6 +53,20 @@ export class OrderAction {
|
|
|
48
53
|
static readonly CANCEL = { cancel: {} };
|
|
49
54
|
static readonly EXPIRE = { expire: {} };
|
|
50
55
|
static readonly FILL = { fill: {} };
|
|
56
|
+
static readonly TRIGGER = { trigger: {} };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export class OrderActionExplanation {
|
|
60
|
+
static readonly NONE = { none: {} };
|
|
61
|
+
static readonly BREACHED_MARGIN_REQUIREMENT = {
|
|
62
|
+
breachedMarginRequirement: {},
|
|
63
|
+
};
|
|
64
|
+
static readonly ORACLE_PRICE_BREACHED_LIMIT_PRICE = {
|
|
65
|
+
oraclePriceBreachedLimitPrice: {},
|
|
66
|
+
};
|
|
67
|
+
static readonly MARKET_ORDER_FILLED_TO_LIMIT_PRICE = {
|
|
68
|
+
marketOrderFilledToLimitPrice: {},
|
|
69
|
+
};
|
|
51
70
|
}
|
|
52
71
|
|
|
53
72
|
export class OrderTriggerCondition {
|
|
@@ -91,6 +110,7 @@ export type DepositRecord = {
|
|
|
91
110
|
};
|
|
92
111
|
bankIndex: BN;
|
|
93
112
|
amount: BN;
|
|
113
|
+
oraclePrice: BN;
|
|
94
114
|
from?: PublicKey;
|
|
95
115
|
to?: PublicKey;
|
|
96
116
|
};
|
|
@@ -141,20 +161,67 @@ export type FundingPaymentRecord = {
|
|
|
141
161
|
|
|
142
162
|
export type LiquidationRecord = {
|
|
143
163
|
ts: BN;
|
|
144
|
-
recordId: BN;
|
|
145
|
-
userAuthority: PublicKey;
|
|
146
164
|
user: PublicKey;
|
|
147
|
-
partial: boolean;
|
|
148
|
-
baseAssetValue: BN;
|
|
149
|
-
baseAssetValueClosed: BN;
|
|
150
|
-
liquidationFee: BN;
|
|
151
|
-
feeToLiquidator: BN;
|
|
152
|
-
feeToInsuranceFund: BN;
|
|
153
165
|
liquidator: PublicKey;
|
|
166
|
+
liquidationType: LiquidationType;
|
|
167
|
+
marginRequirement: BN;
|
|
154
168
|
totalCollateral: BN;
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
169
|
+
liquidatePerp: LiquidatePerpRecord;
|
|
170
|
+
liquidateBorrow: LiquidateBorrowRecord;
|
|
171
|
+
liquidateBorrowForPerpPnl: LiquidateBorrowForPerpPnlRecord;
|
|
172
|
+
liquidatePerpPnlForDeposit: LiquidatePerpPnlForDepositRecord;
|
|
173
|
+
};
|
|
174
|
+
|
|
175
|
+
export class LiquidationType {
|
|
176
|
+
static readonly LIQUIDATE_PERP = { liquidatePerp: {} };
|
|
177
|
+
static readonly LIQUIDATE_BORROW = { liquidateBorrow: {} };
|
|
178
|
+
static readonly LIQUIDATE_BORROW_FOR_PERP_PNL = {
|
|
179
|
+
liquidateBorrowForPerpPnl: {},
|
|
180
|
+
};
|
|
181
|
+
static readonly LIQUIDATE_PERP_PNL_FOR_DEPOSIT = {
|
|
182
|
+
liquidatePerpPnlForDeposit: {},
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export type LiquidatePerpRecord = {
|
|
187
|
+
marketIndex: BN;
|
|
188
|
+
orderIds: BN[];
|
|
189
|
+
oraclePrice: BN;
|
|
190
|
+
baseAssetAmount: BN;
|
|
191
|
+
quoteAssetAmount: BN;
|
|
192
|
+
userPnl: BN;
|
|
193
|
+
liquidatorPnl: BN;
|
|
194
|
+
canceledOrdersFee: BN;
|
|
195
|
+
userOrderId: BN;
|
|
196
|
+
liquidatorOrderId: BN;
|
|
197
|
+
fillRecordId: BN;
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
export type LiquidateBorrowRecord = {
|
|
201
|
+
assetBankIndex: BN;
|
|
202
|
+
assetPrice: BN;
|
|
203
|
+
assetTransfer: BN;
|
|
204
|
+
liabilityBankIndex: BN;
|
|
205
|
+
liabilityPrice: BN;
|
|
206
|
+
liabilityTransfer: BN;
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
export type LiquidateBorrowForPerpPnlRecord = {
|
|
210
|
+
marketIndex: BN;
|
|
211
|
+
marketOraclePrice: BN;
|
|
212
|
+
pnlTransfer: BN;
|
|
213
|
+
liabilityBankIndex: BN;
|
|
214
|
+
liabilityPrice: BN;
|
|
215
|
+
liabilityTransfer: BN;
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
export type LiquidatePerpPnlForDepositRecord = {
|
|
219
|
+
marketIndex: BN;
|
|
220
|
+
marketOraclePrice: BN;
|
|
221
|
+
pnlTransfer: BN;
|
|
222
|
+
assetBankIndex: BN;
|
|
223
|
+
assetPrice: BN;
|
|
224
|
+
assetTransfer: BN;
|
|
158
225
|
};
|
|
159
226
|
|
|
160
227
|
export type OrderRecord = {
|
|
@@ -163,7 +230,10 @@ export type OrderRecord = {
|
|
|
163
230
|
maker: PublicKey;
|
|
164
231
|
takerOrder: Order;
|
|
165
232
|
makerOrder: Order;
|
|
233
|
+
takerUnsettledPnl: BN;
|
|
234
|
+
makerUnsettledPnl: BN;
|
|
166
235
|
action: OrderAction;
|
|
236
|
+
actionExplanation: OrderActionExplanation;
|
|
167
237
|
filler: PublicKey;
|
|
168
238
|
fillRecordId: BN;
|
|
169
239
|
marketIndex: BN;
|
|
@@ -218,9 +288,9 @@ export type MarketAccount = {
|
|
|
218
288
|
openInterest: BN;
|
|
219
289
|
marginRatioInitial: number;
|
|
220
290
|
marginRatioMaintenance: number;
|
|
221
|
-
marginRatioPartial: number;
|
|
222
291
|
nextFillRecordId: BN;
|
|
223
292
|
pnlPool: PoolBalance;
|
|
293
|
+
liquidationFee: BN;
|
|
224
294
|
};
|
|
225
295
|
|
|
226
296
|
export type BankAccount = {
|
|
@@ -244,6 +314,7 @@ export type BankAccount = {
|
|
|
244
314
|
maintenanceAssetWeight: BN;
|
|
245
315
|
initialLiabilityWeight: BN;
|
|
246
316
|
maintenanceLiabilityWeight: BN;
|
|
317
|
+
liquidationFee: BN;
|
|
247
318
|
};
|
|
248
319
|
|
|
249
320
|
export type PoolBalance = {
|
|
@@ -260,6 +331,8 @@ export type AMM = {
|
|
|
260
331
|
lastMarkPriceTwapTs: BN;
|
|
261
332
|
lastOraclePriceTwap: BN;
|
|
262
333
|
lastOraclePriceTwapTs: BN;
|
|
334
|
+
lastOracleMarkSpreadPct: BN;
|
|
335
|
+
lastOracleConfPct: BN;
|
|
263
336
|
oracle: PublicKey;
|
|
264
337
|
oracleSource: OracleSource;
|
|
265
338
|
fundingPeriod: BN;
|
|
@@ -274,6 +347,8 @@ export type AMM = {
|
|
|
274
347
|
totalFee: BN;
|
|
275
348
|
minimumQuoteAssetTradeSize: BN;
|
|
276
349
|
baseAssetAmountStepSize: BN;
|
|
350
|
+
maxBaseAssetAmountRatio: number;
|
|
351
|
+
maxSlippageRatio: number;
|
|
277
352
|
lastOraclePrice: BN;
|
|
278
353
|
baseSpread: number;
|
|
279
354
|
curveUpdateIntensity: number;
|
|
@@ -290,6 +365,7 @@ export type AMM = {
|
|
|
290
365
|
lastAskPriceTwap: BN;
|
|
291
366
|
longSpread: BN;
|
|
292
367
|
shortSpread: BN;
|
|
368
|
+
maxSpread: number;
|
|
293
369
|
};
|
|
294
370
|
|
|
295
371
|
// # User Account Types
|
|
@@ -321,6 +397,7 @@ export type UserAccount = {
|
|
|
321
397
|
};
|
|
322
398
|
positions: UserPosition[];
|
|
323
399
|
orders: Order[];
|
|
400
|
+
beingLiquidated: boolean;
|
|
324
401
|
};
|
|
325
402
|
|
|
326
403
|
export type UserBankBalance = {
|
|
@@ -347,8 +424,9 @@ export type Order = {
|
|
|
347
424
|
reduceOnly: boolean;
|
|
348
425
|
triggerPrice: BN;
|
|
349
426
|
triggerCondition: OrderTriggerCondition;
|
|
427
|
+
triggered: boolean;
|
|
350
428
|
discountTier: OrderDiscountTier;
|
|
351
|
-
existingPositionDirection: PositionDirection
|
|
429
|
+
existingPositionDirection: PositionDirection;
|
|
352
430
|
referrer: PublicKey;
|
|
353
431
|
postOnly: boolean;
|
|
354
432
|
immediateOrCancel: boolean;
|
|
@@ -362,7 +440,6 @@ export type OrderParams = {
|
|
|
362
440
|
orderType: OrderType;
|
|
363
441
|
userOrderId: number;
|
|
364
442
|
direction: PositionDirection;
|
|
365
|
-
quoteAssetAmount: BN;
|
|
366
443
|
baseAssetAmount: BN;
|
|
367
444
|
price: BN;
|
|
368
445
|
marketIndex: BN;
|
|
@@ -381,11 +458,49 @@ export type OrderParams = {
|
|
|
381
458
|
};
|
|
382
459
|
};
|
|
383
460
|
|
|
461
|
+
export type NecessaryOrderParams = {
|
|
462
|
+
orderType: OrderType;
|
|
463
|
+
marketIndex: BN;
|
|
464
|
+
baseAssetAmount: BN;
|
|
465
|
+
direction: PositionDirection;
|
|
466
|
+
};
|
|
467
|
+
|
|
468
|
+
export type OptionalOrderParams = {
|
|
469
|
+
[Property in keyof OrderParams]?: OrderParams[Property];
|
|
470
|
+
} & NecessaryOrderParams;
|
|
471
|
+
|
|
472
|
+
export const DefaultOrderParams = {
|
|
473
|
+
orderType: OrderType.MARKET,
|
|
474
|
+
userOrderId: 0,
|
|
475
|
+
direction: PositionDirection.LONG,
|
|
476
|
+
baseAssetAmount: ZERO,
|
|
477
|
+
price: ZERO,
|
|
478
|
+
marketIndex: ZERO,
|
|
479
|
+
reduceOnly: false,
|
|
480
|
+
postOnly: false,
|
|
481
|
+
immediateOrCancel: false,
|
|
482
|
+
triggerPrice: ZERO,
|
|
483
|
+
triggerCondition: OrderTriggerCondition.ABOVE,
|
|
484
|
+
positionLimit: ZERO,
|
|
485
|
+
oraclePriceOffset: ZERO,
|
|
486
|
+
padding0: ZERO,
|
|
487
|
+
padding1: ZERO,
|
|
488
|
+
optionalAccounts: {
|
|
489
|
+
discountToken: false,
|
|
490
|
+
referrer: false,
|
|
491
|
+
},
|
|
492
|
+
};
|
|
493
|
+
|
|
384
494
|
export type MakerInfo = {
|
|
385
495
|
maker: PublicKey;
|
|
386
496
|
order: Order;
|
|
387
497
|
};
|
|
388
498
|
|
|
499
|
+
export type TakerInfo = {
|
|
500
|
+
taker: PublicKey;
|
|
501
|
+
order: Order;
|
|
502
|
+
};
|
|
503
|
+
|
|
389
504
|
// # Misc Types
|
|
390
505
|
export interface IWallet {
|
|
391
506
|
signTransaction(tx: Transaction): Promise<Transaction>;
|
|
@@ -427,6 +542,7 @@ export type FeeStructure = {
|
|
|
427
542
|
makerRebateNumerator: BN;
|
|
428
543
|
makerRebateDenominator: BN;
|
|
429
544
|
fillerRewardStructure: OrderFillerRewardStructure;
|
|
545
|
+
cancelOrderFee: BN;
|
|
430
546
|
};
|
|
431
547
|
|
|
432
548
|
export type OracleGuardRails = {
|
|
@@ -448,4 +564,4 @@ export type OrderFillerRewardStructure = {
|
|
|
448
564
|
timeBasedRewardLowerBound: BN;
|
|
449
565
|
};
|
|
450
566
|
|
|
451
|
-
export type MarginCategory = 'Initial' | '
|
|
567
|
+
export type MarginCategory = 'Initial' | 'Maintenance';
|
package/src/userName.js
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.decodeName = exports.encodeName = exports.DEFAULT_USER_NAME = exports.MAX_NAME_LENGTH = void 0;
|
|
4
|
+
exports.MAX_NAME_LENGTH = 32;
|
|
5
|
+
exports.DEFAULT_USER_NAME = 'Main Account';
|
|
6
|
+
function encodeName(name) {
|
|
7
|
+
if (name.length > exports.MAX_NAME_LENGTH) {
|
|
8
|
+
throw Error(`User name (${name}) longer than 32 characters`);
|
|
9
|
+
}
|
|
10
|
+
const buffer = Buffer.alloc(32);
|
|
11
|
+
buffer.fill(name);
|
|
12
|
+
buffer.fill(' ', name.length);
|
|
13
|
+
return Array(...buffer);
|
|
14
|
+
}
|
|
15
|
+
exports.encodeName = encodeName;
|
|
16
|
+
function decodeName(bytes) {
|
|
17
|
+
const buffer = Buffer.from(bytes);
|
|
18
|
+
return buffer.toString('utf8').trim();
|
|
19
|
+
}
|
|
20
|
+
exports.decodeName = decodeName;
|
package/src/util/computeUnits.ts
CHANGED
|
@@ -9,7 +9,7 @@ export async function findComputeUnitConsumption(
|
|
|
9
9
|
const tx = await connection.getTransaction(txSignature, { commitment });
|
|
10
10
|
const computeUnits = [];
|
|
11
11
|
const regex = new RegExp(
|
|
12
|
-
`Program ${programId.toString()} consumed ([0-9]{0,6}) of
|
|
12
|
+
`Program ${programId.toString()} consumed ([0-9]{0,6}) of ([0-9]{0,7}) compute units`
|
|
13
13
|
);
|
|
14
14
|
tx.meta.logMessages.forEach((logMessage) => {
|
|
15
15
|
const match = logMessage.match(regex);
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.promiseTimeout = void 0;
|
|
4
|
+
function promiseTimeout(promise, timeoutMs) {
|
|
5
|
+
let timeoutId;
|
|
6
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
7
|
+
timeoutId = setTimeout(() => resolve(null), timeoutMs);
|
|
8
|
+
});
|
|
9
|
+
return Promise.race([promise, timeoutPromise]).then((result) => {
|
|
10
|
+
clearTimeout(timeoutId);
|
|
11
|
+
return result;
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
exports.promiseTimeout = promiseTimeout;
|
package/src/util/tps.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
+
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
+
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
+
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
+
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
12
|
+
exports.estimateTps = void 0;
|
|
13
|
+
function estimateTps(programId, connection, failed) {
|
|
14
|
+
return __awaiter(this, void 0, void 0, function* () {
|
|
15
|
+
let signatures = yield connection.getSignaturesForAddress(programId, undefined, 'finalized');
|
|
16
|
+
if (failed) {
|
|
17
|
+
signatures = signatures.filter((signature) => signature.err);
|
|
18
|
+
}
|
|
19
|
+
const numberOfSignatures = signatures.length;
|
|
20
|
+
if (numberOfSignatures === 0) {
|
|
21
|
+
return 0;
|
|
22
|
+
}
|
|
23
|
+
return (numberOfSignatures /
|
|
24
|
+
(signatures[0].blockTime - signatures[numberOfSignatures - 1].blockTime));
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
exports.estimateTps = estimateTps;
|