|
| 1 | +import { |
| 2 | + Injectable, |
| 3 | + Logger, |
| 4 | + BadRequestException, |
| 5 | + InternalServerErrorException, |
| 6 | + ServiceUnavailableException, |
| 7 | +} from '@nestjs/common'; |
| 8 | +import { ConfigService } from '@nestjs/config'; |
| 9 | +import * as StellarSdk from 'stellar-sdk'; |
| 10 | + |
| 11 | +@Injectable() |
| 12 | +export class BlockchainService { |
| 13 | + private readonly logger = new Logger(BlockchainService.name); |
| 14 | + private readonly horizonServer: StellarSdk.Horizon.Server; |
| 15 | + private readonly networkPassphrase: string; |
| 16 | + |
| 17 | + constructor(private readonly configService: ConfigService) { |
| 18 | + const horizonUrl = |
| 19 | + this.configService.get<string>('STELLAR_HORIZON_URL') || |
| 20 | + 'https://horizon-testnet.stellar.org'; |
| 21 | + |
| 22 | + this.networkPassphrase = |
| 23 | + this.configService.get<string>('STELLAR_NETWORK_PASSPHRASE') || |
| 24 | + StellarSdk.Networks.TESTNET; |
| 25 | + |
| 26 | + this.horizonServer = new StellarSdk.Horizon.Server(horizonUrl); |
| 27 | + this.logger.log(`BlockchainService Horizon client initialized: ${horizonUrl}`); |
| 28 | + } |
| 29 | + |
| 30 | + async submitRepayment(signedXdr: string): Promise<{ transactionHash: string }> { |
| 31 | + const transaction = this.parseTransaction(signedXdr); |
| 32 | + |
| 33 | + const hash = await this.submitToHorizon(transaction); |
| 34 | + |
| 35 | + await this.waitForLedgerConfirmation(hash); |
| 36 | + |
| 37 | + return { transactionHash: hash }; |
| 38 | + } |
| 39 | + |
| 40 | + private parseTransaction(signedXdr: string): StellarSdk.Transaction { |
| 41 | + try { |
| 42 | + const parsed = StellarSdk.TransactionBuilder.fromXDR( |
| 43 | + signedXdr, |
| 44 | + this.networkPassphrase, |
| 45 | + ); |
| 46 | + |
| 47 | + if (parsed instanceof StellarSdk.FeeBumpTransaction) { |
| 48 | + throw new BadRequestException({ |
| 49 | + code: 'TRANSACTION_FEE_BUMP_NOT_SUPPORTED', |
| 50 | + message: 'Fee bump transactions are not supported for loan repayments.', |
| 51 | + }); |
| 52 | + } |
| 53 | + |
| 54 | + return parsed; |
| 55 | + } catch (error) { |
| 56 | + if (error instanceof BadRequestException) { |
| 57 | + throw error; |
| 58 | + } |
| 59 | + |
| 60 | + throw new BadRequestException({ |
| 61 | + code: 'TRANSACTION_INVALID_XDR', |
| 62 | + message: 'The provided XDR string is malformed or invalid.', |
| 63 | + }); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + private async submitToHorizon(transaction: StellarSdk.Transaction): Promise<string> { |
| 68 | + try { |
| 69 | + const result = await this.horizonServer.submitTransaction(transaction); |
| 70 | + return result.hash; |
| 71 | + } catch (error) { |
| 72 | + this.handleHorizonError(error); |
| 73 | + } |
| 74 | + } |
| 75 | + |
| 76 | + private async waitForLedgerConfirmation( |
| 77 | + hash: string, |
| 78 | + maxRetries = 30, |
| 79 | + delayMs = 2000, |
| 80 | + ): Promise<void> { |
| 81 | + for (let attempt = 1; attempt <= maxRetries; attempt++) { |
| 82 | + try { |
| 83 | + const tx = await this.horizonServer |
| 84 | + .transactions() |
| 85 | + .transaction(hash) |
| 86 | + .call(); |
| 87 | + |
| 88 | + if (tx.ledger_attr > 0) { |
| 89 | + this.logger.log( |
| 90 | + `Transaction ${hash} confirmed in ledger ${tx.ledger_attr}`, |
| 91 | + ); |
| 92 | + return; |
| 93 | + } |
| 94 | + } catch { |
| 95 | + // Transaction not yet visible in Horizon — continue polling |
| 96 | + } |
| 97 | + |
| 98 | + if (attempt < maxRetries) { |
| 99 | + await new Promise((resolve) => setTimeout(resolve, delayMs)); |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + throw new ServiceUnavailableException({ |
| 104 | + code: 'TRANSACTION_CONFIRMATION_TIMEOUT', |
| 105 | + message: |
| 106 | + 'Transaction was submitted but not confirmed within the expected time.', |
| 107 | + }); |
| 108 | + } |
| 109 | + |
| 110 | + private handleHorizonError(error: unknown): never { |
| 111 | + const err = error as { |
| 112 | + response?: { |
| 113 | + data?: { |
| 114 | + extras?: { |
| 115 | + result_codes?: { |
| 116 | + transaction?: string; |
| 117 | + operations?: string[]; |
| 118 | + }; |
| 119 | + }; |
| 120 | + }; |
| 121 | + }; |
| 122 | + message?: string; |
| 123 | + }; |
| 124 | + |
| 125 | + const resultCodes = err?.response?.data?.extras?.result_codes; |
| 126 | + |
| 127 | + if (resultCodes) { |
| 128 | + const txCode = resultCodes.transaction; |
| 129 | + const opCodes = resultCodes.operations ?? []; |
| 130 | + const allCodes = [txCode, ...opCodes].filter(Boolean); |
| 131 | + |
| 132 | + const code = `STELLAR_TRANSACTION_FAILED`; |
| 133 | + const message = `Transaction rejected by the Stellar network: ${allCodes.join(', ')}`; |
| 134 | + |
| 135 | + throw new BadRequestException({ code, message }); |
| 136 | + } |
| 137 | + |
| 138 | + const message = err?.message ?? 'Unknown error'; |
| 139 | + |
| 140 | + if ( |
| 141 | + message.toLowerCase().includes('timeout') || |
| 142 | + message.toLowerCase().includes('network') |
| 143 | + ) { |
| 144 | + throw new ServiceUnavailableException({ |
| 145 | + code: 'STELLAR_NETWORK_UNAVAILABLE', |
| 146 | + message: |
| 147 | + 'Stellar network is temporarily unavailable. Please try again later.', |
| 148 | + }); |
| 149 | + } |
| 150 | + |
| 151 | + this.logger.error(`Horizon submission error: ${message}`); |
| 152 | + throw new InternalServerErrorException({ |
| 153 | + code: 'STELLAR_SUBMISSION_FAILED', |
| 154 | + message: |
| 155 | + 'Failed to submit transaction to the Stellar network. Please try again.', |
| 156 | + }); |
| 157 | + } |
| 158 | +} |
0 commit comments