@drift-labs/sdk 0.2.0-master.1 → 0.2.0-master.10

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 (112) hide show
  1. package/lib/accounts/types.d.ts +1 -0
  2. package/lib/admin.d.ts +6 -3
  3. package/lib/admin.js +39 -7
  4. package/lib/clearingHouse.d.ts +13 -14
  5. package/lib/clearingHouse.js +166 -106
  6. package/lib/config.js +1 -1
  7. package/lib/constants/banks.js +8 -1
  8. package/lib/constants/numericConstants.d.ts +1 -0
  9. package/lib/constants/numericConstants.js +2 -1
  10. package/lib/factory/bigNum.d.ts +8 -2
  11. package/lib/factory/bigNum.js +14 -6
  12. package/lib/idl/clearing_house.json +277 -55
  13. package/lib/index.d.ts +2 -1
  14. package/lib/index.js +6 -1
  15. package/lib/math/amm.d.ts +6 -1
  16. package/lib/math/amm.js +124 -41
  17. package/lib/math/auction.js +4 -1
  18. package/lib/math/orders.d.ts +2 -2
  19. package/lib/math/orders.js +18 -11
  20. package/lib/math/position.js +3 -1
  21. package/lib/math/repeg.js +1 -1
  22. package/lib/math/trade.d.ts +1 -1
  23. package/lib/math/trade.js +7 -10
  24. package/lib/orderParams.d.ts +14 -5
  25. package/lib/orderParams.js +8 -96
  26. package/lib/orders.d.ts +1 -2
  27. package/lib/orders.js +6 -85
  28. package/lib/slot/SlotSubscriber.d.ts +7 -0
  29. package/lib/slot/SlotSubscriber.js +3 -0
  30. package/lib/tx/utils.js +1 -1
  31. package/lib/types.d.ts +75 -1
  32. package/lib/types.js +42 -1
  33. package/package.json +3 -3
  34. package/src/accounts/bulkAccountLoader.js +197 -0
  35. package/src/accounts/bulkUserSubscription.js +33 -0
  36. package/src/accounts/fetch.js +29 -0
  37. package/src/accounts/pollingClearingHouseAccountSubscriber.js +311 -0
  38. package/src/accounts/pollingOracleSubscriber.js +93 -0
  39. package/src/accounts/pollingTokenAccountSubscriber.js +90 -0
  40. package/src/accounts/pollingUserAccountSubscriber.js +132 -0
  41. package/src/accounts/types.js +10 -0
  42. package/src/accounts/utils.js +7 -0
  43. package/src/accounts/webSocketAccountSubscriber.js +93 -0
  44. package/src/accounts/webSocketClearingHouseAccountSubscriber.js +233 -0
  45. package/src/accounts/webSocketUserAccountSubscriber.js +62 -0
  46. package/src/addresses/marketAddresses.js +26 -0
  47. package/src/addresses/pda.js +104 -0
  48. package/src/admin.ts +60 -8
  49. package/src/assert/assert.js +9 -0
  50. package/src/clearingHouse.ts +223 -183
  51. package/src/config.ts +1 -1
  52. package/src/constants/banks.ts +8 -1
  53. package/src/constants/numericConstants.ts +1 -0
  54. package/src/events/eventList.js +77 -0
  55. package/src/events/eventSubscriber.js +139 -0
  56. package/src/events/fetchLogs.js +50 -0
  57. package/src/events/pollingLogProvider.js +64 -0
  58. package/src/events/sort.js +44 -0
  59. package/src/events/txEventCache.js +71 -0
  60. package/src/events/types.js +20 -0
  61. package/src/events/webSocketLogProvider.js +41 -0
  62. package/src/examples/makeTradeExample.js +80 -0
  63. package/src/factory/bigNum.js +364 -0
  64. package/src/factory/bigNum.ts +26 -9
  65. package/src/factory/oracleClient.js +20 -0
  66. package/src/idl/clearing_house.json +277 -55
  67. package/src/index.js +69 -0
  68. package/src/index.ts +2 -1
  69. package/src/math/amm.js +369 -0
  70. package/src/math/amm.ts +207 -52
  71. package/src/math/auction.js +42 -0
  72. package/src/math/auction.ts +5 -1
  73. package/src/math/bankBalance.js +75 -0
  74. package/src/math/conversion.js +11 -0
  75. package/src/math/funding.js +248 -0
  76. package/src/math/market.js +57 -0
  77. package/src/math/oracles.js +26 -0
  78. package/src/math/orders.js +110 -0
  79. package/src/math/orders.ts +17 -13
  80. package/src/math/position.js +140 -0
  81. package/src/math/position.ts +5 -1
  82. package/src/math/repeg.js +128 -0
  83. package/src/math/repeg.ts +2 -1
  84. package/src/math/state.js +15 -0
  85. package/src/math/trade.js +253 -0
  86. package/src/math/trade.ts +23 -25
  87. package/src/math/utils.js +0 -1
  88. package/src/mockUSDCFaucet.js +171 -0
  89. package/src/oracles/oracleClientCache.js +19 -0
  90. package/src/oracles/pythClient.js +46 -0
  91. package/src/oracles/quoteAssetOracleClient.js +32 -0
  92. package/src/oracles/switchboardClient.js +69 -0
  93. package/src/oracles/types.js +2 -0
  94. package/src/orderParams.js +20 -0
  95. package/src/orderParams.ts +20 -141
  96. package/src/orders.js +134 -0
  97. package/src/orders.ts +7 -131
  98. package/src/slot/SlotSubscriber.js +39 -0
  99. package/src/slot/SlotSubscriber.ts +11 -1
  100. package/src/token/index.js +38 -0
  101. package/src/tx/retryTxSender.js +188 -0
  102. package/src/tx/types.js +2 -0
  103. package/src/tx/utils.js +17 -0
  104. package/src/tx/utils.ts +1 -1
  105. package/src/types.js +114 -0
  106. package/src/types.ts +69 -3
  107. package/src/userName.js +20 -0
  108. package/src/util/promiseTimeout.js +14 -0
  109. package/src/util/tps.js +27 -0
  110. package/src/wallet.js +35 -0
  111. package/src/util/computeUnits.js +0 -17
  112. package/src/util/computeUnits.js.map +0 -1
