tornado-pool-relayer/src/services/provider.service.ts

57 lines
1.8 KiB
TypeScript
Raw Normal View History

import { ethers } from 'ethers';
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
2021-10-13 17:18:24 +02:00
import { ChainId } from '@/types';
2021-12-09 15:58:05 +01:00
import { CONTRACT_NETWORKS, OFF_CHAIN_ORACLE } from '@/constants';
2021-10-13 17:18:24 +02:00
import { TornadoPool__factory as TornadoPool, OffchainOracle__factory as OffchainOracle } from '@/artifacts';
@Injectable()
export class ProviderService {
private readonly chainId: number;
2021-12-09 15:58:05 +01:00
private readonly rpcUrl: string;
2021-10-21 16:45:02 +02:00
private readonly providers: Map<ChainId, ethers.providers.StaticJsonRpcProvider> = new Map();
constructor(private configService: ConfigService) {
this.chainId = this.configService.get<number>('base.chainId');
2021-12-09 15:58:05 +01:00
this.rpcUrl = this.configService.get('base.rpcUrl');
}
2021-10-21 16:45:02 +02:00
get provider() {
2021-12-09 15:58:05 +01:00
return this.getProvider(this.chainId, this.rpcUrl);
2021-10-21 16:45:02 +02:00
}
2021-12-09 15:58:05 +01:00
getProvider(chainId: ChainId, rpcUrl: string) {
2021-10-21 16:45:02 +02:00
if (!this.providers.has(chainId)) {
2021-12-09 15:58:05 +01:00
this.providers.set(chainId, new ethers.providers.StaticJsonRpcProvider(rpcUrl, chainId));
2021-10-21 16:45:02 +02:00
}
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.providers.get(chainId)!;
}
getTornadoPool() {
2021-10-21 16:45:02 +02:00
return TornadoPool.connect(CONTRACT_NETWORKS[this.chainId], this.provider);
2021-10-13 17:18:24 +02:00
}
getOffChainOracle() {
2021-12-09 15:58:05 +01:00
const oracleRpcUrl = this.configService.get('base.oracleRpcUrl');
const provider = this.getProvider(ChainId.MAINNET, oracleRpcUrl);
2021-10-13 17:18:24 +02:00
return OffchainOracle.connect(OFF_CHAIN_ORACLE, provider);
}
async checkSenderBalance() {
try {
const balance = await this.getBalance(this.configService.get<string>('base.address'));
return balance.gt(ethers.utils.parseEther(this.configService.get('base.minimumBalance')));
} catch {
return false;
}
}
async getBalance(address: string) {
return await this.provider.getBalance(address);
}
}