subscriber-polling.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. import { assert, isHexString } from "../utils/index.js";
  2. import type { AbstractProvider, Subscriber } from "./abstract-provider.js";
  3. import type { EventFilter, OrphanFilter, ProviderEvent } from "./provider.js";
  4. function copy(obj: any): any {
  5. return JSON.parse(JSON.stringify(obj));
  6. }
  7. /**
  8. * Return the polling subscriber for common events.
  9. *
  10. * @_docloc: api/providers/abstract-provider
  11. */
  12. export function getPollingSubscriber(provider: AbstractProvider, event: ProviderEvent): Subscriber {
  13. if (event === "block") { return new PollingBlockSubscriber(provider); }
  14. if (isHexString(event, 32)) { return new PollingTransactionSubscriber(provider, event); }
  15. assert(false, "unsupported polling event", "UNSUPPORTED_OPERATION", {
  16. operation: "getPollingSubscriber", info: { event }
  17. });
  18. }
  19. // @TODO: refactor this
  20. /**
  21. * A **PollingBlockSubscriber** polls at a regular interval for a change
  22. * in the block number.
  23. *
  24. * @_docloc: api/providers/abstract-provider
  25. */
  26. export class PollingBlockSubscriber implements Subscriber {
  27. #provider: AbstractProvider;
  28. #poller: null | number;
  29. #interval: number;
  30. // The most recent block we have scanned for events. The value -2
  31. // indicates we still need to fetch an initial block number
  32. #blockNumber: number;
  33. /**
  34. * Create a new **PollingBlockSubscriber** attached to %%provider%%.
  35. */
  36. constructor(provider: AbstractProvider) {
  37. this.#provider = provider;
  38. this.#poller = null;
  39. this.#interval = 4000;
  40. this.#blockNumber = -2;
  41. }
  42. /**
  43. * The polling interval.
  44. */
  45. get pollingInterval(): number { return this.#interval; }
  46. set pollingInterval(value: number) { this.#interval = value; }
  47. async #poll(): Promise<void> {
  48. try {
  49. const blockNumber = await this.#provider.getBlockNumber();
  50. // Bootstrap poll to setup our initial block number
  51. if (this.#blockNumber === -2) {
  52. this.#blockNumber = blockNumber;
  53. return;
  54. }
  55. // @TODO: Put a cap on the maximum number of events per loop?
  56. if (blockNumber !== this.#blockNumber) {
  57. for (let b = this.#blockNumber + 1; b <= blockNumber; b++) {
  58. // We have been stopped
  59. if (this.#poller == null) { return; }
  60. await this.#provider.emit("block", b);
  61. }
  62. this.#blockNumber = blockNumber;
  63. }
  64. } catch (error) {
  65. // @TODO: Minor bump, add an "error" event to let subscribers
  66. // know things went awry.
  67. //console.log(error);
  68. }
  69. // We have been stopped
  70. if (this.#poller == null) { return; }
  71. this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);
  72. }
  73. start(): void {
  74. if (this.#poller) { return; }
  75. this.#poller = this.#provider._setTimeout(this.#poll.bind(this), this.#interval);
  76. this.#poll();
  77. }
  78. stop(): void {
  79. if (!this.#poller) { return; }
  80. this.#provider._clearTimeout(this.#poller);
  81. this.#poller = null;
  82. }
  83. pause(dropWhilePaused?: boolean): void {
  84. this.stop();
  85. if (dropWhilePaused) { this.#blockNumber = -2; }
  86. }
  87. resume(): void {
  88. this.start();
  89. }
  90. }
  91. /**
  92. * An **OnBlockSubscriber** can be sub-classed, with a [[_poll]]
  93. * implmentation which will be called on every new block.
  94. *
  95. * @_docloc: api/providers/abstract-provider
  96. */
  97. export class OnBlockSubscriber implements Subscriber {
  98. #provider: AbstractProvider;
  99. #poll: (b: number) => void;
  100. #running: boolean;
  101. /**
  102. * Create a new **OnBlockSubscriber** attached to %%provider%%.
  103. */
  104. constructor(provider: AbstractProvider) {
  105. this.#provider = provider;
  106. this.#running = false;
  107. this.#poll = (blockNumber: number) => {
  108. this._poll(blockNumber, this.#provider);
  109. }
  110. }
  111. /**
  112. * Called on every new block.
  113. */
  114. async _poll(blockNumber: number, provider: AbstractProvider): Promise<void> {
  115. throw new Error("sub-classes must override this");
  116. }
  117. start(): void {
  118. if (this.#running) { return; }
  119. this.#running = true;
  120. this.#poll(-2);
  121. this.#provider.on("block", this.#poll);
  122. }
  123. stop(): void {
  124. if (!this.#running) { return; }
  125. this.#running = false;
  126. this.#provider.off("block", this.#poll);
  127. }
  128. pause(dropWhilePaused?: boolean): void { this.stop(); }
  129. resume(): void { this.start(); }
  130. }
  131. export class PollingBlockTagSubscriber extends OnBlockSubscriber {
  132. readonly #tag: string;
  133. #lastBlock: number;
  134. constructor(provider: AbstractProvider, tag: string) {
  135. super(provider);
  136. this.#tag = tag;
  137. this.#lastBlock = -2;
  138. }
  139. pause(dropWhilePaused?: boolean): void {
  140. if (dropWhilePaused) { this.#lastBlock = -2; }
  141. super.pause(dropWhilePaused);
  142. }
  143. async _poll(blockNumber: number, provider: AbstractProvider): Promise<void> {
  144. const block = await provider.getBlock(this.#tag);
  145. if (block == null) { return; }
  146. if (this.#lastBlock === -2) {
  147. this.#lastBlock = block.number;
  148. } else if (block.number > this.#lastBlock) {
  149. provider.emit(this.#tag, block.number);
  150. this.#lastBlock = block.number;
  151. }
  152. }
  153. }
  154. /**
  155. * @_ignore:
  156. *
  157. * @_docloc: api/providers/abstract-provider
  158. */
  159. export class PollingOrphanSubscriber extends OnBlockSubscriber {
  160. #filter: OrphanFilter;
  161. constructor(provider: AbstractProvider, filter: OrphanFilter) {
  162. super(provider);
  163. this.#filter = copy(filter);
  164. }
  165. async _poll(blockNumber: number, provider: AbstractProvider): Promise<void> {
  166. throw new Error("@TODO");
  167. console.log(this.#filter);
  168. }
  169. }
  170. /**
  171. * A **PollingTransactionSubscriber** will poll for a given transaction
  172. * hash for its receipt.
  173. *
  174. * @_docloc: api/providers/abstract-provider
  175. */
  176. export class PollingTransactionSubscriber extends OnBlockSubscriber {
  177. #hash: string;
  178. /**
  179. * Create a new **PollingTransactionSubscriber** attached to
  180. * %%provider%%, listening for %%hash%%.
  181. */
  182. constructor(provider: AbstractProvider, hash: string) {
  183. super(provider);
  184. this.#hash = hash;
  185. }
  186. async _poll(blockNumber: number, provider: AbstractProvider): Promise<void> {
  187. const tx = await provider.getTransactionReceipt(this.#hash);
  188. if (tx) { provider.emit(this.#hash, tx); }
  189. }
  190. }
  191. /**
  192. * A **PollingEventSubscriber** will poll for a given filter for its logs.
  193. *
  194. * @_docloc: api/providers/abstract-provider
  195. */
  196. export class PollingEventSubscriber implements Subscriber {
  197. #provider: AbstractProvider;
  198. #filter: EventFilter;
  199. #poller: (b: number) => void;
  200. #running: boolean;
  201. // The most recent block we have scanned for events. The value -2
  202. // indicates we still need to fetch an initial block number
  203. #blockNumber: number;
  204. /**
  205. * Create a new **PollingTransactionSubscriber** attached to
  206. * %%provider%%, listening for %%filter%%.
  207. */
  208. constructor(provider: AbstractProvider, filter: EventFilter) {
  209. this.#provider = provider;
  210. this.#filter = copy(filter);
  211. this.#poller = this.#poll.bind(this);
  212. this.#running = false;
  213. this.#blockNumber = -2;
  214. }
  215. async #poll(blockNumber: number): Promise<void> {
  216. // The initial block hasn't been determined yet
  217. if (this.#blockNumber === -2) { return; }
  218. const filter = copy(this.#filter);
  219. filter.fromBlock = this.#blockNumber + 1;
  220. filter.toBlock = blockNumber;
  221. const logs = await this.#provider.getLogs(filter);
  222. // No logs could just mean the node has not indexed them yet,
  223. // so we keep a sliding window of 60 blocks to keep scanning
  224. if (logs.length === 0) {
  225. if (this.#blockNumber < blockNumber - 60) {
  226. this.#blockNumber = blockNumber - 60;
  227. }
  228. return;
  229. }
  230. for (const log of logs) {
  231. this.#provider.emit(this.#filter, log);
  232. // Only advance the block number when logs were found to
  233. // account for networks (like BNB and Polygon) which may
  234. // sacrifice event consistency for block event speed
  235. this.#blockNumber = log.blockNumber;
  236. }
  237. }
  238. start(): void {
  239. if (this.#running) { return; }
  240. this.#running = true;
  241. if (this.#blockNumber === -2) {
  242. this.#provider.getBlockNumber().then((blockNumber) => {
  243. this.#blockNumber = blockNumber;
  244. });
  245. }
  246. this.#provider.on("block", this.#poller);
  247. }
  248. stop(): void {
  249. if (!this.#running) { return; }
  250. this.#running = false;
  251. this.#provider.off("block", this.#poller);
  252. }
  253. pause(dropWhilePaused?: boolean): void {
  254. this.stop();
  255. if (dropWhilePaused) { this.#blockNumber = -2; }
  256. }
  257. resume(): void {
  258. this.start();
  259. }
  260. }