@@ -0,0 +1,171 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
10
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
11
+ }) : function(o, v) {
12
+ o["default"] = v;
13
+ });
14
+ var __importStar = (this && this.__importStar) || function (mod) {
15
+ if (mod && mod.__esModule) return mod;
16
+ var result = {};
17
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
18
+ __setModuleDefault(result, mod);
19
+ return result;
20
+ };
21
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
22
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
23
+ return new (P || (P = Promise))(function (resolve, reject) {
24
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
25
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
26
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
27
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
28
+ });
29
+ };
30
+ var __importDefault = (this && this.__importDefault) || function (mod) {
31
+ return (mod && mod.__esModule) ? mod : { "default": mod };
32
+ };
33
+ Object.defineProperty(exports, "__esModule", { value: true });
34
+ exports.MockUSDCFaucet = void 0;
35
+ const anchor = __importStar(require("@project-serum/anchor"));
36
+ const anchor_1 = require("@project-serum/anchor");
37
+ const spl_token_1 = require("@solana/spl-token");
38
+ const web3_js_1 = require("@solana/web3.js");
39
+ const mock_usdc_faucet_json_1 = __importDefault(require("./idl/mock_usdc_faucet.json"));
40
+ class MockUSDCFaucet {
41
+ constructor(connection, wallet, programId, opts) {
42
+ this.connection = connection;
43
+ this.wallet = wallet;
44
+ this.opts = opts || anchor_1.AnchorProvider.defaultOptions();
45
+ const provider = new anchor_1.AnchorProvider(connection, wallet, this.opts);
46
+ this.provider = provider;
47
+ this.program = new anchor_1.Program(mock_usdc_faucet_json_1.default, programId, provider);
48
+ }
49
+ getMockUSDCFaucetStatePublicKeyAndNonce() {
50
+ return __awaiter(this, void 0, void 0, function* () {
51
+ return anchor.web3.PublicKey.findProgramAddress([Buffer.from(anchor.utils.bytes.utf8.encode('mock_usdc_faucet'))], this.program.programId);
52
+ });
53
+ }
54
+ getMockUSDCFaucetStatePublicKey() {
55
+ return __awaiter(this, void 0, void 0, function* () {
56
+ if (this.mockUSDCFaucetStatePublicKey) {
57
+ return this.mockUSDCFaucetStatePublicKey;
58
+ }
59
+ this.mockUSDCFaucetStatePublicKey = (yield this.getMockUSDCFaucetStatePublicKeyAndNonce())[0];
60
+ return this.mockUSDCFaucetStatePublicKey;
61
+ });
62
+ }
63
+ initialize() {
64
+ return __awaiter(this, void 0, void 0, function* () {
65
+ const stateAccountRPCResponse = yield this.connection.getParsedAccountInfo(yield this.getMockUSDCFaucetStatePublicKey());
66
+ if (stateAccountRPCResponse.value !== null) {
67
+ throw new Error('Faucet already initialized');
68
+ }
69
+ const fakeUSDCMint = anchor.web3.Keypair.generate();
70
+ const createUSDCMintAccountIx = web3_js_1.SystemProgram.createAccount({
71
+ fromPubkey: this.wallet.publicKey,
72
+ newAccountPubkey: fakeUSDCMint.publicKey,
73
+ lamports: yield spl_token_1.Token.getMinBalanceRentForExemptMint(this.connection),
74
+ space: spl_token_1.MintLayout.span,
75
+ programId: spl_token_1.TOKEN_PROGRAM_ID,
76
+ });
77
+ const [mintAuthority, _mintAuthorityNonce] = yield web3_js_1.PublicKey.findProgramAddress([fakeUSDCMint.publicKey.toBuffer()], this.program.programId);
78
+ const initUSDCMintIx = spl_token_1.Token.createInitMintInstruction(spl_token_1.TOKEN_PROGRAM_ID, fakeUSDCMint.publicKey, 6, mintAuthority, null);
79
+ const [mockUSDCFaucetStatePublicKey, mockUSDCFaucetStateNonce] = yield this.getMockUSDCFaucetStatePublicKeyAndNonce();
80
+ return yield this.program.rpc.initialize(mockUSDCFaucetStateNonce, {
81
+ accounts: {
82
+ mockUsdcFaucetState: mockUSDCFaucetStatePublicKey,
83
+ admin: this.wallet.publicKey,
84
+ mintAccount: fakeUSDCMint.publicKey,
85
+ rent: web3_js_1.SYSVAR_RENT_PUBKEY,
86
+ systemProgram: anchor.web3.SystemProgram.programId,
87
+ },
88
+ instructions: [createUSDCMintAccountIx, initUSDCMintIx],
89
+ signers: [fakeUSDCMint],
90
+ });
91
+ });
92
+ }
93
+ fetchState() {
94
+ return __awaiter(this, void 0, void 0, function* () {
95
+ return yield this.program.account.mockUsdcFaucetState.fetch(yield this.getMockUSDCFaucetStatePublicKey());
96
+ });
97
+ }
98
+ mintToUser(userTokenAccount, amount) {
99
+ return __awaiter(this, void 0, void 0, function* () {
100
+ const state = yield this.fetchState();
101
+ return yield this.program.rpc.mintToUser(amount, {
102
+ accounts: {
103
+ mockUsdcFaucetState: yield this.getMockUSDCFaucetStatePublicKey(),
104
+ mintAccount: state.mint,
105
+ userTokenAccount,
106
+ mintAuthority: state.mintAuthority,
107
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
108
+ },
109
+ });
110
+ });
111
+ }
112
+ createAssociatedTokenAccountAndMintTo(userPublicKey, amount) {
113
+ return __awaiter(this, void 0, void 0, function* () {
114
+ const [associatedTokenPublicKey, createAssociatedAccountIx, mintToTx] = yield this.createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount);
115
+ const tx = new web3_js_1.Transaction().add(createAssociatedAccountIx).add(mintToTx);
116
+ const txSig = yield this.program.provider.sendAndConfirm(tx, [], this.opts);
117
+ return [associatedTokenPublicKey, txSig];
118
+ });
119
+ }
120
+ createAssociatedTokenAccountAndMintToInstructions(userPublicKey, amount) {
121
+ return __awaiter(this, void 0, void 0, function* () {
122
+ const state = yield this.fetchState();
123
+ const associateTokenPublicKey = yield this.getAssosciatedMockUSDMintAddress({ userPubKey: userPublicKey });
124
+ const createAssociatedAccountIx = spl_token_1.Token.createAssociatedTokenAccountInstruction(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, associateTokenPublicKey, userPublicKey, this.wallet.publicKey);
125
+ const mintToIx = yield this.program.instruction.mintToUser(amount, {
126
+ accounts: {
127
+ mockUsdcFaucetState: yield this.getMockUSDCFaucetStatePublicKey(),
128
+ mintAccount: state.mint,
129
+ userTokenAccount: associateTokenPublicKey,
130
+ mintAuthority: state.mintAuthority,
131
+ tokenProgram: spl_token_1.TOKEN_PROGRAM_ID,
132
+ },
133
+ });
134
+ return [associateTokenPublicKey, createAssociatedAccountIx, mintToIx];
135
+ });
136
+ }
137
+ getAssosciatedMockUSDMintAddress(props) {
138
+ return __awaiter(this, void 0, void 0, function* () {
139
+ const state = yield this.fetchState();
140
+ return spl_token_1.Token.getAssociatedTokenAddress(spl_token_1.ASSOCIATED_TOKEN_PROGRAM_ID, spl_token_1.TOKEN_PROGRAM_ID, state.mint, props.userPubKey);
141
+ });
142
+ }
143
+ getTokenAccountInfo(props) {
144
+ return __awaiter(this, void 0, void 0, function* () {
145
+ const assosciatedKey = yield this.getAssosciatedMockUSDMintAddress(props);
146
+ const state = yield this.fetchState();
147
+ const token = new spl_token_1.Token(this.connection, state.mint, spl_token_1.TOKEN_PROGRAM_ID,
148
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
149
+ // @ts-ignore
150
+ this.provider.payer);
151
+ return yield token.getAccountInfo(assosciatedKey);
152
+ });
153
+ }
154
+ subscribeToTokenAccount(props) {
155
+ return __awaiter(this, void 0, void 0, function* () {
156
+ try {
157
+ const tokenAccountKey = yield this.getAssosciatedMockUSDMintAddress(props);
158
+ props.callback(yield this.getTokenAccountInfo(props));
159
+ // Couldn't find a way to do it using anchor framework subscription, someone on serum discord recommended this way
160
+ this.connection.onAccountChange(tokenAccountKey, (_accountInfo /* accountInfo is a buffer which we don't know how to deserialize */) => __awaiter(this, void 0, void 0, function* () {
161
+ props.callback(yield this.getTokenAccountInfo(props));
162
+ }));
163
+ return true;
164
+ }
165
+ catch (e) {
166
+ return false;
167
+ }
168
+ });
169
+ }
170
+ }
171
+ exports.MockUSDCFaucet = MockUSDCFaucet;
@@ -0,0 +1,19 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.OracleClientCache = void 0;
4
+ const oracleClient_1 = require("../factory/oracleClient");
5
+ class OracleClientCache {
6
+ constructor() {
7
+ this.cache = new Map();
8
+ }
9
+ get(oracleSource, connection) {
10
+ const key = Object.keys(oracleSource)[0];
11
+ if (this.cache.has(key)) {
12
+ return this.cache.get(key);
13
+ }
14
+ const client = oracleClient_1.getOracleClient(oracleSource, connection);
15
+ this.cache.set(key, client);
16
+ return client;
17
+ }
18
+ }
19
+ exports.OracleClientCache = OracleClientCache;
@@ -0,0 +1,46 @@
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.convertPythPrice = exports.PythClient = void 0;
13
+ const client_1 = require("@pythnetwork/client");
14
+ const anchor_1 = require("@project-serum/anchor");
15
+ const numericConstants_1 = require("../constants/numericConstants");
16
+ class PythClient {
17
+ constructor(connection) {
18
+ this.connection = connection;
19
+ }
20
+ getOraclePriceData(pricePublicKey) {
21
+ return __awaiter(this, void 0, void 0, function* () {
22
+ const accountInfo = yield this.connection.getAccountInfo(pricePublicKey);
23
+ return this.getOraclePriceDataFromBuffer(accountInfo.data);
24
+ });
25
+ }
26
+ getOraclePriceDataFromBuffer(buffer) {
27
+ const priceData = client_1.parsePriceData(buffer);
28
+ return {
29
+ price: convertPythPrice(priceData.aggregate.price, priceData.exponent),
30
+ slot: new anchor_1.BN(priceData.lastSlot.toString()),
31
+ confidence: convertPythPrice(priceData.confidence, priceData.exponent),
32
+ twap: convertPythPrice(priceData.twap.value, priceData.exponent),
33
+ twapConfidence: convertPythPrice(priceData.twac.value, priceData.exponent),
34
+ hasSufficientNumberOfDataPoints: true,
35
+ };
36
+ }
37
+ }
38
+ exports.PythClient = PythClient;
39
+ function convertPythPrice(price, exponent) {
40
+ exponent = Math.abs(exponent);
41
+ const pythPrecision = numericConstants_1.TEN.pow(new anchor_1.BN(exponent).abs());
42
+ return new anchor_1.BN(price * Math.pow(10, exponent))
43
+ .mul(numericConstants_1.MARK_PRICE_PRECISION)
44
+ .div(pythPrecision);
45
+ }
46
+ exports.convertPythPrice = convertPythPrice;
@@ -0,0 +1,32 @@
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.QuoteAssetOracleClient = exports.QUOTE_ORACLE_PRICE_DATA = void 0;
13
+ const anchor_1 = require("@project-serum/anchor");
14
+ const numericConstants_1 = require("../constants/numericConstants");
15
+ exports.QUOTE_ORACLE_PRICE_DATA = {
16
+ price: numericConstants_1.MARK_PRICE_PRECISION,
17
+ slot: new anchor_1.BN(0),
18
+ confidence: new anchor_1.BN(1),
19
+ hasSufficientNumberOfDataPoints: true,
20
+ };
21
+ class QuoteAssetOracleClient {
22
+ constructor() { }
23
+ getOraclePriceData(_pricePublicKey) {
24
+ return __awaiter(this, void 0, void 0, function* () {
25
+ return Promise.resolve(exports.QUOTE_ORACLE_PRICE_DATA);
26
+ });
27
+ }
28
+ getOraclePriceDataFromBuffer(_buffer) {
29
+ return exports.QUOTE_ORACLE_PRICE_DATA;
30
+ }
31
+ }
32
+ exports.QuoteAssetOracleClient = QuoteAssetOracleClient;
@@ -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;
@@ -1,154 +1,33 @@
1
- import {
2
- OrderParams,
3
- OrderTriggerCondition,
4
- OrderType,
5
- PositionDirection,
6
- } from './types';
1
+ import { OptionalOrderParams, OrderTriggerCondition, OrderType } from './types';
7
2
  import { BN } from '@project-serum/anchor';
