postchain-client 1.3.2 → 1.5.0

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 (47) hide show
  1. package/README.md +244 -167
  2. package/built/cjs/index.js +589 -46
  3. package/built/cjs/index.js.map +1 -1
  4. package/built/esm/index.js +31594 -34572
  5. package/built/esm/index.js.map +1 -1
  6. package/built/index.d.ts +2 -0
  7. package/built/index.js +2 -0
  8. package/built/index.js.map +1 -1
  9. package/built/src/blockchainClient/blockchainClient.d.ts +3 -0
  10. package/built/src/blockchainClient/blockchainClient.js +251 -0
  11. package/built/src/blockchainClient/blockchainClient.js.map +1 -0
  12. package/built/src/blockchainClient/errors.d.ts +15 -0
  13. package/built/src/blockchainClient/errors.js +26 -0
  14. package/built/src/blockchainClient/errors.js.map +1 -0
  15. package/built/src/blockchainClient/interface.d.ts +108 -0
  16. package/built/src/blockchainClient/interface.js +2 -0
  17. package/built/src/blockchainClient/interface.js.map +1 -0
  18. package/built/src/blockchainClient/types.d.ts +91 -0
  19. package/built/src/blockchainClient/types.js +8 -0
  20. package/built/src/blockchainClient/types.js.map +1 -0
  21. package/built/src/blockchainClient/utils.d.ts +18 -0
  22. package/built/src/blockchainClient/utils.js +157 -0
  23. package/built/src/blockchainClient/utils.js.map +1 -0
  24. package/built/src/gtv/definition.js +1 -1
  25. package/built/src/gtv/definition.js.map +1 -1
  26. package/built/src/gtx/errors.js +1 -1
  27. package/built/src/gtx/errors.js.map +1 -1
  28. package/built/src/gtx/gtx.d.ts +4 -3
  29. package/built/src/gtx/gtx.js +17 -9
  30. package/built/src/gtx/gtx.js.map +1 -1
  31. package/built/src/promiEvent/promiEventEmitter.d.ts +24 -0
  32. package/built/src/promiEvent/promiEventEmitter.js +56 -0
  33. package/built/src/promiEvent/promiEventEmitter.js.map +1 -0
  34. package/built/src/promiEvent/promiEvents.d.ts +12 -0
  35. package/built/src/promiEvent/promiEvents.js +61 -0
  36. package/built/src/promiEvent/promiEvents.js.map +1 -0
  37. package/built/src/restclient/errors.d.ts +1 -1
  38. package/built/src/restclient/errors.js +6 -2
  39. package/built/src/restclient/errors.js.map +1 -1
  40. package/built/src/restclient/restclient.d.ts +15 -0
  41. package/built/src/restclient/restclient.js +10 -6
  42. package/built/src/restclient/restclient.js.map +1 -1
  43. package/built/src/restclient/restclientutil.d.ts +2 -1
  44. package/built/src/restclient/restclientutil.js.map +1 -1
  45. package/built/umd/index.js +31594 -34570
  46. package/built/umd/index.js.map +1 -1
  47. package/package.json +4 -3
@@ -3,6 +3,8 @@
3
3
  var bn_js = require('bn.js');
4
4
  var crypto = require('crypto');
5
5
  var secp256k1 = require('secp256k1');
6
+ var _ = require('lodash');
7
+ var events = require('events');
6
8
 
