// SPDX-License-Identifier: ISC pragma solidity ^0.8.19; struct VaultAccount { uint128 amount; // Total amount, analogous to market cap uint128 shares; // Total shares, analogous to shares outstanding } /// @title VaultAccount Library /// @author Drake Evans (Frax Finance) github.com/drakeevans, modified from work by @Boring_Crypto github.com/boring_crypto /// @notice Provides a library for use with the VaultAccount struct, provides convenient math implementations /// @dev Uses uint128 to save on storage library VaultAccountingLibrary { /// @notice Calculates the shares value in relationship to `amount` and `total` /// @dev Given an amount, return the appropriate number of shares function toShares(VaultAccount memory total, uint256 amount, bool roundUp) internal pure returns (uint256 shares) { if (total.amount == 0) { shares = amount; } else { shares = (amount * total.shares) / total.amount; if (roundUp && (shares * total.amount) / total.shares < amount) { shares = shares + 1; } } } /// @notice Calculates the amount value in relationship to `shares` and `total` /// @dev Given a number of shares, returns the appropriate amount function toAmount(VaultAccount memory total, uint256 shares, bool roundUp) internal pure returns (uint256 amount) { if (total.shares == 0) { amount = shares; } else { amount = (shares * total.amount) / total.shares; if (roundUp && (amount * total.shares) / total.amount < shares) { amount = amount + 1; } } } }