Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sdk: add isUserBankrupt #399

Merged
merged 3 commits into from
Mar 20, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
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)
);
}