8
- import { ZERO } from './constants/numericConstants';
9
3
 
10
4
  export function getLimitOrderParams(
11
- marketIndex: BN,
12
- direction: PositionDirection,
13
- baseAssetAmount: BN,
14
- price: BN,
15
- reduceOnly: boolean,
16
- discountToken = false,
17
- referrer = false,
18
- userOrderId = 0,
19
- postOnly = false,
20
- oraclePriceOffset = ZERO,
21
- immediateOrCancel = false
22
- ): OrderParams {
23
- return {
24
- orderType: OrderType.LIMIT,
25
- userOrderId,
26
- marketIndex,
27
- direction,
28
- quoteAssetAmount: ZERO,
29
- baseAssetAmount,
30
- price,
31
- reduceOnly,
32
- postOnly,
33
- immediateOrCancel,
34
- positionLimit: ZERO,
35
- padding0: true,
36
- padding1: ZERO,
37
- optionalAccounts: {
38
- discountToken,
39
- referrer,
40
- },
41
- triggerCondition: OrderTriggerCondition.ABOVE,
42
- triggerPrice: ZERO,
43
- oraclePriceOffset,
44
- };
5
+ params: Omit<OptionalOrderParams, 'orderType'> & { price: BN }
6
+ ): OptionalOrderParams {
7
+ return Object.assign({}, params, { orderType: OrderType.LIMIT });
45
8
  }
