All V2 vaults share a common base type VaultBaseV1
, which implements the TokenizedShares
trait, and contains a method exchange_rate
that allows you to calculate the amount of underlying assets backing a single vault shares token.
If the return type of this function (f64
) you may use the decimal
library, or other similar crates to helper with calculating the exchange rate in a suitable return value. The reference implementation of the exchange_rate
function is below.
fn exchange_rate(&mut self, mint: &spl_token::state::Mint) -> f64 {
// sync shares first
self.sync_shares(mint);
let total_deposited_balance =
spl_token::amount_to_ui_amount(self.total_deposited_balance, mint.decimals);
let total_shares = spl_token::amount_to_ui_amount(self.total_shares, mint.decimals);
total_deposited_balance / total_shares
}
If implementing the exchange rate function manually, make sure to update the cached token mint supply values in the VaultBaseV1
type before calculation, otherwise you may have out-of-date input values.
The VaultBaseV1
type is fixed at 560-bytes in length, and occupies the first 560 bytes of the data buffer for all vault types. Note that because anchor uses an account discriminator, you will need to access the the VaultBaseV1
bytes starting at an offset of 8
.
There are two methods of accessing the VaultBaseV1
type:
The first and cheapest option is to avoid deserializing implementing vault types (ie: do not deserialize the MultiDepositOptimizerV1
type), and directly deserialize the data buffer into a VaultBaseV1
object.
Deserialize the implementing vault type (ie: deserialize the MultiDepositOptimizerV1
type), and then accessing the TokenizedSharesTrait
.