postchain-client 2.0.2 → 2.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (125) hide show
  1. package/README.md +5 -0
  2. package/built/cjs/index.js +144 -70
  3. package/built/cjs/index.js.map +1 -1
  4. package/built/esm/index.js +3290 -402
  5. package/built/esm/index.js.map +1 -1
  6. package/built/src/ICCF/IccfProofTxMaterialBuilder.d.ts +1 -0
  7. package/built/src/ICCF/IccfProofTxMaterialBuilder.js +1 -1
  8. package/built/src/ICCF/IccfProofTxMaterialBuilder.js.map +1 -1
  9. package/built/src/ICCF/error.d.ts +1 -0
  10. package/built/src/ICCF/error.js.map +1 -1
  11. package/built/src/ICCF/interfaces.d.ts +1 -0
  12. package/built/src/ICCF/types.d.ts +1 -0
  13. package/built/src/ICCF/utils.d.ts +1 -0
  14. package/built/src/ICCF/utils.js +1 -0
  15. package/built/src/ICCF/utils.js.map +1 -1
  16. package/built/src/blockchainClient/blockchainClient.js +61 -3
  17. package/built/src/blockchainClient/blockchainClient.js.map +1 -1
  18. package/built/src/blockchainClient/clientStub.js +5 -1
  19. package/built/src/blockchainClient/clientStub.js.map +1 -1
  20. package/built/src/blockchainClient/enums.d.ts +2 -1
  21. package/built/src/blockchainClient/enums.js +1 -0
  22. package/built/src/blockchainClient/enums.js.map +1 -1
  23. package/built/src/blockchainClient/errors.d.ts +1 -0
  24. package/built/src/blockchainClient/errors.js.map +1 -1
  25. package/built/src/blockchainClient/failoverStrategies.js +3 -1
  26. package/built/src/blockchainClient/failoverStrategies.js.map +1 -1
  27. package/built/src/blockchainClient/httpUtil.d.ts +1 -0
  28. package/built/src/blockchainClient/httpUtil.js +1 -0
  29. package/built/src/blockchainClient/httpUtil.js.map +1 -1
  30. package/built/src/blockchainClient/interface.d.ts +2 -0
  31. package/built/src/blockchainClient/requestWithFailoverStrategy.d.ts +1 -0
  32. package/built/src/blockchainClient/requestWithFailoverStrategy.js.map +1 -1
  33. package/built/src/blockchainClient/types.d.ts +4 -1
  34. package/built/src/blockchainClient/utils.d.ts +3 -1
  35. package/built/src/blockchainClient/utils.js +16 -13
  36. package/built/src/blockchainClient/utils.js.map +1 -1
  37. package/built/src/blockchainClient/validation/anchoringTransaction.d.ts +1 -0
  38. package/built/src/blockchainClient/validation/anchoringTransaction.js +1 -0
  39. package/built/src/blockchainClient/validation/anchoringTransaction.js.map +1 -1
  40. package/built/src/blockchainClient/validation/bufferSchema.d.ts +1 -0
  41. package/built/src/blockchainClient/validation/bufferSchema.js +1 -0
  42. package/built/src/blockchainClient/validation/bufferSchema.js.map +1 -1
  43. package/built/src/blockchainClient/validation/merkleHash.js +0 -1
  44. package/built/src/blockchainClient/validation/merkleHash.js.map +1 -1
  45. package/built/src/blockchainClient/validation/rawGtx.js +1 -0
  46. package/built/src/blockchainClient/validation/rawGtx.js.map +1 -1
  47. package/built/src/blockchainClient/validation/requests.js +1 -0
  48. package/built/src/blockchainClient/validation/requests.js.map +1 -1
  49. package/built/src/blockchainClient/validation/txRid.d.ts +1 -0
  50. package/built/src/blockchainClient/validation/txRid.js.map +1 -1
  51. package/built/src/encryption/encryption.d.ts +1 -0
  52. package/built/src/encryption/encryption.js +1 -0
  53. package/built/src/encryption/encryption.js.map +1 -1
  54. package/built/src/encryption/errors.d.ts +1 -0
  55. package/built/src/encryption/errors.js.map +1 -1
  56. package/built/src/encryption/types.d.ts +1 -0
  57. package/built/src/formatter.d.ts +1 -0
  58. package/built/src/formatter.js +1 -0
  59. package/built/src/formatter.js.map +1 -1
  60. package/built/src/gtv/index.js +7 -0
  61. package/built/src/gtv/index.js.map +1 -1
  62. package/built/src/gtv/types.d.ts +1 -0
  63. package/built/src/gtx/gtx.d.ts +2 -1
  64. package/built/src/gtx/gtx.js +4 -3
  65. package/built/src/gtx/gtx.js.map +1 -1
  66. package/built/src/gtx/serialization.d.ts +1 -0
  67. package/built/src/gtx/serialization.js +1 -0
  68. package/built/src/gtx/serialization.js.map +1 -1
  69. package/built/src/gtx/types.d.ts +1 -0
  70. package/built/src/utils/calculateTransactionRid.d.ts +1 -0
  71. package/built/src/utils/calculateTransactionRid.js.map +1 -1
  72. package/built/src/utils/constants.d.ts +1 -0
  73. package/built/src/utils/constants.js +1 -0
  74. package/built/src/utils/constants.js.map +1 -1
  75. package/built/src/utils/decodeTransactionToGtx.d.ts +1 -0
  76. package/built/src/utils/decodeTransactionToGtx.js.map +1 -1
  77. package/built/src/utils/dump.js +1 -0
  78. package/built/src/utils/dump.js.map +1 -1
  79. package/built/src/utils/encodeTransaction.d.ts +1 -0
  80. package/built/src/utils/encodeTransaction.js.map +1 -1
  81. package/built/test/common/mocks.d.ts +17 -0
  82. package/built/test/common/mocks.js +21 -1
  83. package/built/test/common/mocks.js.map +1 -1
  84. package/built/test/integration/clientGetTransactionStatus.test.js +2 -2
  85. package/built/test/integration/clientGetTransactionStatus.test.js.map +1 -1
  86. package/built/test/integration/clientQuery.test.js +2 -2
  87. package/built/test/integration/clientQuery.test.js.map +1 -1
  88. package/built/test/integration/clientSendTransaction.test.js +1 -1
  89. package/built/test/integration/clientSendTransaction.test.js.map +1 -1
  90. package/built/test/integration/clientSignAndSendUniqueTransaction.test.js +1 -1
  91. package/built/test/integration/clientSignAndSendUniqueTransaction.test.js.map +1 -1
  92. package/built/test/integration/createClientIntegration.test.js +3 -0
  93. package/built/test/integration/createClientIntegration.test.js.map +1 -1
  94. package/built/test/integration/signAndSendUniqueTransaction.test.js +7 -6
  95. package/built/test/integration/signAndSendUniqueTransaction.test.js.map +1 -1
  96. package/built/test/integrationChromiaNetwork/getTransactionConfirmationLevel.test.js +1 -0
  97. package/built/test/integrationChromiaNetwork/getTransactionConfirmationLevel.test.js.map +1 -1
  98. package/built/test/integrationChromiaNetwork/requestWithFailoverStrategy.test.js +4 -3
  99. package/built/test/integrationChromiaNetwork/requestWithFailoverStrategy.test.js.map +1 -1
  100. package/built/test/integrationChromiaNetwork/signAndSendUniqueTransaction.test.js +10 -7
  101. package/built/test/integrationChromiaNetwork/signAndSendUniqueTransaction.test.js.map +1 -1
  102. package/built/test/pcctf/getSuites.test.js +1 -1
  103. package/built/test/pcctf/getSuites.test.js.map +1 -1
  104. package/built/test/pcctf/helpers.js +1 -1
  105. package/built/test/pcctf/helpers.js.map +1 -1
  106. package/built/test/unit/blockchainClient/client.test.js +2 -1
  107. package/built/test/unit/blockchainClient/client.test.js.map +1 -1
  108. package/built/test/unit/blockchainClient/getTransactionConfirmationLevel.test.js +2 -2
  109. package/built/test/unit/blockchainClient/getTransactionConfirmationLevel.test.js.map +1 -1
  110. package/built/test/unit/blockchainClient/sendTransaction.test.js +14 -8
  111. package/built/test/unit/blockchainClient/sendTransaction.test.js.map +1 -1
  112. package/built/test/unit/blockchainClient/statusPollIntervals.test.js +35 -28
  113. package/built/test/unit/blockchainClient/statusPollIntervals.test.js.map +1 -1
  114. package/built/test/unit/failoverStrategies.test.js +15 -14
  115. package/built/test/unit/failoverStrategies.test.js.map +1 -1
  116. package/built/test/unit/gtv/gtvHash.test.js +44 -0
  117. package/built/test/unit/gtv/gtvHash.test.js.map +1 -1
  118. package/built/test/unit/gtx/newSignatureProvider.test.js +4 -4
  119. package/built/test/unit/gtx/newSignatureProvider.test.js.map +1 -1
  120. package/built/test/unit/httpUtil.test.js +4 -0
  121. package/built/test/unit/httpUtil.test.js.map +1 -1
  122. package/built/umd/index.js +99 -26
  123. package/built/umd/index.js.map +1 -1
  124. package/changelog.md +19 -1
  125. package/package.json +1 -1
