|
| 1 | +/** |
| 2 | + * @prettier |
| 3 | + */ |
| 4 | +import { |
| 5 | + DefiOperation, |
| 6 | + DefiOperationListResult, |
| 7 | + DepositResult, |
| 8 | + DepositToVaultOptions, |
| 9 | + GetOperationOptions, |
| 10 | + IDefiVault, |
| 11 | + ListOperationsOptions, |
| 12 | + ResumeDepositOptions, |
| 13 | +} from './iDefiVault'; |
| 14 | +import { IWallet } from '../wallet'; |
| 15 | +import { BitGoBase } from '../bitgoBase'; |
| 16 | + |
| 17 | +/** |
| 18 | + * Error thrown when a concurrent active deposit already exists for the (wallet, vault) pair. |
| 19 | + */ |
| 20 | +export class ActiveOperationExistsError extends Error { |
| 21 | + public readonly operationId: string; |
| 22 | + |
| 23 | + constructor(operationId: string) { |
| 24 | + super(`An active deposit operation already exists: ${operationId}`); |
| 25 | + this.name = 'ActiveOperationExistsError'; |
| 26 | + this.operationId = operationId; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +/** |
| 31 | + * Orchestrates ERC-4626 vault deposit and withdraw flows for a wallet. |
| 32 | + * |
| 33 | + * Exposed as `wallet.defi` on the Wallet class. See TDD §6.3.1 for the full |
| 34 | + * design: the SDK sequences two txRequest-create calls (approve + deposit) and |
| 35 | + * returns an operationId that the UI uses for status tracking and recovery. |
| 36 | + */ |
| 37 | +export class DefiVault implements IDefiVault { |
| 38 | + private readonly wallet: IWallet; |
| 39 | + private readonly bitgo: BitGoBase; |
| 40 | + |
| 41 | + constructor(wallet: IWallet) { |
| 42 | + this.wallet = wallet; |
| 43 | + this.bitgo = wallet.bitgo; |
| 44 | + } |
| 45 | + |
| 46 | + /** |
| 47 | + * Deposit an amount of underlying asset into a vault. |
| 48 | + * |
| 49 | + * Internally creates two txRequests (approve + deposit) and returns the |
| 50 | + * operationId that links them. If the deposit txRequest creation fails after |
| 51 | + * the approve succeeds, the approve is auto-cancelled (fail-fast). |
| 52 | + * |
| 53 | + * @param params.vaultId - DeFi-service vault identifier |
| 54 | + * @param params.amount - amount in base units of the underlying asset |
| 55 | + * @param params.clientIdempotencyKey - optional client idempotency key |
| 56 | + */ |
| 57 | + async depositToVault(params: DepositToVaultOptions): Promise<DepositResult> { |
| 58 | + if (!params.vaultId) { |
| 59 | + throw new Error('vaultId is required'); |
| 60 | + } |
| 61 | + if (!params.amount) { |
| 62 | + throw new Error('amount is required'); |
| 63 | + } |
| 64 | + |
| 65 | + // Layer-1 pre-flight: reject if an active deposit already exists for this (wallet, vault) |
| 66 | + const activeOps: DefiOperationListResult = await this.bitgo |
| 67 | + .get(this.bitgo.microservicesUrl(this.operationsUrl())) |
| 68 | + .query({ vaultId: params.vaultId, state: 'active' }) |
| 69 | + .result(); |
| 70 | + |
| 71 | + if (activeOps.items && activeOps.items.length > 0) { |
| 72 | + throw new ActiveOperationExistsError(activeOps.items[0].operationId); |
| 73 | + } |
| 74 | + |
| 75 | + // Step 1: Create approve txRequest |
| 76 | + const approveIntent = { |
| 77 | + intentType: 'defi-approve', |
| 78 | + vaultId: params.vaultId, |
| 79 | + amount: params.amount, |
| 80 | + ...(params.clientIdempotencyKey ? { clientIdempotencyKey: params.clientIdempotencyKey } : {}), |
| 81 | + }; |
| 82 | + |
| 83 | + const approveTxRequest = await this.createTxRequest(approveIntent); |
| 84 | + const operationId = (approveTxRequest.intent as Record<string, unknown>)?.operationId as string; |
| 85 | + const approveTxRequestId = approveTxRequest.txRequestId; |
| 86 | + |
| 87 | + if (!operationId) { |
| 88 | + throw new Error('operationId not found in approve txRequest response'); |
| 89 | + } |
| 90 | + |
| 91 | + // Step 2: Create deposit txRequest |
| 92 | + // On failure, auto-cancel the approve txRequest (fail-fast per TDD §6.3.1) |
| 93 | + let depositTxRequestId: string; |
| 94 | + try { |
| 95 | + const depositIntent = { |
| 96 | + intentType: 'defi-deposit', |
| 97 | + vaultId: params.vaultId, |
| 98 | + amount: params.amount, |
| 99 | + operationId, |
| 100 | + ...(params.clientIdempotencyKey ? { clientIdempotencyKey: params.clientIdempotencyKey } : {}), |
| 101 | + }; |
| 102 | + |
| 103 | + const depositTxRequest = await this.createTxRequest(depositIntent); |
| 104 | + depositTxRequestId = depositTxRequest.txRequestId; |
| 105 | + } catch (err) { |
| 106 | + // Fail-fast: cancel the approve txRequest before throwing |
| 107 | + try { |
| 108 | + await this.cancelTxRequest(approveTxRequestId); |
| 109 | + } catch { |
| 110 | + // Best-effort cancel; the reconciler will clean up if this fails |
| 111 | + } |
| 112 | + throw err; |
| 113 | + } |
| 114 | + |
| 115 | + return { |
| 116 | + operationId, |
| 117 | + txRequestIds: { |
| 118 | + approve: approveTxRequestId, |
| 119 | + deposit: depositTxRequestId, |
| 120 | + }, |
| 121 | + }; |
| 122 | + } |
| 123 | + |
| 124 | + /** |
| 125 | + * Resume a partially-completed deposit. Call this when the SDK process died |
| 126 | + * between the approve and deposit txRequest creation. |
| 127 | + * |
| 128 | + * @param params.operationId - the operationId from the original depositToVault call |
| 129 | + */ |
| 130 | + async resumeDeposit(params: ResumeDepositOptions): Promise<DepositResult> { |
| 131 | + if (!params.operationId) { |
| 132 | + throw new Error('operationId is required'); |
| 133 | + } |
| 134 | + |
| 135 | + // Fetch the operation to get the vault and amount details |
| 136 | + const operation = await this.getOperation({ operationId: params.operationId }); |
| 137 | + |
| 138 | + if (operation.associatedTxRequestId) { |
| 139 | + throw new Error('Deposit txRequest already exists for this operation; nothing to resume'); |
| 140 | + } |
| 141 | + |
| 142 | + if (!operation.txRequestId) { |
| 143 | + throw new Error('Approve txRequest not found for this operation; cannot resume'); |
| 144 | + } |
| 145 | + |
| 146 | + // Issue the deposit txRequest using the existing operation's details |
| 147 | + const depositIntent = { |
| 148 | + intentType: 'defi-deposit', |
| 149 | + vaultId: operation.vaultId, |
| 150 | + amount: operation.assetAmount, |
| 151 | + operationId: params.operationId, |
| 152 | + }; |
| 153 | + |
| 154 | + const depositTxRequest = await this.createTxRequest(depositIntent); |
| 155 | + |
| 156 | + return { |
| 157 | + operationId: params.operationId, |
| 158 | + txRequestIds: { |
| 159 | + approve: operation.txRequestId, |
| 160 | + deposit: depositTxRequest.txRequestId, |
| 161 | + }, |
| 162 | + }; |
| 163 | + } |
| 164 | + |
| 165 | + /** |
| 166 | + * Get the current state of a DeFi operation. |
| 167 | + * |
| 168 | + * @param params.operationId - the operation to retrieve |
| 169 | + */ |
| 170 | + async getOperation(params: GetOperationOptions): Promise<DefiOperation> { |
| 171 | + if (!params.operationId) { |
| 172 | + throw new Error('operationId is required'); |
| 173 | + } |
| 174 | + |
| 175 | + return await this.bitgo.get(this.bitgo.microservicesUrl(this.operationUrl(params.operationId))).result(); |
| 176 | + } |
| 177 | + |
| 178 | + /** |
| 179 | + * List operations for a vault filtered by walletId. |
| 180 | + * |
| 181 | + * @param params.vaultId - vault to list operations for |
| 182 | + * @param params.state - optional state filter |
| 183 | + * @param params.type - optional type filter (DEPOSIT | WITHDRAW) |
| 184 | + * @param params.limit - page size |
| 185 | + * @param params.cursor - pagination cursor |
| 186 | + */ |
| 187 | + async listOperations(params: ListOperationsOptions): Promise<DefiOperationListResult> { |
| 188 | + if (!params.vaultId) { |
| 189 | + throw new Error('vaultId is required'); |
| 190 | + } |
| 191 | + |
| 192 | + const query: Record<string, string | number> = { |
| 193 | + walletId: this.wallet.id(), |
| 194 | + vaultId: params.vaultId, |
| 195 | + }; |
| 196 | + if (params.state) query.state = params.state; |
| 197 | + if (params.type) query.type = params.type; |
| 198 | + if (params.limit) query.limit = params.limit; |
| 199 | + if (params.cursor) query.cursor = params.cursor; |
| 200 | + |
| 201 | + return await this.bitgo |
| 202 | + .get(this.bitgo.microservicesUrl(this.vaultOperationsUrl(params.vaultId))) |
| 203 | + .query(query) |
| 204 | + .result(); |
| 205 | + } |
| 206 | + |
| 207 | + // ── Internal helpers ──────────────────────────────────────────────── |
| 208 | + |
| 209 | + private async createTxRequest(intent: Record<string, unknown>): Promise<{ txRequestId: string; intent: unknown }> { |
| 210 | + return await this.bitgo |
| 211 | + .post(this.bitgo.url('/wallet/' + this.wallet.id() + '/txrequests', 2)) |
| 212 | + .send({ intent }) |
| 213 | + .result(); |
| 214 | + } |
| 215 | + |
| 216 | + private async cancelTxRequest(txRequestId: string): Promise<void> { |
| 217 | + await this.bitgo.del(this.bitgo.url('/wallet/' + this.wallet.id() + '/txrequests/' + txRequestId, 2)).result(); |
| 218 | + } |
| 219 | + |
| 220 | + private operationsUrl(): string { |
| 221 | + return `/api/defi-service/v1/wallets/${this.wallet.id()}/operations`; |
| 222 | + } |
| 223 | + |
| 224 | + private operationUrl(operationId: string): string { |
| 225 | + return `/api/defi-service/v1/operations/${operationId}`; |
| 226 | + } |
| 227 | + |
| 228 | + private vaultOperationsUrl(vaultId: string): string { |
| 229 | + return `/api/defi-service/v1/vaults/${vaultId}/operations`; |
| 230 | + } |
| 231 | +} |
0 commit comments