-
Notifications
You must be signed in to change notification settings - Fork 306
feat(sdk-core): pre-flight balance check for depositToVault #9293
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
Open
bitgo-ai-agent-dev
wants to merge
1
commit into
master
Choose a base branch
from
DEFI-371-pre-flight-balance-check-deposit
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+208
−14
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,7 @@ | ||
| /** | ||
| * @prettier | ||
| */ | ||
| import BigNumber from 'bignumber.js'; | ||
| import * as t from 'io-ts'; | ||
| import { GetVaultResponse, VaultProtocol } from '@bitgo/public-types'; | ||
| import { | ||
|
|
@@ -35,6 +36,24 @@ export class ActiveOperationExistsError extends Error { | |
| } | ||
| } | ||
|
|
||
| /** | ||
| * Error thrown when the wallet does not hold sufficient balance of the underlying asset | ||
| * to cover the requested deposit amount. | ||
| */ | ||
| export class InsufficientBalanceError extends Error { | ||
| public readonly assetToken: string; | ||
| public readonly available: string; | ||
| public readonly requested: string; | ||
|
|
||
| constructor(assetToken: string, available: string, requested: string) { | ||
| super(`Insufficient ${assetToken} balance: requested ${requested}, available ${available}`); | ||
| this.name = 'InsufficientBalanceError'; | ||
| this.assetToken = assetToken; | ||
| this.available = available; | ||
| this.requested = requested; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Orchestrates ERC-4626 vault deposit and withdraw flows for a wallet. | ||
| * | ||
|
|
@@ -90,6 +109,8 @@ export class DefiVault implements IDefiVault { | |
|
|
||
| const config = await this.getVaultConfig({ vaultId: params.vaultId }); | ||
|
|
||
| await this.assertSufficientAssetBalance(config, params.amount); | ||
|
|
||
| if (config.protocol === VaultProtocol.CONCRETE_BTCCX) { | ||
| return this.depositToConcreteVault(params); | ||
| } else if (config.protocol === VaultProtocol.MORPHO) { | ||
|
|
@@ -293,6 +314,45 @@ export class DefiVault implements IDefiVault { | |
|
|
||
| // ── Internal helpers ──────────────────────────────────────────────── | ||
|
|
||
| /** | ||
| * Fetch a fresh wallet snapshot and assert the spendable balance of | ||
| * `config.assetToken` is at least `amount` (base units). | ||
| * | ||
| * Fetches with `?allTokens=true` so ERC-20 token balances are included. | ||
| * When `config.assetToken` equals the wallet's native coin (e.g. BTC on a | ||
| * BTC wallet), the top-level `spendableBalanceString` is used directly. | ||
| * Otherwise the `tokens` array is searched for an entry whose `tokenName` | ||
| * matches `config.assetToken`. | ||
| * | ||
| * Throws {@link InsufficientBalanceError} on insufficient balance and | ||
| * propagates network errors as-is. | ||
| */ | ||
| private async assertSufficientAssetBalance(config: GetVaultResponse, amount: string): Promise<void> { | ||
| const walletData: Record<string, any> = await this.bitgo.get(this.wallet.url()).query({ allTokens: true }).result(); | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is there no better typing for the |
||
|
|
||
| const assetToken = config.assetToken; | ||
| const walletCoin = config.coin; | ||
|
|
||
| let spendableBalance: string; | ||
|
|
||
| if (assetToken === walletCoin) { | ||
| // Native coin (e.g. BTC on a BTC wallet) | ||
| spendableBalance = (walletData.spendableBalanceString as string | undefined) ?? '0'; | ||
| } else { | ||
| // ERC-20 or other token — look in the tokens array | ||
| const tokens: Record<string, any>[] = Array.isArray(walletData.tokens) ? walletData.tokens : []; | ||
| const tokenEntry = tokens.find((t) => t.tokenName === assetToken); | ||
| spendableBalance = (tokenEntry?.spendableBalanceString as string | undefined) ?? '0'; | ||
| } | ||
|
|
||
| const available = new BigNumber(spendableBalance); | ||
| const requested = new BigNumber(amount); | ||
|
|
||
| if (requested.isGreaterThan(available)) { | ||
| throw new InsufficientBalanceError(assetToken, spendableBalance, amount); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Extract txRequestId from a sendMany result. | ||
| * sendMany returns different shapes depending on wallet type: | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,2 @@ | ||
| export * from './iDefiVault'; | ||
| export { DefiVault, ActiveOperationExistsError } from './defiVault'; | ||
| export { DefiVault, ActiveOperationExistsError, InsufficientBalanceError } from './defiVault'; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
nit - consider moving this to an error.ts file