@drift-labs/sdk 0.2.0-master.7 → 0.2.0-master.8

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.
Files changed (65) hide show
  1. package/lib/clearingHouse.js +38 -25
  2. package/lib/constants/banks.js +9 -1
  3. package/package.json +1 -1
  4. package/src/accounts/bulkAccountLoader.js +197 -0
  5. package/src/accounts/bulkUserSubscription.js +33 -0
  6. package/src/accounts/fetch.js +29 -0
  7. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  8. package/src/accounts/pollingOracleSubscriber.js +93 -0
  9. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  10. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  11. package/src/accounts/types.js +10 -0
  12. package/src/accounts/utils.js +7 -0
  13. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  14. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  15. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  16. package/src/addresses/marketAddresses.js +26 -0
  17. package/src/addresses/pda.js +104 -0
  18. package/src/assert/assert.js +9 -0
  19. package/src/clearingHouse.ts +43 -27
  20. package/src/constants/banks.ts +9 -1
  21. package/src/events/eventList.js +77 -0
  22. package/src/events/eventSubscriber.js +139 -0
  23. package/src/events/fetchLogs.js +50 -0
  24. package/src/events/pollingLogProvider.js +64 -0
  25. package/src/events/sort.js +44 -0
  26. package/src/events/txEventCache.js +71 -0
  27. package/src/events/types.js +20 -0
  28. package/src/events/webSocketLogProvider.js +41 -0
  29. package/src/examples/makeTradeExample.js +80 -0
  30. package/src/factory/bigNum.js +364 -0
  31. package/src/factory/oracleClient.js +20 -0
  32. package/src/index.js +69 -0
  33. package/src/math/amm.js +369 -0
  34. package/src/math/auction.js +42 -0
  35. package/src/math/bankBalance.js +75 -0
  36. package/src/math/conversion.js +11 -0
  37. package/src/math/funding.js +248 -0
  38. package/src/math/market.js +57 -0
  39. package/src/math/oracles.js +26 -0
  40. package/src/math/orders.js +110 -0
  41. package/src/math/position.js +140 -0
  42. package/src/math/repeg.js +128 -0
  43. package/src/math/state.js +15 -0
  44. package/src/math/trade.js +253 -0
  45. package/src/math/utils.js +0 -1
  46. package/src/mockUSDCFaucet.js +171 -0
  47. package/src/oracles/oracleClientCache.js +19 -0
  48. package/src/oracles/pythClient.js +46 -0
  49. package/src/oracles/quoteAssetOracleClient.js +32 -0
  50. package/src/oracles/switchboardClient.js +69 -0
  51. package/src/oracles/types.js +2 -0
  52. package/src/orderParams.js +20 -0
  53. package/src/orders.js +134 -0
  54. package/src/slot/SlotSubscriber.js +39 -0
  55. package/src/token/index.js +38 -0
  56. package/src/tx/retryTxSender.js +188 -0
  57. package/src/tx/types.js +2 -0
  58. package/src/tx/utils.js +17 -0
  59. package/src/types.js +114 -0
  60. package/src/userName.js +20 -0
  61. package/src/util/promiseTimeout.js +14 -0
  62. package/src/util/tps.js +27 -0
  63. package/src/wallet.js +35 -0
  64. package/src/util/computeUnits.js +0 -17
  65. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,69 @@
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.SwitchboardClient = void 0;
16
+ const web3_js_1 = require("@solana/web3.js");
17
+ const anchor_1 = require("@project-serum/anchor");
18
+ const numericConstants_1 = require("../constants/numericConstants");
19
+ const wallet_1 = require("../wallet");
20
+ const switchboard_v2_json_1 = __importDefault(require("../idl/switchboard_v2.json"));
21
+ let program;
22
+ class SwitchboardClient {
23
+ constructor(connection) {
24
+ this.connection = connection;
25
+ }
26
+ getOraclePriceData(pricePublicKey) {
27
+ return __awaiter(this, void 0, void 0, function* () {
28
+ const accountInfo = yield this.connection.getAccountInfo(pricePublicKey);
29
+ return this.getOraclePriceDataFromBuffer(accountInfo.data);
30
+ });
31
+ }
32
+ getOraclePriceDataFromBuffer(buffer) {
33
+ const program = this.getProgram();
34
+ const aggregatorAccountData = program.account.aggregatorAccountData.coder.accounts.decode('AggregatorAccountData', buffer);
35
+ const price = convertSwitchboardDecimal(aggregatorAccountData.latestConfirmedRound.result);
36
+ const confidence = convertSwitchboardDecimal(aggregatorAccountData.latestConfirmedRound
37
+ .stdDeviation);
38
+ const hasSufficientNumberOfDataPoints = aggregatorAccountData.latestConfirmedRound.numSuccess >=
39
+ aggregatorAccountData.minOracleResults;
40
+ const slot = aggregatorAccountData.latestConfirmedRound.roundOpenSlot;
41
+ return {
42
+ price,
43
+ slot,
44
+ confidence,
45
+ hasSufficientNumberOfDataPoints,
46
+ };
47
+ }
48
+ getProgram() {
49
+ if (program) {
50
+ return program;
51
+ }
52
+ program = getSwitchboardProgram(this.connection);
53
+ return program;
54
+ }
55
+ }
56
+ exports.SwitchboardClient = SwitchboardClient;
57
+ function getSwitchboardProgram(connection) {
58
+ const DEFAULT_KEYPAIR = web3_js_1.Keypair.fromSeed(new Uint8Array(32).fill(1));
59
+ const programId = web3_js_1.PublicKey.default;
60
+ const wallet = new wallet_1.Wallet(DEFAULT_KEYPAIR);
61
+ const provider = new anchor_1.AnchorProvider(connection, wallet, {});
62
+ return new anchor_1.Program(switchboard_v2_json_1.default, programId, provider);
63
+ }
64
+ function convertSwitchboardDecimal(switchboardDecimal) {
65
+ const switchboardPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(switchboardDecimal.scale));
66
+ return switchboardDecimal.mantissa
67
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
68
+ .div(switchboardPrecision);
69
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getMarketOrderParams = exports.getTriggerLimitOrderParams = exports.getTriggerMarketOrderParams = exports.getLimitOrderParams = void 0;
4
+ const types_1 = require("./types");
5
+ function getLimitOrderParams(params) {
6
+ return Object.assign({}, params, { orderType: types_1.OrderType.LIMIT });
7
+ }
8
+ exports.getLimitOrderParams = getLimitOrderParams;
9
+ function getTriggerMarketOrderParams(params) {
10
+ return Object.assign({}, params, { orderType: types_1.OrderType.TRIGGER_MARKET });
11
+ }
12
+ exports.getTriggerMarketOrderParams = getTriggerMarketOrderParams;
13
+ function getTriggerLimitOrderParams(params) {
14
+ return Object.assign({}, params, { orderType: types_1.OrderType.TRIGGER_LIMIT });
15
+ }
16
+ exports.getTriggerLimitOrderParams = getTriggerLimitOrderParams;
17
+ function getMarketOrderParams(params) {
18
+ return Object.assign({}, params, { orderType: types_1.OrderType.MARKET });
19
+ }
20
+ exports.getMarketOrderParams = getMarketOrderParams;
package/src/orders.js ADDED
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.calculateAmountToTradeForTriggerLimit = exports.calculateAmountToTradeForLimit = exports.calculateBaseAssetAmountMarketCanExecute = exports.calculateNewStateAfterOrder = void 0;
4
+ const types_1 = require("./types");
5
+ const _1 = require(".");
6
+ const market_1 = require("./math/market");
7
+ const numericConstants_1 = require("./constants/numericConstants");
8
+ const amm_1 = require("./math/amm");
9
+ const position_1 = require("./math/position");
10
+ function calculateNewStateAfterOrder(userAccount, userPosition, market, order) {
11
+ if (types_1.isVariant(order.status, 'init')) {
12
+ return null;
13
+ }
14
+ const baseAssetAmountToTrade = calculateBaseAssetAmountMarketCanExecute(market, order);
15
+ if (baseAssetAmountToTrade.lt(market.amm.baseAssetAmountStepSize)) {
16
+ return null;
17
+ }
18
+ const userAccountAfter = Object.assign({}, userAccount);
19
+ const userPositionAfter = Object.assign({}, userPosition);
20
+ const currentPositionDirection = position_1.positionCurrentDirection(userPosition);
21
+ const increasePosition = userPosition.baseAssetAmount.eq(numericConstants_1.ZERO) ||
22
+ isSameDirection(order.direction, currentPositionDirection);
23
+ if (increasePosition) {
24
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountToTrade, order.direction, market);
25
+ const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(market, marketAfter);
26
+ userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
27
+ userPositionAfter.quoteAssetAmount = userPositionAfter.quoteAssetAmount.add(quoteAssetAmountSwapped);
28
+ return [userAccountAfter, userPositionAfter, marketAfter];
29
+ }
30
+ else {
31
+ const reversePosition = baseAssetAmountToTrade.gt(userPosition.baseAssetAmount.abs());
32
+ if (reversePosition) {
33
+ const intermediateMarket = market_1.calculateNewMarketAfterTrade(userPosition.baseAssetAmount, position_1.findDirectionToClose(userPosition), market);
34
+ const { quoteAssetAmountSwapped: baseAssetValue } = calculateAmountSwapped(market, intermediateMarket);
35
+ let pnl;
36
+ if (types_1.isVariant(currentPositionDirection, 'long')) {
37
+ pnl = baseAssetValue.sub(userPosition.quoteAssetAmount);
38
+ }
39
+ else {
40
+ pnl = userPosition.quoteAssetAmount.sub(baseAssetValue);
41
+ }
42
+ userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
43
+ const baseAssetAmountLeft = baseAssetAmountToTrade.sub(userPosition.baseAssetAmount.abs());
44
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountLeft, order.direction, intermediateMarket);
45
+ const { quoteAssetAmountSwapped, baseAssetAmountSwapped } = calculateAmountSwapped(intermediateMarket, marketAfter);
46
+ userPositionAfter.quoteAssetAmount = quoteAssetAmountSwapped;
47
+ userPositionAfter.baseAssetAmount = baseAssetAmountSwapped;
48
+ return [userAccountAfter, userPositionAfter, marketAfter];
49
+ }
50
+ else {
51
+ const marketAfter = market_1.calculateNewMarketAfterTrade(baseAssetAmountToTrade, order.direction, market);
52
+ const { quoteAssetAmountSwapped: baseAssetValue, baseAssetAmountSwapped, } = calculateAmountSwapped(market, marketAfter);
53
+ const costBasisRealized = userPosition.quoteAssetAmount
54
+ .mul(baseAssetAmountSwapped.abs())
55
+ .div(userPosition.baseAssetAmount.abs());
56
+ let pnl;
57
+ if (types_1.isVariant(currentPositionDirection, 'long')) {
58
+ pnl = baseAssetValue.sub(costBasisRealized);
59
+ }
60
+ else {
61
+ pnl = costBasisRealized.sub(baseAssetValue);
62
+ }
63
+ userAccountAfter.collateral = userAccountAfter.collateral.add(pnl);
64
+ userPositionAfter.baseAssetAmount = userPositionAfter.baseAssetAmount.add(baseAssetAmountSwapped);
65
+ userPositionAfter.quoteAssetAmount =
66
+ userPositionAfter.quoteAssetAmount.sub(costBasisRealized);
67
+ return [userAccountAfter, userPositionAfter, marketAfter];
68
+ }
69
+ }
70
+ }
71
+ exports.calculateNewStateAfterOrder = calculateNewStateAfterOrder;
72
+ function calculateAmountSwapped(marketBefore, marketAfter) {
73
+ return {
74
+ quoteAssetAmountSwapped: marketBefore.amm.quoteAssetReserve
75
+ .sub(marketAfter.amm.quoteAssetReserve)
76
+ .abs()
77
+ .mul(marketBefore.amm.pegMultiplier)
78
+ .div(numericConstants_1.PEG_PRECISION)
79
+ .div(numericConstants_1.AMM_TO_QUOTE_PRECISION_RATIO),
80
+ baseAssetAmountSwapped: marketBefore.amm.baseAssetReserve.sub(marketAfter.amm.baseAssetReserve),
81
+ };
82
+ }
83
+ function calculateBaseAssetAmountMarketCanExecute(market, order, oraclePriceData) {
84
+ if (types_1.isVariant(order.orderType, 'limit')) {
85
+ return calculateAmountToTradeForLimit(market, order, oraclePriceData);
86
+ }
87
+ else if (types_1.isVariant(order.orderType, 'triggerLimit')) {
88
+ return calculateAmountToTradeForTriggerLimit(market, order);
89
+ }
90
+ else if (types_1.isVariant(order.orderType, 'market')) {
91
+ return numericConstants_1.ZERO;
92
+ }
93
+ else {
94
+ return calculateAmountToTradeForTriggerMarket(market, order);
95
+ }
96
+ }
97
+ exports.calculateBaseAssetAmountMarketCanExecute = calculateBaseAssetAmountMarketCanExecute;
98
+ function calculateAmountToTradeForLimit(market, order, oraclePriceData) {
99
+ let limitPrice = order.price;
100
+ if (!order.oraclePriceOffset.eq(numericConstants_1.ZERO)) {
101
+ if (!oraclePriceData) {
102
+ throw Error('Cant calculate limit price for oracle offset oracle without OraclePriceData');
103
+ }
104
+ limitPrice = oraclePriceData.price.add(order.oraclePriceOffset);
105
+ }
106
+ const [maxAmountToTrade, direction] = amm_1.calculateMaxBaseAssetAmountToTrade(market.amm, limitPrice, order.direction);
107
+ const baseAssetAmount = _1.standardizeBaseAssetAmount(maxAmountToTrade, market.amm.baseAssetAmountStepSize);
108
+ // Check that directions are the same
109
+ const sameDirection = isSameDirection(direction, order.direction);
110
+ if (!sameDirection) {
111
+ return numericConstants_1.ZERO;
112
+ }
113
+ return baseAssetAmount.gt(order.baseAssetAmount)
114
+ ? order.baseAssetAmount
115
+ : baseAssetAmount;
116
+ }
117
+ exports.calculateAmountToTradeForLimit = calculateAmountToTradeForLimit;
118
+ function calculateAmountToTradeForTriggerLimit(market, order) {
119
+ if (!order.triggered) {
120
+ return numericConstants_1.ZERO;
121
+ }
122
+ return calculateAmountToTradeForLimit(market, order);
123
+ }
124
+ exports.calculateAmountToTradeForTriggerLimit = calculateAmountToTradeForTriggerLimit;
125
+ function isSameDirection(firstDirection, secondDirection) {
126
+ return ((types_1.isVariant(firstDirection, 'long') && types_1.isVariant(secondDirection, 'long')) ||
127
+ (types_1.isVariant(firstDirection, 'short') && types_1.isVariant(secondDirection, 'short')));
128
+ }
129
+ function calculateAmountToTradeForTriggerMarket(market, order) {
130
+ if (!order.triggered) {
131
+ return numericConstants_1.ZERO;
132
+ }
133
+ return order.baseAssetAmount;
134
+ }
@@ -0,0 +1,39 @@
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.SlotSubscriber = void 0;
13
+ const events_1 = require("events");
14
+ class SlotSubscriber {
15
+ constructor(connection, _config) {
16
+ this.connection = connection;
17
+ this.eventEmitter = new events_1.EventEmitter();
18
+ }
19
+ subscribe() {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ this.currentSlot = yield this.connection.getSlot('confirmed');
22
+ this.subscriptionId = this.connection.onSlotChange((slotInfo) => {
23
+ this.currentSlot = slotInfo.slot;
24
+ this.eventEmitter.emit('newSlot', slotInfo.slot);
25
+ });
26
+ });
27
+ }
28
+ getSlot() {
29
+ return this.currentSlot;
30
+ }
31
+ unsubscribe() {
32
+ return __awaiter(this, void 0, void 0, function* () {
33
+ if (this.subscriptionId) {
34
+ yield this.connection.removeSlotChangeListener(this.subscriptionId);
35
+ }
36
+ });
37
+ }
38
+ }
39
+ exports.SlotSubscriber = SlotSubscriber;
@@ -0,0 +1,38 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseTokenAccount = void 0;
4
+ const spl_token_1 = require("@solana/spl-token");
5
+ const web3_js_1 = require("@solana/web3.js");
6
+ function parseTokenAccount(data) {
7
+ const accountInfo = spl_token_1.AccountLayout.decode(data);
8
+ accountInfo.mint = new web3_js_1.PublicKey(accountInfo.mint);
9
+ accountInfo.owner = new web3_js_1.PublicKey(accountInfo.owner);
10
+ accountInfo.amount = spl_token_1.u64.fromBuffer(accountInfo.amount);
11
+ if (accountInfo.delegateOption === 0) {
12
+ accountInfo.delegate = null;
13
+ // eslint-disable-next-line new-cap
14
+ accountInfo.delegatedAmount = new spl_token_1.u64(0);
15
+ }
16
+ else {
17
+ accountInfo.delegate = new web3_js_1.PublicKey(accountInfo.delegate);
18
+ accountInfo.delegatedAmount = spl_token_1.u64.fromBuffer(accountInfo.delegatedAmount);
19
+ }
20
+ accountInfo.isInitialized = accountInfo.state !== 0;
21
+ accountInfo.isFrozen = accountInfo.state === 2;
22
+ if (accountInfo.isNativeOption === 1) {
23
+ accountInfo.rentExemptReserve = spl_token_1.u64.fromBuffer(accountInfo.isNative);
24
+ accountInfo.isNative = true;
25
+ }
26
+ else {
27
+ accountInfo.rentExemptReserve = null;
28
+ accountInfo.isNative = false;
29
+ }
30
+ if (accountInfo.closeAuthorityOption === 0) {
31
+ accountInfo.closeAuthority = null;
32
+ }
33
+ else {
34
+ accountInfo.closeAuthority = new web3_js_1.PublicKey(accountInfo.closeAuthority);
35
+ }
36
+ return accountInfo;
37
+ }
38
+ exports.parseTokenAccount = parseTokenAccount;
@@ -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;
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -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/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
+ };
@@ -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;
@@ -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;