46
9
 
47
10
  export function getTriggerMarketOrderParams(
48
- marketIndex: BN,
49
- direction: PositionDirection,
50
- baseAssetAmount: BN,
51
- triggerPrice: BN,
52
- triggerCondition: OrderTriggerCondition,
53
- reduceOnly: boolean,
54
- discountToken = false,
55
- referrer = false,
56
- userOrderId = 0
57
- ): OrderParams {
58
- return {
59
- orderType: OrderType.TRIGGER_MARKET,
60
- userOrderId,
61
- marketIndex,
62
- direction,
63
- quoteAssetAmount: ZERO,
64
- baseAssetAmount,
65
- price: ZERO,
66
- reduceOnly,
67
- postOnly: false,
68
- immediateOrCancel: false,
69
- positionLimit: ZERO,
70
- padding0: true,
71
- padding1: ZERO,
72
- optionalAccounts: {
73
- discountToken,
74
- referrer,
75
- },
76
- triggerCondition,
77
- triggerPrice,
78
- oraclePriceOffset: ZERO,
79
- };
11
+ params: Omit<OptionalOrderParams, 'orderType'> & {
12
+ triggerCondition: OrderTriggerCondition;
13
+ triggerPrice: BN;
14
+ }
15
+ ): OptionalOrderParams {
16
+ return Object.assign({}, params, { orderType: OrderType.TRIGGER_MARKET });
80
17
  }
