Skip to content

Commit a2237a8

Browse files
sdk: optimize drift holdings calculation (#895)
Synced from glamsystems/glam f6539540ee729ebdf451831e2abcc11d2866ec47
1 parent e935d5a commit a2237a8

File tree

1 file changed

+44
-13
lines changed

1 file changed

+44
-13
lines changed

src/cmds/drift-protocol.ts

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -239,29 +239,60 @@ export function installDriftProtocolCommands(
239239
user.perpPositions.map((p) => p.marketIndex),
240240
);
241241

242-
for (const {
243-
marketIndex,
244-
scaledBalance,
245-
balanceType,
246-
} of user.spotPositions) {
247-
const spotMarket = spotMarkets.find(
248-
(m) => m.marketIndex === marketIndex,
242+
const total = [];
243+
for (const spotPosition of user.spotPositions) {
244+
const {
245+
name: spotMarketName,
246+
decimals,
247+
marketIndex,
248+
cumulativeDepositInterest,
249+
cumulativeBorrowInterest,
250+
lastOraclePrice,
251+
} = spotMarkets.find(
252+
(m) => m.marketIndex === spotPosition.marketIndex,
249253
)!;
250-
const { uiAmount } = spotMarket.calcSpotBalance(
251-
scaledBalance,
252-
balanceType,
254+
255+
const { uiAmount } = spotPosition.calcBalance(
256+
decimals,
257+
cumulativeDepositInterest,
258+
cumulativeBorrowInterest,
253259
);
260+
const usdValue = (uiAmount * lastOraclePrice.toNumber()) / 1_000_000;
261+
total.push(usdValue);
254262

255263
console.log(
256-
`${uiAmount} ${spotMarket.name} (market index: ${marketIndex})`,
264+
`${uiAmount} ${spotMarketName} (market index: ${marketIndex}): $${usdValue}`,
257265
);
258266
}
259267

260-
for (const { marketIndex, baseAssetAmount } of user.perpPositions) {
268+
for (const perpPosition of user.perpPositions) {
269+
const {
270+
name: perpMarketName,
271+
marketIndex,
272+
lastOraclePrice,
273+
cumulativeFundingRateLong,
274+
cumulativeFundingRateShort,
275+
} = perpMarkets.find(
276+
(m) => m.marketIndex === perpPosition.marketIndex,
277+
)!;
278+
279+
const pos = perpPosition.baseAssetAmount.toNumber() / 1_000_000_000;
280+
const usdValue =
281+
perpPosition
282+
.getUsdValueScaled(
283+
lastOraclePrice,
284+
cumulativeFundingRateLong,
285+
cumulativeFundingRateShort,
286+
)
287+
.toNumber() / 1_000_000;
288+
total.push(usdValue);
289+
261290
console.log(
262-
`Base amount: ${baseAssetAmount} (market index: ${marketIndex})`,
291+
`${pos} ${perpMarketName} (market index: ${marketIndex}): $${usdValue}`,
263292
);
264293
}
294+
295+
console.log(`Total: $${total.reduce((a, b) => a + b, 0)}`);
265296
});
266297

267298
drift

0 commit comments

Comments
 (0)