|
| 1 | +/** |
| 2 | + * Hook for borrow transaction handler |
| 3 | + * Handles the borrow flow logic and transaction execution |
| 4 | + */ |
| 5 | + |
| 6 | +import { parseUnits, type Hex } from "viem"; |
| 7 | +import { useWalletClient } from "wagmi"; |
| 8 | + |
| 9 | +import { BTCVaultsManager } from "../../../../clients/eth-contract"; |
| 10 | +import { CONTRACTS } from "../../../../config/contracts"; |
| 11 | +import { |
| 12 | + addCollateralWithMarketId, |
| 13 | + borrowMoreFromPosition, |
| 14 | +} from "../../../../services/position/positionTransactionService"; |
| 15 | +import { findVaultIndicesForAmount } from "../../../../utils/subsetSum"; |
| 16 | + |
| 17 | +interface AvailableVault { |
| 18 | + txHash: string; |
| 19 | + amountSatoshis: bigint; |
| 20 | +} |
| 21 | + |
| 22 | +interface UseBorrowTransactionProps { |
| 23 | + hasPosition: boolean; |
| 24 | + marketId: string | undefined; |
| 25 | + availableVaults: AvailableVault[]; |
| 26 | + lastBorrowData: { |
| 27 | + collateral: number; |
| 28 | + borrow: number; |
| 29 | + }; |
| 30 | + refetch: () => Promise<void>; |
| 31 | + onBorrowSuccess: () => void; |
| 32 | + setProcessing: (processing: boolean) => void; |
| 33 | +} |
| 34 | + |
| 35 | +export interface UseBorrowTransactionResult { |
| 36 | + handleConfirmBorrow: () => Promise<void>; |
| 37 | +} |
| 38 | + |
| 39 | +/** |
| 40 | + * Handles borrow transaction logic |
| 41 | + */ |
| 42 | +export function useBorrowTransaction({ |
| 43 | + hasPosition, |
| 44 | + marketId, |
| 45 | + availableVaults, |
| 46 | + lastBorrowData, |
| 47 | + refetch, |
| 48 | + onBorrowSuccess, |
| 49 | + setProcessing, |
| 50 | +}: UseBorrowTransactionProps): UseBorrowTransactionResult { |
| 51 | + const { data: walletClient } = useWalletClient(); |
| 52 | + const chain = walletClient?.chain; |
| 53 | + |
| 54 | + const handleConfirmBorrow = async () => { |
| 55 | + setProcessing(true); |
| 56 | + try { |
| 57 | + // Validate wallet connection |
| 58 | + if (!walletClient || !chain) { |
| 59 | + throw new Error("Wallet not connected. Please connect your wallet."); |
| 60 | + } |
| 61 | + |
| 62 | + // Validate market ID |
| 63 | + if (!marketId) { |
| 64 | + throw new Error("Market ID is required for borrowing."); |
| 65 | + } |
| 66 | + |
| 67 | + const { collateral: collateralBTC, borrow: borrowUSDC } = lastBorrowData; |
| 68 | + |
| 69 | + // Validate amounts |
| 70 | + if (borrowUSDC <= 0) { |
| 71 | + throw new Error("Borrow amount must be greater than 0"); |
| 72 | + } |
| 73 | + |
| 74 | + // Convert borrow amount from USDC to bigint (6 decimals) |
| 75 | + const borrowAmountBigint = parseUnits(borrowUSDC.toString(), 6); |
| 76 | + |
| 77 | + if (collateralBTC > 0) { |
| 78 | + // Case 1: Add new collateral and borrow |
| 79 | + // Convert collateral from BTC to satoshis |
| 80 | + const collateralSatoshis = BigInt(Math.round(collateralBTC * 1e8)); |
| 81 | + |
| 82 | + // Find which vaults to use for this collateral amount |
| 83 | + const vaultAmounts = availableVaults.map((v) => v.amountSatoshis); |
| 84 | + const vaultIndices = findVaultIndicesForAmount( |
| 85 | + vaultAmounts, |
| 86 | + collateralSatoshis, |
| 87 | + ); |
| 88 | + |
| 89 | + if (!vaultIndices) { |
| 90 | + throw new Error( |
| 91 | + `Cannot find vault combination for ${collateralBTC} BTC. Please select a different amount.`, |
| 92 | + ); |
| 93 | + } |
| 94 | + |
| 95 | + // Get txHashes for selected vaults |
| 96 | + const pegInTxHashes = vaultIndices.map( |
| 97 | + (i) => availableVaults[i].txHash as Hex, |
| 98 | + ); |
| 99 | + |
| 100 | + // Validate vault statuses before attempting to borrow |
| 101 | + const vaultStatuses = await Promise.all( |
| 102 | + pegInTxHashes.map((txHash) => |
| 103 | + BTCVaultsManager.getPeginRequest( |
| 104 | + CONTRACTS.BTC_VAULTS_MANAGER, |
| 105 | + txHash, |
| 106 | + ), |
| 107 | + ), |
| 108 | + ); |
| 109 | + |
| 110 | + // Check all vaults are in AVAILABLE status (status 2) |
| 111 | + const invalidVaults = vaultStatuses.filter((v) => v.status !== 2); |
| 112 | + if (invalidVaults.length > 0) { |
| 113 | + const statusNames = invalidVaults.map((v) => |
| 114 | + v.status === 0 |
| 115 | + ? "Pending" |
| 116 | + : v.status === 1 |
| 117 | + ? "Verified" |
| 118 | + : v.status === 3 |
| 119 | + ? "InPosition" |
| 120 | + : "Expired", |
| 121 | + ); |
| 122 | + throw new Error( |
| 123 | + `Cannot borrow: ${invalidVaults.length} vault(s) are not in AVAILABLE status. Current statuses: ${statusNames.join(", ")}. Only vaults with AVAILABLE status (status 2) can be used for borrowing.`, |
| 124 | + ); |
| 125 | + } |
| 126 | + |
| 127 | + await addCollateralWithMarketId( |
| 128 | + walletClient, |
| 129 | + chain, |
| 130 | + CONTRACTS.VAULT_CONTROLLER, |
| 131 | + pegInTxHashes, |
| 132 | + marketId, |
| 133 | + borrowAmountBigint, |
| 134 | + ); |
| 135 | + } else { |
| 136 | + // Case 2: Borrow more from existing position (no new collateral) |
| 137 | + if (!hasPosition) { |
| 138 | + throw new Error( |
| 139 | + "No existing position found. Please add collateral first.", |
| 140 | + ); |
| 141 | + } |
| 142 | + |
| 143 | + await borrowMoreFromPosition( |
| 144 | + walletClient, |
| 145 | + chain, |
| 146 | + CONTRACTS.VAULT_CONTROLLER, |
| 147 | + marketId, |
| 148 | + borrowAmountBigint, |
| 149 | + ); |
| 150 | + } |
| 151 | + |
| 152 | + // Refetch position data to update UI |
| 153 | + await refetch(); |
| 154 | + |
| 155 | + // Success - show success modal |
| 156 | + onBorrowSuccess(); |
| 157 | + } catch (error) { |
| 158 | + // Log detailed error information for debugging |
| 159 | + console.error("Borrow failed:", error); |
| 160 | + console.error("Error details:", { |
| 161 | + message: error instanceof Error ? error.message : "Unknown error", |
| 162 | + cause: error instanceof Error ? error.cause : undefined, |
| 163 | + stack: error instanceof Error ? error.stack : undefined, |
| 164 | + fullError: error, |
| 165 | + }); |
| 166 | + |
| 167 | + // TODO: Show error to user with proper error handling UI |
| 168 | + } finally { |
| 169 | + setProcessing(false); |
| 170 | + } |
| 171 | + }; |
| 172 | + |
| 173 | + return { |
| 174 | + handleConfirmBorrow, |
| 175 | + }; |
| 176 | +} |
0 commit comments