Skip to content
Draft
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
155 changes: 136 additions & 19 deletions modules/sdk-core/src/bitgo/defi/defiVault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
} from './iDefiVault';
import { IWallet } from '../wallet';
import { BitGoBase } from '../bitgoBase';
import { ApiResponseError } from '../errors';
import { decodeWithCodec } from '../utils';

/**
Expand Down Expand Up @@ -69,6 +70,58 @@ export class ActiveOperationExistsError extends Error {
}
}

/**
* The D7 create-time stop: Wallet Platform refused the deposit-leg create
* because the operation's approve leg still has an unresolved pending
* approval (hot wallets). The deposit cannot exist until the approve PA is
* approved and the approve transaction is signed — render the approve
* approval state, do **not** auto-resume yet.
*
* Extends {@link ActiveOperationExistsError} so existing catch blocks keep
* working; narrow with `instanceof DepositStoppedForApproveApprovalError`
* for the explicit approve-PA screen.
*/
export class DepositStoppedForApproveApprovalError extends ActiveOperationExistsError {
/** The approve leg's pending approval id — the approval the user must grant. */
public readonly approvePendingApprovalId?: string;
/** The original 409 response error, preserved for WP log correlation via its requestId. */
public readonly cause?: unknown;

constructor(params: {
operationId: string;
vaultId: string;
assetAmount: string;
approvePendingApprovalId?: string;
/** The original 409, preserved for WP log correlation via its requestId. */
cause?: unknown;
}) {
super(params);
this.name = 'DepositStoppedForApproveApprovalError';
this.approvePendingApprovalId = params.approvePendingApprovalId;
this.message = `DeFi deposit stopped until the approve leg signs (operation ${params.operationId})`;
this.cause = params.cause;
}
}

/**
* Machine-readable error code Wallet Platform embeds in the 409 Conflict
* body when the D7 create-time stop refuses a hot-wallet deposit create
* (`result.code`). The stable contract between WP (DEFI-1511) and this SDK —
* to be promoted into `@bitgo/public-types` when WP implements the stop so
* both sides are compile-time checked against the same constant.
*/
export const DEPOSIT_STOPPED_APPROVE_PA_ERROR_CODE = 'defi_deposit_stopped_approve_pa';

/**
* Stable message fragment Wallet Platform embeds in the 409 body's `error`
* message field — the source of the SDK's `ApiResponseError.message`
* (createResponseErrorString) — when the D7 create-time stop refuses a
* hot-wallet deposit create. Secondary detection only: the authoritative
* match is {@link DEPOSIT_STOPPED_APPROVE_PA_ERROR_CODE} in the response
* body; this fragment covers error bodies without the code field.
*/
export const DEPOSIT_STOPPED_FOR_OPEN_APPROVE_PA = 'DeFi deposit stopped until the approve leg signs';

/**
* Orchestrates ERC-4626 vault deposit and withdraw flows for a wallet.
*
Expand Down Expand Up @@ -221,23 +274,15 @@ export class DefiVault implements IDefiVault {

const approveTxRequestId = this.extractTxRequestId(approveResult);
const operationId = this.extractOperationId(approveResult);
const approvePendingApprovalId = this.extractPendingApprovalId(approveResult);

if (!operationId) {
throw new Error('operationId not found in approve txRequest response');
}

// Step 2: Deposit txRequest via sendMany
const depositResult = await this.wallet.sendMany({
type: 'defiDeposit',
defiParams: {
vaultId: params.vaultId,
amount: params.amount,
operationId,
},
...(params.walletPassphrase ? { walletPassphrase: params.walletPassphrase } : {}),
});
const depositResult = await this.sendDepositLeg(params, operationId, approvePendingApprovalId);
const depositTxRequestId = this.extractTxRequestId(depositResult);
const approvePendingApprovalId = this.extractPendingApprovalId(approveResult);
const depositPendingApprovalId = this.extractPendingApprovalId(depositResult);

return {
Expand All @@ -255,6 +300,55 @@ export class DefiVault implements IDefiVault {
};
}

/**
* Issue the deposit leg of an erc4626 deposit. When Wallet Platform
* refuses the create because the operation's approve leg has an
* unresolved approval (hot wallets — the "D7" create-time stop in the
* self-custody TDD), maps that one error to the typed
* {@link DepositStoppedForApproveApprovalError} so callers render the
* approve-approval state instead of surfacing a raw 409. Unrelated
* errors propagate unchanged.
*/
private async sendDepositLeg(
params: DepositToVaultOptions,
operationId: string,
approvePendingApprovalId?: string
): Promise<Record<string, unknown>> {
try {
return await this.wallet.sendMany({
type: 'defiDeposit',
defiParams: {
vaultId: params.vaultId,
amount: params.amount,
operationId,
},
...(params.walletPassphrase ? { walletPassphrase: params.walletPassphrase } : {}),
});
} catch (e) {
// The create-time stop: WP refuses the deposit create while the
// operation's approve leg has an unresolved approval (hot wallets).
// Detection is the machine-readable code in the response body
// first, the stable message fragment second (bodies without the
// code field).
const result = e instanceof ApiResponseError ? (e.result as Record<string, unknown> | undefined) : undefined;
const isDepositStoppedForApproveApproval =
e instanceof ApiResponseError &&
e.status === 409 &&
(result?.code === DEPOSIT_STOPPED_APPROVE_PA_ERROR_CODE ||
e.message.includes(DEPOSIT_STOPPED_FOR_OPEN_APPROVE_PA));
if (isDepositStoppedForApproveApproval) {
throw new DepositStoppedForApproveApprovalError({
operationId,
vaultId: params.vaultId,
assetAmount: params.amount,
approvePendingApprovalId,
cause: e,
});
}
throw e;
}
}

