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
67 changes: 38 additions & 29 deletions modules/sdk-core/src/bitgo/defi/defiVault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,16 +158,10 @@ export class DefiVault implements IDefiVault {
* calls (approve + deposit) and returns the operationId that links them.
*/
private async depositToErc4626Vault(params: DepositToVaultOptions): Promise<Erc4626DepositResult> {
// TODO(CGD-1709): Re-enable active operation pre-flight check once the
// defi-service operations endpoint is deployed and returning active state.
// const activeOps: DefiOperationListResult = await this.bitgo
// .get(this.bitgo.microservicesUrl(this.operationsUrl()))
// .query({ vaultId: params.vaultId, state: 'active' })
// .result();
//
// if (activeOps.items && activeOps.items.length > 0) {
// throw new ActiveOperationExistsError(activeOps.items[0].operationId);
// }
// (The active-operation pre-flight check previously sketched here targeted a
// wallet-scoped operations route that does not exist and a 'active' state
// the API never returns. It is re-added correctly in the seamless-recovery
// work against the vault-scoped route with state: 'pending', type: 'DEPOSIT'.)

// Step 1: Approve txRequest via sendMany
const approveResult = await this.wallet.sendMany({
Expand Down Expand Up @@ -212,15 +206,21 @@ export class DefiVault implements IDefiVault {
* between the approve and deposit txRequest creation.
*
* @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)
* @param params.walletPassphrase - required for hot wallets, omit for custody
*/
async resumeDeposit(params: ResumeDepositOptions): Promise<DepositResult> {
if (!params.operationId) {
throw new Error('operationId is required');
if (!params.vaultId || !params.operationId) {
throw new Error('vaultId and operationId are required');
}

// Fetch the operation to get the vault and amount details
const operation = await this.getOperation({ operationId: params.operationId });
const operation = await this.getOperation({ vaultId: params.vaultId, operationId: params.operationId });

if (operation.vaultId !== params.vaultId) {
throw new Error(`operation ${params.operationId} does not belong to vault ${params.vaultId}`);
}

if (operation.associatedTxRequestId) {
throw new Error('Deposit txRequest already exists for this operation; nothing to resume');
Expand Down Expand Up @@ -251,49 +251,58 @@ export class DefiVault implements IDefiVault {
}

/**
* Get the current state of a DeFi operation.
* Get the current state of a DeFi operation from the vault-scoped
* defi-service route.
*
* @param params.vaultId - the vault the operation belongs to
* @param params.operationId - the operation to retrieve
*/
async getOperation(params: GetOperationOptions): Promise<DefiOperation> {
if (!params.operationId) {
throw new Error('operationId is required');
if (!params.vaultId || !params.operationId) {
throw new Error('vaultId and operationId are required');
}

return await this.bitgo.get(this.bitgo.microservicesUrl(this.operationsUrl() + '/' + params.operationId)).result();
return await this.bitgo
.get(this.bitgo.microservicesUrl(`${this.operationsUrl(params.vaultId)}/${params.operationId}`))
.set('enterprise-id', this.wallet.toJSON().enterprise)
.result();
}

/**
* List operations for a vault filtered by walletId.
* List operations for a vault from the vault-scoped defi-service route.
*
* @param params.vaultId - vault to list operations for
* @param params.state - optional state filter
* @param params.walletId - optional wallet filter
* @param params.state - optional state filter (pending | completed | cancelled)
* @param params.type - optional type filter (DEPOSIT | WITHDRAW)
* @param params.limit - page size
* @param params.cursor - pagination cursor
* @param params.nextCursor - pagination cursor from a previous response
*/
async listOperations(params: ListOperationsOptions): Promise<DefiOperationListResult> {
if (!params.vaultId) {
throw new Error('vaultId is required');
}

const query: Record<string, string | number> = {
vaultId: params.vaultId,
};
const query: Record<string, string | number> = {};
if (params.walletId) query.walletId = params.walletId;
if (params.state) query.state = params.state;
if (params.type) query.type = params.type;
if (params.limit) query.limit = params.limit;
if (params.cursor) query.cursor = params.cursor;
if (params.nextCursor) query.nextCursor = params.nextCursor;

return await this.bitgo.get(this.bitgo.microservicesUrl(this.operationsUrl())).query(query).result();
return await this.bitgo
.get(this.bitgo.microservicesUrl(this.operationsUrl(params.vaultId)))
.query(query)
.set('enterprise-id', this.wallet.toJSON().enterprise)
.result();
}

/**
* Withdraw vault shares from a DeFi vault.
*
* Issues a single sendMany call (defiWithdraw) and returns the operationId
* and txRequestId. The state machine for withdrawal is simpler than deposit:
* CREATED → WITHDRAW_TX_REQUESTED → WITHDRAW_SIGNED → WITHDRAW_CONFIRMED → COMPLETED
* and txRequestId. The operation the caller observes transitions through the
* API states `pending → completed | cancelled` (lowercase).
*
* @param params.vaultId - DeFi-service vault identifier
* @param params.amount - amount in base units of the vault share token
Expand Down Expand Up @@ -468,7 +477,7 @@ export class DefiVault implements IDefiVault {
};
}

private operationsUrl(): string {
return `/api/defi-service/v1/wallets/${this.wallet.id()}/operations`;
private operationsUrl(vaultId: string): string {
return `/api/defi-service/v1/vaults/${vaultId}/operations`;
}
}
22 changes: 16 additions & 6 deletions modules/sdk-core/src/bitgo/defi/iDefiVault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,33 +16,43 @@ export interface DepositToVaultOptions {
export interface ResumeDepositOptions {
/** operationId of the partially-completed deposit */
operationId: string;
/** vault the operation belongs to — required to fetch the operation from the vault-scoped route */
vaultId: string;
/** Wallet passphrase — required for hot wallets, omit for custody */
walletPassphrase?: string;
}

export interface GetOperationOptions {
/** DeFi-service vault identifier — required by the vault-scoped route */
vaultId: string;
operationId: string;
}

export interface ListOperationsOptions {
vaultId: string;
state?: string;
type?: string;
/** filter by wallet — the API accepts an optional walletId query param */
walletId?: string;
state?: DefiOperationState;
type?: 'DEPOSIT' | 'WITHDRAW';
limit?: number;
cursor?: string;
/** pagination cursor from a previous response's nextCursor */
nextCursor?: string;
}

export interface GetVaultConfigOptions {
vaultId: string;
}

/** defi-service operation states as returned by the public API (lowercase). */
export type DefiOperationState = 'pending' | 'completed' | 'cancelled';

export interface DefiOperation {
operationId: string;
walletId: string;
vaultId: string;
type: 'DEPOSIT' | 'WITHDRAW';
assetAmount: string;
state: string;
state: DefiOperationState;
txRequestId?: string;
associatedTxRequestId?: string;
createdAt: string;
Expand All @@ -68,8 +78,8 @@ export type MorphoDepositResult = Erc4626DepositResult;
export type DepositResult = ConcreteDepositResult | Erc4626DepositResult;

export interface DefiOperationListResult {
items: DefiOperation[];
nextCursor?: string;
operations: DefiOperation[];
nextCursor?: string | null;
}

export interface WithdrawFromVaultOptions {
Expand Down
103 changes: 77 additions & 26 deletions modules/sdk-core/test/unit/bitgo/defi/defiVault.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import assert from 'assert';
import 'should';
import { CoinFeature } from '@bitgo/statics';
import { VaultProtocol } from '@bitgo/public-types';
import { ActiveOperationExistsError, DefiVault, Wallet } from '../../../../src';
import { ActiveOperationExistsError, DefiVault, Erc4626DepositResult, Wallet } from '../../../../src';

describe('DefiVault', function () {
let wallet: Wallet;
Expand Down Expand Up @@ -584,7 +584,7 @@ describe('DefiVault', function () {
vaultId: 'vlt-galaxy-usdc',
type: 'DEPOSIT',
assetAmount: '1000000',
state: 'APPROVE_TX_REQUESTED',
state: 'pending',
txRequestId: 'txreq-approve-existing',
associatedTxRequestId: undefined,
createdAt: '2026-05-14T07:12:00Z',
Expand All @@ -604,14 +604,25 @@ describe('DefiVault', function () {
},
});

const result = await defiVault.resumeDeposit({ operationId: 'op-resume-1' });
const rawResult = await defiVault.resumeDeposit({ operationId: 'op-resume-1', vaultId: 'vlt-galaxy-usdc' });
// resumeDeposit's Erc4626 branch — the union result needs narrowing for property access.
const result = rawResult as Erc4626DepositResult;

(result as any).operationId.should.equal('op-resume-1');
(result as any).txRequestIds.approve.should.equal('txreq-approve-existing');
(result as any).txRequestIds.deposit.should.equal('txreq-deposit-resume');
result.operationId.should.equal('op-resume-1');
result.txRequestIds.approve.should.equal('txreq-approve-existing');
result.txRequestIds.deposit.should.equal('txreq-deposit-resume');

// getOperation must hit the vault-scoped route with the enterprise-id header
mockBitGo.get.firstCall.args[0].should.endWith(
'/api/defi-service/v1/vaults/vlt-galaxy-usdc/operations/op-resume-1'
);
getOpReq.set.firstCall.args.should.deepEqual(['enterprise-id', 'test-enterprise-id']);

// Verify sendMany was called with correct defiParams
const depositArgs: any = sendManyStub.firstCall.args[0];
const depositArgs = sendManyStub.firstCall.args[0] as
| { type: string; defiParams: { vaultId: string; amount: string; operationId: string } }
| undefined;
assert.ok(depositArgs, 'sendMany must have been called');
depositArgs.type.should.equal('defiDeposit');
depositArgs.defiParams.vaultId.should.equal('vlt-galaxy-usdc');
depositArgs.defiParams.amount.should.equal('1000000');
Expand All @@ -625,7 +636,7 @@ describe('DefiVault', function () {
vaultId: 'vlt-galaxy-usdc',
type: 'DEPOSIT',
assetAmount: '1000000',
state: 'DEPOSIT_TX_REQUESTED',
state: 'pending',
txRequestId: 'txreq-approve-x',
associatedTxRequestId: 'txreq-deposit-x',
createdAt: '2026-05-14T07:12:00Z',
Expand All @@ -635,25 +646,49 @@ describe('DefiVault', function () {
const getOpReq = mockRequest(operation);
mockBitGo.get.returns(getOpReq);

await assert.rejects(() => defiVault.resumeDeposit({ operationId: 'op-already-done' }), {
message: 'Deposit txRequest already exists for this operation; nothing to resume',
});
await assert.rejects(
() => defiVault.resumeDeposit({ operationId: 'op-already-done', vaultId: 'vlt-galaxy-usdc' }),
{ message: 'Deposit txRequest already exists for this operation; nothing to resume' }
);
});

it('should throw if operationId is missing', async function () {
await assert.rejects(() => defiVault.resumeDeposit({ operationId: '' }), { message: 'operationId is required' });
it('should throw if the operation belongs to a different vault', async function () {
const operation = {
operationId: 'op-other-vault',
walletId: 'test-wallet-id',
vaultId: 'vlt-other-usdc',
type: 'DEPOSIT',
assetAmount: '1000000',
state: 'pending',
txRequestId: 'txreq-approve-x',
createdAt: '2026-05-14T07:12:00Z',
updatedAt: '2026-05-14T07:12:00Z',
};

mockBitGo.get.returns(mockRequest(operation));

await assert.rejects(
() => defiVault.resumeDeposit({ operationId: 'op-other-vault', vaultId: 'vlt-galaxy-usdc' }),
{ message: 'operation op-other-vault does not belong to vault vlt-galaxy-usdc' }
);
});

it('should throw if vaultId or operationId is missing', async function () {
await assert.rejects(() => defiVault.resumeDeposit({ operationId: '', vaultId: '' }), {
message: 'vaultId and operationId are required',
});
});
});

describe('getOperation', function () {
it('should fetch an operation by ID', async function () {
it('should fetch an operation by ID from the vault-scoped route with the enterprise-id header', async function () {
const operation = {
operationId: 'op-get-1',
walletId: 'test-wallet-id',
vaultId: 'vlt-galaxy-usdc',
type: 'DEPOSIT',
assetAmount: '1000000',
state: 'COMPLETED',
state: 'completed',
txRequestId: 'txreq-1',
associatedTxRequestId: 'txreq-2',
createdAt: '2026-05-14T07:12:00Z',
Expand All @@ -663,26 +698,31 @@ describe('DefiVault', function () {
const req = mockRequest(operation);
mockBitGo.get.returns(req);

const result = await defiVault.getOperation({ operationId: 'op-get-1' });
const result = await defiVault.getOperation({ vaultId: 'vlt-galaxy-usdc', operationId: 'op-get-1' });
result.should.deepEqual(operation);

mockBitGo.get.firstCall.args[0].should.endWith('/api/defi-service/v1/vaults/vlt-galaxy-usdc/operations/op-get-1');
req.set.firstCall.args.should.deepEqual(['enterprise-id', 'test-enterprise-id']);
});

it('should throw if operationId is missing', async function () {
await assert.rejects(() => defiVault.getOperation({ operationId: '' }), { message: 'operationId is required' });
it('should throw if vaultId or operationId is missing', async function () {
await assert.rejects(() => defiVault.getOperation({ vaultId: '', operationId: '' }), {
message: 'vaultId and operationId are required',
});
});
});

describe('listOperations', function () {
it('should list operations for a vault', async function () {
it('should list operations for a vault from the vault-scoped route', async function () {
const listResult = {
items: [
operations: [
{
operationId: 'op-1',
walletId: 'test-wallet-id',
vaultId: 'vlt-galaxy-usdc',
type: 'DEPOSIT',
assetAmount: '1000000',
state: 'COMPLETED',
state: 'completed',
createdAt: '2026-05-14T07:12:00Z',
updatedAt: '2026-05-14T07:18:00Z',
},
Expand All @@ -695,18 +735,29 @@ describe('DefiVault', function () {

const result = await defiVault.listOperations({
vaultId: 'vlt-galaxy-usdc',
state: 'COMPLETED',
walletId: 'test-wallet-id',
state: 'pending',
type: 'DEPOSIT',
limit: 10,
nextCursor: 'cursor-abc',
});

result.items.length.should.equal(1);
result.operations.length.should.equal(1);
result.operations[0].state.should.equal('completed');
result.nextCursor!.should.equal('cursor-abc');

// Verify query params
// vaultId moves from the query into the path
mockBitGo.get.firstCall.args[0].should.endWith('/api/defi-service/v1/vaults/vlt-galaxy-usdc/operations');
req.set.firstCall.args.should.deepEqual(['enterprise-id', 'test-enterprise-id']);

// Verify query params — nextCursor (not cursor), no vaultId in the query
const queryArgs = req.query.firstCall.args[0];
queryArgs.vaultId.should.equal('vlt-galaxy-usdc');
queryArgs.state.should.equal('COMPLETED');
queryArgs.should.not.have.property('vaultId');
queryArgs.walletId.should.equal('test-wallet-id');
queryArgs.state.should.equal('pending');
queryArgs.type.should.equal('DEPOSIT');
queryArgs.limit.should.equal(10);
queryArgs.nextCursor.should.equal('cursor-abc');
});

it('should throw if vaultId is missing', async function () {
Expand Down