81
18
 
82
19
  export function getTriggerLimitOrderParams(
83
- marketIndex: BN,
84
- direction: PositionDirection,
85
- baseAssetAmount: BN,
86
- price: BN,
87
- triggerPrice: BN,
88
- triggerCondition: OrderTriggerCondition,
89
- reduceOnly: boolean,
90
- discountToken = false,
91
- referrer = false,
92
- userOrderId = 0
93
- ): OrderParams {
94
- return {
95
- orderType: OrderType.TRIGGER_LIMIT,
96
- userOrderId,
97
- marketIndex,
98
- direction,
99
- quoteAssetAmount: ZERO,
100
- baseAssetAmount,
101
- price,
102
- reduceOnly,
103
- postOnly: false,
104
- immediateOrCancel: false,
105
- positionLimit: ZERO,
106
- padding0: true,
107
- padding1: ZERO,
108
- optionalAccounts: {
109
- discountToken,
110
- referrer,
111
- },
112
- triggerCondition,
113
- triggerPrice,
114
- oraclePriceOffset: ZERO,
115
- };
20
+ params: Omit<OptionalOrderParams, 'orderType'> & {
21
+ triggerCondition: OrderTriggerCondition;
22
+ triggerPrice: BN;
23
+ price: BN;
24
+ }
25
+ ): OptionalOrderParams {
26
+ return Object.assign({}, params, { orderType: OrderType.TRIGGER_LIMIT });
116
27
  }
