Skip to content

Commit

Permalink
sdk: add isUserBankrupt (#399)
Browse files Browse the repository at this point in the history
* sdk: add isUserBankrupt

* update CHANGELOG.md

* fix quoteAssetAmount
  • Loading branch information
wphan committed Mar 20, 2023
1 parent 46ac76b commit 3713c56
Show file tree
Hide file tree
Showing 4 changed files with 45 additions and 0 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Features

- sdk: add isUserBankrupt ([#399](https://github.com/drift-labs/protocol-v2/pull/399))

### Fixes

### Breaking
Expand Down
1 change: 1 addition & 0 deletions sdk/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,5 +68,6 @@ export * from './dlob/DLOBOrders';
export * from './dlob/NodeList';
export * from './userMap/userMap';
export * from './userMap/userStatsMap';
export * from './math/bankruptcy';

export { BN, PublicKey, pyth };
34 changes: 34 additions & 0 deletions sdk/src/math/bankruptcy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { ZERO, hasOpenOrders, isVariant } from '..';
import { User } from '../user';

export function isUserBankrupt(user: User): boolean {
const userAccount = user.getUserAccount();
let hasLiability = false;
for (const position of userAccount.spotPositions) {
if (position.scaledBalance.gt(ZERO)) {
if (isVariant(position.balanceType, 'deposit')) {
return false;
}
if (isVariant(position.balanceType, 'borrow')) {
hasLiability = true;
}
}
}

for (const position of userAccount.perpPositions) {
if (
!position.baseAssetAmount.eq(ZERO) ||
position.quoteAssetAmount.gt(ZERO) ||
hasOpenOrders(position) ||
position.lpShares.gt(ZERO)
) {
return false;
}

if (position.quoteAssetAmount.lt(ZERO)) {
hasLiability = true;
}
}

return hasLiability;
}
8 changes: 8 additions & 0 deletions sdk/src/math/position.ts
Original file line number Diff line number Diff line change
Expand Up @@ -270,3 +270,11 @@ export function positionCurrentDirection(
export function isEmptyPosition(userPosition: PerpPosition): boolean {
return userPosition.baseAssetAmount.eq(ZERO) && userPosition.openOrders === 0;
}

export function hasOpenOrders(position: PerpPosition): boolean {
return (
position.openOrders != 0 ||
!position.openBids.eq(ZERO) ||
!position.openAsks.eq(ZERO)
);
}

0 comments on commit 3713c56

Please sign in to comment.