58 lines
1.5 KiB
TypeScript
58 lines
1.5 KiB
TypeScript
import {
|
|
fetchTransactionBlockHeight,
|
|
initializeElectrumClient,
|
|
} from "@electrum-cash/protocol";
|
|
|
|
export interface ElectrumServiceConfig {
|
|
host?: string;
|
|
applicationIdentifier?: string;
|
|
}
|
|
|
|
export abstract class BlockchainService {
|
|
abstract hasSeenTransaction(transactionHash: string): Promise<boolean>;
|
|
}
|
|
|
|
/**
|
|
* Small Electrum adapter used by CLI services.
|
|
* Keeps connection logic in one place and exposes a tiny API.
|
|
*/
|
|
export class ElectrumService {
|
|
private readonly host: string;
|
|
private readonly applicationIdentifier: string;
|
|
private clientPromise?: ReturnType<typeof initializeElectrumClient>;
|
|
|
|
constructor(config: ElectrumServiceConfig = {}) {
|
|
this.host =
|
|
config.host ?? process.env["ELECTRUM_HOST"] ?? "bch.imaginary.cash";
|
|
this.applicationIdentifier = "xo-cli";
|
|
}
|
|
|
|
private async getClient() {
|
|
if (!this.clientPromise) {
|
|
this.clientPromise = initializeElectrumClient(
|
|
this.applicationIdentifier,
|
|
this.host,
|
|
);
|
|
}
|
|
|
|
return this.clientPromise;
|
|
}
|
|
|
|
/**
|
|
* Returns true when the transaction is known by Electrum
|
|
* (confirmed or currently in mempool).
|
|
*/
|
|
async hasSeenTransaction(transactionHash: string): Promise<boolean> {
|
|
try {
|
|
const client = await this.getClient();
|
|
const height = await fetchTransactionBlockHeight(client, transactionHash);
|
|
|
|
// Electrum returns numbers for known transactions
|
|
// (e.g. >0 confirmed, 0/-1 unconfirmed variants).
|
|
return typeof height === "number";
|
|
} catch {
|
|
return false;
|
|
}
|
|
}
|
|
}
|