package/README.md CHANGED
@@ -451,6 +451,11 @@ Backend
451
451
 
452
452
  ## Contributing to the Project
453
453
 
454
+ ### Code conventions
455
+
456
+ * Remember to `import { Buffer } from "buffer";` in all `.ts` and `.js` files in `src/` which refers to `Buffer` to
457
+ ensure seamless functionality in web browsers.
458
+
454
459
  ### Run tests
455
460
 
456
461
  Unit tests:
@@ -1,6 +1,7 @@
1
1
  'use strict';
2
2
 
3
3
  var merklehashts = require('merklehashts');
4
+ var buffer = require('buffer');
4
5
  var bn_js = require('bn.js');
5
6
  var zod = require('zod');
6
7
  var crypto = require('crypto');
@@ -84,7 +85,7 @@ class MissingSignerException extends CustomError {
84
85
  }
85
86
  }
86
87
 
87
- const bufferSchema = zod.z.custom(val => Buffer.isBuffer(val), {
88
+ const bufferSchema = zod.z.custom(val => buffer.Buffer.isBuffer(val), {
88
89
  message: "Expected Buffer",
89
90
  });
90
91
  const rawGtvSchema = zod.z.lazy(() => zod.z.union([
@@ -105,11 +106,11 @@ function isRawGtx(value) {
105
106
  return result.success;
106
107
  }
107
108
 
108
- function pgBytes(buffer) {
109
- if (!Buffer.isBuffer(buffer)) {
110
- throw new PgBytesInputException(buffer);
109
+ function pgBytes(buffer$1) {
110
+ if (!buffer.Buffer.isBuffer(buffer$1)) {
111
+ throw new PgBytesInputException(buffer$1);
111
112
  }
112
- return `\\x${buffer.toString("hex")}`;
113
+ return `\\x${buffer$1.toString("hex")}`;
113
114
  }
114
115
  /**
115
116
  * Converts hex string to Buffer
@@ -117,7 +118,7 @@ function pgBytes(buffer) {
117
118
  * @returns {Buffer}
118
119
  */
119
120
  function toBuffer(key) {
120
- return Buffer.from(key, "hex");
121
+ return buffer.Buffer.from(key, "hex");
121
122
  }
122
123
  /**
123
124
  * Converts Buffer to hex string
@@ -142,7 +143,7 @@ class PgBytesInputException extends Error {
142
143
  }
143
144
  }
144
145
  function ensureBuffer(value) {
145
- if (value instanceof Buffer) {
146
+ if (value instanceof buffer.Buffer) {
146
147
  return value;
147
148
  }
148
149
  else {
@@ -162,7 +163,7 @@ function checkGtvType(value) {
162
163
  if (value == null) {
163
164
  return true;
164
165
  }
165
- if (Buffer.isBuffer(value)) {
166
+ if (buffer.Buffer.isBuffer(value)) {
166
167
  return true;
167
168
  }
168
169
  if (typeof value === "string" || typeof value === "bigint") {
@@ -228,7 +229,7 @@ function removeDuplicateSigners(signers) {
228
229
  });
229
230
  const result = [];
230
231
  signersAsString.forEach(item => {
231
- result.push(Buffer.from(item, "hex"));
232
+ result.push(buffer.Buffer.from(item, "hex"));
232
233
  });
233
234
  return result;
234
235
  }
@@ -317,7 +318,7 @@ function createTypedArg(value) {
317
318
  if (value == null) {
318
319
  return { type: "null", value: null };
319
320
  }
320
- if (Buffer.isBuffer(value)) {
321
+ if (buffer.Buffer.isBuffer(value)) {
321
322
  return { type: "byteArray", value: value };
322
323
  }
323
324
  if (typeof value === "boolean") {
@@ -385,7 +386,19 @@ function sortDictPairByKey(dict) {
385
386
  return sortedDict;
386
387
  }
387
388
 
389
+ const MERKLE_HASH_VERSIONS = {
390
+ ONE: 1,
391
+ TWO: 2,
392
+ UNSET: NaN,
393
+ };
394
+
388
395
  const gtvHash2 = (obj, merkleHashVersion) => {
396
+ if (!Object.values(MERKLE_HASH_VERSIONS).includes(merkleHashVersion)) {
397
+ throw new Error("Merkle hash version is not valid");
398
+ }
399
+ if (isNaN(merkleHashVersion)) {
400
+ throw new Error("Merkle hash version is not set");
401
+ }
389
402
  return merklehashts.gtvHash(obj, merkleHashVersion);
390
403
  };
391
404
  const encode$1 = encodeValue;
@@ -411,7 +424,7 @@ class MissingPrivKeyArgumentException extends Error {
411
424
 
412
425
  function createPublicKey(privKey) {
413
426
  validatePrivKeyFormat(privKey);
414
- return Buffer.from(secp256k1__namespace.publicKeyCreate(privKey, true).buffer);
427
+ return buffer.Buffer.from(secp256k1__namespace.publicKeyCreate(privKey, true).buffer);
415
428
  }
416
429
  function randomBytes(size) {
417
430
  return crypto__namespace.randomBytes(size);
@@ -421,7 +434,7 @@ function sha256(buffer) {
421
434
  }
422
435
  const hash256 = sha256;
423
436
  function hashConcat(items) {
424
- return hash256(Buffer.concat(items));
437
+ return hash256(buffer.Buffer.concat(items));
425
438
  }
426
439
  /**
427
440
  * @param content the content that the signature signs. It will be digested before validating.
@@ -462,7 +475,7 @@ function sign$1(content, privKey) {
462
475
  * @return the signature
463
476
  */
464
477
  function signDigest(digestBuffer, privKey) {
465
- return Buffer.from(secp256k1__namespace.ecdsaSign(digestBuffer, privKey).signature);
478
+ return buffer.Buffer.from(secp256k1__namespace.ecdsaSign(digestBuffer, privKey).signature);
466
479
  }
467
480
  /**
468
481
  * Creates a key pair (which usually represents one user)
@@ -479,7 +492,7 @@ function makeKeyPair(privKey) {
479
492
  do {
480
493
  privKey = randomBytes(32);
481
494
  } while (!secp256k1__namespace.privateKeyVerify(privKey));
482
- pubKey = Buffer.from(secp256k1__namespace.publicKeyCreate(privKey).buffer);
495
+ pubKey = buffer.Buffer.from(secp256k1__namespace.publicKeyCreate(privKey).buffer);
483
496
  }
484
497
  return { pubKey, privKey };
485
498
  }
@@ -497,14 +510,14 @@ function makeTuid() {
497
510
  */
498
511
  function verifyKeyPair(privKey) {
499
512
  validatePrivKeyFormat(privKey);
500
- const pubKey = Buffer.from(secp256k1__namespace.publicKeyCreate(privKey).buffer);
513
+ const pubKey = buffer.Buffer.from(secp256k1__namespace.publicKeyCreate(privKey).buffer);
501
514
  return { pubKey, privKey };
502
515
  }
503
516
  function validatePrivKeyFormat(privKey) {
504
517
  if (!privKey) {
505
518
  throw new MissingPrivKeyArgumentException();
506
519
  }
507
- if (!Buffer.isBuffer(privKey) || privKey.length !== 32) {
520
+ if (!buffer.Buffer.isBuffer(privKey) || privKey.length !== 32) {
508
521
  throw new PrivKeyFormatException(privKey);
509
522
  }
510
523
  }
@@ -602,7 +615,7 @@ function gtxToRawGtx(gtx) {
602
615
  }
603
616
  function sign(gtx, privOrSigProv, merkleHashVersion, pubKey) {
604
617
  return __awaiter$9(this, void 0, void 0, function* () {
605
- if (privOrSigProv instanceof Buffer) {
618
+ if (privOrSigProv instanceof buffer.Buffer) {
606
619
  const digestToSign = getDigestToSign(gtx, merkleHashVersion);
607
620
  const signature = signDigest(digestToSign, privOrSigProv);
608
621
  return addSignature(pubKey || makeKeyPair(privOrSigProv).pubKey, signature, gtx);
@@ -610,7 +623,7 @@ function sign(gtx, privOrSigProv, merkleHashVersion, pubKey) {
610
623
  else {
611
624
  // Removes signatures and extract the rawgtxBody
612
625
  const rawGtxBody = gtxToRawGtxBody(gtx);
613
- const signature = yield privOrSigProv.sign(rawGtxBody);
626
+ const signature = yield privOrSigProv.sign(rawGtxBody, merkleHashVersion);
614
627
  return addSignature(privOrSigProv.pubKey, signature, gtx);
615
628
  }
616
629
  });
@@ -680,7 +693,7 @@ function checkExistingGTXSignatures(txHash, gtx) {
680
693
  }
681
694
  return true;
682
695
  }
683
- function newSignatureProvider(merkleHashVersion, keyPair) {
696
+ function newSignatureProvider(keyPair) {
684
697
  let pub, priv;
685
698
  if (keyPair) {
686
699
  priv = ensureBuffer(keyPair.privKey);
@@ -691,7 +704,7 @@ function newSignatureProvider(merkleHashVersion, keyPair) {
691
704
  }
692
705
  return {
693
706
  pubKey: pub,
694
- sign: (gtx) => __awaiter$9(this, void 0, void 0, function* () {
707
+ sign: (gtx, merkleHashVersion) => __awaiter$9(this, void 0, void 0, function* () {
695
708
  const signature = getDigestToSignFromRawGtxBody(gtx, merkleHashVersion);
696
709
  return signDigest(signature, priv);
697
710
  }),
@@ -709,7 +722,7 @@ function rawGtvToGtx(gtv) {
709
722
  throw new Error("Second element must be an array");
710
723
  }
711
724
  gtvArray[1].forEach(element => {
712
- if (!Buffer.isBuffer(element)) {
725
+ if (!buffer.Buffer.isBuffer(element)) {
713
726
  throw new Error("Element must be a buffer");
714
727
  }
715
728
  });
@@ -721,7 +734,7 @@ function rawGtvToGtxBody(gtv) {
721
734
  throw new Error("Gtv must be an array of size 3");
722
735
  }
723
736
  const array = gtv;
724
- if (!Buffer.isBuffer(array[0])) {
737
+ if (!buffer.Buffer.isBuffer(array[0])) {
725
738
  throw new Error("First element must be a byte array");
726
739
  }
727
740
  if (!Array.isArray(array[1])) {
@@ -731,7 +744,7 @@ function rawGtvToGtxBody(gtv) {
731
744
  throw new Error("Third element must be an array");
732
745
  }
733
746
  array[2].forEach(element => {
734
- if (!Buffer.isBuffer(element)) {
747
+ if (!buffer.Buffer.isBuffer(element)) {
735
748
  throw new Error("Element must be a buffer");
736
749
  }
737
750
  });
@@ -988,6 +1001,7 @@ exports.TransactionEvent = void 0;
988
1001
  TransactionEvent["DappConfirmed"] = "dappConfirmed";
989
1002
  TransactionEvent["DappReceived"] = "dappReceived";
990
1003
  TransactionEvent["Signed"] = "signed";
1004
+ TransactionEvent["Rejected"] = "rejected";
991
1005
  })(exports.TransactionEvent || (exports.TransactionEvent = {}));
992
1006
  exports.AnchoringStatus = void 0;
993
1007
  (function (AnchoringStatus) {
@@ -1082,7 +1096,7 @@ const createNodeManager = ({ nodeUrls, useStickyNode = false, unavailableDuratio
1082
1096
  };
1083
1097
  };
1084
1098
 
1085
- const BufferSchema = zod.z.union([zod.z.instanceof(Uint8Array), zod.z.instanceof(Buffer)]);
1099
+ const BufferSchema = zod.z.union([zod.z.instanceof(Uint8Array), zod.z.instanceof(buffer.Buffer)]);
1086
1100
 
1087
1101
  const TxRidSchema = BufferSchema.refine(x => x.length === 32, "Rid must be 32 bytes long");
1088
1102
  const isTxRidValid = (rid, options) => {
@@ -1104,12 +1118,12 @@ const isTxRidValid = (rid, options) => {
1104
1118
  };
1105
1119
 
1106
1120
  const AnchoringTransactionSchema = zod.z.object({
1107
- txRid: zod.z.instanceof(Buffer).superRefine((rid, refCtx) => {
1121
+ txRid: zod.z.instanceof(buffer.Buffer).superRefine((rid, refCtx) => {
1108
1122
  const txRidValidation = TxRidSchema.safeParse(rid);
1109
1123
  if (!txRidValidation.success)
1110
1124
  txRidValidation.error.issues.forEach(issue => refCtx.addIssue(issue));
1111
1125
  }),
1112
- txData: zod.z.instanceof(Buffer).refine(data => data.length > 0, {
1126
+ txData: zod.z.instanceof(buffer.Buffer).refine(data => data.length > 0, {
1113
1127
  message: "txData must be a non-empty Buffer",
1114
1128
  }),
1115
1129
  txOpIndex: zod.z.number().int().nonnegative({ message: "txOpIndex must be a non-negative integer" }),
@@ -1156,7 +1170,7 @@ const RawGtvSchema = zod.z.union([
1156
1170
  zod.z.string(),
1157
1171
  zod.z.number(),
1158
1172
  zod.z.bigint(),
1159
- zod.z.instanceof(Buffer),
1173
+ zod.z.instanceof(buffer.Buffer),
1160
1174
  zod.z.array(zod.z.unknown()),
1161
1175
  zod.z.record(zod.z.unknown()),
1162
1176
  ]);
@@ -1186,9 +1200,9 @@ const TransactionConfirmationProofSchema = zod.z.object({
1186
1200
  proof: zod.z.string(),
1187
1201
  });
1188
1202
  const ConfirmationProofSchema = zod.z.object({
1189
- hash: zod.z.instanceof(Buffer),
1190
- blockHeader: zod.z.instanceof(Buffer),
1191
- witness: zod.z.instanceof(Buffer),
1203
+ hash: zod.z.instanceof(buffer.Buffer),
1204
+ blockHeader: zod.z.instanceof(buffer.Buffer),
1205
+ witness: zod.z.instanceof(buffer.Buffer),
1192
1206
  merkleProofTree: RawGtvSchema,
1193
1207
  txIndex: zod.z.number(),
1194
1208
  });
@@ -1203,17 +1217,17 @@ const TransactionInfoResponseSchema = zod.z.object({
1203
1217
  txData: zod.z.string(),
1204
1218
  });
1205
1219
  const TransactionInfoSchema = zod.z.object({
1206
- blockRid: zod.z.instanceof(Buffer),
1220
+ blockRid: zod.z.instanceof(buffer.Buffer),
1207
1221
  blockHeight: zod.z.number(),
1208
- blockHeader: zod.z.instanceof(Buffer),
1209
- witness: zod.z.instanceof(Buffer),
1222
+ blockHeader: zod.z.instanceof(buffer.Buffer),
1223
+ witness: zod.z.instanceof(buffer.Buffer),
1210
1224
  timestamp: zod.z.number(),
1211
- txRid: zod.z.instanceof(Buffer),
1212
- txHash: zod.z.instanceof(Buffer),
1213
- txData: zod.z.instanceof(Buffer),
1225
+ txRid: zod.z.instanceof(buffer.Buffer),
1226
+ txHash: zod.z.instanceof(buffer.Buffer),
1227
+ txData: zod.z.instanceof(buffer.Buffer),
1214
1228
  });
1215
1229
  zod.z.object({
1216
- txRid: zod.z.instanceof(Buffer),
1230
+ txRid: zod.z.instanceof(buffer.Buffer),
1217
1231
  rejectReason: zod.z.string(),
1218
1232
  rejectTimestamp: zod.z.number(),
1219
1233
  });
@@ -1296,18 +1310,12 @@ function encodeTransaction(gtx) {
1296
1310
  return serialize(gtx);
1297
1311
  }
1298
1312
 
1299
- const MERKLE_HASH_VERSIONS = {
1300
- ONE: 1,
1301
- TWO: 2,
1302
- };
1303
-
1304
1313
  const MerkleHashSchema = zod.z.object({
1305
1314
  merkle_hash_version: zod.z.number().int().positive(),
1306
1315
  });
1307
1316
  const validateMerkleHash = (data) => {
1308
1317
  const result = MerkleHashSchema.safeParse(data);
1309
1318
  if (!result.success) {
1310
- console.warn("MERKLE_HASH_WARNING: version not found or endpoint unreachable");
1311
1319
  return { merkle_hash_version: MERKLE_HASH_VERSIONS.ONE };
1312
1320
  }
1313
1321
  return result.data;
@@ -1373,7 +1381,7 @@ function post(path, endpoint, requestBody) {
1373
1381
  return __awaiter$8(this, void 0, void 0, function* () {
1374
1382
  debug(`POST URL ${new URL(path, endpoint).href}`);
1375
1383
  debug(`POST body ${JSON.stringify(requestBody)}`);
1376
- if (Buffer.isBuffer(requestBody)) {
1384
+ if (buffer.Buffer.isBuffer(requestBody)) {
1377
1385
  try {
1378
1386
  const requestOptions = {
1379
1387
  method: "post",
@@ -1415,8 +1423,8 @@ function constructBufferResponseBody(response) {
1415
1423
  const contentType = response.headers.get("content-type");
1416
1424
  if (contentType === "application/octet-stream") {
1417
1425
  const responseBuffer = yield response.arrayBuffer();
1418
- const buffer = Buffer.from(responseBuffer);
1419
- return decodeValue(buffer);
1426
+ const buffer$1 = buffer.Buffer.from(responseBuffer);
1427
+ return decodeValue(buffer$1);
1420
1428
  }
1421
1429
  if (contentType === "application/json") {
1422
1430
  return yield response.json();
@@ -1583,7 +1591,8 @@ function retryRequest({ method, path, config, postObject, validateStatusCode, })
1583
1591
  let error = null;
1584
1592
  let transactionTimestamp = undefined;
1585
1593
  const { nodeManager } = config;
1586
- for (const endpoint of nodeManager.getAvailableNodes()) {
1594
+ const availableNodes = nodeManager.getAvailableNodes();
1595
+ for (const endpoint of availableNodes) {
1587
1596
  for (let attempt = 0; attempt < config.attemptsPerEndpoint; attempt++) {
1588
1597
  const response = yield handleRequest(method, path, endpoint.url, postObject);
1589
1598
  error = (_a = response === null || response === void 0 ? void 0 : response.error) !== null && _a !== void 0 ? _a : null;
@@ -1594,6 +1603,7 @@ function retryRequest({ method, path, config, postObject, validateStatusCode, })
1594
1603
  const isServerError = statusCode ? hasServerError(statusCode) : false;
1595
1604
  if (isStatusCodeValid && !error) {
1596
1605
  // Find a way to have this handled more elegantly in the node manager.
1606
+ nodeManager.lastUsedNode = endpoint;
1597
1607
  if (nodeManager.stickedNode !== endpoint) {
1598
1608
  nodeManager.setStickyNode(endpoint);
1599
1609
  }
@@ -1744,7 +1754,7 @@ function getClientConfigFromSettings(settings) {
1744
1754
  nodeManager,
1745
1755
  endpointPool,
1746
1756
  chainId: settings.blockchainIid,
1747
- merkleHashVersion: (_k = settings.merkleHashVersion) !== null && _k !== void 0 ? _k : 0,
1757
+ merkleHashVersion: (_k = settings.merkleHashVersion) !== null && _k !== void 0 ? _k : MERKLE_HASH_VERSIONS.UNSET,
1748
1758
  });
1749
1759
  }
1750
1760
  throw new MissingBlockchainIdentifierError();
@@ -1759,17 +1769,18 @@ function getClientConfigFromSettings(settings) {
1759
1769
  nodeManager,
1760
1770
  endpointPool,
1761
1771
  chainId: directoryChainIid,
1762
- merkleHashVersion: (_l = settings.merkleHashVersion) !== null && _l !== void 0 ? _l : 0,
1772
+ merkleHashVersion: (_l = settings.merkleHashVersion) !== null && _l !== void 0 ? _l : MERKLE_HASH_VERSIONS.UNSET,
1763
1773
  });
1764
1774
  }))();
1765
1775
  return {
1766
1776
  endpointPool,
1767
1777
  nodeManager: nodeManager,
1768
1778
  blockchainRid: blockchainRidToUse,
1769
- merkleHashVersion: (_e = settings.merkleHashVersion) !== null && _e !== void 0 ? _e : 0,
1779
+ merkleHashVersion: (_e = settings.merkleHashVersion) !== null && _e !== void 0 ? _e : MERKLE_HASH_VERSIONS.UNSET,
1770
1780
  dappStatusPolling: setStatusPolling(settings.dappStatusPolling),
1771
1781
  clusterAnchoringStatusPolling: setStatusPolling(settings.clusterAnchoringStatusPolling),
1772
1782
  systemAnchoringStatusPolling: setStatusPolling(settings.systemAnchoringStatusPolling),
1783
+ retryTransactionPolling: setRetryTransactionPolling(settings.retryTransactionPolling),
1773
1784
  failoverStrategy: ((_f = settings.failOverConfig) === null || _f === void 0 ? void 0 : _f.strategy) || defaultFailoverConfig.strategy,
1774
1785
  attemptsPerEndpoint: ((_g = settings.failOverConfig) === null || _g === void 0 ? void 0 : _g.attemptsPerEndpoint) || defaultFailoverConfig.attemptsPerEndpoint,
1775
1786
  attemptInterval: ((_h = settings.failOverConfig) === null || _h === void 0 ? void 0 : _h.attemptInterval) || defaultFailoverConfig.attemptInterval,
@@ -1805,7 +1816,6 @@ function nodeDiscovery({ nodeManager, directoryEndpointPool, failOverConfig, blo
1805
1816
  endpointPool: directoryEndpointPool,
1806
1817
  chainId: directoryIid,
1807
1818
  failOverConfig,
1808
- merkleHashVersion: 0,
1809
1819
  });
1810
1820
  const blockchainRidToUse = yield (() => __awaiter$5(this, void 0, void 0, function* () {
1811
1821
  if (blockchainRid) {
@@ -1817,7 +1827,6 @@ function nodeDiscovery({ nodeManager, directoryEndpointPool, failOverConfig, blo
1817
1827
  endpointPool: directoryEndpointPool,
1818
1828
  chainId: blockchainIid,
1819
1829
  failOverConfig,
1820
- merkleHashVersion: 0,
1821
1830
  });
1822
1831
  }
1823
1832
  throw new MissingBlockchainIdentifierError();
@@ -1825,7 +1834,6 @@ function nodeDiscovery({ nodeManager, directoryEndpointPool, failOverConfig, blo
1825
1834
  const D1Client = yield createClient({
1826
1835
  nodeUrlPool: getUrlsFromEndpoints(directoryEndpointPool),
1827
1836
  blockchainRid: directoryBRID,
1828
- merkleHashVersion: 0,
1829
1837
  });
1830
1838
  return yield getBlockchainApiUrls(D1Client, ensureBuffer(blockchainRidToUse));
1831
1839
  });
@@ -1850,13 +1858,13 @@ function convertToRellOperation(operations) {
1850
1858
  }
1851
1859
  function getSerializedGTX(gtx) {
1852
1860
  const gtxBytes = encodeTransaction(gtx);
1853
- if (!Buffer.isBuffer(gtxBytes)) {
1861
+ if (!buffer.Buffer.isBuffer(gtxBytes)) {
1854
1862
  throw new SerializedTransactionFormatException();
1855
1863
  }
1856
1864
  return gtxBytes;
1857
1865
  }
1858
1866
  function getGTXFromBufferOrTransactionOrOperation(transaction, blockchainRid) {
1859
- if (Buffer.isBuffer(transaction)) {
1867
+ if (buffer.Buffer.isBuffer(transaction)) {
1860
1868
  return deserialize(transaction);
1861
1869
  }
1862
1870
  else if ("operations" in transaction) {
@@ -1958,8 +1966,8 @@ const isKeyPair = (keypair) => {
1958
1966
  keypair !== null &&
1959
1967
  "privKey" in keypair &&
1960
1968
  "pubKey" in keypair &&
1961
- keypair.privKey instanceof Buffer &&
1962
- keypair.pubKey instanceof Buffer);
1969
+ keypair.privKey instanceof buffer.Buffer &&
1970
+ keypair.pubKey instanceof buffer.Buffer);
1963
1971
  };
1964
1972
  function getNodeUrlsFromSettings(settings) {
1965
1973
  var _a;
@@ -1998,7 +2006,6 @@ function getSystemClient(directoryNodeUrlPool, directoryChainRid) {
1998
2006
  return yield createClient({
1999
2007
  directoryNodeUrlPool,
2000
2008
  blockchainRid: directoryChainRid,
2001
- merkleHashVersion: 0,
2002
2009
  });
2003
2010
  });
2004
2011
  }
@@ -2037,7 +2044,7 @@ const getUrlsFromEndpoints = (endpointPool) => {
2037
2044
  function awaitDappConfirmation(txRID, dappStatusPolling, getTransactionStatus) {
2038
2045
  var _a;
2039
2046
  return __awaiter$5(this, void 0, void 0, function* () {
2040
- let lastKnownResult;
2047
+ let lastKnownResult = null;
2041
2048
  for (let i = 0; i < dappStatusPolling.count; i++) {
2042
2049
  lastKnownResult = yield getTransactionStatus(txRID);
2043
2050
  if (lastKnownResult.status === exports.ResponseStatus.Confirmed) {
@@ -2048,10 +2055,7 @@ function awaitDappConfirmation(txRID, dappStatusPolling, getTransactionStatus) {
2048
2055
  }
2049
2056
  yield sleep(dappStatusPolling.interval);
2050
2057
  }
2051
- // TS issue. This could be fixed by implementing new retry strategy
2052
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
2053
- //@ts-expect-error
2054
- return lastKnownResult;
2058
+ throw new Error(`Retry count exceeded. Confirmation not received. Last transaction status: ${lastKnownResult === null || lastKnownResult === void 0 ? void 0 : lastKnownResult.status}`);
2055
2059
  });
2056
2060
  }
2057
2061
  function awaitClusterAnchoringChainConfirmation(txRID, clusterAnchoringStatusPolling, getClusterAnchoringTransactionConfirmation) {
@@ -2165,6 +2169,13 @@ function setStatusPolling(statusPolling) {
2165
2169
  count: (_b = statusPolling === null || statusPolling === void 0 ? void 0 : statusPolling.count) !== null && _b !== void 0 ? _b : 20,
2166
2170
  };
2167
2171
  }
2172
+ function setRetryTransactionPolling(statusPolling) {
2173
+ var _a, _b;
2174
+ return {
2175
+ interval: (_a = statusPolling === null || statusPolling === void 0 ? void 0 : statusPolling.interval) !== null && _a !== void 0 ? _a : 500,
2176
+ count: (_b = statusPolling === null || statusPolling === void 0 ? void 0 : statusPolling.count) !== null && _b !== void 0 ? _b : 3,
2177
+ };
2178
+ }
2168
2179
  function linkPromiEvents(event1, event2) {
2169
2180
  const transactionEvents = Object.values(exports.TransactionEvent).filter((event) => typeof event === "string");
2170
2181
  /* eslint-disable @typescript-eslint/no-explicit-any */
@@ -2236,11 +2247,12 @@ function getBlockchainRidFromIid({ endpointPool, chainId, failOverConfig = {}, n
2236
2247
  dappStatusPolling: setStatusPolling(),
2237
2248
  clusterAnchoringStatusPolling: setStatusPolling(),
2238
2249
  systemAnchoringStatusPolling: setStatusPolling(),
2250
+ retryTransactionPolling: setRetryTransactionPolling(),
2239
2251
  failoverStrategy: mergedFailOverConfig.strategy,
2240
2252
  attemptsPerEndpoint: mergedFailOverConfig.attemptsPerEndpoint,
2241
2253
  attemptInterval: mergedFailOverConfig.attemptInterval,
2242
2254
  unreachableDuration: mergedFailOverConfig.unreachableDuration,
2243
- merkleHashVersion: 0,
2255
+ merkleHashVersion: MERKLE_HASH_VERSIONS.UNSET,
2244
2256
  };
2245
2257
  const { error, statusCode, rspBody } = yield requestWithFailoverStrategy(Method.GET, `/brid/iid_${chainId}`, config);
2246
2258
  const blockchainRid = isString(rspBody);
@@ -2364,7 +2376,7 @@ function fetchAndVerifyTransaction(sourceClient, txToProveRID, proofHash, txToPr
2364
2376
  const rawTx = yield sourceClient.getTransaction(txToProveRID);
2365
2377
  const txGtv = decodeValue(rawTx);
2366
2378
  const fetchedTxHash = gtvHash2(txGtv, sourceClient.config.merkleHashVersion);
2367
- if (Buffer.compare(fetchedTxHash, proofHash)) {
2379
+ if (buffer.Buffer.compare(fetchedTxHash, proofHash)) {
2368
2380
  // We received another hash for tx RID than what was included in proof
2369
2381
  // Possibly rouge or faulty node(s). Anyway, we need to give up.
2370
2382
  throw new MissingTransactionProof(proofHash, fetchedTxHash);
@@ -2374,7 +2386,7 @@ function fetchAndVerifyTransaction(sourceClient, txToProveRID, proofHash, txToPr
2374
2386
  throw new DifferentNumberOfSignersException((_c = (_b = fetchedTx.signatures) === null || _b === void 0 ? void 0 : _b.length) !== null && _c !== void 0 ? _c : 0, txToProveSigners.length);
2375
2387
  }
2376
2388
  const txRID = getDigestToSign(fetchedTx, sourceClient.config.merkleHashVersion);
2377
- if (Buffer.compare(txRID, ensureBuffer(txToProveRID))) {
2389
+ if (buffer.Buffer.compare(txRID, ensureBuffer(txToProveRID))) {
2378
2390
  throw new ProofRidException();
2379
2391
  }
2380
2392
  for (const signer of txToProveSigners) {
@@ -2548,7 +2560,7 @@ function getAnchoringClient(client, dappBlockchainRid, cluster) {
2548
2560
  if (!sourceClusterInfo || !sourceClusterInfo.anchoring_chain) {
2549
2561
  throw Error("Cluster info could not be found");
2550
2562
  }
2551
- const networkSettings = Object.assign(Object.assign({}, client.config), { directoryNodeUrlPool: getUrlsFromEndpoints(client.config.endpointPool), blockchainRid: toString(sourceClusterInfo.anchoring_chain), merkleHashVersion: 0 });
2563
+ const networkSettings = Object.assign(Object.assign({}, client.config), { directoryNodeUrlPool: getUrlsFromEndpoints(client.config.endpointPool), blockchainRid: toString(sourceClusterInfo.anchoring_chain) });
2552
2564
  const clientConfiguredToAnchoringchain = yield createClient(networkSettings);
2553
2565
  return clientConfiguredToAnchoringchain;
2554
2566
  });
@@ -2906,6 +2918,48 @@ function createClient(settings) {
2906
2918
  }
2907
2919
  });
2908
2920
  },
2921
+ sendTransactionWithRetries(transaction, callback, confirmationLevel = exports.ChainConfirmationLevel.Dapp) {
2922
+ const client = this;
2923
+ function sendOnce() {
2924
+ return client.sendTransaction(transaction, true, callback, confirmationLevel);
2925
+ }
2926
+ const promiEvent = new Web3PromiEvent((resolve, reject) => __awaiter$1(this, void 0, void 0, function* () {
2927
+ let error = null;
2928
+ // await sleep(1000);
2929
+ for (let i = 0; i < config.retryTransactionPolling.count; i++) {
2930
+ info(`sendTransactionWithRetries attempt ${i + 1} of ${config.retryTransactionPolling.count}`);
2931
+ const tmpPromiEvent = sendOnce()
2932
+ .on(exports.TransactionEvent.ClusterAnchoringConfirmation, receipt => {
2933
+ promiEvent.emit(exports.TransactionEvent.ClusterAnchoringConfirmation, receipt);
2934
+ })
2935
+ .on(exports.TransactionEvent.SystemAnchoringConfirmation, receipt => {
2936
+ promiEvent.emit(exports.TransactionEvent.SystemAnchoringConfirmation, receipt);
2937
+ })
2938
+ .on(exports.TransactionEvent.DappReceived, receipt => {
2939
+ promiEvent.emit(exports.TransactionEvent.DappReceived, receipt);
2940
+ })
2941
+ .on(exports.TransactionEvent.Signed, receipt => {
2942
+ promiEvent.emit(exports.TransactionEvent.Signed, receipt);
2943
+ })
2944
+ .on(exports.TransactionEvent.DappConfirmed, receipt => {
2945
+ promiEvent.emit(exports.TransactionEvent.DappConfirmed, receipt);
2946
+ })
2947
+ .catch(tmpError => {
2948
+ warning(`sendTransactionWithRetries error on attempt ${i + 1} of ${config.retryTransactionPolling.count}: ${tmpError}`);
2949
+ promiEvent.emit(exports.TransactionEvent.Rejected, tmpError);
2950
+ error = tmpError;
2951
+ });
2952
+ const tmpReceipt = yield tmpPromiEvent;
2953
+ if (tmpReceipt) {
2954
+ resolve(tmpReceipt);
2955
+ return;
2956
+ }
2957
+ yield sleep(config.retryTransactionPolling.interval);
2958
+ }
2959
+ reject(error);
2960
+ }));
2961
+ return promiEvent;
2962
+ },
2909
2963
  sendTransaction(transaction, doStatusPolling = true, callback, confirmationLevel = exports.ChainConfirmationLevel.Dapp) {
2910
2964
  const promiEvent = new Web3PromiEvent((resolve, reject) => __awaiter$1(this, void 0, void 0, function* () {
2911
2965
  var _a, _b;
@@ -2940,14 +2994,15 @@ function createClient(settings) {
2940
2994
  clusterAnchoringStatusPolling: client.config.clusterAnchoringStatusPolling,
2941
2995
  systemAnchoringStatusPolling: client.config.systemAnchoringStatusPolling,
2942
2996
  };
2943
- let transactionReceipt = yield handleDappConfirmations(transactionRid, doStatusPolling, confirmationLevel, promiEvent, statusPollingConfig.dappStatusPolling, () => client.getTransactionStatus(transactionRid, callback), client);
2997
+ const stickyNodeClient = yield createStickyNodeClient(client); //to avoid false rejections by oblivious nodes
2998
+ let transactionReceipt = yield handleDappConfirmations(transactionRid, doStatusPolling, confirmationLevel, promiEvent, statusPollingConfig.dappStatusPolling, () => stickyNodeClient.getTransactionStatus(transactionRid, callback), stickyNodeClient);
2944
2999
  if (confirmationLevel === exports.ChainConfirmationLevel.None ||
2945
3000
  confirmationLevel === exports.ChainConfirmationLevel.Dapp) {
2946
3001
  resolve(transactionReceipt);
2947
3002
  return;
2948
3003
  }
2949
3004
  const { anchoringClient, systemAnchoringChainBridString } = yield getAnchoringClientAndSystemChainRid(client);
2950
- transactionReceipt = yield handleSystemConfirmations(transactionReceipt, confirmationLevel, promiEvent, statusPollingConfig, anchoringClient, systemAnchoringChainBridString, () => client.getClusterAnchoringTransactionConfirmation(transactionRid, anchoringClient, callback), anchoredTxRid => client.getSystemAnchoringTransactionConfirmation(anchoredTxRid, anchoringClient, systemAnchoringChainBridString, callback));
3005
+ transactionReceipt = yield handleSystemConfirmations(transactionReceipt, confirmationLevel, promiEvent, statusPollingConfig, anchoringClient, systemAnchoringChainBridString, () => stickyNodeClient.getClusterAnchoringTransactionConfirmation(transactionRid, anchoringClient, callback), anchoredTxRid => stickyNodeClient.getSystemAnchoringTransactionConfirmation(anchoredTxRid, anchoringClient, systemAnchoringChainBridString, callback));
2951
3006
  resolve(transactionReceipt);
2952
3007
  }
2953
3008
  catch (error) {
@@ -3367,6 +3422,21 @@ function createClient(settings) {
3367
3422
  return merkleHashVersion;
3368
3423
  });
3369
3424
  }
3425
+ function createStickyNodeClient(client) {
3426
+ var _a;
3427
+ return __awaiter$1(this, void 0, void 0, function* () {
3428
+ if (!client.config.nodeManager.lastUsedNode) {
3429
+ throw new Error("No last used node found; cannot create sticky node client");
3430
+ }
3431
+ const stickyNodeClient = yield createClient({
3432
+ nodeUrlPool: (_a = client.config.nodeManager.lastUsedNode) === null || _a === void 0 ? void 0 : _a.url,
3433
+ blockchainRid: client.config.blockchainRid,
3434
+ merkleHashVersion: client.config.merkleHashVersion,
3435
+ useStickyNode: true,
3436
+ });
3437
+ return stickyNodeClient;
3438
+ });
3439
+ }
3370
3440
  });
3371
3441
  }
3372
3442
 
@@ -3392,6 +3462,7 @@ function createStubClient() {
3392
3462
  dappStatusPolling: setStatusPolling({ interval: 5000, count: 5 }),
3393
3463
  clusterAnchoringStatusPolling: setStatusPolling(),
3394
3464
  systemAnchoringStatusPolling: setStatusPolling(),
3465
+ retryTransactionPolling: setRetryTransactionPolling(),
3395
3466
  failoverStrategy: exports.FailoverStrategy.AbortOnError,
3396
3467
  attemptsPerEndpoint: 3,
3397
3468
  attemptInterval: 5000,
@@ -3411,6 +3482,9 @@ function createStubClient() {
3411
3482
  sendTransaction() {
3412
3483
  return new Web3PromiEvent((_resolve, reject) => reject("sendTransaction rejected"));
3413
3484
  },
3485
+ sendTransactionWithRetries() {
3486
+ return new Web3PromiEvent((_resolve, reject) => reject("sendTransactionWithRetries rejected"));
3487
+ },
3414
3488
  signAndSendUniqueTransaction() {
3415
3489
  return new Web3PromiEvent((_resolve, reject) => reject("signAndSendUniqueTransaction rejected"));
3416
3490
  },
@@ -3536,7 +3610,7 @@ function dumpGtv(rawGtv) {
3536
3610
  if (typeof value === "bigint") {
3537
3611
  return `${value.toString()}L`;
3538
3612
  }
3539
- if (Buffer.isBuffer(value)) {
3613
+ if (buffer.Buffer.isBuffer(value)) {
3540
3614
  return toString(value);
3541
3615
  }
3542
3616
  if (typeof value === "object" &&