signer-noncemanager.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.NonceManager = void 0;
  4. const index_js_1 = require("../utils/index.js");
  5. const abstract_signer_js_1 = require("./abstract-signer.js");
  6. /**
  7. * A **NonceManager** wraps another [[Signer]] and automatically manages
  8. * the nonce, ensuring serialized and sequential nonces are used during
  9. * transaction.
  10. */
  11. class NonceManager extends abstract_signer_js_1.AbstractSigner {
  12. /**
  13. * The Signer being managed.
  14. */
  15. signer;
  16. #noncePromise;
  17. #delta;
  18. /**
  19. * Creates a new **NonceManager** to manage %%signer%%.
  20. */
  21. constructor(signer) {
  22. super(signer.provider);
  23. (0, index_js_1.defineProperties)(this, { signer });
  24. this.#noncePromise = null;
  25. this.#delta = 0;
  26. }
  27. async getAddress() {
  28. return this.signer.getAddress();
  29. }
  30. connect(provider) {
  31. return new NonceManager(this.signer.connect(provider));
  32. }
  33. async getNonce(blockTag) {
  34. if (blockTag === "pending") {
  35. if (this.#noncePromise == null) {
  36. this.#noncePromise = super.getNonce("pending");
  37. }
  38. const delta = this.#delta;
  39. return (await this.#noncePromise) + delta;
  40. }
  41. return super.getNonce(blockTag);
  42. }
  43. /**
  44. * Manually increment the nonce. This may be useful when managng
  45. * offline transactions.
  46. */
  47. increment() {
  48. this.#delta++;
  49. }
  50. /**
  51. * Resets the nonce, causing the **NonceManager** to reload the current
  52. * nonce from the blockchain on the next transaction.
  53. */
  54. reset() {
  55. this.#delta = 0;
  56. this.#noncePromise = null;
  57. }
  58. async sendTransaction(tx) {
  59. const noncePromise = this.getNonce("pending");
  60. this.increment();
  61. tx = await this.signer.populateTransaction(tx);
  62. tx.nonce = await noncePromise;
  63. // @TODO: Maybe handle interesting/recoverable errors?
  64. // Like don't increment if the tx was certainly not sent
  65. return await this.signer.sendTransaction(tx);
  66. }
  67. signTransaction(tx) {
  68. return this.signer.signTransaction(tx);
  69. }
  70. signMessage(message) {
  71. return this.signer.signMessage(message);
  72. }
  73. signTypedData(domain, types, value) {
  74. return this.signer.signTypedData(domain, types, value);
  75. }
  76. }
  77. exports.NonceManager = NonceManager;
  78. //# sourceMappingURL=signer-noncemanager.js.map