rpc-client/src/rpcNetwork.ts

113 lines
1.9 KiB
TypeScript
Raw Normal View History

2022-06-27 19:36:29 +00:00
import RpcQuery from "./rpcQuery.js";
2022-07-19 18:43:28 +00:00
// @ts-ignore
import DHT from "@hyperswarm/dht";
2022-06-27 19:36:29 +00:00
export default class RpcNetwork {
constructor(dht = new DHT()) {
this._dht = dht;
2022-06-27 19:56:27 +00:00
this._ready = this._dht.ready();
2022-06-27 19:36:29 +00:00
}
private _dht: typeof DHT;
get dht() {
return this._dht;
2022-06-27 19:36:29 +00:00
}
private _majorityThreshold = 0.75;
get majorityThreshold(): number {
return this._majorityThreshold;
2022-06-27 19:36:29 +00:00
}
set majorityThreshold(value: number) {
this._majorityThreshold = value;
2022-06-27 19:36:29 +00:00
}
private _maxTtl = 12 * 60 * 60;
2022-06-27 19:36:29 +00:00
get maxTtl(): number {
return this._maxTtl;
}
set maxTtl(value: number) {
this._maxTtl = value;
}
private _queryTimeout = 30;
2022-06-27 19:36:29 +00:00
get queryTimeout(): number {
return this._queryTimeout;
}
set queryTimeout(value: number) {
this._queryTimeout = value;
}
private _relayTimeout = 2;
get relayTimeout(): number {
return this._relayTimeout;
2022-06-27 19:36:29 +00:00
}
set relayTimeout(value: number) {
this._relayTimeout = value;
2022-06-27 19:36:29 +00:00
}
private _relays: string[] = [];
get relays(): string[] {
return this._relays;
}
private _ready: Promise<void>;
get ready(): Promise<void> {
return this._ready;
}
private _force: boolean = false;
2022-06-27 19:36:29 +00:00
get force(): boolean {
return this._force;
}
set force(value: boolean) {
this._force = value;
}
public addRelay(pubkey: string): void {
this._relays.push(pubkey);
this._relays = [...new Set(this._relays)];
}
public removeRelay(pubkey: string): boolean {
if (!this._relays.includes(pubkey)) {
return false;
}
delete this._relays[this._relays.indexOf(pubkey)];
this._relays = Object.values(this._relays);
return true;
}
public clearRelays(): void {
this._relays = [];
}
2022-06-27 19:36:29 +00:00
public query(
query: string,
chain: string,
data: object | any[] = {},
force: boolean = false
): RpcQuery {
return new RpcQuery(this, {
query,
chain,
data,
force: force || this._force,
});
}
}