|
| 1 | +import "server-only"; |
| 2 | + |
| 3 | +import { db } from "@/lib/db"; |
| 4 | +import { workflowExecutions } from "@/lib/db/schema"; |
| 5 | +import { eq } from "drizzle-orm"; |
| 6 | +import { ethers } from "ethers"; |
| 7 | +import { initializeParaSigner } from "@/lib/para/wallet-helpers"; |
| 8 | +import { type StepInput, withStepLogging } from "@/lib/steps/step-handler"; |
| 9 | +import { getErrorMessage } from "@/lib/utils"; |
| 10 | + |
| 11 | +type TransferFundsResult = |
| 12 | + | { success: true; transactionHash: string } |
| 13 | + | { success: false; error: string }; |
| 14 | + |
| 15 | +export type TransferFundsCoreInput = { |
| 16 | + amount: string; |
| 17 | + recipientAddress: string; |
| 18 | +}; |
| 19 | + |
| 20 | +export type TransferFundsInput = StepInput & TransferFundsCoreInput; |
| 21 | + |
| 22 | +/** |
| 23 | + * Get userId from executionId by querying the workflowExecutions table |
| 24 | + */ |
| 25 | +async function getUserIdFromExecution( |
| 26 | + executionId: string | undefined |
| 27 | +): Promise<string> { |
| 28 | + if (!executionId) { |
| 29 | + throw new Error("Execution ID is required to get user ID"); |
| 30 | + } |
| 31 | + |
| 32 | + const execution = await db |
| 33 | + .select({ userId: workflowExecutions.userId }) |
| 34 | + .from(workflowExecutions) |
| 35 | + .where(eq(workflowExecutions.id, executionId)) |
| 36 | + .limit(1); |
| 37 | + |
| 38 | + if (execution.length === 0) { |
| 39 | + throw new Error(`Execution not found: ${executionId}`); |
| 40 | + } |
| 41 | + |
| 42 | + return execution[0].userId; |
| 43 | +} |
| 44 | + |
| 45 | +/** |
| 46 | + * Core transfer logic |
| 47 | + */ |
| 48 | +async function stepHandler( |
| 49 | + input: TransferFundsInput |
| 50 | +): Promise<TransferFundsResult> { |
| 51 | + console.log("[Transfer Funds] Starting step with input:", { |
| 52 | + amount: input.amount, |
| 53 | + recipientAddress: input.recipientAddress, |
| 54 | + hasContext: !!input._context, |
| 55 | + executionId: input._context?.executionId, |
| 56 | + }); |
| 57 | + |
| 58 | + const { amount, recipientAddress, _context } = input; |
| 59 | + |
| 60 | + // Validate recipient address |
| 61 | + if (!ethers.isAddress(recipientAddress)) { |
| 62 | + console.error("[Transfer Funds] Invalid recipient address:", recipientAddress); |
| 63 | + return { |
| 64 | + success: false, |
| 65 | + error: `Invalid recipient address: ${recipientAddress}`, |
| 66 | + }; |
| 67 | + } |
| 68 | + |
| 69 | + // Validate amount |
| 70 | + if (!amount || amount.trim() === "") { |
| 71 | + console.error("[Transfer Funds] Amount is missing"); |
| 72 | + return { |
| 73 | + success: false, |
| 74 | + error: "Amount is required", |
| 75 | + }; |
| 76 | + } |
| 77 | + |
| 78 | + let amountInWei: bigint; |
| 79 | + try { |
| 80 | + amountInWei = ethers.parseEther(amount); |
| 81 | + console.log("[Transfer Funds] Amount parsed:", { amount, amountInWei: amountInWei.toString() }); |
| 82 | + } catch (error) { |
| 83 | + console.error("[Transfer Funds] Failed to parse amount:", error); |
| 84 | + return { |
| 85 | + success: false, |
| 86 | + error: `Invalid amount format: ${getErrorMessage(error)}`, |
| 87 | + }; |
| 88 | + } |
| 89 | + |
| 90 | + // Get userId from executionId (passed via _context) |
| 91 | + if (!_context?.executionId) { |
| 92 | + console.error("[Transfer Funds] No execution ID in context"); |
| 93 | + return { |
| 94 | + success: false, |
| 95 | + error: "Execution ID is required to identify the user", |
| 96 | + }; |
| 97 | + } |
| 98 | + |
| 99 | + let userId: string; |
| 100 | + try { |
| 101 | + console.log("[Transfer Funds] Looking up user from execution:", _context.executionId); |
| 102 | + userId = await getUserIdFromExecution(_context.executionId); |
| 103 | + console.log("[Transfer Funds] Found userId:", userId); |
| 104 | + } catch (error) { |
| 105 | + console.error("[Transfer Funds] Failed to get user ID:", error); |
| 106 | + return { |
| 107 | + success: false, |
| 108 | + error: `Failed to get user ID: ${getErrorMessage(error)}`, |
| 109 | + }; |
| 110 | + } |
| 111 | + |
| 112 | + // Sepolia testnet RPC URL |
| 113 | + // TODO: Make this configurable in the future |
| 114 | + const SEPOLIA_RPC_URL = "https://chain.techops.services/eth-sepolia"; |
| 115 | + |
| 116 | + let signer; |
| 117 | + try { |
| 118 | + console.log("[Transfer Funds] Initializing Para signer for user:", userId); |
| 119 | + signer = await initializeParaSigner(userId, SEPOLIA_RPC_URL); |
| 120 | + const signerAddress = await signer.getAddress(); |
| 121 | + console.log("[Transfer Funds] Signer initialized successfully:", signerAddress); |
| 122 | + } catch (error) { |
| 123 | + console.error("[Transfer Funds] Failed to initialize wallet:", error); |
| 124 | + return { |
| 125 | + success: false, |
| 126 | + error: `Failed to initialize wallet: ${getErrorMessage(error)}`, |
| 127 | + }; |
| 128 | + } |
| 129 | + |
| 130 | + // Send transaction |
| 131 | + try { |
| 132 | + console.log("[Transfer Funds] Sending transaction:", { |
| 133 | + to: recipientAddress, |
| 134 | + value: amountInWei.toString(), |
| 135 | + }); |
| 136 | + |
| 137 | + const tx = await signer.sendTransaction({ |
| 138 | + to: recipientAddress, |
| 139 | + value: amountInWei, |
| 140 | + }); |
| 141 | + |
| 142 | + console.log("[Transfer Funds] Transaction sent, hash:", tx.hash); |
| 143 | + console.log("[Transfer Funds] Waiting for confirmation..."); |
| 144 | + |
| 145 | + // Wait for transaction to be mined |
| 146 | + const receipt = await tx.wait(); |
| 147 | + |
| 148 | + if (!receipt) { |
| 149 | + console.error("[Transfer Funds] No receipt received"); |
| 150 | + return { |
| 151 | + success: false, |
| 152 | + error: "Transaction sent but receipt not available", |
| 153 | + }; |
| 154 | + } |
| 155 | + |
| 156 | + console.log("[Transfer Funds] Transaction confirmed:", { |
| 157 | + hash: receipt.hash, |
| 158 | + status: receipt.status, |
| 159 | + blockNumber: receipt.blockNumber, |
| 160 | + }); |
| 161 | + |
| 162 | + return { |
| 163 | + success: true, |
| 164 | + transactionHash: receipt.hash, |
| 165 | + }; |
| 166 | + } catch (error) { |
| 167 | + console.error("[Transfer Funds] Transaction failed:", error); |
| 168 | + return { |
| 169 | + success: false, |
| 170 | + error: `Transaction failed: ${getErrorMessage(error)}`, |
| 171 | + }; |
| 172 | + } |
| 173 | +} |
| 174 | + |
| 175 | +/** |
| 176 | + * Transfer Funds Step |
| 177 | + * Transfers ETH from the user's wallet to a recipient address |
| 178 | + */ |
| 179 | +export async function transferFundsStep( |
| 180 | + input: TransferFundsInput |
| 181 | +): Promise<TransferFundsResult> { |
| 182 | + "use step"; |
| 183 | + |
| 184 | + return withStepLogging(input, () => stepHandler(input)); |
| 185 | +} |
| 186 | + |
| 187 | +export const _integrationType = "web3"; |
0 commit comments