/**
* Resume a partially-completed deposit. Call this when the SDK process died
* between the approve and deposit txRequest creation, or catch
Expand All @@ -272,6 +366,12 @@ export class DefiVault implements IDefiVault {
* `pendingApprovalIds` are returned even when the legs are gated; callers
* discover pending approvals via the wallet's pending-approval listing.
*
* Convergence loop under the D7 stop (hot wallets): while the approve leg
* is not signed-or-later — an open PA, or approved-but-unsigned — resume
* returns the approve-only state (no `txRequestIds.deposit`) instead of
* throwing. Sign the approve, then resume again: the deposit leg is
* created once the approve is signed-or-later.
*
* @param params.operationId - the operationId from the original depositToVault call
* @param params.vaultId - the vault the operation belongs to (from the original call
* or from ActiveOperationExistsError)
Expand Down Expand Up @@ -322,15 +422,32 @@ export class DefiVault implements IDefiVault {
}

// Issue the deposit txRequest using the existing operation's details
const depositResult = await this.wallet.sendMany({
type: 'defiDeposit',
defiParams: {
vaultId: operation.vaultId,
amount: operation.assetAmount,
operationId: params.operationId,
},
...(params.walletPassphrase ? { walletPassphrase: params.walletPassphrase } : {}),
});
let depositResult: Record<string, unknown>;
try {
depositResult = await this.sendDepositLeg(
{
vaultId: operation.vaultId,
amount: operation.assetAmount,
walletPassphrase: params.walletPassphrase,
},
params.operationId
);
} catch (e) {
// D7 stop: the approve leg is not signed-or-later yet (an open PA is
// the concrete case), so the deposit cannot exist. Treat the stop as
// "not yet", not an error: return the current state — approve leg
// only — so the caller signs the approve and resumes again. Any other
// error still propagates.
if (e instanceof DepositStoppedForApproveApprovalError) {
return {
operationId: params.operationId,
txRequestIds: {
approve: approveTxRequestId,
},
};
}
throw e;
}

const depositPendingApprovalId = this.extractPendingApprovalId(depositResult);

Expand Down
3 changes: 2 additions & 1 deletion modules/sdk-core/src/bitgo/defi/iDefiVault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ export interface ConcreteDepositResult {

export interface Erc4626DepositResult {
operationId: string;
txRequestIds: { approve: string; deposit: string };
/** The deposit leg id; absent when the deposit leg has not been issued yet — a gated approve stops its creation (D7); resume again once the approve signs. */
txRequestIds: { approve: string; deposit?: string };
/** Set when a wallet policy gated the legs; ids of the legs' pending approvals. */
pendingApprovalIds?: { approve?: string; deposit?: string };
}
Expand Down
8 changes: 7 additions & 1 deletion modules/sdk-core/src/bitgo/defi/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,8 @@
export * from './iDefiVault';
export { DefiVault, ActiveOperationExistsError } from './defiVault';
export {
DefiVault,
ActiveOperationExistsError,
DepositStoppedForApproveApprovalError,
DEPOSIT_STOPPED_APPROVE_PA_ERROR_CODE,
DEPOSIT_STOPPED_FOR_OPEN_APPROVE_PA,
} from './defiVault';
Loading
Loading