diff --git a/sdk/src/index.ts b/sdk/src/index.ts index 802fc9d6..0a43257b 100644 --- a/sdk/src/index.ts +++ b/sdk/src/index.ts @@ -16,6 +16,7 @@ export * from './clearingHouseUser'; export * from './clearingHouse'; export * from './factory/clearingHouse'; export * from './factory/clearingHouseUser'; +export * from './math/collateral'; export * from './math/conversion'; export * from './math/funding'; export * from './math/insuranceFund'; diff --git a/sdk/src/math/collateral.ts b/sdk/src/math/collateral.ts new file mode 100644 index 00000000..b480d0cb --- /dev/null +++ b/sdk/src/math/collateral.ts @@ -0,0 +1,27 @@ +import { MarketsAccount, StateAccount } from '../types'; +import { Connection } from '@solana/web3.js'; + +/** + * Client collateral is represented by the balance of the collateral wallet, as specified in the state, minus the sum of + * each markets undistributed fees. + * + * @param connection + * @param state + * @param marketsAccount + * @returns Precision : QUOTE_ASSET_PRECISION + */ +export async function calculateUserCollateralSize( + connection: Connection, + state: StateAccount, + marketsAccount: MarketsAccount +): Promise { + const collateralVaultPublicKey = state.collateralVault; + const collateralVaultAmount = new BN( + ( + await connection.getTokenAccountBalance(collateralVaultPublicKey) + ).value.amount + ); + return marketsAccount.markets.reduce((collateralVaultAmount, market) => { + return collateralVaultAmount.sub(market.amm.totalFee); + }, collateralVaultAmount); +}