|
| 1 | +import { Injectable, Logger, BadRequestException } from '@nestjs/common'; |
| 2 | +import { ConfigService } from '@nestjs/config'; |
| 3 | + |
| 4 | +interface StellarTransaction { |
| 5 | + id: string; |
| 6 | + envelope_xdr: string; |
| 7 | + result_xdr: string; |
| 8 | + result_meta_xdr: string; |
| 9 | + tx: { |
| 10 | + source_account: string; |
| 11 | + fee: number; |
| 12 | + seq_num: string; |
| 13 | + operations: Array<{ |
| 14 | + type: string; |
| 15 | + [key: string]: unknown; |
| 16 | + }>; |
| 17 | + }; |
| 18 | +} |
| 19 | + |
| 20 | +interface TransactionVerificationResult { |
| 21 | + isValid: boolean; |
| 22 | + transaction?: StellarTransaction; |
| 23 | + error?: string; |
| 24 | +} |
| 25 | + |
| 26 | +@Injectable() |
| 27 | +export class StellarBlockchainService { |
| 28 | + private readonly logger = new Logger(StellarBlockchainService.name); |
| 29 | + private readonly horizonUrl: string; |
| 30 | + private readonly stellarNetwork: string; |
| 31 | + |
| 32 | + constructor(private configService: ConfigService) { |
| 33 | + this.horizonUrl = this.configService.get<string>( |
| 34 | + 'STELLAR_HORIZON_URL', |
| 35 | + 'https://horizon-testnet.stellar.org', |
| 36 | + ); |
| 37 | + this.stellarNetwork = this.configService.get<string>('STELLAR_NETWORK', 'TESTNET'); |
| 38 | + |
| 39 | + this.logger.log(`Initialized with Horizon URL: ${this.horizonUrl}`); |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Verify a transaction hash exists on the Stellar blockchain |
| 44 | + * @param transactionHash - The transaction hash to verify (64 hex characters) |
| 45 | + * @returns TransactionVerificationResult with verification status |
| 46 | + */ |
| 47 | + async verifyTransaction(transactionHash: string): Promise<TransactionVerificationResult> { |
| 48 | + try { |
| 49 | + // Validate hash format before making API call |
| 50 | + if (!this.isValidTransactionHash(transactionHash)) { |
| 51 | + return { |
| 52 | + isValid: false, |
| 53 | + error: 'Invalid transaction hash format', |
| 54 | + }; |
| 55 | + } |
| 56 | + |
| 57 | + const response = await fetch( |
| 58 | + `${this.horizonUrl}/transactions/${transactionHash}`, |
| 59 | + { |
| 60 | + method: 'GET', |
| 61 | + headers: { |
| 62 | + 'Content-Type': 'application/json', |
| 63 | + }, |
| 64 | + }, |
| 65 | + ); |
| 66 | + |
| 67 | + if (!response.ok) { |
| 68 | + if (response.status === 404) { |
| 69 | + this.logger.warn(`Transaction ${transactionHash} not found on blockchain`); |
| 70 | + return { |
| 71 | + isValid: false, |
| 72 | + error: 'Transaction not found on the Stellar blockchain', |
| 73 | + }; |
| 74 | + } |
| 75 | + |
| 76 | + this.logger.error( |
| 77 | + `Horizon API error: ${response.status} ${response.statusText}`, |
| 78 | + ); |
| 79 | + return { |
| 80 | + isValid: false, |
| 81 | + error: `Horizon API returned ${response.status}`, |
| 82 | + }; |
| 83 | + } |
| 84 | + |
| 85 | + const transaction: StellarTransaction = await response.json(); |
| 86 | + |
| 87 | + // Verify transaction has successful result |
| 88 | + if (!this.isSuccessfulTransaction(transaction)) { |
| 89 | + this.logger.warn(`Transaction ${transactionHash} did not execute successfully`); |
| 90 | + return { |
| 91 | + isValid: false, |
| 92 | + error: 'Transaction did not execute successfully on the blockchain', |
| 93 | + }; |
| 94 | + } |
| 95 | + |
| 96 | + this.logger.log(`Transaction ${transactionHash} verified successfully`); |
| 97 | + return { |
| 98 | + isValid: true, |
| 99 | + transaction, |
| 100 | + }; |
| 101 | + } catch (error) { |
| 102 | + this.logger.error( |
| 103 | + `Error verifying transaction: ${error instanceof Error ? error.message : String(error)}`, |
| 104 | + ); |
| 105 | + return { |
| 106 | + isValid: false, |
| 107 | + error: 'Failed to verify transaction on blockchain', |
| 108 | + }; |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * Validate transaction hash format |
| 114 | + * Stellar transaction hashes are 64 hexadecimal characters |
| 115 | + * @param hash - The hash to validate |
| 116 | + * @returns boolean indicating if hash is valid format |
| 117 | + */ |
| 118 | + private isValidTransactionHash(hash: string): boolean { |
| 119 | + const transactionHashRegex = /^[a-f0-9]{64}$/i; |
| 120 | + return transactionHashRegex.test(hash); |
| 121 | + } |
| 122 | + |
| 123 | + /** |
| 124 | + * Check if transaction executed successfully |
| 125 | + * A successful transaction should have result_xdr that indicates success |
| 126 | + * @param transaction - The transaction object from Horizon API |
| 127 | + * @returns boolean indicating if transaction was successful |
| 128 | + */ |
| 129 | + private isSuccessfulTransaction(transaction: StellarTransaction): boolean { |
| 130 | + try { |
| 131 | + // Check if result_meta_xdr exists (indicates transaction was processed) |
| 132 | + if (!transaction.result_meta_xdr || !transaction.tx) { |
| 133 | + return false; |
| 134 | + } |
| 135 | + |
| 136 | + // Transaction exists and was processed successfully |
| 137 | + return true; |
| 138 | + } catch (error) { |
| 139 | + this.logger.error('Error checking transaction success:', error); |
| 140 | + return false; |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + /** |
| 145 | + * Get transaction details from blockchain |
| 146 | + * @param transactionHash - The transaction hash to retrieve |
| 147 | + * @returns Promise resolving to transaction details or null if not found |
| 148 | + */ |
| 149 | + async getTransactionDetails(transactionHash: string): Promise<StellarTransaction | null> { |
| 150 | + try { |
| 151 | + if (!this.isValidTransactionHash(transactionHash)) { |
| 152 | + return null; |
| 153 | + } |
| 154 | + |
| 155 | + const response = await fetch( |
| 156 | + `${this.horizonUrl}/transactions/${transactionHash}`, |
| 157 | + { |
| 158 | + method: 'GET', |
| 159 | + headers: { |
| 160 | + 'Content-Type': 'application/json', |
| 161 | + }, |
| 162 | + }, |
| 163 | + ); |
| 164 | + |
| 165 | + if (!response.ok) { |
| 166 | + return null; |
| 167 | + } |
| 168 | + |
| 169 | + return await response.json(); |
| 170 | + } catch (error) { |
| 171 | + this.logger.error('Error fetching transaction details:', error); |
| 172 | + return null; |
| 173 | + } |
| 174 | + } |
| 175 | +} |
0 commit comments