Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export * from './addresses';
export * from './admin';
export * from './clearingHouseUser';
export * from './clearingHouse';
export * from './math/collateral';
export * from './math/conversion';
export * from './math/funding';
export * from './math/insuranceFund';
Expand Down
28 changes: 28 additions & 0 deletions sdk/src/math/collateral.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { MarketsAccount, StateAccount } from '../types';
import BN from 'bn.js';
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<BN> {
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.div(new BN(2)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this trying to calculate how much of the collateral is the users? If so i don't think you need to divide by two

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@0xbigz mentioned in Discord that the collateral wallet holds the user collateral plus the insurance fund, which is equal to the amount of half of the total fees collected (as in calculateInsuranceFundSize ). So this was my attempt to 'back out' the insurance portion from the collateral balance.

I may have misunderstood him though - @0xbigz thoughts?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ping :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

None of the fees are owned by the users, so I think it's safe to subtract the entire totalFee (the exchange can use them in various ways)

}, collateralVaultAmount);
}