7
9
  function _interopNamespaceDefault(e) {
8
10
  var n = Object.create(null);
@@ -53,7 +55,7 @@ function getAugmentedNamespace(n) {
53
55
  }
54
56
 
55
57
  // eslint-disable-next-line @typescript-eslint/no-var-requires
56
- const asn = require("asn1.js/lib/asn1");
58
+ const asn = require("@chromia/asn1/lib/asn1");
57
59
  const ASNDictPair = asn.define("DictPair", function () {
58
60
  this.seq().obj(this.key("name").utf8str(), this.key("value").use(rawGTV));
59
61
  });
@@ -94,7 +96,7 @@ class NumberOfSignersAndSignaturesException extends Error {
94
96
  }
95
97
  class MissingSignerException extends Error {
96
98
  constructor() {
97
- super(`No such signer, remember to call addSignerToGtx() before adding a signature`);
99
+ super(`No such signer, remember to add signer to transaction before adding a signature`);
98
100
  }
99
101
  }
100
102
 
@@ -1636,7 +1638,7 @@ var index = /*#__PURE__*/Object.freeze({
1636
1638
  const encode = encodeValueGtx;
1637
1639
  const decode = decodeValueGtx;
1638
1640
 
1639
- var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1641
+ var __awaiter$8 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1640
1642
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1641
1643
  return new (P || (P = Promise))(function (resolve, reject) {
1642
1644
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -1688,16 +1690,16 @@ function gtvTxBody(gtx) {
1688
1690
  ];
1689
1691
  }
1690
1692
  function sign(gtx, privOrSigProv, pubKey) {
1691
- return __awaiter$5(this, void 0, void 0, function* () {
1693
+ return __awaiter$8(this, void 0, void 0, function* () {
1692
1694
  if (privOrSigProv instanceof Buffer) {
1693
1695
  const digestToSign = getDigestToSign(gtx);
1694
1696
  const signature = signDigest(digestToSign, privOrSigProv);
1695
- addSignature(pubKey || makeKeyPair(privOrSigProv).pubKey, signature, gtx);
1697
+ return addSignature(pubKey || makeKeyPair(privOrSigProv).pubKey, signature, gtx);
1696
1698
  }
1697
1699
  else {
1698
1700
  const digestToSign = getDigestToSign(gtx);
1699
1701
  const signature = yield privOrSigProv.sign(digestToSign);
1700
- addSignature(privOrSigProv.pubKey, signature, gtx);
1702
+ return addSignature(privOrSigProv.pubKey, signature, gtx);
1701
1703
  }
1702
1704
  });
1703
1705
  }
@@ -1713,16 +1715,14 @@ function signRawTransaction(_keyPair, _rawTransaction) {
1713
1715
  */
1714
1716
  function addSignature(pubKeyBuffer, signatureBuffer, gtx) {
1715
1717
  if (!gtx.signatures) {
1716
- gtx.signatures = Array(gtx.signers.length).fill(Buffer.alloc(64));
1717
- }
1718
- if (gtx.signers.length !== gtx.signatures.length) {
1719
- throw new NumberOfSignersAndSignaturesException();
1718
+ gtx.signatures = Array(gtx.signers.length);
1720
1719
  }
1721
1720
  const signerIndex = gtx.signers.findIndex((signer) => pubKeyBuffer.equals(signer));
1722
1721
  if (signerIndex === -1) {
1723
1722
  throw new MissingSignerException();
1724
1723
  }
1725
1724
  gtx.signatures[signerIndex] = signatureBuffer;
1725
+ return gtx;
1726
1726
  }
1727
1727
  function serialize(gtx) {
1728
1728
  if (!gtx.signatures) {
@@ -1760,6 +1760,16 @@ function checkGTXSignatures(txHash, gtx) {
1760
1760
  }
1761
1761
  return true;
1762
1762
  }
1763
+ function checkExistingGTXSignatures(txHash, gtx) {
1764
+ for (const i in gtx.signers) {
1765
+ if (gtx.signatures[i]) {
1766
+ const signValid = checkDigestSignature(txHash, gtx.signers[i], gtx.signatures[i]);
1767
+ if (!signValid)
1768
+ return signValid;
1769
+ }
1770
+ }
1771
+ return true;
1772
+ }
1763
1773
  function newSignatureProvider(keyPair) {
1764
1774
  let pub, priv;
1765
1775
  if (keyPair) {
@@ -1771,7 +1781,7 @@ function newSignatureProvider(keyPair) {
1771
1781
  }
1772
1782
  return {
1773
1783
  pubKey: pub,
1774
- sign: (digest) => __awaiter$5(this, void 0, void 0, function* () { return signDigest(digest, priv); })
1784
+ sign: (digest) => __awaiter$8(this, void 0, void 0, function* () { return signDigest(digest, priv); }),
1775
1785
  };
1776
1786
  }
1777
1787
 
@@ -1780,6 +1790,7 @@ var gtx = /*#__PURE__*/Object.freeze({
1780
1790
  addSignature: addSignature,
1781
1791
  addSignerToGtx: addSignerToGtx,
1782
1792
  addTransactionToGtx: addTransactionToGtx,
1793
+ checkExistingGTXSignatures: checkExistingGTXSignatures,
1783
1794
  checkGTXSignatures: checkGTXSignatures,
1784
1795
  deserialize: deserialize,
1785
1796
  emptyGtx: emptyGtx,
@@ -1853,7 +1864,7 @@ var logger = /*#__PURE__*/Object.freeze({
1853
1864
  warning: warning
1854
1865
  });
1855
1866
 
1856
- var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1867
+ var __awaiter$7 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
1857
1868
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1858
1869
  return new (P || (P = Promise))(function (resolve, reject) {
1859
1870
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -1862,13 +1873,13 @@ var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _argu
1862
1873
  step((generator = generator.apply(thisArg, _arguments || [])).next());
1863
1874
  });
1864
1875
  };
1865
- function createClient(restApiClient, blockchainRID, functionNames) {
1876
+ function createClient$1(restApiClient, blockchainRID, functionNames) {
1866
1877
  functionNames.push("message");
1867
1878
  function transaction(gtx$1) {
1868
1879
  return {
1869
1880
  gtx: gtx$1,
1870
1881
  sign: function (privOrSigProv, pubKey) {
1871
- return __awaiter$4(this, void 0, void 0, function* () {
1882
+ return __awaiter$7(this, void 0, void 0, function* () {
1872
1883
  debug(`signing transaction with ${privOrSigProv instanceof Buffer
1873
1884
  ? "privkey: " + privOrSigProv.toString("hex")
1874
1885
  : "signature provider [pubkey: " + privOrSigProv.pubKey + "]"}`);
@@ -1944,16 +1955,16 @@ function createClient(restApiClient, blockchainRID, functionNames) {
1944
1955
 
1945
1956
  var gtxclient = /*#__PURE__*/Object.freeze({
1946
1957
  __proto__: null,
1947
- createClient: createClient
1958
+ createClient: createClient$1
1948
1959
  });
1949
1960
 
1950
- var ResponseStatus;
1961
+ var ResponseStatus$1;
1951
1962
  (function (ResponseStatus) {
1952
1963
  ResponseStatus["Confirmed"] = "confirmed";
1953
1964
  ResponseStatus["Rejected"] = "rejected";
1954
1965
  ResponseStatus["Unknown"] = "unknown";
1955
1966
  ResponseStatus["Waiting"] = "waiting";
1956
- })(ResponseStatus || (ResponseStatus = {}));
1967
+ })(ResponseStatus$1 || (ResponseStatus$1 = {}));
1957
1968
  var Method;
1958
1969
  (function (Method) {
1959
1970
  Method["GET"] = "get";
@@ -1974,8 +1985,12 @@ class TxRejectedError extends Error {
1974
1985
  }
1975
1986
  }
1976
1987
  class UnexpectedStatusError extends Error {
1977
- constructor(status) {
1978
- super(`Unexpected status code from server: ${status}`);
1988
+ constructor(status, error) {
1989
+ let errorMessage = `Unexpected status code from server. Code: ${status}.`;
1990
+ if (error) {
1991
+ errorMessage += ` Message: ${error}.`;
1992
+ }
1993
+ super(errorMessage);
1979
1994
  }
1980
1995
  }
1981
1996
  class LostMessageError extends Error {
@@ -2009,7 +2024,7 @@ class EmptyListOfUrlsException extends Error {
2009
2024
  }
2010
2025
  }
2011
2026
 
2012
- var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2027
+ var __awaiter$6 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2013
2028
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2014
2029
  return new (P || (P = Promise))(function (resolve, reject) {
2015
2030
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -2019,7 +2034,7 @@ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _argu
2019
2034
  });
2020
2035
  };
2021
2036
  function handleRequest(method, path, endpoint, postObject) {
2022
- return __awaiter$3(this, void 0, void 0, function* () {
2037
+ return __awaiter$6(this, void 0, void 0, function* () {
2023
2038
  if (method == Method.GET) {
2024
2039
  return yield get(path, endpoint);
2025
2040
  }
@@ -2034,7 +2049,7 @@ function handleRequest(method, path, endpoint, postObject) {
2034
2049
  * @param endpoint
2035
2050
  */
2036
2051
  function get(path, endpoint) {
2037
- return __awaiter$3(this, void 0, void 0, function* () {
2052
+ return __awaiter$6(this, void 0, void 0, function* () {
2038
2053
  debug("GET URL " + new URL(path, endpoint).href);
2039
2054
  try {
2040
2055
  const response = yield fetch(new URL(path, endpoint).href);
@@ -2057,7 +2072,7 @@ function get(path, endpoint) {
2057
2072
  * @param requestBody request body
2058
2073
  */
2059
2074
  function post(path, endpoint, requestBody) {
2060
- return __awaiter$3(this, void 0, void 0, function* () {
2075
+ return __awaiter$6(this, void 0, void 0, function* () {
2061
2076
  debug("POST URL " + new URL(path, endpoint).href);
2062
2077
  debug("POST body " + JSON.stringify(requestBody));
2063
2078
  if (Buffer.isBuffer(requestBody)) {
@@ -2096,7 +2111,7 @@ function post(path, endpoint, requestBody) {
2096
2111
  });
2097
2112
  }
2098
2113
 
2099
- var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2114
+ var __awaiter$5 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2100
2115
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2101
2116
  return new (P || (P = Promise))(function (resolve, reject) {
2102
2117
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -2126,7 +2141,7 @@ function getBrid(urlBase, chainId) {
2126
2141
  }
2127
2142
  }
2128
2143
  function requestWithRetry(method, path, config, postObject) {
2129
- return __awaiter$2(this, void 0, void 0, function* () {
2144
+ return __awaiter$5(this, void 0, void 0, function* () {
2130
2145
  let statusCode, rspBody, error;
2131
2146
  const noRetryStatusCodes = [200, 400, 409, 500];
2132
2147
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
@@ -2172,7 +2187,7 @@ var restclientutil = /*#__PURE__*/Object.freeze({
2172
2187
  sleep: sleep
2173
2188
  });
2174
2189
 
2175
- var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2190
+ var __awaiter$4 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2176
2191
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2177
2192
  return new (P || (P = Promise))(function (resolve, reject) {
2178
2193
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -2192,8 +2207,8 @@ function createRestClient(endpointPool, blockchainRID, maxSockets = 10, pollingI
2192
2207
  attemptInterval: (failOverConfig === null || failOverConfig === void 0 ? void 0 : failOverConfig.attemptInterval) || 500,
2193
2208
  },
2194
2209
  getTransaction: function (txRID, callback) {
2195
- return __awaiter$1(this, void 0, void 0, function* () {
2196
- if (!validTxRID(txRID)) {
2210
+ return __awaiter$4(this, void 0, void 0, function* () {
2211
+ if (!validTxRID$1(txRID)) {
2197
2212
  callback(new UnvalidTxRidException(txRID), null);
2198
2213
  }
2199
2214
  else {
@@ -2203,7 +2218,7 @@ function createRestClient(endpointPool, blockchainRID, maxSockets = 10, pollingI
2203
2218
  });
2204
2219
  },
2205
2220
  postTransaction: function (serializedTransaction, callback) {
2206
- return __awaiter$1(this, void 0, void 0, function* () {
2221
+ return __awaiter$4(this, void 0, void 0, function* () {
2207
2222
  if (!Buffer.isBuffer(serializedTransaction)) {
2208
2223
  throw new SerializedTransactionFormatException();
2209
2224
  }
@@ -2215,8 +2230,8 @@ function createRestClient(endpointPool, blockchainRID, maxSockets = 10, pollingI
2215
2230
  });
2216
2231
  },
2217
2232
  status: function (txRID, callback) {
2218
- return __awaiter$1(this, void 0, void 0, function* () {
2219
- if (!validTxRID(txRID)) {
2233
+ return __awaiter$4(this, void 0, void 0, function* () {
2234
+ if (!validTxRID$1(txRID)) {
2220
2235
  callback(new UnvalidTxRidException(txRID), null);
2221
2236
  }
2222
2237
  else {
@@ -2226,9 +2241,9 @@ function createRestClient(endpointPool, blockchainRID, maxSockets = 10, pollingI
2226
2241
  });
2227
2242
  },
2228
2243
  query: function (nameOrQueryObject, queryArguments) {
2229
- return __awaiter$1(this, void 0, void 0, function* () {
2244
+ return __awaiter$4(this, void 0, void 0, function* () {
2230
2245
  // eslint-disable-next-line no-async-promise-executor
2231
- return new Promise((resolve, reject) => __awaiter$1(this, void 0, void 0, function* () {
2246
+ return new Promise((resolve, reject) => __awaiter$4(this, void 0, void 0, function* () {
2232
2247
  const callback = (error, result) => {
2233
2248
  if (error) {
2234
2249
  reject(error);
@@ -2251,16 +2266,16 @@ function createRestClient(endpointPool, blockchainRID, maxSockets = 10, pollingI
2251
2266
  else {
2252
2267
  const status = result.status;
2253
2268
  switch (status) {
2254
- case ResponseStatus.Confirmed:
2269
+ case ResponseStatus$1.Confirmed:
2255
2270
  resolve(null);
2256
2271
  break;
2257
- case ResponseStatus.Rejected:
2272
+ case ResponseStatus$1.Rejected:
2258
2273
  reject(new TxRejectedError(result.rejectReason));
2259
2274
  break;
2260
- case ResponseStatus.Unknown:
2275
+ case ResponseStatus$1.Unknown:
2261
2276
  reject(new LostMessageError());
2262
2277
  break;
2263
- case ResponseStatus.Waiting:
2278
+ case ResponseStatus$1.Waiting:
2264
2279
  setTimeout(() => this.waitConfirmation(txRID).then(resolve, reject), this.config.pollingInterval);
2265
2280
  break;
2266
2281
  default:
@@ -2294,7 +2309,7 @@ function createRestClient(endpointPool, blockchainRID, maxSockets = 10, pollingI
2294
2309
  * Validates that txRID is a Buffer of 32 bytes.
2295
2310
  * @param txRID A buffer of 32 bytes
2296
2311
  */
2297
- function validTxRID(txRID) {
2312
+ function validTxRID$1(txRID) {
2298
2313
  if (txRID.length != 32) {
2299
2314
  const error$1 = new UnvalidTxRidException(txRID);
2300
2315
  error(error$1.toString());
@@ -2330,14 +2345,14 @@ function handleGetResponse(error$1, statusCode, responseObject, callback) {
2330
2345
  callback(null, null);
2331
2346
  }
2332
2347
  else if (statusCode !== 200) {
2333
- callback(new UnexpectedStatusError(statusCode), responseObject);
2348
+ callback(new UnexpectedStatusError(statusCode, responseObjectPrintable), responseObject);
2334
2349
  }
2335
2350
  else {
2336
2351
  callback(null, responseObject);
2337
2352
  }
2338
2353
  }
2339
2354
  catch (error$1) {
2340
- error("restclient.handleGetResponse(): Failed to call callback function " +
2355
+ error("restclient.handleGetResponse(): Failed to call the callback function. " +
2341
2356
  error$1);
2342
2357
  }
2343
2358
  }
@@ -2356,8 +2371,12 @@ function handlePostResponse(error$1, statusCode, responseObject, callback) {
2356
2371
  callback(error$1);
2357
2372
  }
2358
2373
  else if (statusCode != 200) {
2359
- error(`Unexpected status code from server: ${statusCode}`);
2360
- callback(new UnexpectedStatusError(statusCode), responseObject);
2374
+ let errorMessage = `Unexpected status code from server. Code: ${statusCode}.`;
2375
+ if (responseObjectPrintable) {
2376
+ errorMessage += ` Message: ${responseObjectPrintable}.`;
2377
+ }
2378
+ error(errorMessage);
2379
+ callback(new UnexpectedStatusError(statusCode, responseObjectPrintable), responseObject);
2361
2380
  }
2362
2381
  else {
2363
2382
  info(`Calling responseCallback with responseObject: ${responseObjectPrintable}`);
@@ -2372,7 +2391,9 @@ function handlePostResponse(error$1, statusCode, responseObject, callback) {
2372
2391
 
2373
2392
  var restclient = /*#__PURE__*/Object.freeze({
2374
2393
  __proto__: null,
2375
- createRestClient: createRestClient
2394
+ createRestClient: createRestClient,
2395
+ handleGetResponse: handleGetResponse,
2396
+ handlePostResponse: handlePostResponse
2376
2397
  });
2377
2398
 
2378
2399
  var internalNodePrefix = Buffer.alloc(1, 0);
@@ -2495,7 +2516,7 @@ class BlockchainUrlUndefinedException extends Error {
2495
2516
  }
2496
2517
  }
2497
2518
 
2498
- var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2519
+ var __awaiter$3 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2499
2520
  function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2500
2521
  return new (P || (P = Promise))(function (resolve, reject) {
2501
2522
  function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
@@ -2510,10 +2531,10 @@ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _argume
2510
2531
  * @param rest rest client configured to node running chain0
2511
2532
  */
2512
2533
  function chromiaClientProvider(chain0BRID, rest) {
2513
- const chain0Client = createClient(rest, chain0BRID, []);
2534
+ const chain0Client = createClient$1(rest, chain0BRID, []);
2514
2535
  return {
2515
2536
  blockchainConnection: function (dappBRID) {
2516
- return __awaiter(this, void 0, void 0, function* () {
2537
+ return __awaiter$3(this, void 0, void 0, function* () {
2517
2538
  const queryObject = {
2518
2539
  type: "cm_get_blockchain_api_urls",
2519
2540
  blockchain_rid: dappBRID,
@@ -2533,7 +2554,528 @@ var chromiaClientProvider$1 = /*#__PURE__*/Object.freeze({
2533
2554
  chromiaClientProvider: chromiaClientProvider
2534
2555
  });
2535
2556
 
2557
+ var ResponseStatus;
2558
+ (function (ResponseStatus) {
2559
+ ResponseStatus["Confirmed"] = "confirmed";
2560
+ ResponseStatus["Rejected"] = "rejected";
2561
+ ResponseStatus["Unknown"] = "unknown";
2562
+ ResponseStatus["Waiting"] = "waiting";
2563
+ })(ResponseStatus || (ResponseStatus = {}));
2564
+
2565
+ class MissingBlockchainError extends Error {
2566
+ constructor() {
2567
+ super(`No target blockchain was provided`);
2568
+ }
2569
+ }
2570
+ class MissingNodeUrlError extends Error {
2571
+ constructor() {
2572
+ super(`No node url or directory node url was provided`);
2573
+ }
2574
+ }
2575
+ class InvalidTransactionFormatException extends Error {
2576
+ constructor() {
2577
+ super(`The transaction is not in the right format`);
2578
+ }
2579
+ }
2580
+ class getTransactionRIDException extends Error {
2581
+ constructor(error) {
2582
+ super(`"Error occurred while getting transaction RID:", ${error}`);
2583
+ }
2584
+ }
2585
+
2586
+ var __awaiter$2 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2587
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2588
+ return new (P || (P = Promise))(function (resolve, reject) {
2589
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2590
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2591
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2592
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2593
+ });
2594
+ };
2595
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
2596
+ require("web3-core-promievent");
2597
+ function getConfig(settings) {
2598
+ var _a, _b;
2599
+ return __awaiter$2(this, void 0, void 0, function* () {
2600
+ if (!settings.nodeURLPool && !settings.directoryNodeURLPool) {
2601
+ throw new MissingNodeUrlError();
2602
+ }
2603
+ if (!settings.blockchainRID &&
2604
+ typeof settings.blockchainIID === "undefined") {
2605
+ throw new MissingBlockchainError();
2606
+ }
2607
+ const nodeUrlPool = settings.directoryNodeURLPool
2608
+ ? yield getNodeUrls(settings)
2609
+ : typeof settings.nodeURLPool === "string"
2610
+ ? [settings.nodeURLPool]
2611
+ : Array.isArray(settings.nodeURLPool)
2612
+ ? settings.nodeURLPool
2613
+ : [];
2614
+ return {
2615
+ endpointPool: nodeUrlPool,
2616
+ blockchainRID: settings.blockchainRID
2617
+ ? toBuffer(settings.blockchainRID)
2618
+ : toBuffer(yield getBrid(nodeUrlPool[0], settings.blockchainIID)),
2619
+ pollingInterval: settings.pollingInterval || 500,
2620
+ attemptsPerEndpoint: ((_a = settings.failOverConfig) === null || _a === void 0 ? void 0 : _a.attemptsPerEndpoint) || 3,
2621
+ attemptInterval: ((_b = settings.failOverConfig) === null || _b === void 0 ? void 0 : _b.attemptInterval) || 500,
2622
+ };
2623
+ });
2624
+ }
2625
+ function validTxRID(txRID) {
2626
+ if (txRID.length != 32) {
2627
+ const error$1 = new UnvalidTxRidException(txRID);
2628
+ error(error$1.toString());
2629
+ return false;
2630
+ }
2631
+ return true;
2632
+ }
2633
+ function getNodeUrls(settings) {
2634
+ return __awaiter$2(this, void 0, void 0, function* () {
2635
+ if (!settings.blockchainRID) {
2636
+ throw new MissingBlockchainError();
2637
+ }
2638
+ const nodeUrlPool = Array.isArray(settings.directoryNodeURLPool)
2639
+ ? settings.directoryNodeURLPool
2640
+ : typeof settings.directoryNodeURLPool === "string"
2641
+ ? [settings.directoryNodeURLPool]
2642
+ : [];
2643
+ const directoryBRID = yield getBrid(nodeUrlPool[0], 0);
2644
+ const queryObject = {
2645
+ type: "cm_get_blockchain_api_urls",
2646
+ blockchain_rid: settings.blockchainRID
2647
+ ? settings.blockchainRID
2648
+ : yield getBrid(nodeUrlPool[0], settings.blockchainIID),
2649
+ };
2650
+ const rest = createRestClient(nodeUrlPool, directoryBRID);
2651
+ const baseUrls = yield rest.query(queryObject);
2652
+ if (!baseUrls.length) {
2653
+ throw new BlockchainUrlUndefinedException(directoryBRID);
2654
+ }
2655
+ return baseUrls;
2656
+ });
2657
+ }
2658
+ function convertToRellOperation(operations) {
2659
+ return operations.map((operation) => {
2660
+ var _a;
2661
+ return {
2662
+ opName: operation.name,
2663
+ args: (_a = operation.args) !== null && _a !== void 0 ? _a : [],
2664
+ };
2665
+ });
2666
+ }
2667
+ function getSerializedGTX(gtx$1) {
2668
+ const gtxBytes = serialize(gtx$1);
2669
+ if (!Buffer.isBuffer(gtxBytes)) {
2670
+ throw new SerializedTransactionFormatException();
2671
+ }
2672
+ return gtxBytes;
2673
+ }
2674
+ function getGTXFromBufferOrTransactionOrOperation(transaction, blockchainRID) {
2675
+ if (Buffer.isBuffer(transaction)) {
2676
+ return deserialize(transaction);
2677
+ }
2678
+ else if ("operations" in transaction) {
2679
+ return {
2680
+ blockchainRID,
2681
+ operations: convertToRellOperation(transaction.operations),
2682
+ signers: transaction.signers,
2683
+ signatures: [],
2684
+ };
2685
+ }
2686
+ else if ("name" in transaction) {
2687
+ return {
2688
+ blockchainRID,
2689
+ operations: convertToRellOperation([transaction]),
2690
+ signers: [],
2691
+ signatures: [],
2692
+ };
2693
+ }
2694
+ else {
2695
+ throw new InvalidTransactionFormatException();
2696
+ }
2697
+ }
2698
+ const callbackPromiseBuilder = (reject, resolve, callback) => {
2699
+ return (error, result) => {
2700
+ if (error) {
2701
+ if (typeof callback === "function") {
2702
+ callback(error, null);
2703
+ }
2704
+ reject(error);
2705
+ }
2706
+ else {
2707
+ if (typeof callback === "function") {
2708
+ callback(null, result);
2709
+ }
2710
+ resolve(result);
2711
+ }
2712
+ };
2713
+ };
2714
+ const handlePostResponsePromisified = (error, statusCode, rspBody) => {
2715
+ return new Promise((resolve, reject) => {
2716
+ handlePostResponse(error, statusCode, rspBody, (_error) => {
2717
+ if (_error) {
2718
+ reject(_error);
2719
+ }
2720
+ else {
2721
+ resolve();
2722
+ }
2723
+ });
2724
+ });
2725
+ };
2726
+
2727
+ /*
2728
+ This file is part of web3.js.
2729
+
2730
+ web3.js is free software: you can redistribute it and/or modify
2731
+ it under the terms of the GNU Lesser General Public License as published by
2732
+ the Free Software Foundation, either version 3 of the License, or
2733
+ (at your option) any later version.
2734
+
2735
+ web3.js is distributed in the hope that it will be useful,
2736
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
2737
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2738
+ GNU Lesser General Public License for more details.
2739
+
2740
+ You should have received a copy of the GNU Lesser General Public License
2741
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
2742
+ */
2743
+ class Web3EventEmitter {
2744
+ constructor() {
2745
+ this._emitter = new events.EventEmitter();
2746
+ }
2747
+ on(eventName, fn) {
2748
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
2749
+ this._emitter.on(eventName, fn);
2750
+ }
2751
+ once(eventName, fn) {
2752
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
2753
+ this._emitter.once(eventName, fn);
2754
+ }
2755
+ off(eventName, fn) {
2756
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
2757
+ this._emitter.off(eventName, fn);
2758
+ }
2759
+ emit(eventName, params) {
2760
+ this._emitter.emit(eventName, params);
2761
+ }
2762
+ listenerCount(eventName) {
2763
+ return this._emitter.listenerCount(eventName);
2764
+ }
2765
+ listeners(eventName) {
2766
+ return this._emitter.listeners(eventName);
2767
+ }
2768
+ eventNames() {
2769
+ return this._emitter.eventNames();
2770
+ }
2771
+ removeAllListeners() {
2772
+ return this._emitter.removeAllListeners();
2773
+ }
2774
+ setMaxListenerWarningThreshold(maxListenersWarningThreshold) {
2775
+ this._emitter.setMaxListeners(maxListenersWarningThreshold);
2776
+ }
2777
+ getMaxListeners() {
2778
+ return this._emitter.getMaxListeners();
2779
+ }
2780
+ }
2781
+
2782
+ /*
2783
+ This file is part of web3.js.
2784
+
2785
+ web3.js is free software: you can redistribute it and/or modify
2786
+ it under the terms of the GNU Lesser General Public License as published by
2787
+ the Free Software Foundation, either version 3 of the License, or
2788
+ (at your option) any later version.
2789
+
2790
+ web3.js is distributed in the hope that it will be useful,
2791
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
2792
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
2793
+ GNU Lesser General Public License for more details.
2794
+
2795
+ You should have received a copy of the GNU Lesser General Public License
2796
+ along with web3.js. If not, see <http://www.gnu.org/licenses/>.
2797
+ */
2798
+ var __awaiter$1 = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2799
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2800
+ return new (P || (P = Promise))(function (resolve, reject) {
2801
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2802
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2803
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2804
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2805
+ });
2806
+ };
2807
+ var _a;
2808
+ class Web3PromiEvent extends Web3EventEmitter {
2809
+ constructor(executor) {
2810
+ super();
2811
+ // public tag to treat object as promise by different libs
2812
+ // eslint-disable-next-line @typescript-eslint/prefer-as-const
2813
+ this[_a] = "Promise";
2814
+ this._promise = new Promise(executor);
2815
+ }
2816
+ then(onfulfilled, onrejected) {
2817
+ return __awaiter$1(this, void 0, void 0, function* () {
2818
+ return this._promise.then(onfulfilled, onrejected);
2819
+ });
2820
+ }
2821
+ catch(onrejected) {
2822
+ return __awaiter$1(this, void 0, void 0, function* () {
2823
+ return this._promise.catch(onrejected);
2824
+ });
2825
+ }
2826
+ finally(onfinally) {
2827
+ return __awaiter$1(this, void 0, void 0, function* () {
2828
+ return this._promise.finally(onfinally);
2829
+ });
2830
+ }
2831
+ on(eventName, fn) {
2832
+ super.on(eventName, fn);
2833
+ return this;
2834
+ }
2835
+ once(eventName, fn) {
2836
+ super.once(eventName, fn);
2837
+ return this;
2838
+ }
2839
+ }
2840
+ _a = Symbol.toStringTag;
2841
+
2842
+ var __awaiter = (undefined && undefined.__awaiter) || function (thisArg, _arguments, P, generator) {
2843
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2844
+ return new (P || (P = Promise))(function (resolve, reject) {
2845
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2846
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2847
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2848
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
2849
+ });
2850
+ };
2851
+ function createClient(settings) {
2852
+ return __awaiter(this, void 0, void 0, function* () {
2853
+ const blockchainRID = settings.blockchainRID;
2854
+ return {
2855
+ config: yield getConfig(settings),
2856
+ query(nameOrQueryObject, args, callback) {
2857
+ return __awaiter(this, void 0, void 0, function* () {
2858
+ let _name, _args;
2859
+ if (typeof nameOrQueryObject === "string") {
2860
+ _name = nameOrQueryObject;
2861
+ _args = args;
2862
+ }
2863
+ else {
2864
+ _name = nameOrQueryObject === null || nameOrQueryObject === void 0 ? void 0 : nameOrQueryObject.name;
2865
+ _args = nameOrQueryObject === null || nameOrQueryObject === void 0 ? void 0 : nameOrQueryObject.args;
2866
+ }
2867
+ const { error, statusCode, rspBody } = yield requestWithRetry(Method.POST, `query_gtv/${blockchainRID}`, this.config, encodeValue(toQueryObjectGTV(_name, _args)));
2868
+ return new Promise((resolve, reject) => {
2869
+ handlePostResponse(error, statusCode, rspBody, callbackPromiseBuilder(reject, resolve, callback));
2870
+ });
2871
+ });
2872
+ },
2873
+ signTransaction(transaction, signMethod, callback) {
2874
+ return __awaiter(this, void 0, void 0, function* () {
2875
+ const signMethodIsPrivKey = "privKey" in signMethod;
2876
+ debug(`signing transaction with ${signMethodIsPrivKey
2877
+ ? "privkey: " + signMethod.privKey.toString("hex")
2878
+ : "signature provider [pubkey: " + toString(signMethod.pubKey) + "]"}`);
2879
+ const gtx$1 = getGTXFromBufferOrTransactionOrOperation(transaction, this.config.blockchainRID);
2880
+ try {
2881
+ const signedTx = yield (signMethodIsPrivKey
2882
+ ? sign(gtx$1, signMethod.privKey, signMethod.pubKey)
2883
+ : sign(gtx$1, signMethod));
2884
+ const gtxBytes = getSerializedGTX(signedTx);
2885
+ if (typeof callback === "function") {
2886
+ callback(null, gtxBytes);
2887
+ }
2888
+ return gtxBytes;
2889
+ }
2890
+ catch (error) {
2891
+ if (typeof callback === "function") {
2892
+ callback(error, null);
2893
+ }
2894
+ throw new Error(error);
2895
+ }
2896
+ });
2897
+ },
2898
+ sendTransaction(transaction, callback) {
2899
+ const promiEvent = new Web3PromiEvent((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
2900
+ const gtx$1 = getGTXFromBufferOrTransactionOrOperation(transaction, this.config.blockchainRID);
2901
+ if (gtx$1.signers.length !== gtx$1.signatures.length) {
2902
+ reject(new NumberOfSignersAndSignaturesException());
2903
+ }
2904
+ const gtxBytes = getSerializedGTX(gtx$1);
2905
+ const transactionObject = {
2906
+ tx: gtxBytes.toString("hex"),
2907
+ };
2908
+ const { error: error$1, statusCode, rspBody } = yield requestWithRetry(Method.POST, "tx/" + blockchainRID, this.config, transactionObject);
2909
+ const transactionRID = getDigestToSign(gtx$1);
2910
+ try {
2911
+ yield handlePostResponsePromisified(error$1, statusCode, rspBody);
2912
+ if (typeof callback === "function") {
2913
+ callback(null, {
2914
+ status: ResponseStatus.Waiting,
2915
+ statusCode,
2916
+ transactionRID,
2917
+ });
2918
+ }
2919
+ }
2920
+ catch (_error) {
2921
+ if (typeof callback === "function") {
2922
+ callback(_error, null);
2923
+ }
2924
+ return reject(_error);
2925
+ }
2926
+ promiEvent.emit("sent", {
2927
+ status: ResponseStatus.Waiting,
2928
+ statusCode: statusCode,
2929
+ transactionRID,
2930
+ });
2931
+ const waitConfirmation = (txRID) => {
2932
+ return new Promise((resolve, reject) => {
2933
+ this.getTransactionStatus(txRID, (error$1, result) => {
2934
+ if (error$1) {
2935
+ reject(error$1);
2936
+ }
2937
+ else {
2938
+ const status = result.status;
2939
+ switch (status) {
2940
+ case ResponseStatus.Confirmed:
2941
+ resolve(ResponseStatus.Confirmed);
2942
+ break;
2943
+ case ResponseStatus.Rejected:
2944
+ reject(new TxRejectedError(result.rejectReason));
2945
+ break;
2946
+ case ResponseStatus.Unknown:
2947
+ reject(new LostMessageError());
2948
+ break;
2949
+ case ResponseStatus.Waiting:
2950
+ setTimeout(() => waitConfirmation(txRID).then(resolve, reject), this.config.pollingInterval);
2951
+ break;
2952
+ default:
2953
+ error(status);
2954
+ reject(new UnexpectedResponseError());
2955
+ }
2956
+ }
2957
+ });
2958
+ });
2959
+ };
2960
+ try {
2961
+ waitConfirmation(getDigestToSign(gtx$1)).then((confirmationStatus) => {
2962
+ resolve({
2963
+ status: confirmationStatus,
2964
+ statusCode: statusCode,
2965
+ transactionRID,
2966
+ });
2967
+ });
2968
+ }
2969
+ catch (error) {
2970
+ reject(error);
2971
+ }
2972
+ }));
2973
+ return promiEvent;
2974
+ },
2975
+ signAndSendUniqueTransaction(transactionOrOperation, signMethod, callback) {
2976
+ const promiEvent = new Web3PromiEvent((resolve, reject) => {
2977
+ const signMethodIsPrivKey = "privKey" in signMethod;
2978
+ let _pubKey;
2979
+ if (signMethodIsPrivKey) {
2980
+ _pubKey = !signMethod.pubKey
2981
+ ? makeKeyPair(signMethod.privKey).pubKey
2982
+ : signMethod.pubKey;
2983
+ }
2984
+ const transaction = "name" in transactionOrOperation
2985
+ ? {
2986
+ operations: [transactionOrOperation],
2987
+ signers: [signMethod.pubKey || _pubKey],
2988
+ }
2989
+ : transactionOrOperation;
2990
+ const hasNop = transaction.operations.some((operation) => {
2991
+ return operation.name === "nop";
2992
+ });
2993
+ const transactionWithNop = hasNop
2994
+ ? transaction
2995
+ : this.addNop(transaction);
2996
+ this.signTransaction(transactionWithNop, signMethod)
2997
+ .then((signedTx) => {
2998
+ const sendTransactionPromiEvent = this.sendTransaction(signedTx, callback);
2999
+ sendTransactionPromiEvent.on("sent", (receipt) => {
3000
+ promiEvent.emit("sent", receipt);
3001
+ });
3002
+ resolve(sendTransactionPromiEvent);
3003
+ })
3004
+ .catch((error) => {
3005
+ reject(error);
3006
+ });
3007
+ });
3008
+ return promiEvent;
3009
+ },
3010
+ getTransaction(transactionRID, callback) {
3011
+ return __awaiter(this, void 0, void 0, function* () {
3012
+ if (!validTxRID(transactionRID)) {
3013
+ if (typeof callback === "function") {
3014
+ callback(new UnvalidTxRidException(transactionRID), null);
3015
+ }
3016
+ throw new UnvalidTxRidException(transactionRID);
3017
+ }
3018
+ const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, "tx/" + blockchainRID + "/" + transactionRID.toString("hex"), this.config);
3019
+ return new Promise((resolve, reject) => {
3020
+ handleGetResponse(error, statusCode, statusCode === 200 ? toBuffer(rspBody.tx) : rspBody, callbackPromiseBuilder(reject, resolve, callback));
3021
+ });
3022
+ });
3023
+ },
3024
+ getTransactionStatus(transactionRID, callback) {
3025
+ return __awaiter(this, void 0, void 0, function* () {
3026
+ if (!validTxRID(transactionRID)) {
3027
+ const error = new UnvalidTxRidException(transactionRID);
3028
+ if (typeof callback === "function") {
3029
+ callback(error, null);
3030
+ }
3031
+ throw error;
3032
+ }
3033
+ const { error, statusCode, rspBody } = yield requestWithRetry(Method.GET, "tx/" +
3034
+ blockchainRID +
3035
+ "/" +
3036
+ transactionRID.toString("hex") +
3037
+ "/status", this.config);
3038
+ return new Promise((resolve, reject) => {
3039
+ handleGetResponse(error, statusCode, rspBody, callbackPromiseBuilder(reject, resolve, callback));
3040
+ });
3041
+ });
3042
+ },
3043
+ addNop(transaction) {
3044
+ const _transaction = _.cloneDeep(transaction);
3045
+ const noOperation = {
3046
+ name: "nop",
3047
+ args: [crypto.randomBytes(32)],
3048
+ };
3049
+ _transaction.operations = [..._transaction.operations, noOperation];
3050
+ return _transaction;
3051
+ },
3052
+ getTransactionRID(transaction) {
3053
+ try {
3054
+ const gtx$1 = getGTXFromBufferOrTransactionOrOperation(transaction, this.config.blockchainRID);
3055
+ return getDigestToSign(gtx$1);
3056
+ }
3057
+ catch (e) {
3058
+ throw new getTransactionRIDException(e);
3059
+ }
3060
+ },
3061
+ encodeTransaction(transaction) {
3062
+ const gtx$1 = getGTXFromBufferOrTransactionOrOperation(transaction, this.config.blockchainRID);
3063
+ return serialize(gtx$1);
3064
+ },
3065
+ decodeTransactionToGTX(encodedTransaction) {
3066
+ const gtx$1 = deserialize(encodedTransaction);
3067
+ debug(`Output from deserializing a raw transaction: ${JSON.stringify(gtx$1)}`);
3068
+ return gtx$1;
3069
+ },
3070
+ getClientNodeURLPool() {
3071
+ return this.config.endpointPool;
3072
+ },
3073
+ };
3074
+ });
3075
+ }
3076
+
2536
3077
  exports.chromiaClient = chromiaClientProvider$1;
3078
+ exports.createClient = createClient;
2537
3079
  exports.encryption = encryption$1;
2538
3080
  exports.formatter = formatter;
2539
3081
  exports.gtv = index;
@@ -2541,6 +3083,7 @@ exports.gtx = gtx;
2541
3083
  exports.gtxClient = gtxclient;
2542
3084
  exports.logger = logger;
2543
3085
  exports.merkle = merkleHelper;
3086
+ exports.newSignatureProvider = newSignatureProvider;
2544
3087
  exports.restClient = restclient;
2545
3088
  exports.restClientutil = restclientutil;
2546
3089
  //# sourceMappingURL=index.js.map