@drift-labs/sdk 0.2.0-master.32 → 0.2.0-master.34
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/accounts/bulkAccountLoader.js +2 -1
- package/lib/accounts/pollingClearingHouseAccountSubscriber.d.ts +2 -2
- package/lib/accounts/pollingClearingHouseAccountSubscriber.js +8 -8
- package/lib/accounts/types.d.ts +1 -0
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.d.ts +2 -2
- package/lib/accounts/webSocketClearingHouseAccountSubscriber.js +7 -7
- package/lib/addresses/marketAddresses.js +1 -1
- package/lib/addresses/pda.d.ts +4 -4
- package/lib/addresses/pda.js +23 -22
- package/lib/admin.d.ts +30 -32
- package/lib/admin.js +111 -119
- package/lib/clearingHouse.d.ts +43 -34
- package/lib/clearingHouse.js +353 -193
- package/lib/clearingHouseConfig.d.ts +2 -2
- package/lib/clearingHouseUser.d.ts +26 -5
- package/lib/clearingHouseUser.js +151 -51
- package/lib/config.d.ts +2 -0
- package/lib/config.js +5 -1
- package/lib/constants/numericConstants.d.ts +1 -0
- package/lib/constants/numericConstants.js +3 -2
- package/lib/dlob/DLOB.d.ts +18 -11
- package/lib/dlob/DLOB.js +179 -107
- package/lib/dlob/DLOBNode.js +2 -10
- package/lib/dlob/NodeList.js +1 -1
- package/lib/events/eventSubscriber.d.ts +1 -0
- package/lib/events/eventSubscriber.js +11 -4
- package/lib/events/fetchLogs.d.ts +3 -1
- package/lib/events/fetchLogs.js +13 -5
- package/lib/events/pollingLogProvider.js +1 -1
- package/lib/events/types.d.ts +1 -1
- package/lib/events/webSocketLogProvider.js +1 -1
- package/lib/factory/bigNum.d.ts +5 -4
- package/lib/factory/bigNum.js +36 -6
- package/lib/idl/clearing_house.json +1540 -1246
- package/lib/index.d.ts +3 -0
- package/lib/index.js +3 -0
- package/lib/math/amm.js +9 -9
- package/lib/math/exchangeStatus.d.ts +4 -0
- package/lib/math/exchangeStatus.js +18 -0
- package/lib/math/funding.js +10 -10
- package/lib/math/margin.js +6 -1
- package/lib/math/market.js +9 -9
- package/lib/math/orders.d.ts +7 -3
- package/lib/math/orders.js +39 -31
- package/lib/math/repeg.js +3 -3
- package/lib/math/spotBalance.js +3 -3
- package/lib/math/spotPosition.js +2 -2
- package/lib/serum/serumFulfillmentConfigMap.d.ts +10 -0
- package/lib/serum/serumFulfillmentConfigMap.js +17 -0
- package/lib/serum/serumSubscriber.d.ts +4 -0
- package/lib/serum/serumSubscriber.js +16 -1
- package/lib/types.d.ts +60 -75
- package/lib/types.js +2 -1
- package/lib/userMap/userMap.d.ts +17 -1
- package/lib/userMap/userMap.js +12 -0
- package/lib/userName.d.ts +1 -0
- package/lib/userName.js +3 -2
- package/package.json +1 -1
- package/src/accounts/bulkAccountLoader.ts +5 -1
- package/src/accounts/pollingClearingHouseAccountSubscriber.ts +9 -9
- package/src/accounts/webSocketClearingHouseAccountSubscriber.ts +8 -8
- package/src/addresses/marketAddresses.ts +2 -2
- package/src/addresses/pda.ts +20 -20
- package/src/admin.ts +246 -221
- package/src/assert/assert.js +9 -0
- package/src/clearingHouse.ts +556 -236
- package/src/clearingHouseConfig.ts +2 -2
- package/src/clearingHouseUser.ts +237 -87
- package/src/config.ts +8 -1
- package/src/constants/numericConstants.ts +5 -1
- package/src/dlob/DLOB.ts +257 -120
- package/src/dlob/DLOBNode.ts +2 -14
- package/src/dlob/NodeList.ts +1 -1
- package/src/events/eventList.js +77 -0
- package/src/events/eventSubscriber.ts +18 -4
- package/src/events/fetchLogs.ts +20 -5
- package/src/events/pollingLogProvider.ts +1 -1
- package/src/events/types.ts +2 -1
- package/src/events/webSocketLogProvider.ts +1 -1
- package/src/examples/makeTradeExample.js +157 -0
- package/src/factory/bigNum.ts +59 -6
- package/src/idl/clearing_house.json +1540 -1246
- package/src/idl/pyth.json +98 -2
- package/src/index.ts +3 -0
- package/src/math/amm.ts +9 -9
- package/src/math/exchangeStatus.ts +31 -0
- package/src/math/funding.ts +20 -10
- package/src/math/margin.ts +7 -1
- package/src/math/market.ts +9 -9
- package/src/math/orders.ts +44 -29
- package/src/math/repeg.ts +3 -3
- package/src/math/spotBalance.ts +4 -4
- package/src/math/spotPosition.ts +2 -2
- package/src/serum/serumFulfillmentConfigMap.ts +26 -0
- package/src/serum/serumSubscriber.ts +20 -1
- package/src/token/index.js +38 -0
- package/src/tx/types.js +2 -0
- package/src/tx/utils.js +17 -0
- package/src/types.ts +65 -51
- package/src/userMap/userMap.ts +25 -1
- package/src/userName.ts +2 -1
- package/src/util/computeUnits.js +27 -0
- package/src/util/getTokenAddress.js +9 -0
- package/src/util/promiseTimeout.js +14 -0
- package/src/util/tps.js +27 -0
- package/tests/bn/test.ts +22 -1
- package/tests/dlob/helpers.ts +252 -81
- package/tests/dlob/test.ts +1040 -219
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.EventList = void 0;
|
|
4
|
+
class Node {
|
|
5
|
+
constructor(event, next, prev) {
|
|
6
|
+
this.event = event;
|
|
7
|
+
this.next = next;
|
|
8
|
+
this.prev = prev;
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
class EventList {
|
|
12
|
+
constructor(eventType, maxSize, sortFn, orderDirection) {
|
|
13
|
+
this.eventType = eventType;
|
|
14
|
+
this.maxSize = maxSize;
|
|
15
|
+
this.sortFn = sortFn;
|
|
16
|
+
this.orderDirection = orderDirection;
|
|
17
|
+
this.size = 0;
|
|
18
|
+
}
|
|
19
|
+
insert(event) {
|
|
20
|
+
this.size++;
|
|
21
|
+
const newNode = new Node(event);
|
|
22
|
+
if (this.head === undefined) {
|
|
23
|
+
this.head = this.tail = newNode;
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
26
|
+
if (this.sortFn(this.head.event, newNode.event) ===
|
|
27
|
+
(this.orderDirection === 'asc' ? 'less than' : 'greater than')) {
|
|
28
|
+
this.head.prev = newNode;
|
|
29
|
+
newNode.next = this.head;
|
|
30
|
+
this.head = newNode;
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
let currentNode = this.head;
|
|
34
|
+
while (currentNode.next !== undefined &&
|
|
35
|
+
this.sortFn(currentNode.next.event, newNode.event) !==
|
|
36
|
+
(this.orderDirection === 'asc' ? 'less than' : 'greater than')) {
|
|
37
|
+
currentNode = currentNode.next;
|
|
38
|
+
}
|
|
39
|
+
newNode.next = currentNode.next;
|
|
40
|
+
if (currentNode.next !== undefined) {
|
|
41
|
+
newNode.next.prev = newNode;
|
|
42
|
+
}
|
|
43
|
+
currentNode.next = newNode;
|
|
44
|
+
newNode.prev = currentNode;
|
|
45
|
+
}
|
|
46
|
+
if (this.size > this.maxSize) {
|
|
47
|
+
this.detach();
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
detach() {
|
|
51
|
+
const node = this.tail;
|
|
52
|
+
if (node.prev !== undefined) {
|
|
53
|
+
node.prev.next = node.next;
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
this.head = node.next;
|
|
57
|
+
}
|
|
58
|
+
if (node.next !== undefined) {
|
|
59
|
+
node.next.prev = node.prev;
|
|
60
|
+
}
|
|
61
|
+
else {
|
|
62
|
+
this.tail = node.prev;
|
|
63
|
+
}
|
|
64
|
+
this.size--;
|
|
65
|
+
}
|
|
66
|
+
toArray() {
|
|
67
|
+
return Array.from(this);
|
|
68
|
+
}
|
|
69
|
+
*[Symbol.iterator]() {
|
|
70
|
+
let node = this.head;
|
|
71
|
+
while (node) {
|
|
72
|
+
yield node.event;
|
|
73
|
+
node = node.next;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
exports.EventList = EventList;
|
|
@@ -26,6 +26,7 @@ export class EventSubscriber {
|
|
|
26
26
|
private logProvider: LogProvider;
|
|
27
27
|
public eventEmitter: StrictEventEmitter<EventEmitter, EventSubscriberEvents>;
|
|
28
28
|
private lastSeenSlot: number;
|
|
29
|
+
private lastSeenBlockTime: number | undefined;
|
|
29
30
|
public lastSeenTxSig: string;
|
|
30
31
|
|
|
31
32
|
public constructor(
|
|
@@ -70,8 +71,8 @@ export class EventSubscriber {
|
|
|
70
71
|
return true;
|
|
71
72
|
}
|
|
72
73
|
|
|
73
|
-
this.logProvider.subscribe((txSig, slot, logs) => {
|
|
74
|
-
this.handleTxLogs(txSig, slot, logs);
|
|
74
|
+
this.logProvider.subscribe((txSig, slot, logs, mostRecentBlockTime) => {
|
|
75
|
+
this.handleTxLogs(txSig, slot, logs, mostRecentBlockTime);
|
|
75
76
|
}, true);
|
|
76
77
|
|
|
77
78
|
return true;
|
|
@@ -85,7 +86,8 @@ export class EventSubscriber {
|
|
|
85
86
|
private handleTxLogs(
|
|
86
87
|
txSig: TransactionSignature,
|
|
87
88
|
slot: number,
|
|
88
|
-
logs: string[]
|
|
89
|
+
logs: string[],
|
|
90
|
+
mostRecentBlockTime: number | undefined
|
|
89
91
|
): void {
|
|
90
92
|
if (this.txEventCache.has(txSig)) {
|
|
91
93
|
return;
|
|
@@ -94,6 +96,10 @@ export class EventSubscriber {
|
|
|
94
96
|
const wrappedEvents = this.parseEventsFromLogs(txSig, slot, logs);
|
|
95
97
|
for (const wrappedEvent of wrappedEvents) {
|
|
96
98
|
this.eventListMap.get(wrappedEvent.eventType).insert(wrappedEvent);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
// dont emit event till we've added all the events to the eventListMap
|
|
102
|
+
for (const wrappedEvent of wrappedEvents) {
|
|
97
103
|
this.eventEmitter.emit('newEvent', wrappedEvent);
|
|
98
104
|
}
|
|
99
105
|
|
|
@@ -106,6 +112,14 @@ export class EventSubscriber {
|
|
|
106
112
|
if (slot > this.lastSeenSlot) {
|
|
107
113
|
this.lastSeenTxSig = txSig;
|
|
108
114
|
}
|
|
115
|
+
|
|
116
|
+
if (
|
|
117
|
+
this.lastSeenBlockTime === undefined ||
|
|
118
|
+
mostRecentBlockTime > this.lastSeenBlockTime
|
|
119
|
+
) {
|
|
120
|
+
this.lastSeenBlockTime = mostRecentBlockTime;
|
|
121
|
+
}
|
|
122
|
+
|
|
109
123
|
this.txEventCache.add(txSig, wrappedEvents);
|
|
110
124
|
}
|
|
111
125
|
|
|
@@ -134,7 +148,7 @@ export class EventSubscriber {
|
|
|
134
148
|
beforeTx = response.earliestTx;
|
|
135
149
|
|
|
136
150
|
for (const { txSig, slot, logs } of response.transactionLogs) {
|
|
137
|
-
this.handleTxLogs(txSig, slot, logs);
|
|
151
|
+
this.handleTxLogs(txSig, slot, logs, response.mostRecentBlockTime);
|
|
138
152
|
}
|
|
139
153
|
}
|
|
140
154
|
}
|
package/src/events/fetchLogs.ts
CHANGED
|
@@ -3,6 +3,7 @@ import {
|
|
|
3
3
|
Connection,
|
|
4
4
|
Finality,
|
|
5
5
|
PublicKey,
|
|
6
|
+
TransactionResponse,
|
|
6
7
|
TransactionSignature,
|
|
7
8
|
} from '@solana/web3.js';
|
|
8
9
|
import { WrappedEvents } from './types';
|
|
@@ -14,8 +15,17 @@ type FetchLogsResponse = {
|
|
|
14
15
|
earliestSlot: number;
|
|
15
16
|
mostRecentSlot: number;
|
|
16
17
|
transactionLogs: Log[];
|
|
18
|
+
mostRecentBlockTime: number | undefined;
|
|
17
19
|
};
|
|
18
20
|
|
|
21
|
+
function mapTransactionResponseToLog(transaction: TransactionResponse): Log {
|
|
22
|
+
return {
|
|
23
|
+
txSig: transaction.transaction.signatures[0],
|
|
24
|
+
slot: transaction.slot,
|
|
25
|
+
logs: transaction.meta.logMessages,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
|
|
19
29
|
export async function fetchLogs(
|
|
20
30
|
connection: Connection,
|
|
21
31
|
programId: PublicKey,
|
|
@@ -57,11 +67,7 @@ export async function fetchLogs(
|
|
|
57
67
|
);
|
|
58
68
|
|
|
59
69
|
return transactions.map((transaction) => {
|
|
60
|
-
return
|
|
61
|
-
txSig: transaction.transaction.signatures[0],
|
|
62
|
-
slot: transaction.slot,
|
|
63
|
-
logs: transaction.meta.logMessages,
|
|
64
|
-
};
|
|
70
|
+
return mapTransactionResponseToLog(transaction);
|
|
65
71
|
});
|
|
66
72
|
})
|
|
67
73
|
)
|
|
@@ -76,6 +82,7 @@ export async function fetchLogs(
|
|
|
76
82
|
mostRecentTx: mostRecent.signature,
|
|
77
83
|
earliestSlot: earliest.slot,
|
|
78
84
|
mostRecentSlot: mostRecent.slot,
|
|
85
|
+
mostRecentBlockTime: mostRecent.blockTime,
|
|
79
86
|
};
|
|
80
87
|
}
|
|
81
88
|
|
|
@@ -93,6 +100,14 @@ export class LogParser {
|
|
|
93
100
|
this.program = program;
|
|
94
101
|
}
|
|
95
102
|
|
|
103
|
+
public parseEventsFromTransaction(
|
|
104
|
+
transaction: TransactionResponse
|
|
105
|
+
): WrappedEvents {
|
|
106
|
+
const transactionLogObject = mapTransactionResponseToLog(transaction);
|
|
107
|
+
|
|
108
|
+
return this.parseEventsFromLogs(transactionLogObject);
|
|
109
|
+
}
|
|
110
|
+
|
|
96
111
|
public parseEventsFromLogs(event: Log): WrappedEvents {
|
|
97
112
|
const records: WrappedEvents = [];
|
|
98
113
|
// @ts-ignore
|
|
@@ -58,7 +58,7 @@ export class PollingLogProvider implements LogProvider {
|
|
|
58
58
|
const { mostRecentTx, transactionLogs } = response;
|
|
59
59
|
|
|
60
60
|
for (const { txSig, slot, logs } of transactionLogs) {
|
|
61
|
-
callback(txSig, slot, logs);
|
|
61
|
+
callback(txSig, slot, logs, response.mostRecentBlockTime);
|
|
62
62
|
}
|
|
63
63
|
|
|
64
64
|
this.mostRecentSeenTx = mostRecentTx;
|
package/src/events/types.ts
CHANGED
|
@@ -17,7 +17,7 @@ export class WebSocketLogProvider implements LogProvider {
|
|
|
17
17
|
this.subscriptionId = this.connection.onLogs(
|
|
18
18
|
this.programId,
|
|
19
19
|
(logs, ctx) => {
|
|
20
|
-
callback(logs.signature, ctx.slot, logs.logs);
|
|
20
|
+
callback(logs.signature, ctx.slot, logs.logs, undefined);
|
|
21
21
|
},
|
|
22
22
|
this.commitment
|
|
23
23
|
);
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
var __awaiter =
|
|
3
|
+
(this && this.__awaiter) ||
|
|
4
|
+
function (thisArg, _arguments, P, generator) {
|
|
5
|
+
function adopt(value) {
|
|
6
|
+
return value instanceof P
|
|
7
|
+
? value
|
|
8
|
+
: new P(function (resolve) {
|
|
9
|
+
resolve(value);
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
return new (P || (P = Promise))(function (resolve, reject) {
|
|
13
|
+
function fulfilled(value) {
|
|
14
|
+
try {
|
|
15
|
+
step(generator.next(value));
|
|
16
|
+
} catch (e) {
|
|
17
|
+
reject(e);
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function rejected(value) {
|
|
21
|
+
try {
|
|
22
|
+
step(generator['throw'](value));
|
|
23
|
+
} catch (e) {
|
|
24
|
+
reject(e);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function step(result) {
|
|
28
|
+
result.done
|
|
29
|
+
? resolve(result.value)
|
|
30
|
+
: adopt(result.value).then(fulfilled, rejected);
|
|
31
|
+
}
|
|
32
|
+
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
Object.defineProperty(exports, '__esModule', { value: true });
|
|
36
|
+
exports.getTokenAddress = void 0;
|
|
37
|
+
const anchor_1 = require('@project-serum/anchor');
|
|
38
|
+
const __1 = require('..');
|
|
39
|
+
const spl_token_1 = require('@solana/spl-token');
|
|
40
|
+
const web3_js_1 = require('@solana/web3.js');
|
|
41
|
+
const __2 = require('..');
|
|
42
|
+
const banks_1 = require('../constants/spotMarkets');
|
|
43
|
+
const getTokenAddress = (mintAddress, userPubKey) => {
|
|
44
|
+
return spl_token_1.Token.getAssociatedTokenAddress(
|
|
45
|
+
new web3_js_1.PublicKey(`ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL`),
|
|
46
|
+
spl_token_1.TOKEN_PROGRAM_ID,
|
|
47
|
+
new web3_js_1.PublicKey(mintAddress),
|
|
48
|
+
new web3_js_1.PublicKey(userPubKey)
|
|
49
|
+
);
|
|
50
|
+
};
|
|
51
|
+
exports.getTokenAddress = getTokenAddress;
|
|
52
|
+
const main = () =>
|
|
53
|
+
__awaiter(void 0, void 0, void 0, function* () {
|
|
54
|
+
// Initialize Drift SDK
|
|
55
|
+
const sdkConfig = __2.initialize({ env: 'devnet' });
|
|
56
|
+
// Set up the Wallet and Provider
|
|
57
|
+
const privateKey = process.env.BOT_PRIVATE_KEY; // stored as an array string
|
|
58
|
+
const keypair = web3_js_1.Keypair.fromSecretKey(
|
|
59
|
+
Uint8Array.from(JSON.parse(privateKey))
|
|
60
|
+
);
|
|
61
|
+
const wallet = new __1.Wallet(keypair);
|
|
62
|
+
// Set up the Connection
|
|
63
|
+
const rpcAddress = process.env.RPC_ADDRESS; // can use: https://api.devnet.solana.com for devnet; https://api.mainnet-beta.solana.com for mainnet;
|
|
64
|
+
const connection = new web3_js_1.Connection(rpcAddress);
|
|
65
|
+
// Set up the Provider
|
|
66
|
+
const provider = new anchor_1.AnchorProvider(
|
|
67
|
+
connection,
|
|
68
|
+
wallet,
|
|
69
|
+
anchor_1.AnchorProvider.defaultOptions()
|
|
70
|
+
);
|
|
71
|
+
// Check SOL Balance
|
|
72
|
+
const lamportsBalance = yield connection.getBalance(wallet.publicKey);
|
|
73
|
+
console.log('SOL balance:', lamportsBalance / Math.pow(10, 9));
|
|
74
|
+
// Misc. other things to set up
|
|
75
|
+
const usdcTokenAddress = yield exports.getTokenAddress(
|
|
76
|
+
sdkConfig.USDC_MINT_ADDRESS,
|
|
77
|
+
wallet.publicKey.toString()
|
|
78
|
+
);
|
|
79
|
+
// Set up the Drift Clearing House
|
|
80
|
+
const clearingHousePublicKey = new web3_js_1.PublicKey(
|
|
81
|
+
sdkConfig.CLEARING_HOUSE_PROGRAM_ID
|
|
82
|
+
);
|
|
83
|
+
const clearingHouse = new __2.ClearingHouse({
|
|
84
|
+
connection,
|
|
85
|
+
wallet: provider.wallet,
|
|
86
|
+
programID: clearingHousePublicKey,
|
|
87
|
+
});
|
|
88
|
+
yield clearingHouse.subscribe();
|
|
89
|
+
// Set up Clearing House user client
|
|
90
|
+
const user = new __2.ClearingHouseUser({
|
|
91
|
+
clearingHouse,
|
|
92
|
+
userAccountPublicKey: yield clearingHouse.getUserAccountPublicKey(),
|
|
93
|
+
});
|
|
94
|
+
//// Check if clearing house account exists for the current wallet
|
|
95
|
+
const userAccountExists = yield user.exists();
|
|
96
|
+
if (!userAccountExists) {
|
|
97
|
+
//// Create a Clearing House account by Depositing some USDC ($10,000 in this case)
|
|
98
|
+
const depositAmount = new anchor_1.BN(10000).mul(__2.QUOTE_PRECISION);
|
|
99
|
+
yield clearingHouse.initializeUserAccountAndDepositCollateral(
|
|
100
|
+
depositAmount,
|
|
101
|
+
yield exports.getTokenAddress(
|
|
102
|
+
usdcTokenAddress.toString(),
|
|
103
|
+
wallet.publicKey.toString()
|
|
104
|
+
),
|
|
105
|
+
banks_1.SpotMarkets['devnet'][0].marketIndex
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
yield user.subscribe();
|
|
109
|
+
// Get current price
|
|
110
|
+
const solMarketInfo = sdkConfig.PERP_MARKETS.find(
|
|
111
|
+
(market) => market.baseAssetSymbol === 'SOL'
|
|
112
|
+
);
|
|
113
|
+
const currentMarketPrice = __2.calculateMarkPrice(
|
|
114
|
+
clearingHouse.getMarketAccount(solMarketInfo.marketIndex),
|
|
115
|
+
undefined
|
|
116
|
+
);
|
|
117
|
+
const formattedPrice = __2.convertToNumber(
|
|
118
|
+
currentMarketPrice,
|
|
119
|
+
__2.PRICE_PRECISION
|
|
120
|
+
);
|
|
121
|
+
console.log(`Current Market Price is $${formattedPrice}`);
|
|
122
|
+
// Estimate the slippage for a $5000 LONG trade
|
|
123
|
+
const solMarketAccount = clearingHouse.getMarketAccount(
|
|
124
|
+
solMarketInfo.marketIndex
|
|
125
|
+
);
|
|
126
|
+
const longAmount = new anchor_1.BN(5000).mul(__2.QUOTE_PRECISION);
|
|
127
|
+
const slippage = __2.convertToNumber(
|
|
128
|
+
__2.calculateTradeSlippage(
|
|
129
|
+
__2.PositionDirection.LONG,
|
|
130
|
+
longAmount,
|
|
131
|
+
solMarketAccount,
|
|
132
|
+
'quote',
|
|
133
|
+
undefined
|
|
134
|
+
)[0],
|
|
135
|
+
__2.PRICE_PRECISION
|
|
136
|
+
);
|
|
137
|
+
console.log(
|
|
138
|
+
`Slippage for a $5000 LONG on the SOL market would be $${slippage}`
|
|
139
|
+
);
|
|
140
|
+
// Make a $5000 LONG trade
|
|
141
|
+
yield clearingHouse.openPosition(
|
|
142
|
+
__2.PositionDirection.LONG,
|
|
143
|
+
longAmount,
|
|
144
|
+
solMarketInfo.marketIndex
|
|
145
|
+
);
|
|
146
|
+
console.log(`LONGED $5000 SOL`);
|
|
147
|
+
// Reduce the position by $2000
|
|
148
|
+
const reduceAmount = new anchor_1.BN(2000).mul(__2.QUOTE_PRECISION);
|
|
149
|
+
yield clearingHouse.openPosition(
|
|
150
|
+
__2.PositionDirection.SHORT,
|
|
151
|
+
reduceAmount,
|
|
152
|
+
solMarketInfo.marketIndex
|
|
153
|
+
);
|
|
154
|
+
// Close the rest of the position
|
|
155
|
+
yield clearingHouse.closePosition(solMarketInfo.marketIndex);
|
|
156
|
+
});
|
|
157
|
+
main();
|
package/src/factory/bigNum.ts
CHANGED
|
@@ -306,7 +306,11 @@ export class BigNum {
|
|
|
306
306
|
* @param fixedPrecision
|
|
307
307
|
* @returns
|
|
308
308
|
*/
|
|
309
|
-
public toFixed(fixedPrecision: number): string {
|
|
309
|
+
public toFixed(fixedPrecision: number, rounded = false): string {
|
|
310
|
+
if (rounded) {
|
|
311
|
+
return this.toRounded(fixedPrecision).toFixed(fixedPrecision);
|
|
312
|
+
}
|
|
313
|
+
|
|
310
314
|
const printString = this.print();
|
|
311
315
|
|
|
312
316
|
const [leftSide, rightSide] = printString.split(BigNum.delim);
|
|
@@ -322,7 +326,41 @@ export class BigNum {
|
|
|
322
326
|
}
|
|
323
327
|
|
|
324
328
|
private getZeroes(count: number) {
|
|
325
|
-
return new Array(count).fill('0').join('');
|
|
329
|
+
return new Array(Math.max(count, 0)).fill('0').join('');
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
public toRounded(roundingPrecision: number) {
|
|
333
|
+
const printString = this.toString();
|
|
334
|
+
|
|
335
|
+
let shouldRoundUp = false;
|
|
336
|
+
|
|
337
|
+
const roundingDigitChar = printString[roundingPrecision];
|
|
338
|
+
|
|
339
|
+
if (roundingDigitChar) {
|
|
340
|
+
const roundingDigitVal = Number(roundingDigitChar);
|
|
341
|
+
if (roundingDigitVal >= 5) shouldRoundUp = true;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
if (shouldRoundUp) {
|
|
345
|
+
const valueWithRoundedPrecisionAdded = this.add(
|
|
346
|
+
BigNum.from(
|
|
347
|
+
new BN(10).pow(new BN(printString.length - roundingPrecision)),
|
|
348
|
+
this.precision
|
|
349
|
+
)
|
|
350
|
+
);
|
|
351
|
+
|
|
352
|
+
const roundedUpPrintString =
|
|
353
|
+
valueWithRoundedPrecisionAdded.toString().slice(0, roundingPrecision) +
|
|
354
|
+
this.getZeroes(printString.length - roundingPrecision);
|
|
355
|
+
|
|
356
|
+
return BigNum.from(roundedUpPrintString, this.precision);
|
|
357
|
+
} else {
|
|
358
|
+
const roundedDownPrintString =
|
|
359
|
+
printString.slice(0, roundingPrecision) +
|
|
360
|
+
this.getZeroes(printString.length - roundingPrecision);
|
|
361
|
+
|
|
362
|
+
return BigNum.from(roundedDownPrintString, this.precision);
|
|
363
|
+
}
|
|
326
364
|
}
|
|
327
365
|
|
|
328
366
|
/**
|
|
@@ -330,7 +368,18 @@ export class BigNum {
|
|
|
330
368
|
* @param fixedPrecision
|
|
331
369
|
* @returns
|
|
332
370
|
*/
|
|
333
|
-
public toPrecision(
|
|
371
|
+
public toPrecision(
|
|
372
|
+
fixedPrecision: number,
|
|
373
|
+
trailingZeroes = false,
|
|
374
|
+
rounded = false
|
|
375
|
+
): string {
|
|
376
|
+
if (rounded) {
|
|
377
|
+
return this.toRounded(fixedPrecision).toPrecision(
|
|
378
|
+
fixedPrecision,
|
|
379
|
+
trailingZeroes
|
|
380
|
+
);
|
|
381
|
+
}
|
|
382
|
+
|
|
334
383
|
const printString = this.print();
|
|
335
384
|
|
|
336
385
|
let precisionPrintString = printString.slice(0, fixedPrecision + 1);
|
|
@@ -404,8 +453,8 @@ export class BigNum {
|
|
|
404
453
|
return precisionPrintString;
|
|
405
454
|
}
|
|
406
455
|
|
|
407
|
-
public toTradePrecision(): string {
|
|
408
|
-
return this.toPrecision(6, true);
|
|
456
|
+
public toTradePrecision(rounded = false): string {
|
|
457
|
+
return this.toPrecision(6, true, rounded);
|
|
409
458
|
}
|
|
410
459
|
|
|
411
460
|
/**
|
|
@@ -448,7 +497,11 @@ export class BigNum {
|
|
|
448
497
|
return `${prefix}${val.replace('-', '')}`;
|
|
449
498
|
}
|
|
450
499
|
|
|
451
|
-
public toMillified(precision = 3): string {
|
|
500
|
+
public toMillified(precision = 3, rounded = false): string {
|
|
501
|
+
if (rounded) {
|
|
502
|
+
return this.toRounded(precision).toMillified(precision);
|
|
503
|
+
}
|
|
504
|
+
|
|
452
505
|
const stringVal = this.print();
|
|
453
506
|
|
|
454
507
|
const [leftSide] = stringVal.split(BigNum.delim);
|