|
| 1 | +import { Injectable, OnModuleInit } from '@nestjs/common'; |
| 2 | +import { ethers } from 'ethers'; |
| 3 | +import { GetConfig } from 'src/config/config'; |
| 4 | +import { BitcoinClient } from 'src/integration/blockchain/bitcoin/bitcoin-client'; |
| 5 | +import { BitcoinService } from 'src/integration/blockchain/bitcoin/bitcoin.service'; |
| 6 | +import { LightningClient } from 'src/integration/blockchain/lightning/lightning-client'; |
| 7 | +import { LightningHelper } from 'src/integration/blockchain/lightning/lightning-helper'; |
| 8 | +import { LightningService } from 'src/integration/blockchain/lightning/services/lightning.service'; |
| 9 | +import ERC20_ABI from 'src/integration/blockchain/shared/evm/abi/erc20.abi.json'; |
| 10 | +import { Blockchain } from 'src/shared/enums/blockchain.enum'; |
| 11 | +import { LightningLogger } from 'src/shared/services/lightning-logger'; |
| 12 | +import { Util } from 'src/shared/utils/util'; |
| 13 | +import { AlchemyNetworkMapper } from 'src/subdomains/alchemy/alchemy-network-mapper'; |
| 14 | +import { AlchemyService } from 'src/subdomains/alchemy/services/alchemy.service'; |
| 15 | +import { EvmUtil } from 'src/subdomains/evm/evm.util'; |
| 16 | +import { BalanceDto, Direction } from '../dto/boltz.dto'; |
| 17 | +import { AssetBoltzRepository } from '../repositories/asset-boltz.repository'; |
| 18 | + |
| 19 | +interface ChainConfig { |
| 20 | + blockchain: Blockchain; |
| 21 | + chainId: number; |
| 22 | + usesAlchemy: boolean; |
| 23 | +} |
| 24 | + |
| 25 | +@Injectable() |
| 26 | +export class BoltzBalanceService implements OnModuleInit { |
| 27 | + private readonly logger = new LightningLogger(BoltzBalanceService); |
| 28 | + |
| 29 | + private readonly bitcoinClient: BitcoinClient; |
| 30 | + private readonly lightningClient: LightningClient; |
| 31 | + |
| 32 | + private evmWalletAddress = ''; |
| 33 | + private citreaProvider: ethers.providers.JsonRpcProvider | null = null; |
| 34 | + private chains: ChainConfig[] = []; |
| 35 | + |
| 36 | + constructor( |
| 37 | + bitcoinService: BitcoinService, |
| 38 | + lightningService: LightningService, |
| 39 | + private readonly alchemyService: AlchemyService, |
| 40 | + private readonly assetBoltzRepository: AssetBoltzRepository, |
| 41 | + ) { |
| 42 | + this.bitcoinClient = bitcoinService.getDefaultClient(); |
| 43 | + this.lightningClient = lightningService.getDefaultClient(); |
| 44 | + } |
| 45 | + |
| 46 | + onModuleInit(): void { |
| 47 | + const config = GetConfig(); |
| 48 | + this.evmWalletAddress = config.boltz.evmWalletAddress; |
| 49 | + const blockchainConfig = config.blockchain; |
| 50 | + |
| 51 | + this.chains = [ |
| 52 | + { blockchain: Blockchain.ETHEREUM, chainId: blockchainConfig.ethereum.chainId, usesAlchemy: true }, |
| 53 | + { blockchain: Blockchain.POLYGON, chainId: blockchainConfig.polygon.chainId, usesAlchemy: true }, |
| 54 | + { blockchain: Blockchain.CITREA, chainId: blockchainConfig.citrea.chainId, usesAlchemy: false }, |
| 55 | + ]; |
| 56 | + |
| 57 | + if (blockchainConfig.citrea.gatewayUrl) { |
| 58 | + this.citreaProvider = new ethers.providers.JsonRpcProvider(blockchainConfig.citrea.gatewayUrl); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + async getWalletBalance(): Promise<BalanceDto[]> { |
| 63 | + const balances: BalanceDto[] = []; |
| 64 | + |
| 65 | + balances.push(... await this.getBtcBalances()); |
| 66 | + balances.push(... await this.getLightningBalances()); |
| 67 | + balances.push(... await this.getEvmBalances()); |
| 68 | + |
| 69 | + return balances; |
| 70 | + } |
| 71 | + |
| 72 | + private async getBtcBalances(): Promise<BalanceDto[]> { |
| 73 | + const balances: BalanceDto[] = []; |
| 74 | + |
| 75 | + try { |
| 76 | + const onchainNode = await this.bitcoinClient.getWalletBalance(); |
| 77 | + balances.push({ blockchain: Blockchain.BITCOIN, asset: 'BTC', balance: LightningHelper.satToBtc(onchainNode) }); |
| 78 | + } catch (error) { |
| 79 | + this.logger.warn(`Failed to fetch BTC onchain balance: ${error.message}`); |
| 80 | + } |
| 81 | + |
| 82 | + try { |
| 83 | + const lndNode = await this.lightningClient.getLndConfirmedWalletBalance(); |
| 84 | + balances.push({ blockchain: Blockchain.LIGHTNING, asset: 'BTC', balance: LightningHelper.satToBtc(lndNode) }); |
| 85 | + } catch (error) { |
| 86 | + this.logger.warn(`Failed to fetch LND wallet balance: ${error.message}`); |
| 87 | + } |
| 88 | + |
| 89 | + return balances; |
| 90 | + } |
| 91 | + |
| 92 | + private async getLightningBalances(): Promise<BalanceDto[]> { |
| 93 | + const balances: BalanceDto[] = []; |
| 94 | + |
| 95 | + try { |
| 96 | + const channels = await this.lightningClient.getChannels(); |
| 97 | + const outgoing = channels.reduce((sum, ch) => sum + Number(ch.local_balance), 0); |
| 98 | + const incoming = channels.reduce((sum, ch) => sum + Number(ch.remote_balance), 0); |
| 99 | + |
| 100 | + balances.push({ blockchain: Blockchain.LIGHTNING, asset: 'BTC', balance: LightningHelper.satToBtc(outgoing), direction: Direction.OUTGOING}); |
| 101 | + balances.push({ blockchain: Blockchain.LIGHTNING, asset: 'BTC', balance: LightningHelper.satToBtc(incoming), direction: Direction.INCOMING }); |
| 102 | + } catch (error) { |
| 103 | + this.logger.warn(`Failed to fetch Lightning balance: ${error.message}`); |
| 104 | + } |
| 105 | + |
| 106 | + return balances; |
| 107 | + } |
| 108 | + |
| 109 | + private async getEvmBalances(): Promise<BalanceDto[]> { |
| 110 | + const balances: BalanceDto[] = []; |
| 111 | + |
| 112 | + // Citrea cBTC (native balance) |
| 113 | + const citreaBalance = await this.getCitreaNativeBalance(); |
| 114 | + if (citreaBalance) balances.push(citreaBalance); |
| 115 | + |
| 116 | + // Token balances from all chains |
| 117 | + for (const chain of this.chains) { |
| 118 | + try { |
| 119 | + if (chain.chainId <= 0) continue; |
| 120 | + |
| 121 | + const tokenBalances = chain.usesAlchemy |
| 122 | + ? await this.getAlchemyTokenBalances(chain) |
| 123 | + : await this.getDirectTokenBalances(chain); |
| 124 | + balances.push(...tokenBalances); |
| 125 | + } catch (error) { |
| 126 | + this.logger.warn(`Failed to fetch balances for ${chain.blockchain}: ${error.message}`); |
| 127 | + } |
| 128 | + } |
| 129 | + |
| 130 | + return balances; |
| 131 | + } |
| 132 | + |
| 133 | + private async getCitreaNativeBalance(): Promise<BalanceDto | null> { |
| 134 | + if (!this.citreaProvider || !this.evmWalletAddress) return null; |
| 135 | + |
| 136 | + try { |
| 137 | + const balanceWei = await this.citreaProvider.getBalance(this.evmWalletAddress); |
| 138 | + const balance = EvmUtil.fromWeiAmount(balanceWei.toString()); |
| 139 | + |
| 140 | + return { blockchain: Blockchain.CITREA, asset: 'cBTC', balance }; |
| 141 | + } catch (error) { |
| 142 | + this.logger.warn(`Failed to fetch Citrea native balance: ${error.message}`); |
| 143 | + return null; |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + private async getAlchemyTokenBalances(chain: ChainConfig): Promise<BalanceDto[]> { |
| 148 | + const balances: BalanceDto[] = []; |
| 149 | + |
| 150 | + try { |
| 151 | + if (!AlchemyNetworkMapper.toAlchemyNetworkByChainId(chain.chainId)) return balances; |
| 152 | + |
| 153 | + if (!this.evmWalletAddress) return balances; |
| 154 | + |
| 155 | + const tokens = await this.assetBoltzRepository.getByBlockchain(chain.blockchain); |
| 156 | + if (tokens.length === 0) return balances; |
| 157 | + |
| 158 | + const tokenAddresses = tokens.map((t) => t.address); |
| 159 | + const tokenBalances = await this.alchemyService.getTokenBalancesByAddresses(chain.chainId, this.evmWalletAddress, tokenAddresses); |
| 160 | + |
| 161 | + for (const tokenBalance of tokenBalances) { |
| 162 | + const token = tokens.find((t) => Util.equalsIgnoreCase(t.address,tokenBalance.contractAddress)); |
| 163 | + if (!token) continue; |
| 164 | + |
| 165 | + const rawBalance = BigInt(tokenBalance.tokenBalance ?? '0'); |
| 166 | + |
| 167 | + balances.push({ |
| 168 | + blockchain: chain.blockchain, |
| 169 | + asset: token.name, |
| 170 | + balance: EvmUtil.fromWeiAmount(rawBalance.toString(), token.decimals), |
| 171 | + }); |
| 172 | + } |
| 173 | + } catch (error) { |
| 174 | + this.logger.warn(`Failed to fetch Alchemy token balances for ${chain.blockchain}: ${error.message}`); |
| 175 | + } |
| 176 | + |
| 177 | + return balances; |
| 178 | + } |
| 179 | + |
| 180 | + private async getDirectTokenBalances(chain: ChainConfig): Promise<BalanceDto[]> { |
| 181 | + const balances: BalanceDto[] = []; |
| 182 | + |
| 183 | + if (!this.citreaProvider || !this.evmWalletAddress) return balances; |
| 184 | + if (chain.blockchain !== Blockchain.CITREA) return balances; |
| 185 | + |
| 186 | + const tokens = await this.assetBoltzRepository.getByBlockchain(chain.blockchain); |
| 187 | + if (tokens.length === 0) return balances; |
| 188 | + |
| 189 | + for (const token of tokens) { |
| 190 | + try { |
| 191 | + const contract = new ethers.Contract(token.address, ERC20_ABI, this.citreaProvider); |
| 192 | + const rawBalance: ethers.BigNumber = await contract.balanceOf(this.evmWalletAddress); |
| 193 | + |
| 194 | + balances.push({ |
| 195 | + blockchain: chain.blockchain, |
| 196 | + asset: token.name, |
| 197 | + balance: EvmUtil.fromWeiAmount(rawBalance.toString(), token.decimals), |
| 198 | + }); |
| 199 | + } catch (error) { |
| 200 | + this.logger.warn(`Failed to fetch ${token.name} balance on ${chain.blockchain}: ${error.message}`); |
| 201 | + } |
| 202 | + } |
| 203 | + |
| 204 | + return balances; |
| 205 | + } |
| 206 | +} |
0 commit comments