117
28
 
118
29
  export function getMarketOrderParams(
119
- marketIndex: BN,
120
- direction: PositionDirection,
121
- quoteAssetAmount: BN,
122
- baseAssetAmount: BN,
123
- reduceOnly: boolean,
124
- price = ZERO,
125
- discountToken = false,
126
- referrer = false
127
- ): OrderParams {
128
- if (baseAssetAmount.eq(ZERO) && quoteAssetAmount.eq(ZERO)) {
129
- throw Error('baseAssetAmount or quoteAssetAmount must be zero');
130
- }
131
-
132
- return {
133
- orderType: OrderType.MARKET,
134
- userOrderId: 0,
135
- marketIndex,
136
- direction,
137
- quoteAssetAmount,
138
- baseAssetAmount,
139
- price,
140
- reduceOnly,
141
- postOnly: false,
142
- immediateOrCancel: false,
143
- positionLimit: ZERO,
144
- padding0: true,
145
- padding1: ZERO,
146
- optionalAccounts: {
147
- discountToken,
148
- referrer,
149
- },
150
- triggerCondition: OrderTriggerCondition.ABOVE,
151
- triggerPrice: ZERO,
152
- oraclePriceOffset: ZERO,
153
- };
30
+ params: Omit<OptionalOrderParams, 'orderType'>
31
+ ): OptionalOrderParams {
32
+ return Object.assign({}, params, { orderType: OrderType.MARKET });
154
33
  }
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
+ }