subscriber-connection.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { getNumber } from "../utils/index.js";
  2. /**
  3. * @TODO
  4. *
  5. * @_docloc: api/providers/abstract-provider
  6. */
  7. export class BlockConnectionSubscriber {
  8. #provider;
  9. #blockNumber;
  10. #running;
  11. #filterId;
  12. constructor(provider) {
  13. this.#provider = provider;
  14. this.#blockNumber = -2;
  15. this.#running = false;
  16. this.#filterId = null;
  17. }
  18. start() {
  19. if (this.#running) {
  20. return;
  21. }
  22. this.#running = true;
  23. this.#filterId = this.#provider._subscribe(["newHeads"], (result) => {
  24. const blockNumber = getNumber(result.number);
  25. const initial = (this.#blockNumber === -2) ? blockNumber : (this.#blockNumber + 1);
  26. for (let b = initial; b <= blockNumber; b++) {
  27. this.#provider.emit("block", b);
  28. }
  29. this.#blockNumber = blockNumber;
  30. });
  31. }
  32. stop() {
  33. if (!this.#running) {
  34. return;
  35. }
  36. this.#running = false;
  37. if (this.#filterId != null) {
  38. this.#provider._unsubscribe(this.#filterId);
  39. this.#filterId = null;
  40. }
  41. }
  42. pause(dropWhilePaused) {
  43. if (dropWhilePaused) {
  44. this.#blockNumber = -2;
  45. }
  46. this.stop();
  47. }
  48. resume() {
  49. this.start();
  50. }
  51. }
  52. //# sourceMappingURL=subscriber-connection.js.map