11import {
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' ;
2224import { BorshAccountsCoder , Program , ProgramAccount } from '@coral-xyz/anchor' ;
2325import { DriftVaults } from './types/drift_vaults' ;
@@ -67,7 +69,7 @@ import { UserMapConfig } from '@drift-labs/sdk';
6769import { calculateRealizedVaultDepositorEquity } from './math' ;
6870import { Metaplex } from '@metaplex-foundation/js' ;
6971import { getOrCreateATAInstruction } from './utils' ;
70- import { VAULT_ADMIN_KEY } from './constants' ;
72+ import { VAULT_ADMIN_KEY , VAULT_SHARES_PRECISION_EXP } from './constants' ;
7173
7274type 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