diff --git a/modules/sdk-core/src/bitgo/defi/defiVault.ts b/modules/sdk-core/src/bitgo/defi/defiVault.ts index 465d5bb5b5..e9a0f54a73 100644 --- a/modules/sdk-core/src/bitgo/defi/defiVault.ts +++ b/modules/sdk-core/src/bitgo/defi/defiVault.ts @@ -23,6 +23,7 @@ import { } from './iDefiVault'; import { IWallet } from '../wallet'; import { BitGoBase } from '../bitgoBase'; +import { ApiResponseError } from '../errors'; import { decodeWithCodec } from '../utils'; /** @@ -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. * @@ -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 { @@ -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> { + 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 | 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 @@ -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) @@ -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; + 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); diff --git a/modules/sdk-core/src/bitgo/defi/iDefiVault.ts b/modules/sdk-core/src/bitgo/defi/iDefiVault.ts index 77657a3994..d0b3d55444 100644 --- a/modules/sdk-core/src/bitgo/defi/iDefiVault.ts +++ b/modules/sdk-core/src/bitgo/defi/iDefiVault.ts @@ -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 }; } diff --git a/modules/sdk-core/src/bitgo/defi/index.ts b/modules/sdk-core/src/bitgo/defi/index.ts index 8569663eeb..2f7ead9d48 100644 --- a/modules/sdk-core/src/bitgo/defi/index.ts +++ b/modules/sdk-core/src/bitgo/defi/index.ts @@ -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'; diff --git a/modules/sdk-core/test/unit/bitgo/defi/defiVault.ts b/modules/sdk-core/test/unit/bitgo/defi/defiVault.ts index 38b1c37d24..c80e1a1777 100644 --- a/modules/sdk-core/test/unit/bitgo/defi/defiVault.ts +++ b/modules/sdk-core/test/unit/bitgo/defi/defiVault.ts @@ -3,7 +3,14 @@ import assert from 'assert'; import 'should'; import { CoinFeature } from '@bitgo/statics'; import { VaultProtocol } from '@bitgo/public-types'; -import { ActiveOperationExistsError, DefiVault, Erc4626DepositResult, Wallet } from '../../../../src'; +import { + ActiveOperationExistsError, + ApiResponseError, + DepositStoppedForApproveApprovalError, + DefiVault, + Erc4626DepositResult, + Wallet, +} from '../../../../src'; describe('DefiVault', function () { let wallet: Wallet; @@ -501,6 +508,11 @@ describe('DefiVault', function () { activeErr.operationId.should.equal('existing-op-id'); activeErr.vaultId.should.equal('vlt-galaxy-usdc'); activeErr.assetAmount.should.equal('1000000'); + // Back-compat guard: the in-flight stop is the base class only — + // callers must not render the approve-PA screen for it, and it + // carries no approve pending approval. + (err instanceof DepositStoppedForApproveApprovalError).should.be.false(); + assert.strictEqual((err as DepositStoppedForApproveApprovalError).approvePendingApprovalId, undefined); return true; } ); @@ -579,6 +591,159 @@ describe('DefiVault', function () { }); }); + describe('deposit stopped by an open approve PA (D7)', function () { + const d7StopMessage = + 'DeFi deposit stopped until the approve leg signs: the approve leg has an unresolved approval'; + + it('maps the stop to DepositStoppedForApproveApprovalError carrying the operation context', async function () { + mockVaultGetWithNoActiveOperations(makeMorphoVault('vlt-galaxy-usdc')); + + const operationId = 'op-uuid-d7-stop'; + const sendManyStub = sinon.stub(wallet, 'sendMany'); + // The approve leg is created but policy-gated: it carries the operationId. + sendManyStub.onFirstCall().resolves({ + pendingApproval: { id: 'pa-approve-d7' }, + txRequest: { + txRequestId: 'txreq-approve-d7', + intent: { intentType: 'defi-approve' }, + transactions: [{ unsignedTx: { coinSpecific: { operationId } } }], + }, + }); + // WP refuses the deposit create while the approve PA is open (D7 stop): + // machine-readable code in the body, human phrase in the message. + const original409 = new ApiResponseError(d7StopMessage, 409, { code: 'defi_deposit_stopped_approve_pa' }); + sendManyStub.onSecondCall().rejects(original409); + + let caught: unknown; + try { + await defiVault.depositToVault({ vaultId: 'vlt-galaxy-usdc', amount: '1000000' }); + } catch (e) { + caught = e; + } + // The subclass is the discriminator for callers: render the + // approve-PA screen, do not auto-resume. The base class still + // matches, so existing catch blocks keep working. + assert.ok(caught instanceof DepositStoppedForApproveApprovalError); + assert.ok(caught instanceof ActiveOperationExistsError); + const stopError = caught as DepositStoppedForApproveApprovalError; + stopError.operationId.should.equal(operationId); + stopError.vaultId.should.equal('vlt-galaxy-usdc'); + stopError.assetAmount.should.equal('1000000'); + stopError.approvePendingApprovalId!.should.equal('pa-approve-d7'); + // The message describes the stop (not the inherited "already + // exists" text), and the original 409 rides along as cause for + // WP log correlation via its requestId. + stopError.message.should.equal(`DeFi deposit stopped until the approve leg signs (operation ${operationId})`); + assert.strictEqual(stopError.cause, original409); + }); + + it('detects the stop by the machine-readable result.code alone (message without the fragment)', async function () { + mockVaultGetWithNoActiveOperations(makeMorphoVault('vlt-galaxy-usdc')); + + const operationId = 'op-uuid-d7-code-only'; + const sendManyStub = sinon.stub(wallet, 'sendMany'); + sendManyStub.onFirstCall().resolves({ + txRequest: { + txRequestId: 'txreq-approve-d7-code', + intent: { intentType: 'defi-approve' }, + transactions: [{ unsignedTx: { coinSpecific: { operationId } } }], + }, + }); + // The authoritative signal is the body code; the human message here + // deliberately lacks the fallback fragment, so only the code can match. + sendManyStub + .onSecondCall() + .rejects( + new ApiResponseError('deposit create refused by policy', 409, { code: 'defi_deposit_stopped_approve_pa' }) + ); + + let caught: unknown; + try { + await defiVault.depositToVault({ vaultId: 'vlt-galaxy-usdc', amount: '1000000' }); + } catch (e) { + caught = e; + } + assert.ok(caught instanceof DepositStoppedForApproveApprovalError); + (caught as DepositStoppedForApproveApprovalError).operationId.should.equal(operationId); + }); + + it('falls back to the stable message fragment when the 409 body carries no result.code', async function () { + mockVaultGetWithNoActiveOperations(makeMorphoVault('vlt-galaxy-usdc')); + + const operationId = 'op-uuid-d7-fragment-only'; + const sendManyStub = sinon.stub(wallet, 'sendMany'); + sendManyStub.onFirstCall().resolves({ + txRequest: { + txRequestId: 'txreq-approve-d7-frag', + intent: { intentType: 'defi-approve' }, + transactions: [{ unsignedTx: { coinSpecific: { operationId } } }], + }, + }); + // Body without the code field — the message fragment is the + // secondary detection signal and must carry the match alone. + sendManyStub.onSecondCall().rejects(new ApiResponseError(d7StopMessage, 409)); + + let caught: unknown; + try { + await defiVault.depositToVault({ vaultId: 'vlt-galaxy-usdc', amount: '1000000' }); + } catch (e) { + caught = e; + } + assert.ok(caught instanceof DepositStoppedForApproveApprovalError); + (caught as DepositStoppedForApproveApprovalError).operationId.should.equal(operationId); + }); + + it('propagates a non-409 error carrying the stop code unchanged', async function () { + mockVaultGetWithNoActiveOperations(makeMorphoVault('vlt-galaxy-usdc')); + + const sendManyStub = sinon.stub(wallet, 'sendMany'); + sendManyStub.onFirstCall().resolves({ + txRequest: { + txRequestId: 'txreq-approve-d7c', + intent: { intentType: 'defi-approve' }, + transactions: [{ unsignedTx: { coinSpecific: { operationId: 'op-uuid-d7c' } } }], + }, + }); + // The stop is a 409 Conflict contract: the same code surfacing on any + // other status must not map to the D7 subclass. + const serverError = new ApiResponseError('internal error wrapping the stop', 500, { + code: 'defi_deposit_stopped_approve_pa', + }); + sendManyStub.onSecondCall().rejects(serverError); + + let caught: unknown; + try { + await defiVault.depositToVault({ vaultId: 'vlt-galaxy-usdc', amount: '1000000' }); + } catch (e) { + caught = e; + } + assert.strictEqual(caught, serverError); + }); + + it('propagates an unrelated 409 unchanged', async function () { + mockVaultGetWithNoActiveOperations(makeMorphoVault('vlt-galaxy-usdc')); + + const sendManyStub = sinon.stub(wallet, 'sendMany'); + sendManyStub.onFirstCall().resolves({ + txRequest: { + txRequestId: 'txreq-approve-d7b', + intent: { intentType: 'defi-approve' }, + transactions: [{ unsignedTx: { coinSpecific: { operationId: 'op-uuid-d7b' } } }], + }, + }); + const unrelated = new ApiResponseError('some other wallet conflict', 409); + sendManyStub.onSecondCall().rejects(unrelated); + + let caught: unknown; + try { + await defiVault.depositToVault({ vaultId: 'vlt-galaxy-usdc', amount: '1000000' }); + } catch (e) { + caught = e; + } + assert.strictEqual(caught, unrelated); + }); + }); + describe('aave_v3 provider', function () { it('should call sendMany for approve and deposit on happy path', async function () { mockVaultGetWithNoActiveOperations(makeAaveVault('vlt-aave-usdc')); @@ -735,6 +900,7 @@ describe('DefiVault', function () { result.operationId.should.equal('op-resume-1'); result.txRequestIds.approve.should.equal('txreq-approve-existing'); + assert.ok(result.txRequestIds.deposit, 'deposit leg must exist on a fully resumed operation'); result.txRequestIds.deposit.should.equal('txreq-deposit-resume'); result.pendingApprovalIds!.deposit!.should.equal('pa-deposit-resume'); @@ -755,6 +921,108 @@ describe('DefiVault', function () { depositArgs.defiParams.operationId.should.equal('op-resume-1'); }); + it('forwards the wallet passphrase to the resumed deposit-leg sendMany', async function () { + const operation = { + operationId: 'op-resume-pw', + walletId: 'test-wallet-id', + vaultId: 'vlt-galaxy-usdc', + type: 'DEPOSIT', + assetAmount: '1000000', + state: 'pending', + txRequestId: undefined, + associatedTxRequestId: 'txreq-approve-pw', + createdAt: '2026-05-14T07:12:00Z', + updatedAt: '2026-05-14T07:12:00Z', + }; + mockBitGo.get.returns(mockRequest(operation)); + + const sendManyStub = sinon.stub(wallet, 'sendMany').resolves({ + txRequest: { + txRequestId: 'txreq-deposit-pw', + intent: { intentType: 'defi-deposit', operationId: 'op-resume-pw' }, + }, + }); + + await defiVault.resumeDeposit({ + operationId: 'op-resume-pw', + vaultId: 'vlt-galaxy-usdc', + walletPassphrase: 'hunter2', + }); + + // The resumed deposit leg must carry the passphrase: without it a + // hot wallet cannot TSS-sign the created leg (review finding). + const depositArgs = sendManyStub.firstCall.args[0] as { walletPassphrase?: string } | undefined; + assert.ok(depositArgs, 'sendMany must have been called'); + depositArgs.walletPassphrase!.should.equal('hunter2'); + }); + + it('returns the approve-only state when the deposit create is stopped by an open approve PA (D7)', async function () { + const operation = { + operationId: 'op-resume-d7', + walletId: 'test-wallet-id', + vaultId: 'vlt-galaxy-usdc', + type: 'DEPOSIT', + assetAmount: '1000000', + state: 'pending', + txRequestId: undefined, + associatedTxRequestId: 'txreq-approve-existing', + createdAt: '2026-05-14T07:12:00Z', + updatedAt: '2026-05-14T07:12:00Z', + }; + mockBitGo.get.returns(mockRequest(operation)); + + // WP refuses the deposit create while the approve leg has an open PA. + const sendManyStub = sinon.stub(wallet, 'sendMany'); + sendManyStub.rejects( + new ApiResponseError( + 'DeFi deposit stopped until the approve leg signs: the approve leg has an unresolved approval', + 409, + { code: 'defi_deposit_stopped_approve_pa' } + ) + ); + + const rawResult = await defiVault.resumeDeposit({ operationId: 'op-resume-d7', vaultId: 'vlt-galaxy-usdc' }); + const result = rawResult as Erc4626DepositResult; + + // The stop reads as "not yet", not an error: the approve leg is + // returned, the absent deposit leg signals "resume again after the + // approve signs". + result.operationId.should.equal('op-resume-d7'); + result.txRequestIds.approve.should.equal('txreq-approve-existing'); + assert.strictEqual(result.txRequestIds.deposit, undefined); + result.should.not.have.property('pendingApprovalIds'); + }); + + it('propagates an unrelated deposit-leg error instead of masking it as the approve-only state', async function () { + const operation = { + operationId: 'op-resume-unrelated', + walletId: 'test-wallet-id', + vaultId: 'vlt-galaxy-usdc', + type: 'DEPOSIT', + assetAmount: '1000000', + state: 'pending', + txRequestId: undefined, + associatedTxRequestId: 'txreq-approve-unrelated', + createdAt: '2026-05-14T07:12:00Z', + updatedAt: '2026-05-14T07:12:00Z', + }; + mockBitGo.get.returns(mockRequest(operation)); + + // Only the D7 stop maps to the approve-only state; an unrelated 409 + // (or any other error) must surface to the caller unchanged. + const unrelated = new ApiResponseError('some other wallet conflict', 409); + const sendManyStub = sinon.stub(wallet, 'sendMany'); + sendManyStub.rejects(unrelated); + + let caught: unknown; + try { + await defiVault.resumeDeposit({ operationId: 'op-resume-unrelated', vaultId: 'vlt-galaxy-usdc' }); + } catch (e) { + caught = e; + } + assert.strictEqual(caught, unrelated); + }); + it('should return the existing legs without issuing a new deposit when the operation is fully created', async function () { const operation = { operationId: 'op-already-done', @@ -778,6 +1046,7 @@ describe('DefiVault', function () { result.operationId.should.equal('op-already-done'); result.txRequestIds.approve.should.equal('txreq-approve-x'); + assert.ok(result.txRequestIds.deposit, 'deposit leg must exist on a fully created operation'); result.txRequestIds.deposit.should.equal('txreq-deposit-x'); // The fully-created path carries no pending-approval ids — the operation // record has none; callers discover PAs via the wallet's approval listing.