Skip to content

Commit 2407121

Browse files
committed
feat(sdk): add calcVaultSharePrice
1 parent 8d1c301 commit 2407121

File tree

1 file changed

+48
-1
lines changed

1 file changed

+48
-1
lines changed

ts/sdk/src/vaultClient.ts

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import {
22
BN,
3+
BigNum,
34
DriftClient,
45
getInsuranceFundStakeAccountPublicKey,
56
getUserAccountPublicKey,
@@ -18,6 +19,7 @@ import {
1819
FuelOverflowStatus,
1920
getFuelOverflowAccountPublicKey,
2021
FUEL_RESET_LOG_ACCOUNT,
22+
QUOTE_PRECISION_EXP,
2123
} from '@drift-labs/sdk';
2224
import { BorshAccountsCoder, Program, ProgramAccount } from '@coral-xyz/anchor';
2325
import { DriftVaults } from './types/drift_vaults';
@@ -67,7 +69,7 @@ import { UserMapConfig } from '@drift-labs/sdk';
6769
import { calculateRealizedVaultDepositorEquity } from './math';
6870
import { Metaplex } from '@metaplex-foundation/js';
6971
import { getOrCreateATAInstruction } from './utils';
70-
import { VAULT_ADMIN_KEY } from './constants';
72+
import { VAULT_ADMIN_KEY, VAULT_SHARES_PRECISION_EXP } from './constants';
7173

7274
type OracleFeedConfig = {
7375
feed: PublicKey;
@@ -3843,4 +3845,49 @@ export class VaultClient {
38433845
},
38443846
});
38453847
}
3848+
3849+
/**
3850+
* Calculate the vault share price (base value per share)
3851+
* @param params vault address or vault account, and precision exponent
3852+
* @returns BigNum representing the base value per share
3853+
*/
3854+
public async calcVaultSharePrice(params: {
3855+
address?: PublicKey;
3856+
vault?: Vault;
3857+
}): Promise<BigNum> {
3858+
let spotPrecisionExp = QUOTE_PRECISION_EXP;
3859+
3860+
try {
3861+
let vaultAccount: Vault;
3862+
if (params.address !== undefined) {
3863+
vaultAccount = await this.program.account.vault.fetch(params.address);
3864+
} else if (params.vault !== undefined) {
3865+
vaultAccount = params.vault;
3866+
} else {
3867+
throw new Error('Must supply address or vault');
3868+
}
3869+
3870+
const spotMarket = this.driftClient.getSpotMarketAccount(
3871+
vaultAccount.spotMarketIndex
3872+
);
3873+
spotPrecisionExp = new BN(spotMarket!.decimals);
3874+
3875+
const totalAccountValue = await this.calculateVaultEquityInDepositAsset({
3876+
vault: vaultAccount,
3877+
factorUnrealizedPNL: true,
3878+
});
3879+
3880+
const vaultTotalShares = vaultAccount.totalShares.toString();
3881+
const totalAccountValueStr = totalAccountValue.toString();
3882+
3883+
return vaultTotalShares === '0'
3884+
? BigNum.from(0, spotPrecisionExp)
3885+
: new BigNum(totalAccountValueStr, spotPrecisionExp)
3886+
.shift(VAULT_SHARES_PRECISION_EXP)
3887+
.div(new BigNum(vaultTotalShares, VAULT_SHARES_PRECISION_EXP));
3888+
} catch (err) {
3889+
console.error('VaultClient calcVaultSharePrice error:', err);
3890+
return BigNum.from(0, spotPrecisionExp);
3891+
}
3892+
}
38463893
}

0 commit comments

Comments
 (0)