quantumcoin 7.0.13 → 7.0.15

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 (213) hide show
  1. package/README-SDK.md +2 -0
  2. package/examples/node_modules/.bin/esbuild +16 -0
  3. package/examples/node_modules/.bin/esbuild.cmd +17 -0
  4. package/examples/node_modules/.bin/esbuild.ps1 +28 -0
  5. package/examples/node_modules/.bin/sdkgen +16 -0
  6. package/examples/node_modules/.bin/sdkgen.cmd +17 -0
  7. package/examples/node_modules/.bin/sdkgen.ps1 +28 -0
  8. package/examples/node_modules/.bin/tsx +16 -0
  9. package/examples/node_modules/.bin/tsx.cmd +17 -0
  10. package/examples/node_modules/.bin/tsx.ps1 +28 -0
  11. package/examples/node_modules/.package-lock.json +144 -0
  12. package/examples/node_modules/@esbuild/win32-x64/README.md +3 -0
  13. package/examples/node_modules/@esbuild/win32-x64/esbuild.exe +0 -0
  14. package/examples/node_modules/@esbuild/win32-x64/package.json +20 -0
  15. package/examples/node_modules/esbuild/LICENSE.md +21 -0
  16. package/examples/node_modules/esbuild/README.md +3 -0
  17. package/examples/node_modules/esbuild/bin/esbuild +223 -0
  18. package/examples/node_modules/esbuild/install.js +289 -0
  19. package/examples/node_modules/esbuild/lib/main.d.ts +716 -0
  20. package/examples/node_modules/esbuild/lib/main.js +2532 -0
  21. package/examples/node_modules/esbuild/package.json +49 -0
  22. package/examples/node_modules/get-tsconfig/LICENSE +21 -0
  23. package/examples/node_modules/get-tsconfig/README.md +235 -0
  24. package/examples/node_modules/get-tsconfig/dist/index.cjs +7 -0
  25. package/examples/node_modules/get-tsconfig/dist/index.d.cts +2088 -0
  26. package/examples/node_modules/get-tsconfig/dist/index.d.mts +2088 -0
  27. package/examples/node_modules/get-tsconfig/dist/index.mjs +7 -0
  28. package/examples/node_modules/get-tsconfig/package.json +46 -0
  29. package/examples/node_modules/quantum-coin-js-sdk/LICENSE +21 -0
  30. package/examples/node_modules/quantum-coin-js-sdk/LICENSE-wasm_exec.js.txt +30 -0
  31. package/examples/node_modules/quantum-coin-js-sdk/README.md +1689 -0
  32. package/examples/node_modules/quantum-coin-js-sdk/example/README.md +14 -0
  33. package/examples/node_modules/quantum-coin-js-sdk/example/conversion-example.js +19 -0
  34. package/examples/node_modules/quantum-coin-js-sdk/example/example-create-contract.js +396 -0
  35. package/examples/node_modules/quantum-coin-js-sdk/example/example-encode-decode-rlp.js +225 -0
  36. package/examples/node_modules/quantum-coin-js-sdk/example/example-event-pack-unpack.js +391 -0
  37. package/examples/node_modules/quantum-coin-js-sdk/example/example-misc.js +100 -0
  38. package/examples/node_modules/quantum-coin-js-sdk/example/example-rpc-send-signRawTransaction.js +318 -0
  39. package/examples/node_modules/quantum-coin-js-sdk/example/example-rpc-send.js +115 -0
  40. package/examples/node_modules/quantum-coin-js-sdk/example/example-send.js +69 -0
  41. package/examples/node_modules/quantum-coin-js-sdk/example/example-token-pack-unpack.js +960 -0
  42. package/examples/node_modules/quantum-coin-js-sdk/example/example-wallet-version4.js +34 -0
  43. package/examples/node_modules/quantum-coin-js-sdk/example/example-wallet.js +43 -0
  44. package/examples/node_modules/quantum-coin-js-sdk/example/example.js +405 -0
  45. package/examples/node_modules/quantum-coin-js-sdk/example/package-lock.json +56 -0
  46. package/examples/node_modules/quantum-coin-js-sdk/example/package.json +15 -0
  47. package/examples/node_modules/quantum-coin-js-sdk/index.d.ts +1047 -0
  48. package/examples/node_modules/quantum-coin-js-sdk/index.js +3182 -0
  49. package/examples/node_modules/quantum-coin-js-sdk/package.json +34 -0
  50. package/examples/node_modules/quantum-coin-js-sdk/tests/encrypted-32.json +1 -0
  51. package/examples/node_modules/quantum-coin-js-sdk/tests/encrypted-36.json +1 -0
  52. package/examples/node_modules/quantum-coin-js-sdk/tests/encrypted-48.json +1 -0
  53. package/examples/node_modules/quantum-coin-js-sdk/tests/generate-verify-vectors.js +91 -0
  54. package/examples/node_modules/quantum-coin-js-sdk/tests/get-gas-price.test.js +59 -0
  55. package/examples/node_modules/quantum-coin-js-sdk/tests/non-transactional.preinit.test.js +41 -0
  56. package/examples/node_modules/quantum-coin-js-sdk/tests/non-transactional.test.js +1389 -0
  57. package/examples/node_modules/quantum-coin-js-sdk/tests/sign-raw-keytype5-context-null.test.js +107 -0
  58. package/examples/node_modules/quantum-coin-js-sdk/tests/sign-raw-transaction.test.js +196 -0
  59. package/examples/node_modules/quantum-coin-js-sdk/tests/sign-verify.test.js +311 -0
  60. package/examples/node_modules/quantum-coin-js-sdk/tests/transactional.relay.test.js +131 -0
  61. package/examples/node_modules/quantum-coin-js-sdk/tests/transactional.rpc.test.js +103 -0
  62. package/examples/node_modules/quantum-coin-js-sdk/tests/verify-vectors.json +95035 -0
  63. package/examples/node_modules/quantum-coin-js-sdk/wasmBase64.d.ts +9 -0
  64. package/examples/node_modules/quantum-coin-js-sdk/wasmBase64.js +16 -0
  65. package/examples/node_modules/quantum-coin-js-sdk/wasm_exec.d.ts +0 -0
  66. package/examples/node_modules/quantum-coin-js-sdk/wasm_exec.js +587 -0
  67. package/examples/node_modules/resolve-pkg-maps/LICENSE +21 -0
  68. package/examples/node_modules/resolve-pkg-maps/README.md +216 -0
  69. package/examples/node_modules/resolve-pkg-maps/dist/index.cjs +1 -0
  70. package/examples/node_modules/resolve-pkg-maps/dist/index.d.cts +11 -0
  71. package/examples/node_modules/resolve-pkg-maps/dist/index.d.mts +11 -0
  72. package/examples/node_modules/resolve-pkg-maps/dist/index.mjs +1 -0
  73. package/examples/node_modules/resolve-pkg-maps/package.json +42 -0
  74. package/examples/node_modules/seed-words/.github/workflows/publish-npmjs.yaml +22 -0
  75. package/examples/node_modules/seed-words/BUILD.md +7 -0
  76. package/examples/node_modules/seed-words/LICENSE +121 -0
  77. package/examples/node_modules/seed-words/README.md +67 -0
  78. package/examples/node_modules/seed-words/dist/seedwords.d.ts +39 -0
  79. package/examples/node_modules/seed-words/package.json +27 -0
  80. package/examples/node_modules/seed-words/seedwords.js +315 -0
  81. package/examples/node_modules/seed-words/seedwords.txt +65536 -0
  82. package/examples/node_modules/seed-words/tsconfig.json +21 -0
  83. package/examples/node_modules/tsx/LICENSE +21 -0
  84. package/examples/node_modules/tsx/README.md +32 -0
  85. package/examples/node_modules/tsx/dist/cjs/api/index.cjs +1 -0
  86. package/examples/node_modules/tsx/dist/cjs/api/index.d.cts +35 -0
  87. package/examples/node_modules/tsx/dist/cjs/api/index.d.mts +35 -0
  88. package/examples/node_modules/tsx/dist/cjs/api/index.mjs +1 -0
  89. package/examples/node_modules/tsx/dist/cjs/index.cjs +1 -0
  90. package/examples/node_modules/tsx/dist/cjs/index.mjs +1 -0
  91. package/examples/node_modules/tsx/dist/cli.cjs +54 -0
  92. package/examples/node_modules/tsx/dist/cli.mjs +55 -0
  93. package/examples/node_modules/tsx/dist/client-BQVF1NaW.mjs +1 -0
  94. package/examples/node_modules/tsx/dist/client-D6NvIMSC.cjs +1 -0
  95. package/examples/node_modules/tsx/dist/esm/api/index.cjs +1 -0
  96. package/examples/node_modules/tsx/dist/esm/api/index.d.cts +35 -0
  97. package/examples/node_modules/tsx/dist/esm/api/index.d.mts +35 -0
  98. package/examples/node_modules/tsx/dist/esm/api/index.mjs +1 -0
  99. package/examples/node_modules/tsx/dist/esm/index.cjs +2 -0
  100. package/examples/node_modules/tsx/dist/esm/index.mjs +2 -0
  101. package/examples/node_modules/tsx/dist/get-pipe-path-BHW2eJdv.mjs +1 -0
  102. package/examples/node_modules/tsx/dist/get-pipe-path-BoR10qr8.cjs +1 -0
  103. package/examples/node_modules/tsx/dist/index-7AaEi15b.mjs +14 -0
  104. package/examples/node_modules/tsx/dist/index-BWFBUo6r.cjs +1 -0
  105. package/examples/node_modules/tsx/dist/index-gbaejti9.mjs +1 -0
  106. package/examples/node_modules/tsx/dist/index-gckBtVBf.cjs +14 -0
  107. package/examples/node_modules/tsx/dist/lexer-DQCqS3nf.mjs +3 -0
  108. package/examples/node_modules/tsx/dist/lexer-DgIbo0BU.cjs +3 -0
  109. package/examples/node_modules/tsx/dist/loader.cjs +1 -0
  110. package/examples/node_modules/tsx/dist/loader.mjs +1 -0
  111. package/examples/node_modules/tsx/dist/node-features-_8ZFwP_x.mjs +1 -0
  112. package/examples/node_modules/tsx/dist/node-features-roYmp9jK.cjs +1 -0
  113. package/examples/node_modules/tsx/dist/package-CeBgXWuR.mjs +1 -0
  114. package/examples/node_modules/tsx/dist/package-Dxt5kIHw.cjs +1 -0
  115. package/examples/node_modules/tsx/dist/patch-repl.cjs +1 -0
  116. package/examples/node_modules/tsx/dist/patch-repl.mjs +1 -0
  117. package/examples/node_modules/tsx/dist/preflight.cjs +1 -0
  118. package/examples/node_modules/tsx/dist/preflight.mjs +1 -0
  119. package/examples/node_modules/tsx/dist/register-2sWVXuRQ.cjs +1 -0
  120. package/examples/node_modules/tsx/dist/register-B7jrtLTO.mjs +1 -0
  121. package/examples/node_modules/tsx/dist/register-CFH5oNdT.mjs +4 -0
  122. package/examples/node_modules/tsx/dist/register-D46fvsV_.cjs +4 -0
  123. package/examples/node_modules/tsx/dist/repl.cjs +3 -0
  124. package/examples/node_modules/tsx/dist/repl.mjs +3 -0
  125. package/examples/node_modules/tsx/dist/require-D4F1Lv60.cjs +1 -0
  126. package/examples/node_modules/tsx/dist/require-DQxpCAr4.mjs +1 -0
  127. package/examples/node_modules/tsx/dist/suppress-warnings.cjs +1 -0
  128. package/examples/node_modules/tsx/dist/suppress-warnings.mjs +1 -0
  129. package/examples/node_modules/tsx/dist/temporary-directory-B83uKxJF.cjs +1 -0
  130. package/examples/node_modules/tsx/dist/temporary-directory-CwHp0_NW.mjs +1 -0
  131. package/examples/node_modules/tsx/dist/types-Cxp8y2TL.d.ts +5 -0
  132. package/examples/node_modules/tsx/package.json +68 -0
  133. package/examples/package-lock.json +6 -6
  134. package/examples/package.json +1 -1
  135. package/generate-sdk.js +30 -9
  136. package/package.json +2 -2
  137. package/src/abi/interface.js +11 -2
  138. package/src/abi/js-abi-coder.js +61 -2
  139. package/src/contract/contract.js +53 -5
  140. package/src/generator/index.js +152 -13
  141. package/src/index.d.ts +1 -0
  142. package/src/providers/index.d.ts +1 -0
  143. package/src/providers/provider.d.ts +16 -0
  144. package/src/providers/provider.js +178 -5
  145. package/src/utils/rlp.js +13 -1
  146. package/src/wallet/wallet.d.ts +10 -0
  147. package/src/wallet/wallet.js +136 -15
  148. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/examples/_test-wallet.js +1 -1
  149. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/examples/_test-wallet.ts +1 -1
  150. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/examples/deploy.js +1 -1
  151. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/examples/deploy.ts +1 -1
  152. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/examples/offline-signing.js +1 -1
  153. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/examples/offline-signing.ts +1 -1
  154. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/examples/write-operations.js +1 -1
  155. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/examples/write-operations.ts +1 -1
  156. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/package-lock.json +6 -6
  157. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/package.json +1 -1
  158. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/src/AllSolidityTypes__factory.js +3 -1
  159. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-js/test/e2e/AllSolidityTypes.e2e.test.js +1 -1
  160. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/examples/_test-wallet.js +1 -1
  161. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/examples/_test-wallet.ts +1 -1
  162. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/examples/deploy.js +1 -1
  163. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/examples/deploy.ts +1 -1
  164. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/examples/offline-signing.js +1 -1
  165. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/examples/offline-signing.ts +1 -1
  166. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/examples/write-operations.js +1 -1
  167. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/examples/write-operations.ts +1 -1
  168. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/package-lock.json +6 -6
  169. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/package.json +1 -1
  170. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/src/AllSolidityTypes__factory.ts +3 -1
  171. package/test/e2e/generated-sdks/all-solidity-types/all-solidity-types-ts/test/e2e/AllSolidityTypes.e2e.test.js +1 -1
  172. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/examples/_test-wallet.js +1 -1
  173. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/examples/_test-wallet.ts +1 -1
  174. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/examples/deploy.js +1 -1
  175. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/examples/deploy.ts +1 -1
  176. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/examples/offline-signing.js +1 -1
  177. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/examples/offline-signing.ts +1 -1
  178. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/examples/write-operations.js +1 -1
  179. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/examples/write-operations.ts +1 -1
  180. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/package-lock.json +6 -6
  181. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/package.json +1 -1
  182. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/src/SimpleERC20.js +9 -3
  183. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/src/SimpleERC20__factory.js +3 -1
  184. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-js/test/e2e/SimpleERC20.e2e.test.js +1 -1
  185. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/examples/_test-wallet.js +1 -1
  186. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/examples/_test-wallet.ts +1 -1
  187. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/examples/deploy.js +1 -1
  188. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/examples/deploy.ts +1 -1
  189. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/examples/offline-signing.js +1 -1
  190. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/examples/offline-signing.ts +1 -1
  191. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/examples/write-operations.js +1 -1
  192. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/examples/write-operations.ts +1 -1
  193. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/package-lock.json +6 -6
  194. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/package.json +1 -1
  195. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/src/SimpleERC20.ts +9 -3
  196. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/src/SimpleERC20__factory.ts +3 -1
  197. package/test/e2e/generated-sdks/simple-erc20/simple-erc20-ts/test/e2e/SimpleERC20.e2e.test.js +1 -1
  198. package/test/e2e/generator-interface.e2e.test.js +6 -4
  199. package/test/e2e/generator-interface.e2e.test.ts +6 -4
  200. package/test/security/abi-decoder-bounds.test.js +122 -0
  201. package/test/security/contract-overrides.test.js +112 -0
  202. package/test/security/generator-injection.test.js +195 -0
  203. package/test/security/malformed-input.test.js +26 -27
  204. package/test/security/rpc-numeric-bounds.test.js +81 -0
  205. package/test/security/rpc-trust.test.js +202 -0
  206. package/test/unit/abi-interface.test.js +12 -5
  207. package/test/unit/abi-interface.test.ts +8 -1
  208. package/test/unit/address-wallet.test.js +53 -0
  209. package/test/unit/address-wallet.test.ts +22 -0
  210. package/test/unit/encoding-units-rlp.test.js +35 -0
  211. package/test/unit/populate-transaction.test.js +33 -0
  212. package/test/unit/providers.test.js +53 -0
  213. package/test/unit/providers.test.ts +53 -0
@@ -0,0 +1,3182 @@
1
+ //index.js
2
+
3
+ /**
4
+ * Quantum Coin Blockchain SDK
5
+ * @module quantum-coin-js-sdk
6
+ * @description Quantum Coin JS SDK provides low level functionality to interact with the Quantum Coin Blockchain.
7
+ * {@link https://github.com/quantumcoinproject/quantum-coin-js-sdk/tree/main/example|Example Project}
8
+ * @example
9
+ *
10
+ * Requires Node.js version v20.18.1 or higher
11
+ *
12
+ * Installation:
13
+ * npm install quantum-coin-js-sdk --save
14
+ *
15
+ * //Adding reference:
16
+ * var qcsdk = require('quantum-coin-js-sdk');
17
+ *
18
+ * //Example initialization with defaults for mainnet
19
+ * //Initialize the SDK first before invoking any other function
20
+ * qcsdk.initialize(null).then((initResult) => {
21
+ *
22
+ * }
23
+ *
24
+ * //Example initialization with specific values
25
+ * //Initialize the SDK first before invoking any other function
26
+ * var clientConfigVal = new qcsdk.Config("https://sdk.readrelay.quantumcoinapi.com", "https://sdk.writerelay.quantumcoinapi.com", 123123, "", ""); //Initialization with Mainnet Config (Block Explorer: https://QuantumScan.com)
27
+ * qcsdk.initialize(clientConfigVal).then((initResult) => {
28
+ *
29
+ * }
30
+ * Example Project: https://github.com/quantumcoinproject/quantum-coin-js-sdk/tree/main/example
31
+ *
32
+ */
33
+
34
+ var wasmexec = require('./wasm_exec');
35
+ var wasmBase64 = require('./wasmBase64');
36
+ const crypto = require("crypto");
37
+ var seedwords = require('seed-words');
38
+
39
+ var config = null;
40
+ var isInitialized = false;
41
+ /** CIRCL WASM namespace (set after InitAccountsWebAssembly). Use getCircl() for access. */
42
+ var circl = null;
43
+ const DEFAULT_GAS = 21000;
44
+ const API_KEY_HEADER_NAME = "X-API-KEY";
45
+ const REQUEST_ID_HEADER_NAME = "X-REQUEST-ID";
46
+
47
+ // Dynamic-fee gas pricing (mirrors quantum-coin-go core/types/dynamic_fee_tx.go).
48
+ // Base dynamic price = defaults.DEFAULT_PRICE / 10. BigInt is used because the
49
+ // level multipliers push the value above Number.MAX_SAFE_INTEGER.
50
+ const DEFAULT_PRICE_WEI = 47619047619047600n;
51
+ const DYNAMIC_BASE_GAS_PRICE_WEI = DEFAULT_PRICE_WEI / 10n;
52
+ const SIGNING_CONTEXT_LEVEL1_MULTIPLIER = 20n;
53
+ const SIGNING_CONTEXT_LEVEL2_MULTIPLIER = 30n;
54
+
55
+ // Key type and seed constants (CIRCL migration; see pqc-circl-migration.md)
56
+ const KEY_TYPE_HYBRIDEDMLDSASLHDSA = 3;
57
+ const KEY_TYPE_HYBRIDEDMLDSASLHDSA5 = 5;
58
+ const SEED_WORD_LIST_LENGTH_HYBRIDEDS = 48;
59
+ const SEED_WORD_LIST_LENGTH_HYBRIDEDMLDSASLHDSA5 = 36;
60
+ const SEED_WORD_LIST_LENGTH_HYBRIDEDMLDSASLHDSA = 32;
61
+ const BASE_SEED_BYTES_HYBRIDEDS = 96;
62
+ const BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA5 = 72;
63
+ const BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA = 64;
64
+ const MIN_PASSPHRASE_LENGTH = 12;
65
+ const INVALID_KEY_TYPE = -1001;
66
+ const CIRCL_CRYPTO_FAILURE = -1002;
67
+ const EXPECTED_WASM_SHA256 = "17aff465c5879e2ff94d33e8ce9d98d6ad6a70849b3e3cad7cccbcc9728e5a02";
68
+
69
+ /**
70
+ * @class
71
+ * @constructor
72
+ * @public
73
+ * @classdesc This is the configuration class required to initialize and interact with Quantum Coin blockchain
74
+ */
75
+ class Config {
76
+ /**
77
+ * Creates a config class
78
+ * @param {string} readUrl - The Read API URL pointing to a read relay. See https://github.com/quantumcoinproject/quantum-coin-go/tree/main/relay. The following URLs are community maintained. Please use your own relay service. Mainnet: https://sdk.readrelay.quantumcoinapi.com
79
+ * @param {string} writeUrl - The Write API URL pointing to a write relay. See https://github.com/quantumcoinproject/quantum-coin-go/tree/main/relay. The following URLs are community maintained. Please use your own relay service. Mainnet: https://sdk.writerelay.quantumcoinapi.com
80
+ * @param {number} chainId - The chain id of the blockchain. Mainnet chainId is 123123. Testnet T4 chainId is 310324.
81
+ * @param {string} readApiKey - Optional parameter if authorization is enabled for the relay service. API Key for authorization. Defaults to null which indicates no authorization.
82
+ * @param {string} writeApiKey - Optional parameter if authorization is enabled for the relay service. API Key for authorization. Defaults to null which indicates no authorization.
83
+ */
84
+
85
+ constructor(readUrl, writeUrl, chainId, readApiKey, writeApiKey) {
86
+ /**
87
+ * The Read API URL pointing to a read relay. See https://github.com/quantumcoinproject/quantum-coin-go/tree/main/relay
88
+ * @type {string}
89
+ * @public
90
+ */
91
+ this.readUrl = readUrl;
92
+
93
+ /**
94
+ * The Read API URL pointing to a read relay. See https://github.com/quantumcoinproject/quantum-coin-go/tree/main/relay
95
+ * @type {string}
96
+ * @public
97
+ */
98
+ this.writeUrl = writeUrl;
99
+
100
+ /**
101
+ * The chain id of the blockchain. Mainnet chainId is 123123. Testnet T4 chainId is 310324.
102
+ * @type {number}
103
+ * @public
104
+ */
105
+ this.chainId = chainId;
106
+
107
+ /**
108
+ * API Key for authorization if authorization is enabled for the relay service. Defaults to null which indicates no authorization.
109
+ * @type {string}
110
+ * @public
111
+ */
112
+ this.readApiKey = readApiKey;
113
+
114
+ /**
115
+ * API Key for authorization if authorization is enabled for the relay service. Defaults to null which indicates no authorization.
116
+ * @type {string}
117
+ * @public
118
+ */
119
+ this.writeApiKey = writeApiKey;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * @class
125
+ * @constructor
126
+ * @public
127
+ * @classdesc This class represents a Wallet. Use the verifyWallet function to verify if a wallet is valid. Verifying the wallet is highly recommended, especially if it comes from an untrusted source. For more details on the underlying cryptography of the Wallet, see https://github.com/quantumcoinproject/circl
128
+ */
129
+ class Wallet {
130
+ /**
131
+ * Creates a Wallet class. The constructor does not verify the wallet. To verify a wallet, call the verifyWallet function explicitly.
132
+ * @param {string} address - Address of the wallet
133
+ * @param {number[]} privateKey - Private Key byte array of the wallet
134
+ * @param {number[]} publicKey - Public Key byte array of the wallet
135
+ * @param {Uint8Array|number[]|null} [preExpansionSeed=null] - Optional pre-expansion seed bytes. Non-null only for seed-derived wallets.
136
+ */
137
+ constructor(address, privateKey, publicKey, preExpansionSeed) {
138
+
139
+ /**
140
+ * Address of the wallet. Is 66 bytes in length including 0x (if the wallet is valid).
141
+ * @type {string}
142
+ * @public
143
+ */
144
+ this.address = address;
145
+
146
+ /**
147
+ * Private Key byte array of the wallet. Is 4064 bytes in length (if the wallet is valid).
148
+ * @type {number[]}
149
+ * @public
150
+ */
151
+ this.privateKey = privateKey;
152
+
153
+ /**
154
+ * Public Key byte array of the wallet. Is 1408 bytes in length (if the wallet is valid).
155
+ * @type {number[]}
156
+ * @public
157
+ */
158
+ this.publicKey = publicKey;
159
+
160
+ /**
161
+ * Pre-expansion seed bytes. Can be null if the wallet was not created from a seed.
162
+ * @type {Uint8Array|number[]|null}
163
+ * @public
164
+ */
165
+ this.preExpansionSeed = preExpansionSeed || null;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * @class
171
+ * @constructor
172
+ * @public
173
+ * @classdesc This class represents a Block.
174
+ */
175
+ class BlockDetails {
176
+ constructor(blockNumber) {
177
+ /**
178
+ * Block Number of the block
179
+ * @type {number}
180
+ * @public
181
+ */
182
+ this.blockNumber = blockNumber;
183
+ }
184
+ }
185
+
186
+ /**
187
+ * @class
188
+ * @constructor
189
+ * @public
190
+ * @classdesc This class represents a result from invoking the getLatestBlock function.
191
+ */
192
+ class LatestBlockDetailsResult {
193
+ constructor(resultCode, blockDetails, response, requestId, err) {
194
+ /**
195
+ * Represents the result of the operation. A value of 0 represents that the operation succeeded. Any other value indicates the operation failed. See the result code section for more details.
196
+ * @type {number}
197
+ * @public
198
+ */
199
+ this.resultCode = resultCode;
200
+
201
+ /**
202
+ * An object of type BlockDetails representing the block. This value is null if the value of resultCode is not 0.
203
+ * @type {BlockDetails}
204
+ * @public
205
+ */
206
+ this.blockDetails = blockDetails;
207
+
208
+ /**
209
+ * An object of representing the raw Response returned by the service. For details, see https://developer.mozilla.org/en-US/docs/Web/API/Response. This value can be null if the value of resultCode is not 0.
210
+ * @type {Object}
211
+ * @public
212
+ */
213
+ this.response = response;
214
+
215
+ /**
216
+ * An unique id to represent the request. This can be null if request failed before it could be sent.
217
+ * @type {string}
218
+ * @public
219
+ */
220
+ this.requestId = requestId;
221
+
222
+ /**
223
+ * An error object if the operation resulted in an error and there was no response. This property is defined only if the resultCode is -10000.
224
+ * @type {Error}
225
+ * @public
226
+ */
227
+ this.err = err;
228
+ }
229
+ }
230
+
231
+ /**
232
+ * @class
233
+ * @constructor
234
+ * @public
235
+ * @classdesc This class represents an Account.
236
+ */
237
+ class AccountDetails {
238
+ constructor(address, balance, nonce, blockNumber) {
239
+ /**
240
+ * Address of the wallet. Is 66 bytes in length including 0x.
241
+ * @type {string}
242
+ * @public
243
+ */
244
+ this.address = address;
245
+
246
+ /**
247
+ * Balance of the account in wei. To convert this to ethers, see https://docs.ethers.org/v4/api-utils.html#ether-strings-and-wei
248
+ * @type {string}
249
+ * @public
250
+ */
251
+ this.balance = balance;
252
+
253
+ /**
254
+ * A monotonically increasing number representing the nonce of the account. After each transaction from the account that gets registered in the blockchain, the nonce increases by 1.
255
+ * @type {number}
256
+ * @public
257
+ */
258
+ this.nonce = nonce;
259
+
260
+ /**
261
+ * The block number as of which the Account details was retrieved.
262
+ * @type {number}
263
+ * @public
264
+ */
265
+ this.blockNumber = blockNumber;
266
+ }
267
+ }
268
+
269
+ /**
270
+ * @class
271
+ * @constructor
272
+ * @public
273
+ * @classdesc This class represents a result from invoking the getAccountDetails function.
274
+ */
275
+ class AccountDetailsResult {
276
+ constructor(resultCode, accountDetails, response, requestId, err) {
277
+ /**
278
+ * Represents the result of the operation. A value of 0 represents that the operation succeeded. Any other value indicates the operation failed. See the result code section for more details.
279
+ * @type {number}
280
+ * @public
281
+ */
282
+ this.resultCode = resultCode;
283
+
284
+ /**
285
+ * An object of type AccountDetails representing the block. This value is null if the value of resultCode is not 0.
286
+ * @type {AccountDetails}
287
+ * @public
288
+ */
289
+ this.accountDetails = accountDetails;
290
+
291
+ /**
292
+ * An object of representing the raw Response returned by the service. For details, see https://developer.mozilla.org/en-US/docs/Web/API/Response. This value can be null if the value of resultCode is not 0.
293
+ * @type {Object}
294
+ * @public
295
+ */
296
+ this.response = response;
297
+
298
+ /**
299
+ * An unique id to represent the request. This can be null if request failed before it could be sent.
300
+ * @type {string}
301
+ * @public
302
+ */
303
+ this.requestId = requestId;
304
+
305
+ /**
306
+ * An error object if the operation resulted in an error and there was no response. This property is defined only if the resultCode is -10000.
307
+ * @type {Error}
308
+ * @public
309
+ */
310
+ this.err = err;
311
+ }
312
+ }
313
+
314
+ /**
315
+ * @class
316
+ * @constructor
317
+ * @public
318
+ * @classdesc This class represents a result from invoking the signSendCoinTransaction function.
319
+ */
320
+ class SignResult {
321
+ constructor(resultCode, txnHash, txnData) {
322
+ /**
323
+ * Represents the result of the operation. A value of 0 represents that the operation succeeded. Any other value indicates the operation failed. See the result code section for more details.
324
+ * @type {number}
325
+ * @public
326
+ */
327
+ this.resultCode = resultCode;
328
+
329
+ /**
330
+ * Hash of the Transaction, to uniquely identify it. Is 66 bytes in length including 0x. This value is null if the value of resultCode is not 0.
331
+ * @type {string}
332
+ * @public
333
+ */
334
+ this.txnHash = txnHash;
335
+
336
+ /**
337
+ * A payload representing the signed transaction.
338
+ * To actually send a transaction, this payload can then be taken to to a different device that is connected to the blockchain relay and then sent using the postTransaction function.
339
+ * This value is null if the value of resultCode is not 0.
340
+ * @type {string}
341
+ * @public
342
+ */
343
+ this.txnData = txnData;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * @class
349
+ * @constructor
350
+ * @public
351
+ * @classdesc This class represents a result from invoking the sendCoins function.
352
+ */
353
+ class SendResult {
354
+ constructor(resultCode, txnHash, response, requestId, err) {
355
+ /**
356
+ * Represents the result of the operation. A value of 0 represents that the operation succeeded. Any other value indicates the operation failed. See the result code section for more details.
357
+ * @type {number}
358
+ * @public
359
+ */
360
+ this.resultCode = resultCode;
361
+
362
+ /**
363
+ * Hash of the Transaction, to uniquely identify it. Is 66 bytes in length including 0x. This value is null if the value of resultCode is not 0.
364
+ * @type {string}
365
+ * @public
366
+ */
367
+ this.txnHash = txnHash;
368
+
369
+ /**
370
+ * An object of representing the raw Response returned by the service. For details, see https://developer.mozilla.org/en-US/docs/Web/API/Response. This value can be null if the value of resultCode is not 0.
371
+ * @type {Object}
372
+ * @public
373
+ */
374
+ this.response = response;
375
+
376
+ /**
377
+ * An unique id to represent the request. This can be null if request failed before it could be sent.
378
+ * @type {string}
379
+ * @public
380
+ */
381
+ this.requestId = requestId;
382
+
383
+ /**
384
+ * An error object if the operation resulted in an error and there was no response. This property is defined only if the resultCode is -10000.
385
+ * @type {Error}
386
+ * @public
387
+ */
388
+ this.err = err;
389
+ }
390
+ }
391
+
392
+ /**
393
+ * @class
394
+ * @constructor
395
+ * @public
396
+ * @classdesc This class represents a Receipt of a transaction that is registered in the blockchain. The transactionReceipt field can be null unless the transaction is registered with the blockchain.
397
+ * While the transaction is pending, this field will be null. You should consider the transaction as succeeded only if the status field's value is 0x1 (success).
398
+ */
399
+ class TransactionReceipt {
400
+ constructor() {
401
+ /**
402
+ * A hexadecimal string representing the total amount of gas used when this transaction was executed in the block.
403
+ * @type {string}
404
+ * @public
405
+ */
406
+ this.cumulativeGasUsed = null;
407
+
408
+ /**
409
+ * A hexadecimal string representing the sum of the base fee and tip paid per unit of gas.
410
+ * @type {string}
411
+ * @public
412
+ */
413
+ this.effectiveGasPrice = null;
414
+
415
+ /**
416
+ * A hexadecimal string representing the amount of gas used by this specific transaction alone.
417
+ * @type {string}
418
+ * @public
419
+ */
420
+ this.gasUsed = null;
421
+
422
+ /**
423
+ * A hexadecimal string representing either 0x1 (success) or 0x0 (failure). Failed transactions can also incur gas fee. You should consider the transaction as succeeded only if the status value is 0x1 (success).
424
+ * @type {string}
425
+ * @public
426
+ */
427
+ this.status = null;
428
+
429
+ /**
430
+ * Hash of the Transaction, to uniquely identify it. Is 66 bytes in length including 0x.
431
+ * @type {string}
432
+ * @public
433
+ */
434
+ this.hash = null;
435
+
436
+ /**
437
+ * A hexadecimal string representing the transaction type. 0x0 is DefaultFeeTxType.
438
+ * @type {string}
439
+ * @public
440
+ */
441
+ this.type = null;
442
+ }
443
+ }
444
+
445
+ /**
446
+ * @class
447
+ * @constructor
448
+ * @public
449
+ * @classdesc This class represents details of a transaction. You should consider the transaction as succeeded only if the status field of the receipt object is 0x1 (success).
450
+ */
451
+ class TransactionDetails {
452
+ constructor() {
453
+ /**
454
+ * A hexadecimal string representing the hash of the block that registered the transaction. This field can be null if the transaction was not registered in the blockchain.
455
+ * @type {string}
456
+ * @public
457
+ */
458
+ this.blockHash = null;
459
+
460
+ /**
461
+ * The number of the block that registered the transaction. This field can be null if the transaction was not registered in the blockchain.
462
+ * @type {number}
463
+ * @public
464
+ */
465
+ this.blockNumber = null;
466
+
467
+ /**
468
+ * A 66 character hexadecimal string representing the address the transaction is sent from.
469
+ * @type {string}
470
+ * @public
471
+ */
472
+ this.from = null;
473
+
474
+ /**
475
+ * A hexadecimal string representing the gas provided for the transaction execution.
476
+ * @type {string}
477
+ * @public
478
+ */
479
+ this.gas = null;
480
+
481
+ /**
482
+ * A hexadecimal string representing the gasPrice used for each paid gas, in Wei.
483
+ * @type {string}
484
+ * @public
485
+ */
486
+ this.gasPrice = null;
487
+
488
+ /**
489
+ * A 66 character hexadecimal string representing the hash of the transaction.
490
+ * @type {string}
491
+ * @public
492
+ */
493
+ this.hash = null;
494
+
495
+ /**
496
+ * A hexadecimal string representing the compiled code of a contract OR the hash of the invoked method signature and encoded parameters.
497
+ * @type {string}
498
+ * @public
499
+ */
500
+ this.input = null;
501
+
502
+ /**
503
+ * A monotonically increasing number representing the nonce of the account. After each transaction from the account that gets registered in the blockchain, the nonce increases by 1.
504
+ * @type {number}
505
+ * @public
506
+ */
507
+ this.nonce = null;
508
+
509
+ /**
510
+ * A 66 character hexadecimal string representing address the transaction is directed to.
511
+ * @type {string}
512
+ * @public
513
+ */
514
+ this.to = null;
515
+
516
+ /**
517
+ * A hexadecimal string representing the value sent with this transaction. The value can be 0 for smart contract transactions, since it only represents the number of coins sent.
518
+ * @type {string}
519
+ * @public
520
+ */
521
+ this.value = null;
522
+
523
+ /**
524
+ * The receipt of the transaction. This field will be null while the transaction is pending (not yet registered in the blockchain).
525
+ * @type {TransactionReceipt}
526
+ * @public
527
+ */
528
+ this.receipt = null;
529
+ }
530
+
531
+ }
532
+
533
+ /**
534
+ * @class
535
+ * @constructor
536
+ * @public
537
+ * @classdesc This class represents a result from invoking the getTransactionDetails function. If transactions get discarded by the blockchain, for reasons such as due to lower than minimum gas fees or invalid nonce, the resultCode will always contain a non-zero value (failure).
538
+ */
539
+ class TransactionDetailsResult {
540
+ constructor(resultCode, transactionDetails, response, requestId, err) {
541
+ /**
542
+ * Represents the result of the operation. A value of 0 represents that the operation succeeded. Any other value indicates the operation failed. See the result code section for more details.
543
+ * @type {number}
544
+ * @public
545
+ */
546
+
547
+ this.resultCode = resultCode;
548
+
549
+ /**
550
+ * An object of type TransactionDetails representing the transaction. This value is null if the value of resultCode is not 0.
551
+ * @type {TransactionDetails}
552
+ * @public
553
+ */
554
+ this.transactionDetails = transactionDetails;
555
+
556
+ /**
557
+ * An object of representing the raw Response returned by the service. For details, see https://developer.mozilla.org/en-US/docs/Web/API/Response. This value can be null if the value of resultCode is not 0.
558
+ * @type {Object}
559
+ * @public
560
+ */
561
+ this.response = response;
562
+
563
+ /**
564
+ * An unique id to represent the request. This can be null if request failed before it could be sent.
565
+ * @type {string}
566
+ * @public
567
+ */
568
+ this.requestId = requestId;
569
+
570
+ /**
571
+ * An error object if the operation resulted in an error and there was no response. This property is defined only if the resultCode is -10000.
572
+ * @type {Error}
573
+ * @public
574
+ */
575
+ this.err = err;
576
+ }
577
+ }
578
+
579
+ /**
580
+ * @class
581
+ * @constructor
582
+ * @public
583
+ * @classdesc This class represents a transaction of an account. You should consider the transaction as succeeded only if the status field is 0x1 (success).
584
+ */
585
+ class AccountTransactionCompact {
586
+ constructor() {
587
+ /**
588
+ * The number of the block that registered the transaction. This field can be null if the transaction was not registered in the blockchain.
589
+ * @type {number}
590
+ * @public
591
+ */
592
+ this.blockNumber = null;
593
+
594
+ /**
595
+ * A 66 character hexadecimal string representing the address the transaction is sent from.
596
+ * @type {string}
597
+ * @public
598
+ */
599
+ this.from = null;
600
+
601
+ /**
602
+ * A 66 character hexadecimal string representing the hash of the transaction.
603
+ * @type {string}
604
+ * @public
605
+ */
606
+ this.hash = null;
607
+
608
+ /**
609
+ * A 66 character hexadecimal string representing address the transaction is directed to.
610
+ * @type {string}
611
+ * @public
612
+ */
613
+ this.to = null;
614
+
615
+ /**
616
+ * A hexadecimal string representing the value sent with this transaction. The value can be 0 for smart contract transactions, since it only represents the number of coins sent.
617
+ * @type {string}
618
+ * @public
619
+ */
620
+ this.value = null;
621
+
622
+ /**
623
+ * A hexadecimal string representing either 0x1 (success) or 0x0 (failure). Failed transactions can also incur gas fee. You should consider the transaction as succeeded only if the status value is 0x1 (success).
624
+ * @type {string}
625
+ * @public
626
+ */
627
+ this.status = null;
628
+ }
629
+
630
+ }
631
+
632
+ /**
633
+ * @class
634
+ * @constructor
635
+ * @public
636
+ * @classdesc This class represents a list of account transactions returned by the listAccountTransactionDetails function.
637
+ */
638
+ class ListAccountTransactionsResponse {
639
+ constructor() {
640
+ /**
641
+ * The number of pages available for listing.
642
+ * @type {number}
643
+ * @public
644
+ */
645
+ this.pageCount = null;
646
+
647
+ /**
648
+ * An array of type AccountTransactionCompact, containing the list of transactions. Can be null if no items are available.
649
+ * @type {(AccountTransactionCompact|Array)}
650
+ * @public
651
+ */
652
+ this.items = null;
653
+ }
654
+
655
+ }
656
+
657
+ /**
658
+ * @class
659
+ * @constructor
660
+ * @public
661
+ * @classdesc This class represents a result from invoking the listAccountTransactionDetails function.
662
+ */
663
+ class AccountTransactionsResult {
664
+ constructor(resultCode, listAccountTransactionsResponse, response, requestId, err) {
665
+ /**
666
+ * Represents the result of the operation. A value of 0 represents that the operation succeeded. Any other value indicates the operation failed. See the result code section for more details.
667
+ * @type {number}
668
+ * @public
669
+ */
670
+ this.resultCode = resultCode;
671
+
672
+ /**
673
+ * An object of type ListAccountTransactionsResponse representing the list of transactions along with metadata. This value is null if the value of resultCode is not 0.
674
+ * @type {ListAccountTransactionsResponse}
675
+ * @public
676
+ */
677
+ this.listAccountTransactionsResponse = listAccountTransactionsResponse;
678
+
679
+ /**
680
+ * An object of representing the raw Response returned by the service. For details, see https://developer.mozilla.org/en-US/docs/Web/API/Response. This value can be null if the value of resultCode is not 0.
681
+ * @type {Object}
682
+ * @public
683
+ */
684
+ this.response = response;
685
+
686
+ /**
687
+ * An unique id to represent the request. This can be null if request failed before it could be sent.
688
+ * @type {string}
689
+ * @public
690
+ */
691
+ this.requestId = requestId;
692
+
693
+ /**
694
+ * An error object if the operation resulted in an error and there was no response. This property is defined only if the resultCode is -10000.
695
+ * @type {Error}
696
+ * @public
697
+ */
698
+ this.err = err;
699
+ }
700
+ }
701
+
702
+ /**
703
+ * @class
704
+ * @constructor
705
+ * @public
706
+ * @classdesc This class represents a signing request that can be passed to signTransaction.
707
+ */
708
+ class TransactionSigningRequest {
709
+ /**
710
+ * Creates a TransactionSigningRequest class.
711
+ * @param {Wallet} wallet - The wallet with which the transaction has to be signed. The constructor does not verify the wallet. To verify a wallet, call the verifyWallet function explicitly.
712
+ * @param {string} toAddress - The address to which the transaction request is made. Can be null (for example, for contract creation).
713
+ * @param {string|BigInt} valueInWei - The value in wei-units. Can be provided as either a hex string (including 0x prefix) or a BigInt. For example, to represent 1 coin, which is 1000000000000000000 in wei-units, set the value to "0xDE0B6B3A7640000" or BigInt("1000000000000000000"). {@link /example/conversion-example.js|Conversion Examples}
714
+ * @param {number} nonce - A monotonically increasing number representing the nonce of the account signing the transaction. After each transaction from the account that gets registered in the blockchain, the nonce increases by 1.
715
+ * @param {string} data - An optional hex string (including 0x) that represents the contract data. Can be null if not invoking or creating a contract.
716
+ * @param {number} gasLimit - A limit of gas to be used. Set 21000 for basic non smart contract transactions.
717
+ * @param {string} remarks - An optional hex string (including 0x) that represents a remark (such as a comment). Maximum 32 bytes length (in bytes). Warning, do not store any sensitive information in this field.
718
+ * @param {number|null} chainId - The chain id of the blockchain. Mainnet chainId is 123123. Testnet T4 chainId is 310324. If null, the chainId specified in the initialize() function will be used.
719
+ * @param {number|null} signingContext - It is recommended that you pass null for this parameter, unless the context needs to be set explicitly. Signing context determines the cryptographic scheme used to sign. The wallet key type should compatible with the signing context. Applicable values are 0,1,2. Default value if not specified will be determined dynamically from the wallet key type. Signing context 1,2 will incur additional gas fee. For information on the schemes, see https://github.com/quantumcoinproject/circl?tab=readme-ov-file#hybrid-schemes
720
+ * Signing context 0: Scheme used is hybrid-ed-mldsa-slhdsa compact (scheme id 3)
721
+ * Signing context 1: Scheme used is hybrid-ed-mldsa-slhdsa-5 (scheme id 5 : 20x the gas fee of scheme 0)
722
+ * Signing context 2: hybrid-ed-mldsa-slhdsa full (scheme id 4 : 30x the gas fee of scheme 0)
723
+ */
724
+ constructor(wallet, toAddress, valueInWei, nonce, data, gasLimit, remarks, chainId, signingContext) {
725
+ /**
726
+ * The wallet that should be used to sign the transaction.
727
+ * @type {Wallet}
728
+ * @public
729
+ */
730
+ this.wallet = wallet;
731
+
732
+ /**
733
+ * The address to which the transaction request is made. Can be null (for example, for contract creation).
734
+ * @type {string|null}
735
+ * @public
736
+ */
737
+ this.toAddress = toAddress;
738
+
739
+ /**
740
+ * The value in wei-units. Can be provided as either a hex string (including 0x prefix) or a BigInt. For example, to represent 1 coin, which is 1000000000000000000 in wei-units, set the value to "0xDE0B6B3A7640000" or BigInt("1000000000000000000"). {@link /example/conversion-example.js|Conversion Examples}
741
+ * @type {string|BigInt|null}
742
+ * @public
743
+ */
744
+ this.valueInWei = valueInWei;
745
+
746
+ /**
747
+ * A monotonically increasing number representing the nonce of the account signing the transaction. After each transaction from the account that gets registered in the blockchain, the nonce increases by 1.
748
+ * @type {number}
749
+ * @public
750
+ */
751
+ this.nonce = nonce;
752
+
753
+ /**
754
+ * An optional hex string (including 0x) that represents the contract data. Can be null if not invoking or creating a contract.
755
+ * @type {string|null}
756
+ * @public
757
+ */
758
+ this.data = data;
759
+
760
+ /**
761
+ * A limit of gas to be used. Set 21000 for basic non smart contract transactions.
762
+ * @type {number}
763
+ * @public
764
+ */
765
+ this.gasLimit = gasLimit;
766
+
767
+ /**
768
+ * An optional hex string (including 0x) that represents a remark (such as a comment). Maximum 32 bytes length (in bytes). Warning, do not store any sensitive information in this field.
769
+ * @type {string|null}
770
+ * @public
771
+ */
772
+ this.remarks = remarks;
773
+
774
+ /**
775
+ * The chain id of the blockchain. Mainnet chainId is 123123. If null, the chainId specified in the initialize() function will be used.
776
+ * @type {number|null}
777
+ * @public
778
+ */
779
+ this.chainId = chainId;
780
+
781
+ /**
782
+ * It is recommended that you pass null for this parameter, unless the context needs to be set explicitly. Signing context determines the cryptographic scheme used to sign. Gas fee varies by context.
783
+ * @type {number|null}
784
+ * @public
785
+ */
786
+ this.signingContext = signingContext;
787
+ }
788
+ }
789
+
790
+ /**
791
+ * @class
792
+ * @constructor
793
+ * @public
794
+ * @classdesc This class represents a result from invoking the packMethodData or unpackMethodData functions.
795
+ */
796
+ class PackUnpackResult {
797
+ /**
798
+ * Creates a PackUnpackResult class.
799
+ * @param {string} error - Error message if any. Empty string if no error.
800
+ * @param {string} result - The actual result as a string. Empty string if there was an error.
801
+ */
802
+ constructor(error, result) {
803
+ /**
804
+ * Error message if any. Empty string if no error.
805
+ * @type {string}
806
+ * @public
807
+ */
808
+ this.error = error;
809
+
810
+ /**
811
+ * The actual result as a string. Empty string if there was an error.
812
+ * @type {string}
813
+ * @public
814
+ */
815
+ this.result = result;
816
+ }
817
+ }
818
+
819
+ /**
820
+ * @class EventLogEncodeResult
821
+ * @classdesc This class represents a result from invoking the encodeEventLog function.
822
+ */
823
+ class EventLogEncodeResult {
824
+ /**
825
+ * Creates an EventLogEncodeResult class.
826
+ * @param {string} error - Error message if any. Empty string if no error.
827
+ * @param {Object|null} result - The actual result object with topics and data. Null if there was an error.
828
+ * @param {string[]} result.topics - Array of topic hex strings (with 0x prefix)
829
+ * @param {string} result.data - Hex-encoded data string (with 0x prefix)
830
+ */
831
+ constructor(error, result) {
832
+ /**
833
+ * Error message if any. Empty string if no error.
834
+ * @type {string}
835
+ * @public
836
+ */
837
+ this.error = error;
838
+
839
+ /**
840
+ * The actual result object with topics and data. Null if there was an error.
841
+ * @type {Object|null}
842
+ * @property {string[]} topics - Array of topic hex strings (with 0x prefix)
843
+ * @property {string} data - Hex-encoded data string (with 0x prefix)
844
+ * @public
845
+ */
846
+ this.result = result;
847
+ }
848
+ }
849
+
850
+ function isLargeNumber(val) {
851
+ if (val === null) {
852
+ return false;
853
+ }
854
+ if (typeof val === 'string' || val instanceof String) {
855
+ var rgx = /^([0-9]+([.][0-9]*)?|[.][0-9]+)$/;
856
+ return Boolean(val.match(rgx));
857
+ }
858
+ return false;
859
+ }
860
+
861
+ function getGlobalObject() {
862
+ return (typeof globalThis !== 'undefined' ? globalThis : typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : this);
863
+ }
864
+
865
+ async function InitAccountsWebAssembly() {
866
+ const go = new global.Go();
867
+ let mod, inst;
868
+ var base64wasm = wasmBase64.getBase64Wasm();
869
+
870
+ const base64bytes = atob(base64wasm);
871
+ if (base64bytes === null || base64bytes === undefined || base64bytes.length === 0) {
872
+ throw new Error("Error parsing base64");
873
+ }
874
+ const wasmBytes = Uint8Array.from(atob(base64wasm), c => c.charCodeAt(0));
875
+
876
+ const hashHex = crypto.createHash('sha256').update(wasmBytes).digest('hex');
877
+ if (hashHex !== EXPECTED_WASM_SHA256) {
878
+ throw new Error("WASM integrity check failed");
879
+ }
880
+
881
+ const g = getGlobalObject();
882
+ if (g) {
883
+ delete g.circl;
884
+ }
885
+
886
+ let result = await WebAssembly.instantiate(wasmBytes, go.importObject);
887
+ mod = result.module;
888
+ inst = result.instance;
889
+ go.run(inst);
890
+
891
+ if (g && g.circl) {
892
+ circl = g.circl;
893
+ delete g.circl;
894
+ if (circl.hybridedmldsaslhdsa) Object.freeze(circl.hybridedmldsaslhdsa);
895
+ if (circl.hybridedmldsaslhdsa5) Object.freeze(circl.hybridedmldsaslhdsa5);
896
+ if (circl.hybridedmldsaslhdsa5) Object.freeze(circl.hybridedmldsaslhdsa5);
897
+ if (circl.hybrideds) Object.freeze(circl.hybrideds);
898
+ Object.freeze(circl);
899
+ }
900
+ }
901
+
902
+ function validateCryptoRandom() {
903
+ if (!circl || !circl.cryptoRandom) {
904
+ return false;
905
+ }
906
+
907
+ const sampleSize = 64;
908
+ const res1 = circl.cryptoRandom(sampleSize);
909
+ const res2 = circl.cryptoRandom(sampleSize);
910
+
911
+ if (!res1 || res1.error || !res1.result || res1.result.length !== sampleSize) {
912
+ return false;
913
+ }
914
+ if (!res2 || res2.error || !res2.result || res2.result.length !== sampleSize) {
915
+ return false;
916
+ }
917
+
918
+ const a = res1.result instanceof Uint8Array ? res1.result : new Uint8Array(res1.result);
919
+ const b = res2.result instanceof Uint8Array ? res2.result : new Uint8Array(res2.result);
920
+
921
+ let identical = true;
922
+ for (let i = 0; i < sampleSize; i++) {
923
+ if (a[i] !== b[i]) { identical = false; break; }
924
+ }
925
+ if (identical) {
926
+ return false;
927
+ }
928
+
929
+ let aAllZero = true, bAllZero = true;
930
+ for (let i = 0; i < sampleSize; i++) {
931
+ if (a[i] !== 0) aAllZero = false;
932
+ if (b[i] !== 0) bAllZero = false;
933
+ }
934
+ if (aAllZero || bAllZero) {
935
+ return false;
936
+ }
937
+
938
+ const seen = new Set(a);
939
+ if (seen.size < 48) {
940
+ return false;
941
+ }
942
+
943
+ return true;
944
+ }
945
+
946
+ /**
947
+ * The initialize function has to be called before attempting to invoke any other function. This function should be called only once.
948
+ *
949
+ * @async
950
+ * @function initialize
951
+ * @param {Config|undefined} clientConfig - A configuration represented by the Config class. A default configuration is used, if not specified.
952
+ * @return {Promise<boolean>} Returns a promise of type boolean; true if the initialization succeeded, else false.
953
+ */
954
+ async function initialize(clientConfig) {
955
+ if (isInitialized === true) {
956
+ return false;
957
+ }
958
+ if (clientConfig === null || clientConfig === undefined) {
959
+ clientConfig = new Config("https://sdk.readrelay.quantumcoinapi.com", "https://sdk.writerelay.quantumcoinapi.com", 123123, "", ""); //default
960
+ }
961
+ if (clientConfig.readUrl === null || clientConfig.writeUrl === null || clientConfig.chainId === null) {
962
+ return false;
963
+ }
964
+ await InitAccountsWebAssembly();
965
+ if (!validateCryptoRandom()) {
966
+ throw new Error("CSPRNG validation failed");
967
+ }
968
+ config = clientConfig;
969
+ isInitialized = await seedwords.initialize();
970
+
971
+ return isInitialized;
972
+ }
973
+
974
+ /**
975
+ * The isAddressValid function validates whether an address is valid or not. An address is of length 66 characters including 0x.
976
+ *
977
+ * @function isAddressValid
978
+ * @param {string} address - A string representing the address to validate.
979
+ * @return {boolean} Returns true if the address validation succeeded, else returns false.
980
+ */
981
+ function isAddressValid(address) {
982
+ if (isInitialized === false) {
983
+ return -1000;
984
+ }
985
+
986
+ if (address === null) {
987
+ return false;
988
+ }
989
+
990
+ if (address.length !== 66) {
991
+ return false;
992
+ }
993
+
994
+ if (typeof address === 'string' || address instanceof String) {
995
+ return IsValidAddress(address);
996
+ }
997
+
998
+ return false;
999
+ }
1000
+
1001
+ /**
1002
+ * Internal: get key type (KEY_TYPE_HYBRIDEDMLDSASLHDSA or KEY_TYPE_HYBRIDEDMLDSASLHDSA5) from private key length.
1003
+ * @param {number[]|Uint8Array} privateKey - Wallet private key bytes.
1004
+ * @returns {number|null} KEY_TYPE_HYBRIDEDMLDSASLHDSA (3), KEY_TYPE_HYBRIDEDMLDSASLHDSA5 (5), or null on error.
1005
+ */
1006
+ function getKeyTypeFromPrivateKey(privateKey) {
1007
+ if (circl == null || !privateKey || typeof privateKey.length !== 'number') {
1008
+ return null;
1009
+ }
1010
+ const len = privateKey.length;
1011
+ const hybridNs = circl.hybridedmldsaslhdsa;
1012
+ const hybrid5Ns = circl.hybridedmldsaslhdsa5 || circl.hybridedmldsaslhdsa5;
1013
+ if (hybridNs && len === hybridNs.PrivateKeySize) {
1014
+ return KEY_TYPE_HYBRIDEDMLDSASLHDSA;
1015
+ }
1016
+ if (hybrid5Ns && len === hybrid5Ns.PrivateKeySize) {
1017
+ return KEY_TYPE_HYBRIDEDMLDSASLHDSA5;
1018
+ }
1019
+ return null;
1020
+ }
1021
+
1022
+ /**
1023
+ * Internal: get key type (KEY_TYPE_HYBRIDEDMLDSASLHDSA or KEY_TYPE_HYBRIDEDMLDSASLHDSA5) from public key length.
1024
+ * @param {number[]|Uint8Array} publicKey - Public key bytes.
1025
+ * @returns {number|null} KEY_TYPE_HYBRIDEDMLDSASLHDSA (3), KEY_TYPE_HYBRIDEDMLDSASLHDSA5 (5), or null on error.
1026
+ */
1027
+ function getKeyTypeFromPublicKey(publicKey) {
1028
+ if (circl == null || !publicKey || typeof publicKey.length !== 'number') {
1029
+ return null;
1030
+ }
1031
+ const len = publicKey.byteLength !== undefined ? publicKey.byteLength : publicKey.length;
1032
+ const hybridNs = circl.hybridedmldsaslhdsa;
1033
+ const hybrid5Ns = circl.hybridedmldsaslhdsa5 || circl.hybridedmldsaslhdsa5;
1034
+ if (hybridNs && typeof hybridNs.PublicKeySize === 'number' && len === hybridNs.PublicKeySize) {
1035
+ return KEY_TYPE_HYBRIDEDMLDSASLHDSA;
1036
+ }
1037
+ if (hybrid5Ns && typeof hybrid5Ns.PublicKeySize === 'number' && len === hybrid5Ns.PublicKeySize) {
1038
+ return KEY_TYPE_HYBRIDEDMLDSASLHDSA5;
1039
+ }
1040
+ return null;
1041
+ }
1042
+
1043
+ /**
1044
+ * Convert key (number[] or Uint8Array) to Uint8Array for CIRCL.
1045
+ * @param {number[]|Uint8Array} key - Key bytes.
1046
+ * @returns {Uint8Array}
1047
+ */
1048
+ function toUint8Array(key) {
1049
+ if (key instanceof Uint8Array) return key;
1050
+ return new Uint8Array(key);
1051
+ }
1052
+
1053
+ /**
1054
+ * The newWallet function creates a new Wallet.
1055
+ * @function newWallet
1056
+ * @param {number|null} keyType - Optional. KEY_TYPE_HYBRIDEDMLDSASLHDSA (3) or KEY_TYPE_HYBRIDEDMLDSASLHDSA5 (5). null/undefined defaults to 3.
1057
+ * @return {Wallet|number} Returns a Wallet object, or -1000 (not initialized), -1001 (invalid key type), -1002 (crypto failure).
1058
+ */
1059
+ function newWallet(keyType) {
1060
+ if (isInitialized === false) {
1061
+ return -1000;
1062
+ }
1063
+ if (circl == null) {
1064
+ return CIRCL_CRYPTO_FAILURE;
1065
+ }
1066
+ if (keyType === null || keyType === undefined) {
1067
+ keyType = KEY_TYPE_HYBRIDEDMLDSASLHDSA;
1068
+ }
1069
+ const hybridNs = circl.hybridedmldsaslhdsa;
1070
+ const hybrid5Ns = circl.hybridedmldsaslhdsa5 || circl.hybridedmldsaslhdsa5;
1071
+ let res;
1072
+ if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA && hybridNs) {
1073
+ res = hybridNs.generateKey();
1074
+ } else if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA5 && hybrid5Ns) {
1075
+ res = hybrid5Ns.generateKey();
1076
+ } else {
1077
+ return INVALID_KEY_TYPE;
1078
+ }
1079
+ if (res && res.error) {
1080
+ return CIRCL_CRYPTO_FAILURE;
1081
+ }
1082
+ if (!res || !res.result || !res.result.publicKey || !res.result.privateKey) {
1083
+ return CIRCL_CRYPTO_FAILURE;
1084
+ }
1085
+ const publicKey = res.result.publicKey instanceof Uint8Array ? Array.from(res.result.publicKey) : res.result.publicKey;
1086
+ const privateKey = res.result.privateKey instanceof Uint8Array ? Array.from(res.result.privateKey) : res.result.privateKey;
1087
+ const address = PublicKeyToAddress(publicKey);
1088
+ return new Wallet(address, privateKey, publicKey);
1089
+ }
1090
+
1091
+ /**
1092
+ * The newWalletSeedWords function creates a new wallet seed word list. The returned array can then be passed to the openWalletFromSeedWords function to create a new wallet.
1093
+ *
1094
+ * @function newWalletSeedWords
1095
+ * @param {number|null} keyType - Optional. KEY_TYPE_HYBRIDEDMLDSASLHDSA (3) or KEY_TYPE_HYBRIDEDMLDSASLHDSA5 (5). null/undefined defaults to 3.
1096
+ * @return {string[]|number|null} Returns an array of seed words (32 or 36 words depending on keyType). Returns -1000 if not initialized, null on failure.
1097
+ */
1098
+ function newWalletSeedWords(keyType) {
1099
+ if (isInitialized === false) {
1100
+ return -1000;
1101
+ }
1102
+ if (circl == null || !circl.cryptoRandom) {
1103
+ return null;
1104
+ }
1105
+ if (keyType === null || keyType === undefined) {
1106
+ keyType = KEY_TYPE_HYBRIDEDMLDSASLHDSA;
1107
+ }
1108
+ if (keyType !== KEY_TYPE_HYBRIDEDMLDSASLHDSA && keyType !== KEY_TYPE_HYBRIDEDMLDSASLHDSA5) {
1109
+ return null;
1110
+ }
1111
+ const baseSeedLen = keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA5 ? BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA5 : BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA;
1112
+ const res = circl.cryptoRandom(baseSeedLen);
1113
+ if (res && res.error) {
1114
+ return null;
1115
+ }
1116
+ if (!res || !res.result || res.result.length !== baseSeedLen) {
1117
+ return null;
1118
+ }
1119
+ const seedArray = res.result instanceof Uint8Array ? res.result : new Uint8Array(res.result);
1120
+ const wordList = seedwords.getWordListFromSeedArray(seedArray);
1121
+ const expectedLen = keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA5 ? SEED_WORD_LIST_LENGTH_HYBRIDEDMLDSASLHDSA5 : SEED_WORD_LIST_LENGTH_HYBRIDEDMLDSASLHDSA;
1122
+ if (wordList == null || wordList.length !== expectedLen) {
1123
+ return null;
1124
+ }
1125
+ return wordList;
1126
+ }
1127
+
1128
+ /**
1129
+ * The openWalletFromSeed function creates a wallet from a raw seed byte array.
1130
+ * Determines the key scheme from the array length: 96 bytes (hybrideds), 72 bytes (hybrid5), or 64 bytes (hybrid).
1131
+ *
1132
+ * @function openWalletFromSeed
1133
+ * @param {Array<number>|Uint8Array} seedArray - The raw seed bytes. Length 96, 72, or 64 depending on scheme.
1134
+ * @return {Wallet|number|null} Returns a Wallet object. Returns -1000 if not initialized, null if the operation failed.
1135
+ */
1136
+ function openWalletFromSeed(seedArray) {
1137
+ if (isInitialized === false) {
1138
+ return -1000;
1139
+ }
1140
+ if (seedArray == null || typeof seedArray.length !== 'number') {
1141
+ return null;
1142
+ }
1143
+ const len = seedArray.length;
1144
+ if (len !== BASE_SEED_BYTES_HYBRIDEDS && len !== BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA5 && len !== BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA) {
1145
+ return null;
1146
+ }
1147
+ if (circl == null) {
1148
+ return null;
1149
+ }
1150
+ let expandedRes;
1151
+ let keyPairRes;
1152
+ const seedU8 = seedArray instanceof Uint8Array ? seedArray : new Uint8Array(seedArray);
1153
+ if (len === BASE_SEED_BYTES_HYBRIDEDS) {
1154
+ const ns = circl.hybrideds;
1155
+ if (!ns) return null;
1156
+ expandedRes = ns.expandSeed(seedU8);
1157
+ if (expandedRes && expandedRes.error) return null;
1158
+ if (!expandedRes || !expandedRes.result) return null;
1159
+ keyPairRes = ns.newKeyFromSeed(expandedRes.result);
1160
+ } else if (len === BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA5) {
1161
+ const ns = circl.hybridedmldsaslhdsa5 || circl.hybridedmldsaslhdsa5;
1162
+ if (!ns) return null;
1163
+ expandedRes = ns.expandSeed(seedU8);
1164
+ if (expandedRes && expandedRes.error) return null;
1165
+ if (!expandedRes || !expandedRes.result) return null;
1166
+ keyPairRes = ns.newKeyFromSeed(expandedRes.result);
1167
+ } else {
1168
+ const ns = circl.hybridedmldsaslhdsa;
1169
+ if (!ns) return null;
1170
+ expandedRes = ns.expandSeed(seedU8);
1171
+ if (expandedRes && expandedRes.error) return null;
1172
+ if (!expandedRes || !expandedRes.result) return null;
1173
+ keyPairRes = ns.newKeyFromSeed(expandedRes.result);
1174
+ }
1175
+ if (keyPairRes && keyPairRes.error) return null;
1176
+ if (!keyPairRes || !keyPairRes.result || !keyPairRes.result.publicKey || !keyPairRes.result.privateKey) return null;
1177
+ const publicKey = keyPairRes.result.publicKey instanceof Uint8Array ? Array.from(keyPairRes.result.publicKey) : keyPairRes.result.publicKey;
1178
+ const privateKey = keyPairRes.result.privateKey instanceof Uint8Array ? Array.from(keyPairRes.result.privateKey) : keyPairRes.result.privateKey;
1179
+ const address = PublicKeyToAddress(publicKey);
1180
+ return new Wallet(address, privateKey, publicKey, seedU8);
1181
+ }
1182
+
1183
+ /**
1184
+ * The openWalletFromSeedWords function creates a wallet from a seed word list. The seed word list is available for wallets created from Desktop/Web/Mobile wallets.
1185
+ * Supports 48 words (hybrideds), 36 words (hybrid5), or 32 words (hybrid) per seed length.
1186
+ *
1187
+ * @function openWalletFromSeedWords
1188
+ * @param {string[]} seedWordList - An array of seed words. Length 48, 36, or 32 depending on scheme.
1189
+ * @return {Wallet|number|null} Returns a Wallet object. Returns -1000 if not initialized, null if the operation failed.
1190
+ */
1191
+ function openWalletFromSeedWords(seedWordList) {
1192
+ if (isInitialized === false) {
1193
+ return -1000;
1194
+ }
1195
+ if (seedWordList == null || typeof seedWordList.length !== 'number') {
1196
+ return null;
1197
+ }
1198
+ const len = seedWordList.length;
1199
+ if (len !== SEED_WORD_LIST_LENGTH_HYBRIDEDS && len !== SEED_WORD_LIST_LENGTH_HYBRIDEDMLDSASLHDSA5 && len !== SEED_WORD_LIST_LENGTH_HYBRIDEDMLDSASLHDSA) {
1200
+ return null;
1201
+ }
1202
+ const seedArray = seedwords.getSeedArrayFromWordList(seedWordList);
1203
+ if (seedArray == null || seedArray.length === undefined) {
1204
+ return null;
1205
+ }
1206
+ return openWalletFromSeed(seedArray);
1207
+ }
1208
+
1209
+ /**
1210
+ * The deserializeEncryptedWallet function opens a wallet backed-up using an application such as the Desktop/Mobile/CLI/Web wallet. This function can take upto a minute or so to execute. You should open wallets only from trusted sources.
1211
+ *
1212
+ * @function deserializeEncryptedWallet
1213
+ * @param {string} walletJsonString - The json string from a wallet file.
1214
+ * @param {string} passphrase - The passphrase used to encrypt the wallet.
1215
+ * @return {Wallet} Returns a Wallet object. Returns null if opening the wallet fails.
1216
+ */
1217
+ function deserializeEncryptedWallet(walletJsonString, passphrase) {
1218
+ if (isInitialized === false) {
1219
+ return -1000;
1220
+ }
1221
+
1222
+ if (walletJsonString == null || passphrase == null) {
1223
+ return null;
1224
+ }
1225
+
1226
+ if (typeof walletJsonString === 'string' || walletJsonString instanceof String) {
1227
+
1228
+ } else {
1229
+ return null;
1230
+ }
1231
+
1232
+ if (typeof passphrase === 'string' || passphrase instanceof String) {
1233
+
1234
+ } else {
1235
+ return null;
1236
+ }
1237
+
1238
+ let walletJsonObj;
1239
+ try {
1240
+ walletJsonObj = JSON.parse(walletJsonString);
1241
+ } catch (e) {
1242
+ return null;
1243
+ }
1244
+
1245
+ if (walletJsonObj == null) {
1246
+ return null;
1247
+ }
1248
+
1249
+ if (walletJsonObj.address == null) {
1250
+ return null;
1251
+ }
1252
+
1253
+ let keyPairString = JsonToWalletKeyPair(walletJsonString, passphrase);
1254
+ if (keyPairString == null) {
1255
+ return null;
1256
+ }
1257
+
1258
+ let keyPairSplit = keyPairString.split(",");
1259
+ if (keyPairSplit.length < 2) {
1260
+ return null;
1261
+ }
1262
+
1263
+ let privateKeyArray = base64ToBytes(keyPairSplit[0]);
1264
+ let publicKeyArray = base64ToBytes(keyPairSplit[1]);
1265
+ let preExpansionSeed = null;
1266
+ if (keyPairSplit.length >= 3 && keyPairSplit[2].length > 0) {
1267
+ preExpansionSeed = base64ToBytes(keyPairSplit[2]);
1268
+ }
1269
+ let address = PublicKeyToAddress(publicKeyArray);
1270
+ if (address == null) {
1271
+ return null;
1272
+ }
1273
+
1274
+ if (typeof address === 'string' || address instanceof String) {
1275
+
1276
+ } else {
1277
+ return null;
1278
+ }
1279
+
1280
+ let addressCheck = "0x" + walletJsonObj.address.toLowerCase();
1281
+ if (addressCheck !== address.toLowerCase()) {
1282
+ return null;
1283
+ }
1284
+
1285
+ let wallet = new Wallet(address, privateKeyArray, publicKeyArray, preExpansionSeed);
1286
+
1287
+ return wallet;
1288
+ }
1289
+
1290
+ /**
1291
+ * The serializeEncryptedWallet function encrypts and serializes a Wallet object to a JSON string readable by the Desktop/Mobile/Web/CLI wallet applications. You can save this string to a file and open the file in one of these wallet applications. You may also open this string using the deserializeEncryptedWallet function. If you loose the passphrase, you will be unable to open the wallet. This function can take upto a minute or so to execute.
1292
+ *
1293
+ * @function serializeEncryptedWallet
1294
+ * @param {Wallet} wallet - A Wallet object representing the wallet to serialize.
1295
+ * @param {string} passphrase - A passphrase used to encrypt the wallet. It should atleast be 12 characters long.
1296
+ * @return {string} Returns the Wallet in JSON string format. If the wallet is invalid, null is returned.
1297
+ */
1298
+ function serializeEncryptedWallet(wallet, passphrase) {
1299
+ if(verifyWallet(wallet) === false) {
1300
+ return null;
1301
+ }
1302
+
1303
+ if (passphrase == null) {
1304
+ return null;
1305
+ }
1306
+
1307
+ if (typeof passphrase === 'string' || passphrase instanceof String) {
1308
+
1309
+ } else {
1310
+ return null;
1311
+ }
1312
+
1313
+ if (passphrase.length < MIN_PASSPHRASE_LENGTH) {
1314
+ return null;
1315
+ }
1316
+
1317
+ let walletJsonString;
1318
+ if (wallet.preExpansionSeed != null && wallet.preExpansionSeed.length > 0) {
1319
+ const seedU8 = wallet.preExpansionSeed instanceof Uint8Array ? wallet.preExpansionSeed : new Uint8Array(wallet.preExpansionSeed);
1320
+ const result = EncryptPreExpansionSeed(seedU8, passphrase);
1321
+ if (result == null || result instanceof Error) {
1322
+ return null;
1323
+ }
1324
+ walletJsonString = result;
1325
+ } else {
1326
+ walletJsonString = KeyPairToWalletJson(wallet.privateKey, wallet.publicKey, passphrase);
1327
+ }
1328
+
1329
+ let walletJson = JSON.parse(walletJsonString);
1330
+ let addressCheck = "0x" + walletJson.address;
1331
+ if (addressCheck.toLowerCase() !== wallet.address.toLowerCase()) {
1332
+ return null;
1333
+ }
1334
+
1335
+ return walletJsonString;
1336
+ }
1337
+
1338
+ /**
1339
+ * The serializeSeedAsEncryptedWallet function encrypts a raw seed byte array into a wallet JSON string
1340
+ * that can be opened with deserializeEncryptedWallet or Desktop/Mobile/Web/CLI wallet applications.
1341
+ * The seed is stored in its pre-expansion form (version 5 wallet format). This function can take
1342
+ * up to a minute or so to execute due to key derivation.
1343
+ *
1344
+ * @function serializeSeedAsEncryptedWallet
1345
+ * @param {Array<number>|Uint8Array} seedArray - The raw seed bytes. Length must be 96, 72, or 64 depending on scheme.
1346
+ * @param {string} passphrase - A passphrase used to encrypt the wallet. Must be at least 12 characters long.
1347
+ * @return {string|number|null} Returns the encrypted wallet JSON string. Returns -1000 if not initialized, null if the operation failed.
1348
+ */
1349
+ function serializeSeedAsEncryptedWallet(seedArray, passphrase) {
1350
+ if (isInitialized === false) {
1351
+ return -1000;
1352
+ }
1353
+ if (seedArray == null || typeof seedArray.length !== 'number') {
1354
+ return null;
1355
+ }
1356
+ const len = seedArray.length;
1357
+ if (len !== BASE_SEED_BYTES_HYBRIDEDS && len !== BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA5 && len !== BASE_SEED_BYTES_HYBRIDEDMLDSASLHDSA) {
1358
+ return null;
1359
+ }
1360
+ if (passphrase == null) {
1361
+ return null;
1362
+ }
1363
+ if (typeof passphrase !== 'string' && !(passphrase instanceof String)) {
1364
+ return null;
1365
+ }
1366
+ if (passphrase.length < MIN_PASSPHRASE_LENGTH) {
1367
+ return null;
1368
+ }
1369
+ const seedU8 = seedArray instanceof Uint8Array ? seedArray : new Uint8Array(seedArray);
1370
+ const result = EncryptPreExpansionSeed(seedU8, passphrase);
1371
+ if (result == null || result instanceof Error) {
1372
+ return null;
1373
+ }
1374
+ return result;
1375
+ }
1376
+
1377
+ function base64ToBytes(base64) {
1378
+ const binString = atob(base64);
1379
+ return Uint8Array.from(binString, (m) => m.codePointAt(0));
1380
+ }
1381
+
1382
+ function bytesToBase64(bytes) {
1383
+ const binString = Array.from(bytes, (byte) =>
1384
+ String.fromCodePoint(byte),
1385
+ ).join("");
1386
+ return btoa(binString);
1387
+ }
1388
+
1389
+ function getRandomRequestId() {
1390
+ return crypto.randomBytes(20).toString('hex');
1391
+ }
1392
+
1393
+ function isByteArray(array) {
1394
+ if (!array) return false;
1395
+ if (array.byteLength !== undefined) return true;
1396
+ if (typeof array.length === 'number' && array.length >= 0) return true;
1397
+ return false;
1398
+ }
1399
+
1400
+ /**
1401
+ * The verifyWallet function verifies whether a Wallet is valid or not. To mitigate spoofing and other attachs, it is highly recommended to verify a wallet, especially if it is from an untrusted source.
1402
+ *
1403
+ * @function verifyWallet
1404
+ * @param {Wallet} wallet - A Wallet object representing the wallet to verify.
1405
+ * @return {boolean} Returns true if the Wallet verification succeeded, else returns false.
1406
+ */
1407
+ function verifyWallet(wallet) {
1408
+ if (isInitialized === false) {
1409
+ return -1000;
1410
+ }
1411
+ if (wallet === null || wallet.address === null || wallet.privateKey === null || wallet.publicKey === null) {
1412
+ return false;
1413
+ }
1414
+ if (isAddressValid(wallet.address) === false) {
1415
+ return false;
1416
+ }
1417
+ if (isByteArray(wallet.privateKey) === false) {
1418
+ return false;
1419
+ }
1420
+ if (isByteArray(wallet.publicKey) === false) {
1421
+ return false;
1422
+ }
1423
+ const keyType = getKeyTypeFromPrivateKey(wallet.privateKey);
1424
+ if (keyType == null) {
1425
+ return false;
1426
+ }
1427
+ const hybridNs = circl && circl.hybridedmldsaslhdsa;
1428
+ const hybrid5Ns = circl && (circl.hybridedmldsaslhdsa5 || circl.hybridedmldsaslhdsa5);
1429
+ if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA && hybridNs && wallet.privateKey.length !== hybridNs.PrivateKeySize) {
1430
+ return false;
1431
+ }
1432
+ if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA5 && hybrid5Ns && wallet.privateKey.length !== hybrid5Ns.PrivateKeySize) {
1433
+ return false;
1434
+ }
1435
+ const address = PublicKeyToAddress(wallet.publicKey);
1436
+ if (address !== wallet.address) {
1437
+ return false;
1438
+ }
1439
+ const message = new TextEncoder().encode("verifyverifyverifyverifyverifyok");
1440
+ const privU8 = toUint8Array(wallet.privateKey);
1441
+ const pubU8 = toUint8Array(wallet.publicKey);
1442
+ let sigRes;
1443
+ let verRes;
1444
+ if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA && hybridNs) {
1445
+ sigRes = hybridNs.sign(privU8, message);
1446
+ if (sigRes && sigRes.error) {
1447
+ return false;
1448
+ }
1449
+ verRes = hybridNs.verify(pubU8, message, sigRes.result);
1450
+ } else if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA5 && hybrid5Ns) {
1451
+ sigRes = hybrid5Ns.sign(privU8, message);
1452
+ if (sigRes && sigRes.error) {
1453
+ return false;
1454
+ }
1455
+ verRes = hybrid5Ns.verify(pubU8, message, sigRes.result);
1456
+ } else {
1457
+ return false;
1458
+ }
1459
+ if (verRes && verRes.error) {
1460
+ return false;
1461
+ }
1462
+ if (!(verRes && verRes.result === true)) {
1463
+ return false;
1464
+ }
1465
+ return true;
1466
+ }
1467
+
1468
+ /**
1469
+ * The serializeWallet function serializes a Wallet object to a JSON string. You should encrypt the string before saving it to disk or a database.
1470
+ *
1471
+ * @function serializeWallet
1472
+ * @param {Wallet} wallet - A Wallet object representing the wallet to serialize.
1473
+ * @return {string} Returns the Wallet in JSON string format. If the wallet is invalid, null is returned.
1474
+ */
1475
+ function serializeWallet(wallet) {
1476
+ if (isInitialized === false) {
1477
+ return -1000;
1478
+ }
1479
+
1480
+ if(verifyWallet(wallet) === false) {
1481
+ return null;
1482
+ }
1483
+
1484
+ var walletJson = {
1485
+ "address": wallet.address,
1486
+ "privateKey": bytesToBase64(wallet.privateKey),
1487
+ "publicKey": bytesToBase64(wallet.publicKey),
1488
+ }
1489
+
1490
+ if (wallet.preExpansionSeed != null && wallet.preExpansionSeed.length > 0) {
1491
+ walletJson.preExpansionSeed = bytesToBase64(wallet.preExpansionSeed);
1492
+ }
1493
+
1494
+ return JSON.stringify(walletJson);
1495
+ }
1496
+
1497
+ /**
1498
+ * The deserializeWallet function creates a Wallet object from a JSON string.
1499
+ *
1500
+ * @function deserializeWallet
1501
+ * @param {string} walletJson - A JSON string representing the wallet to deserialize.
1502
+ * @return {Wallet|null} Returns the Wallet corresponding to the walletJson. If the wallet is invalid or the JSON is malformed, null is returned.
1503
+ */
1504
+ function deserializeWallet(walletJson) {
1505
+ if (isInitialized === false) {
1506
+ return -1000;
1507
+ }
1508
+
1509
+ try {
1510
+ var tempWallet = JSON.parse(walletJson);
1511
+ if (tempWallet == null || typeof tempWallet !== 'object') {
1512
+ return null;
1513
+ }
1514
+
1515
+ var preExpansionSeed = null;
1516
+ if (tempWallet.preExpansionSeed != null && tempWallet.preExpansionSeed.length > 0) {
1517
+ preExpansionSeed = base64ToBytes(tempWallet.preExpansionSeed);
1518
+ }
1519
+
1520
+ var wallet = new Wallet(tempWallet.address, base64ToBytes(tempWallet.privateKey), base64ToBytes(tempWallet.publicKey), preExpansionSeed);
1521
+
1522
+ if (verifyWallet(wallet) === false) {
1523
+ return null;
1524
+ }
1525
+
1526
+ return wallet;
1527
+ } catch (e) {
1528
+ return null;
1529
+ }
1530
+ }
1531
+
1532
+ function transactionGetSigningHash(fromaddress, nonce, toaddress, amount, gas, chainid, data) {
1533
+ let messageData = TxnSigningHash(fromaddress, nonce, toaddress, amount, gas, chainid, data);
1534
+ var messageBytes = [];
1535
+ for (var i = 0; i < messageData.length; ++i) {
1536
+ messageBytes.push(messageData.charCodeAt(i));
1537
+ }
1538
+ return messageBytes;
1539
+ }
1540
+
1541
+ function transactionGetTransactionHash(fromaddress, nonce, toaddress, amount, gas, chainid, data, pkkey, sig) {
1542
+ const arrayPkDataToPass = pkkey.toString().split(",");
1543
+ const typedPkArray = new Uint8Array(arrayPkDataToPass.length);
1544
+ for (let i = 0; i < arrayPkDataToPass.length; i++) {
1545
+ typedPkArray[i] = arrayPkDataToPass[i];
1546
+ }
1547
+ const arraySigDataToPass = sig.toString().split(",");
1548
+ const typedSigArray = new Uint8Array(arraySigDataToPass.length);
1549
+ for (let i = 0; i < arraySigDataToPass.length; i++) {
1550
+ typedSigArray[i] = arraySigDataToPass[i];
1551
+ }
1552
+ var txnHash = TxnHash(fromaddress, nonce, toaddress, amount, gas, chainid, data, typedPkArray, typedSigArray)
1553
+ return txnHash;
1554
+ }
1555
+
1556
+ function transactionGetData(fromaddress, nonce, toaddress, amount, gas, chainid, data, pkkey, sig) {
1557
+ const arrayPkDataToPass = pkkey.toString().split(",");
1558
+ const typedPkArray = new Uint8Array(arrayPkDataToPass.length);
1559
+ for (let i = 0; i < arrayPkDataToPass.length; i++) {
1560
+ typedPkArray[i] = arrayPkDataToPass[i];
1561
+ }
1562
+ const arraySigDataToPass = sig.toString().split(",");
1563
+ const typedSigArray = new Uint8Array(arraySigDataToPass.length);
1564
+ for (let i = 0; i < arraySigDataToPass.length; i++) {
1565
+ typedSigArray[i] = arraySigDataToPass[i];
1566
+ }
1567
+ var txnData = TxnData(fromaddress, nonce, toaddress, amount, gas, chainid, data, typedPkArray, typedSigArray)
1568
+ return txnData;
1569
+ }
1570
+
1571
+ function transactionGetSigningHash2(fromaddress, nonce, toaddress, valueInWeiHex, gas, chainid, data, remarks, signingContext) {
1572
+ let messageDataReturn = TxnSigningHash2(fromaddress, nonce, toaddress, valueInWeiHex, gas, chainid, data, remarks, signingContext);
1573
+ if (messageDataReturn && messageDataReturn.error) {
1574
+ return null;
1575
+ }
1576
+ var messageData = messageDataReturn.result;
1577
+ var messageBytes = [];
1578
+ for (var i = 0; i < messageData.length; ++i) {
1579
+ messageBytes.push(messageData.charCodeAt(i));
1580
+ }
1581
+ return messageBytes;
1582
+ }
1583
+
1584
+ function transactionGetTransactionHash2(fromaddress, nonce, toaddress, valueInWeiHex, gas, chainid, data, remarks, signingContext, pkkey, sig) {
1585
+ const arrayPkDataToPass = pkkey.toString().split(",");
1586
+ const typedPkArray = new Uint8Array(arrayPkDataToPass.length);
1587
+ for (let i = 0; i < arrayPkDataToPass.length; i++) {
1588
+ typedPkArray[i] = arrayPkDataToPass[i];
1589
+ }
1590
+ const arraySigDataToPass = sig.toString().split(",");
1591
+ const typedSigArray = new Uint8Array(arraySigDataToPass.length);
1592
+ for (let i = 0; i < arraySigDataToPass.length; i++) {
1593
+ typedSigArray[i] = arraySigDataToPass[i];
1594
+ }
1595
+ var txnHashReturn = TxnHash2(fromaddress, nonce, toaddress, valueInWeiHex, gas, chainid, data, remarks, signingContext, typedPkArray, typedSigArray)
1596
+ if (txnHashReturn && txnHashReturn.error) {
1597
+ return null;
1598
+ }
1599
+ return txnHashReturn.result;
1600
+ }
1601
+
1602
+ function transactionGetData2(fromaddress, nonce, toaddress, valueInWeiHex, gas, chainid, data, remarks, signingContext, pkkey, sig) {
1603
+ const arrayPkDataToPass = pkkey.toString().split(",");
1604
+ const typedPkArray = new Uint8Array(arrayPkDataToPass.length);
1605
+ for (let i = 0; i < arrayPkDataToPass.length; i++) {
1606
+ typedPkArray[i] = arrayPkDataToPass[i];
1607
+ }
1608
+ const arraySigDataToPass = sig.toString().split(",");
1609
+ const typedSigArray = new Uint8Array(arraySigDataToPass.length);
1610
+ for (let i = 0; i < arraySigDataToPass.length; i++) {
1611
+ typedSigArray[i] = arraySigDataToPass[i];
1612
+ }
1613
+ var txnDataReturn = TxnData2(fromaddress, nonce, toaddress, valueInWeiHex, gas, chainid, data, remarks, signingContext, typedPkArray, typedSigArray)
1614
+ if (txnDataReturn && txnDataReturn.error) {
1615
+ return null;
1616
+ }
1617
+ return txnDataReturn.result;
1618
+ }
1619
+
1620
+ /**
1621
+ * The postTransaction function posts a signed transaction to the blockchain.
1622
+ * This method can be used in conjunction with the signSendCoinTransaction method to submit a transaction that was signed using a cold wallet (offline or disconnected or air-gapped wallet).
1623
+ *
1624
+ * @async
1625
+ * @function postTransaction
1626
+ * @param {string} txnData - A signed transaction string returned by the signSendCoinTransaction function.
1627
+ * @return {Promise<SendResult>} Returns a promise of type SendResult. txnHash will be null in SendResult.
1628
+ */
1629
+ async function postTransaction(txnData) {
1630
+ if (isInitialized === false) {
1631
+ return -1000;
1632
+ }
1633
+
1634
+ if (txnData == null) {
1635
+ return new SendResult(-600, null, null, null);
1636
+ }
1637
+ var url = config.writeUrl + "/transactions";
1638
+
1639
+ let requestId = getRandomRequestId();
1640
+
1641
+ let reqHeaders = new Headers({
1642
+ "Content-Type": "application/json"
1643
+ });
1644
+ reqHeaders.append(REQUEST_ID_HEADER_NAME, requestId);
1645
+ if (config.writeApiKey !== null) {
1646
+ reqHeaders.append(API_KEY_HEADER_NAME, config.writeApiKey); }
1647
+
1648
+
1649
+ let txnDataJson = JSON.stringify({ txnData: txnData });
1650
+
1651
+ try {
1652
+ const response = await fetch(url, {
1653
+ method: 'POST',
1654
+ headers: reqHeaders,
1655
+ body: txnDataJson
1656
+ });
1657
+
1658
+ if (response == null) {
1659
+ return new SendResult(-601, null, null, requestId);
1660
+ }
1661
+
1662
+ if (response.status === 200 || response.status === 204) {
1663
+ return new SendResult(0, null, response, requestId);
1664
+ }
1665
+
1666
+ return new SendResult(-602, null, response, requestId);
1667
+ } catch(error) {
1668
+ return new SendResult(-10000, null, null, requestId, error);
1669
+ }
1670
+ }
1671
+
1672
+ /**
1673
+ * The getLatestBlockDetails function returns details of the latest block of the blockchain.
1674
+ *
1675
+ * @async
1676
+ * @function getLatestBlockDetails
1677
+ * @return {Promise<LatestBlockDetailsResult>} Returns a promise of an object of type LatestBlockDetailsResult.
1678
+ */
1679
+ async function getLatestBlockDetails() {
1680
+ if (isInitialized === false) {
1681
+ return -1000;
1682
+ }
1683
+
1684
+ let requestId = getRandomRequestId();
1685
+
1686
+ let reqHeaders = new Headers({
1687
+ "Content-Type": "application/json"
1688
+ });
1689
+ reqHeaders.append(REQUEST_ID_HEADER_NAME, requestId);
1690
+ if (config.readApiKey !== null) {
1691
+ reqHeaders.append(API_KEY_HEADER_NAME, config.readApiKey);
1692
+ }
1693
+
1694
+ var url = config.readUrl + "/latestblock";
1695
+
1696
+ try {
1697
+ const response = await fetch(url, {
1698
+ headers: reqHeaders,
1699
+ });
1700
+
1701
+ if (response == null) {
1702
+ return new LatestBlockDetailsResult(-100, null, response, requestId);
1703
+ }
1704
+ if (response.status !== 200) {
1705
+ return new LatestBlockDetailsResult(-101, null, response, requestId);
1706
+ }
1707
+
1708
+ const jsonObj = await response.json();
1709
+ if (jsonObj == null) {
1710
+ return new LatestBlockDetailsResult(-102, null, response, requestId);
1711
+ }
1712
+ const result = jsonObj.result;
1713
+
1714
+ if (result == null) {
1715
+ return new LatestBlockDetailsResult(-103, null, response, requestId);
1716
+ }
1717
+
1718
+ if (result.blockNumber == null) {
1719
+ return new LatestBlockDetailsResult(-104, null, response, requestId);
1720
+ }
1721
+
1722
+ let blockNumber = parseInt(result.blockNumber);
1723
+ if (Number.isInteger(blockNumber) === false) {
1724
+ return new LatestBlockDetailsResult(-105, null, response, requestId);
1725
+ }
1726
+
1727
+ var blockDetails = new BlockDetails(blockNumber);
1728
+ return new LatestBlockDetailsResult(0, blockDetails, response, requestId);
1729
+ } catch (error) {
1730
+ return new LatestBlockDetailsResult(-10000, null, null, requestId, error);
1731
+ }
1732
+ }
1733
+
1734
+ /**
1735
+ * The getAccountDetails function returns details of an account corresponding to the address.
1736
+ *
1737
+ * @async
1738
+ * @function getAccountDetails
1739
+ * @param {string} address - The address of the account of which the details have to be retrieved.
1740
+ * @return {Promise<AccountDetailsResult>} Returns a promise of type AccountDetailsResult.
1741
+ */
1742
+ async function getAccountDetails(address) {
1743
+ if (isInitialized === false) {
1744
+ return -1000;
1745
+ }
1746
+
1747
+ if (address == null) {
1748
+ return new AccountDetailsResult(-200, null, null, null);
1749
+ }
1750
+ if (isAddressValid(address) === false) {
1751
+ return new AccountDetailsResult(-201, null, null, null);
1752
+ }
1753
+
1754
+ let nonce = 0;
1755
+ let balance = "0";
1756
+ let requestId = getRandomRequestId();
1757
+
1758
+ let reqHeaders = new Headers({
1759
+ "Content-Type": "application/json"
1760
+ });
1761
+ reqHeaders.append(REQUEST_ID_HEADER_NAME, requestId);
1762
+ if(config.readApiKey !== null) {
1763
+ reqHeaders.append(API_KEY_HEADER_NAME, config.readApiKey);
1764
+ }
1765
+
1766
+ var url = config.readUrl + "/account/" + address;
1767
+
1768
+ try {
1769
+ const response = await fetch(url, {
1770
+ headers: reqHeaders,
1771
+ });
1772
+
1773
+ if(response == null) {
1774
+ return new AccountDetailsResult(-202, null, response, requestId);
1775
+ }
1776
+ if (response.status !== 200) {
1777
+ return new AccountDetailsResult(-203, null, response, requestId);
1778
+ }
1779
+
1780
+ const jsonObj = await response.json();
1781
+ if (jsonObj == null) {
1782
+ return new AccountDetailsResult(-204, null, response, requestId);
1783
+ }
1784
+ const result = jsonObj.result;
1785
+
1786
+ if (result == null) {
1787
+ return new AccountDetailsResult(-205, null, response, requestId);
1788
+ }
1789
+
1790
+ if(result.blockNumber == null) {
1791
+ return new AccountDetailsResult(-206, null, response, requestId);
1792
+ }
1793
+
1794
+ let blockNumber = parseInt(result.blockNumber);
1795
+ if (Number.isInteger(blockNumber) === false) {
1796
+ return new AccountDetailsResult(-207, null, response, requestId);
1797
+ }
1798
+
1799
+ if (result.nonce === null) {
1800
+ nonce = 0;
1801
+ } else {
1802
+ let tempNonce = parseInt(result.nonce);
1803
+ if (Number.isInteger(tempNonce) === true) {
1804
+ nonce = tempNonce;
1805
+ if (nonce < 0) {
1806
+ return new AccountDetailsResult(-208, null, response, requestId);
1807
+ }
1808
+ } else {
1809
+ return new AccountDetailsResult(-209, null, response, requestId);
1810
+ }
1811
+ }
1812
+
1813
+ if (result.balance != null) {
1814
+ if (isLargeNumber(result.balance) === false) {
1815
+ return new AccountDetailsResult(-210, null, response, requestId);
1816
+ } else {
1817
+ balance = result.balance;
1818
+ }
1819
+ }
1820
+
1821
+ var accountDetails = new AccountDetails(address, balance, nonce, blockNumber);
1822
+ return new AccountDetailsResult(0, accountDetails, response, requestId);
1823
+
1824
+ } catch (error) {
1825
+ return new AccountDetailsResult(-10000, null, null, requestId, error);
1826
+ }
1827
+ }
1828
+
1829
+ /**
1830
+ * The getTransactionDetails function returns details of a transaction posted to the blockchain.
1831
+ * Transactions may take a while to get registered in the blockchain. After a transaction is submitted, it may take a while before it is available for reading.
1832
+ * Some transactions that have lower balance than the minimum required for gas fees may be discarded.
1833
+ * In these cases, the transactions may not be returned when invoking the getTransactionDetails function.
1834
+ * You should consider the transaction as succeeded only if the status field of the transactionReceipt object is 0x1 (success).
1835
+ * The transactionReceipt field can be null unless the transaction is registered with the blockchain.
1836
+ * @async
1837
+ * @function getTransactionDetails
1838
+ * @param {string} txnHash - The hash of the transaction to retrieve.
1839
+ * @return {Promise<TransactionDetailsResult>} Returns a promise of type TransactionDetailsResult.
1840
+ */
1841
+ async function getTransactionDetails(txnHash) {
1842
+ if (isInitialized === false) {
1843
+ return -1000;
1844
+ }
1845
+
1846
+ if (txnHash == null) {
1847
+ return new TransactionDetailsResult(-300, null, null, null);
1848
+ }
1849
+ if (isAddressValid(txnHash) === false) {
1850
+ return new TransactionDetailsResult(-301, null, null, null);
1851
+ }
1852
+
1853
+ let requestId = getRandomRequestId();
1854
+
1855
+ let reqHeaders = new Headers({
1856
+ "Content-Type": "application/json"
1857
+ });
1858
+ reqHeaders.append(REQUEST_ID_HEADER_NAME, requestId);
1859
+ if (config.readApiKey !== null) {
1860
+ reqHeaders.append(API_KEY_HEADER_NAME, config.readApiKey);
1861
+ }
1862
+
1863
+ var url = config.readUrl + "/transaction/" + txnHash;
1864
+
1865
+ try {
1866
+ const response = await fetch(url, {
1867
+ headers: reqHeaders,
1868
+ });
1869
+
1870
+ if (response == null) {
1871
+ return new TransactionDetailsResult(-302, null, response, requestId);
1872
+ }
1873
+ if (response.status !== 200) {
1874
+ return new TransactionDetailsResult(-303, null, response, requestId);
1875
+ }
1876
+
1877
+ const jsonObj = await response.json();
1878
+ if (jsonObj == null) {
1879
+ return new TransactionDetailsResult(-304, null, response, requestId);
1880
+ }
1881
+ const result = jsonObj.result;
1882
+
1883
+ if (result == null) {
1884
+ return new TransactionDetailsResult(-305, null, response, requestId);
1885
+ }
1886
+
1887
+ var transactionDetails = new TransactionDetails();
1888
+
1889
+ if (result.blockNumber !== null) {
1890
+ let tempBlockNumber = parseInt(result.blockNumber);
1891
+ if (Number.isInteger(tempBlockNumber) === true) {
1892
+ transactionDetails.blockNumber = tempBlockNumber;
1893
+ }
1894
+ if (tempBlockNumber < 0) {
1895
+ return new TransactionDetailsResult(-306, null, response, requestId);
1896
+ }
1897
+ }
1898
+
1899
+ transactionDetails.blockHash = result.blockHash;
1900
+ transactionDetails.from = result.from;
1901
+ transactionDetails.gas = result.gas;
1902
+ transactionDetails.gasPrice = result.gasPrice;
1903
+ transactionDetails.hash = result.hash;
1904
+ transactionDetails.input = result.input;
1905
+ transactionDetails.nonce = result.nonce;
1906
+ transactionDetails.to = result.to;
1907
+ transactionDetails.value = result.value;
1908
+
1909
+ if(result.receipt !== null) {
1910
+ transactionDetails.receipt = new TransactionReceipt();
1911
+ transactionDetails.receipt.cumulativeGasUsed = result.receipt.cumulativeGasUsed;
1912
+ transactionDetails.receipt.effectiveGasPrice = result.receipt.effectiveGasPrice;
1913
+ transactionDetails.receipt.gasUsed = result.receipt.gasUsed;
1914
+ transactionDetails.receipt.status = result.receipt.status;
1915
+ transactionDetails.receipt.hash = result.receipt.hash;
1916
+ transactionDetails.receipt.type = result.receipt.type;
1917
+ }
1918
+
1919
+ return new TransactionDetailsResult(0, transactionDetails, response, requestId);
1920
+ } catch (error) {
1921
+ return new TransactionDetailsResult(-10000, null, null, requestId, error);
1922
+ }
1923
+ }
1924
+
1925
+ /**
1926
+ * The listAccountTransactions function returns a list of transactions for a specific account.
1927
+ * Transactions may take a while to get registered in the blockchain. After a transaction is submitted, it may take a while before it is available for listing.
1928
+ * Some transactions that have lower balance than the minimum required for gas fees may be discarded.
1929
+ * In these cases, the transactions may not be returned when invoking the listAccountTransactions function.
1930
+ * You should consider the transaction as succeeded only if the status field of the AccountTransactionCompact object is 0x1 (success).
1931
+ * Both transactions from and transactions to the address will be returned in the list.
1932
+ * Use the getTransactionDetails function, passing the hash of the transaction to get detailed information about the transaction.
1933
+ * @async
1934
+ * @function listAccountTransactions
1935
+ * @param {string} address - The address for which the transactions have to be listed.
1936
+ * @param {number} pageNumber - The page number for which the transactions has to be listed for the account. Pass 0 to list the latest page. Pass 1 to list the oldest page. A maximum of 20 transactions are returned in each page. The response of this API includes a field that shows the pageCount (total number of pages available). You can pass any number between 1 to pageCount to get the corresponding page.
1937
+ * @return {Promise<AccountTransactionsResult>} Returns a promise of type AccountTransactionsResult.
1938
+ */
1939
+ async function listAccountTransactions(address, pageNumber) {
1940
+ if (isInitialized === false) {
1941
+ return -1000;
1942
+ }
1943
+
1944
+ if (address === null) {
1945
+ return new AccountTransactionsResult(-700, null, null, null);
1946
+ }
1947
+ if (isAddressValid(address) === false) {
1948
+ return new AccountTransactionsResult(-701, null, null, null);
1949
+ }
1950
+
1951
+ if (pageNumber === null) {
1952
+ pageNumber = 0;
1953
+ } else if (Number.isInteger(pageNumber) === false) {
1954
+ return new AccountTransactionsResult(-702, null, null, null);
1955
+ }
1956
+
1957
+ let requestId = getRandomRequestId();
1958
+
1959
+ let reqHeaders = new Headers({
1960
+ "Content-Type": "application/json"
1961
+ });
1962
+ reqHeaders.append(REQUEST_ID_HEADER_NAME, requestId);
1963
+ if (config.readApiKey !== null) {
1964
+ reqHeaders.append(API_KEY_HEADER_NAME, config.readApiKey);
1965
+ }
1966
+
1967
+ var url = config.readUrl + "/account/" + address + "/transactions/" + pageNumber;
1968
+
1969
+ try {
1970
+ const response = await fetch(url, {
1971
+ headers: reqHeaders,
1972
+ });
1973
+
1974
+ if (response === null) {
1975
+ return new AccountTransactionsResult(-703, null, response, requestId);
1976
+ }
1977
+ if (response.status !== 200) {
1978
+ return new AccountTransactionsResult(-704, null, response, requestId);
1979
+ }
1980
+
1981
+ const jsonObj = await response.json();
1982
+
1983
+ if (jsonObj === null) {
1984
+ return new AccountTransactionsResult(-705, null, response, requestId);
1985
+ }
1986
+ const result = jsonObj;
1987
+
1988
+ if (result.pageCount === null) {
1989
+ return new AccountTransactionsResult(-706, null, response, requestId);
1990
+ }
1991
+
1992
+ var listAccountDetailsResponse = new ListAccountTransactionsResponse();
1993
+
1994
+ let tempPageCount = parseInt(result.pageCount);
1995
+ if (Number.isInteger(tempPageCount) === true) {
1996
+ listAccountDetailsResponse.pageCount = tempPageCount;
1997
+ }
1998
+
1999
+ if (result.items !== null) {
2000
+ if (Array.isArray(result.items) === false) {
2001
+ return new AccountTransactionsResult(-707, null, response, requestId);
2002
+ }
2003
+ listAccountDetailsResponse.items = new Array();
2004
+ for (const item of result.items) {
2005
+ let txn = new AccountTransactionCompact();
2006
+ txn.blockNumber = item.blockNumber;
2007
+ txn.from = item.from;
2008
+ txn.hash = item.hash;
2009
+ txn.to = item.to;
2010
+ txn.value = item.value;
2011
+ txn.status = item.status;
2012
+ listAccountDetailsResponse.items.push(txn);
2013
+ }
2014
+ }
2015
+
2016
+ return new AccountTransactionsResult(0, listAccountDetailsResponse, response, requestId);
2017
+ } catch (error) {
2018
+ return new AccountTransactionsResult(-10000, null, null, requestId, error);
2019
+ }
2020
+ }
2021
+
2022
+ /**
2023
+ * The signSendCoinTransaction function returns a signed transaction. The chainId used for signing should be provided in the initialize() function.
2024
+ * Since the gas fee for sending coins is fixed at 1000 coins, there is no option to set the gas fee explicitly.
2025
+ * This function is useful for offline (cold storage) wallets, where you can sign a transaction offline and then use the postTransaction function to post it on a connected device.
2026
+ * Another usecase for this function is when you want to first store a signed transaction to a database, then queue it and finally submit the transaction by calling the postTransaction function.
2027
+ *
2028
+ * @deprecated Use signRawTransaction instead.
2029
+ * @function signSendCoinTransaction
2030
+ * @param {Wallet} wallet - A Wallet object from which the transaction has to be sent. The address corresponding to the Wallet should have enough coins to cover gas fees as well. A minimum of 1000 coins (1000000000000000000000 wei) are required for gas fees.
2031
+ * @param {string} toAddress - The address to which the coins should be sent.
2032
+ * @param {string} coins - The string representing the number of coins (in ether) to send. To convert between ethers and wei, see https://docs.ethers.org/v4/api-utils.html#ether-strings-and-wei
2033
+ * @param {number} nonce - The nonce of the account retrieved by invoking the getAccountDetails function. You have to carefully manage state of the nonce to avoid sending the coins multiple times, such as when retrying sendCoins after a network error.
2034
+ * @return {Promise<SignResult>} Returns a promise of type SignResult.
2035
+ */
2036
+ async function signSendCoinTransaction(wallet, toAddress, coins, nonce) {
2037
+ if (isInitialized === false) {
2038
+ return -1000;
2039
+ }
2040
+
2041
+ if (wallet == null || toAddress == null || coins == null || nonce == null) {
2042
+ return new SignResult(-500, null, null);
2043
+ }
2044
+
2045
+ if (isAddressValid(toAddress) === false) {
2046
+ return new SignResult(-501, null, null);
2047
+ }
2048
+
2049
+ if (verifyWallet(wallet) === false) {
2050
+ return new SignResult(-502, null, null);
2051
+ }
2052
+
2053
+ if (isLargeNumber(coins) === false) {
2054
+ return new SignResult(-503, null, null);
2055
+ }
2056
+
2057
+ let tempNonce = parseInt(nonce);
2058
+ if (Number.isInteger(tempNonce) === false) {
2059
+ return new SignResult(-504, null, null);
2060
+ }
2061
+ nonce = tempNonce;
2062
+ if (nonce < 0) {
2063
+ return new SignResult(-505, null, null);
2064
+ }
2065
+
2066
+ const contractData = null;
2067
+
2068
+ var txSigningHash = transactionGetSigningHash(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData);
2069
+ if (txSigningHash == null) {
2070
+ return new SignResult(-506, null, null);
2071
+ }
2072
+ const txSigningHashU8 = toUint8Array(txSigningHash);
2073
+ const hybridedsNs = circl && circl.hybrideds;
2074
+ if (!hybridedsNs) {
2075
+ return new SignResult(-507, null, null);
2076
+ }
2077
+ const sigRes = hybridedsNs.signCompact(toUint8Array(wallet.privateKey), txSigningHashU8);
2078
+ if (sigRes && sigRes.error) {
2079
+ return new SignResult(-507, null, null);
2080
+ }
2081
+ const verRes = hybridedsNs.verifyCompact(toUint8Array(wallet.publicKey), txSigningHashU8, sigRes.result);
2082
+ if (verRes && verRes.error) {
2083
+ return new SignResult(-507, null, null);
2084
+ }
2085
+ if (verRes.result !== true) {
2086
+ return new SignResult(-507, null, null);
2087
+ }
2088
+ const quantumSig = sigRes.result instanceof Uint8Array ? Array.from(sigRes.result) : sigRes.result;
2089
+
2090
+ var txHashHex = transactionGetTransactionHash(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData, wallet.publicKey, quantumSig);
2091
+ if (txHashHex == null) {
2092
+ return new SignResult(-508, null, null);
2093
+ }
2094
+
2095
+ var txnData = transactionGetData(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData, wallet.publicKey, quantumSig);
2096
+ if (txnData == null) {
2097
+ return new SignResult(-509, null, null);
2098
+ }
2099
+
2100
+ return new SignResult(0, txHashHex, txnData);
2101
+ }
2102
+
2103
+ /**
2104
+ * The signTransaction function returns a signed transaction. The chainId used for signing should be provided in the initialize() function.
2105
+ * Since the gas fee for sending coins is fixed at 1000 coins, there is no option to set the gas fee explicitly.
2106
+ * This function is useful for offline (cold storage) wallets, where you can sign a transaction offline and then use the postTransaction function to post it on a connected device.
2107
+ * Another usecase for this function is when you want to first store a signed transaction to a database, then queue it and finally submit the transaction by calling the postTransaction function.
2108
+ *
2109
+ * @deprecated Use signRawTransaction instead.
2110
+ * @function signTransaction
2111
+ * @param {Wallet} wallet - A Wallet object from which the transaction has to be sent. The address corresponding to the Wallet should have enough coins to cover gas fees as well. A minimum of 1000 coins (1000000000000000000000 wei) are required for gas fees.
2112
+ * @param {string} toAddress - The address to which the coins should be sent.
2113
+ * @param {string} coins - The string representing the number of coins (in ether) to send. To convert between ethers and wei, see https://docs.ethers.org/v4/api-utils.html#ether-strings-and-wei
2114
+ * @param {number} nonce - The nonce of the account retrieved by invoking the getAccountDetails function. You have to carefully manage state of the nonce to avoid sending the coins multiple times, such as when retrying sendCoins after a network error.
2115
+ * @param {string} data - Ignored. This parameter is accepted but not used. Use signRawTransaction to pass contract data.
2116
+ * @return {Promise<SignResult>} Returns a promise of type SignResult.
2117
+ */
2118
+ async function signTransaction(wallet, toAddress, coins, nonce, data) {
2119
+ if (isInitialized === false) {
2120
+ return -1000;
2121
+ }
2122
+
2123
+ if (wallet == null || toAddress == null || coins == null || nonce == null) {
2124
+ return new SignResult(-500, null, null);
2125
+ }
2126
+
2127
+ if (isAddressValid(toAddress) === false) {
2128
+ return new SignResult(-501, null, null);
2129
+ }
2130
+
2131
+ if (verifyWallet(wallet) === false) {
2132
+ return new SignResult(-502, null, null);
2133
+ }
2134
+
2135
+ if (isLargeNumber(coins) === false) {
2136
+ return new SignResult(-503, null, null);
2137
+ }
2138
+
2139
+ let tempNonce = parseInt(nonce);
2140
+ if (Number.isInteger(tempNonce) === false) {
2141
+ return new SignResult(-504, null, null);
2142
+ }
2143
+ nonce = tempNonce;
2144
+ if (nonce < 0) {
2145
+ return new SignResult(-505, null, null);
2146
+ }
2147
+
2148
+ const contractData = null;
2149
+
2150
+ var txSigningHash = transactionGetSigningHash(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData);
2151
+ if (txSigningHash == null) {
2152
+ return new SignResult(-506, null, null);
2153
+ }
2154
+ const txSigningHashU8 = toUint8Array(txSigningHash);
2155
+ const hybridedsNs = circl && circl.hybrideds;
2156
+ if (!hybridedsNs) {
2157
+ return new SignResult(-507, null, null);
2158
+ }
2159
+ const sigRes = hybridedsNs.signCompact(toUint8Array(wallet.privateKey), txSigningHashU8);
2160
+ if (sigRes && sigRes.error) {
2161
+ return new SignResult(-507, null, null);
2162
+ }
2163
+ const verRes = hybridedsNs.verifyCompact(toUint8Array(wallet.publicKey), txSigningHashU8, sigRes.result);
2164
+ if (verRes && verRes.error) {
2165
+ return new SignResult(-507, null, null);
2166
+ }
2167
+ if (verRes.result !== true) {
2168
+ return new SignResult(-507, null, null);
2169
+ }
2170
+ const quantumSig = sigRes.result instanceof Uint8Array ? Array.from(sigRes.result) : sigRes.result;
2171
+
2172
+ var txHashHex = transactionGetTransactionHash(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData, wallet.publicKey, quantumSig);
2173
+ if (txHashHex == null) {
2174
+ return new SignResult(-508, null, null);
2175
+ }
2176
+
2177
+ var txnData = transactionGetData(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData, wallet.publicKey, quantumSig);
2178
+ if (txnData == null) {
2179
+ return new SignResult(-509, null, null);
2180
+ }
2181
+
2182
+ return new SignResult(0, txHashHex, txnData);
2183
+ }
2184
+
2185
+ /**
2186
+ * Helper function to convert a hex string to Uint8Array
2187
+ * @param {string} hex - Hex string with or without 0x prefix
2188
+ * @return {Uint8Array} Uint8Array representation of the hex string, or empty array if null/undefined
2189
+ */
2190
+ function hexStringToUint8Array(hex) {
2191
+ // Return empty array if null or undefined
2192
+ if (hex === null || hex === undefined) {
2193
+ return new Uint8Array(0);
2194
+ }
2195
+
2196
+ // Remove 0x prefix if present
2197
+ if (hex.startsWith('0x')) {
2198
+ hex = hex.slice(2);
2199
+ }
2200
+
2201
+ if (/[^0-9a-fA-F]/.test(hex)) {
2202
+ return new Uint8Array(0);
2203
+ }
2204
+
2205
+ // Ensure even length (pad with leading zero if needed)
2206
+ if (hex.length % 2 !== 0) {
2207
+ hex = '0' + hex;
2208
+ }
2209
+
2210
+ // Convert hex string to Uint8Array
2211
+ const bytes = new Uint8Array(hex.length / 2);
2212
+ for (let i = 0; i < hex.length; i += 2) {
2213
+ bytes[i / 2] = parseInt(hex.substr(i, 2), 16);
2214
+ }
2215
+
2216
+ return bytes;
2217
+ }
2218
+
2219
+ /**
2220
+ * The signRawTransaction function returns a signed transaction. The chainId used for signing can be provided in the TransactionSigningRequest, or if null, the chainId specified in the initialize() function will be used.
2221
+ * With this function, you can set the gasLimit explicitly compared to signTransaction.
2222
+ * You can also pass data to be signed, such as when creating or invoking a smart contract.
2223
+ * Since the gas fee is fixed at 1000 coins for 21000 units of gas, there is no option to set the gas fee explicitly.
2224
+ * This function is useful for offline (cold storage) wallets, where you can sign a transaction offline and then use the postTransaction function to post it on a connected device.
2225
+ * Another usecase for this function is when you want to first store a signed transaction to a database, then queue it and finally submit the transaction by calling the postTransaction function.
2226
+ *
2227
+ * @function signRawTransaction
2228
+ * @param {TransactionSigningRequest} transactionSigningRequest - An object of type TransactionSigningRequest with the transaction signing details.
2229
+ * @return {SignResult} Returns a promise of type SignResult.
2230
+ */
2231
+ function signRawTransaction(transactionSigningRequest) {
2232
+ if (isInitialized === false) {
2233
+ return -1000;
2234
+ }
2235
+
2236
+ if (transactionSigningRequest.wallet == null || transactionSigningRequest.nonce == null || transactionSigningRequest.gasLimit == null) {
2237
+ return new SignResult(-900, null, null);
2238
+ }
2239
+
2240
+ if (transactionSigningRequest.toAddress !== null && isAddressValid(transactionSigningRequest.toAddress) === false) {
2241
+ return new SignResult(-901, null, null);
2242
+ }
2243
+
2244
+ if (verifyWallet(transactionSigningRequest.wallet) === false) {
2245
+ return new SignResult(-902, null, null);
2246
+ }
2247
+
2248
+ // Convert valueInWei to hex if needed
2249
+ let valueInWeiHex = null;
2250
+ if (transactionSigningRequest.valueInWei !== null) {
2251
+ if (typeof transactionSigningRequest.valueInWei === 'bigint') {
2252
+ // Convert BigInt to hex string
2253
+ valueInWeiHex = '0x' + transactionSigningRequest.valueInWei.toString(16);
2254
+ } else if (typeof transactionSigningRequest.valueInWei === 'string') {
2255
+ if (transactionSigningRequest.valueInWei.startsWith('0x') === false || /[^0-9a-fA-F]/.test(transactionSigningRequest.valueInWei.slice(2))) {
2256
+ return new SignResult(-903, null, null);
2257
+ }
2258
+ valueInWeiHex = transactionSigningRequest.valueInWei;
2259
+ } else {
2260
+ return new SignResult(-923, null, null);
2261
+ }
2262
+ }
2263
+
2264
+ let tempNonce = parseInt(transactionSigningRequest.nonce);
2265
+ if (Number.isInteger(tempNonce) === false) {
2266
+ return new SignResult(-904, null, null);
2267
+ }
2268
+ let nonce = tempNonce;
2269
+ if (nonce < 0) {
2270
+ return new SignResult(-905, null, null);
2271
+ }
2272
+
2273
+ let data = null;
2274
+ if (transactionSigningRequest.data !== null) {
2275
+ if (typeof transactionSigningRequest.data !== 'string' || transactionSigningRequest.data.startsWith('0x') === false || /[^0-9a-fA-F]/.test(transactionSigningRequest.data.slice(2))) {
2276
+ return new SignResult(-906, null, null);
2277
+ }
2278
+ data = hexStringToUint8Array(transactionSigningRequest.data);
2279
+ }
2280
+
2281
+ let tempGasLimit = parseInt(transactionSigningRequest.gasLimit);
2282
+ if (Number.isInteger(tempGasLimit) === false) {
2283
+ return new SignResult(-907, null, null);
2284
+ }
2285
+ let gasLimit = tempGasLimit;
2286
+ if (gasLimit < 0) {
2287
+ return new SignResult(-908, null, null);
2288
+ }
2289
+
2290
+ let remarks = null;
2291
+ if (transactionSigningRequest.remarks !== null) {
2292
+ if (typeof transactionSigningRequest.remarks !== 'string' || transactionSigningRequest.remarks.startsWith('0x') === false || /[^0-9a-fA-F]/.test(transactionSigningRequest.remarks.slice(2))) {
2293
+ return new SignResult(-909, null, null);
2294
+ }
2295
+ remarks = hexStringToUint8Array(transactionSigningRequest.remarks);
2296
+ if (remarks.length > 32) {
2297
+ return new SignResult(-910, null, null);
2298
+ }
2299
+ }
2300
+
2301
+ // Use chainId from request if provided, otherwise use the one from initialize()
2302
+ let chainId;
2303
+ if (transactionSigningRequest.chainId !== null && transactionSigningRequest.chainId !== undefined) {
2304
+ // Validate chainId if provided
2305
+ let tempChainId = parseInt(transactionSigningRequest.chainId);
2306
+ if (Number.isInteger(tempChainId) === false) {
2307
+ return new SignResult(-911, null, null);
2308
+ }
2309
+ chainId = tempChainId;
2310
+ if (chainId < 0) {
2311
+ return new SignResult(-912, null, null);
2312
+ }
2313
+ } else {
2314
+ // Use chainId from initialize()
2315
+ chainId = config.chainId;
2316
+ }
2317
+
2318
+ let signingContext = transactionSigningRequest.signingContext;
2319
+ const keyTypeForContext = getKeyTypeFromPrivateKey(transactionSigningRequest.wallet.privateKey);
2320
+ if (signingContext === null || signingContext === undefined) {
2321
+ if (keyTypeForContext === KEY_TYPE_HYBRIDEDMLDSASLHDSA) {
2322
+ signingContext = 0;
2323
+ } else if (keyTypeForContext === KEY_TYPE_HYBRIDEDMLDSASLHDSA5) {
2324
+ signingContext = 1;
2325
+ } else {
2326
+ return new SignResult(-913, null, null);
2327
+ }
2328
+ }
2329
+
2330
+ let txSigningHash = transactionGetSigningHash2(transactionSigningRequest.wallet.address, nonce, transactionSigningRequest.toAddress, valueInWeiHex, gasLimit, chainId, data, remarks, signingContext);
2331
+ if (txSigningHash == null) {
2332
+ return new SignResult(-914, null, null);
2333
+ }
2334
+ const txSigningHashU8 = toUint8Array(txSigningHash);
2335
+ const wallet = transactionSigningRequest.wallet;
2336
+ const privU8 = toUint8Array(wallet.privateKey);
2337
+ const pubU8 = toUint8Array(wallet.publicKey);
2338
+ let sigRes;
2339
+ let verRes;
2340
+ const hybridNs = circl && circl.hybridedmldsaslhdsa;
2341
+ const hybrid5Ns = circl && (circl.hybridedmldsaslhdsa5 || circl.hybridedmldsaslhdsa5);
2342
+ if (signingContext === 0 && hybridNs) {
2343
+ sigRes = hybridNs.signCompact(privU8, txSigningHashU8);
2344
+ if (sigRes && sigRes.error) return new SignResult(-915, null, null);
2345
+ verRes = hybridNs.verifyCompact(pubU8, txSigningHashU8, sigRes.result);
2346
+ } else if (signingContext === 1 && hybrid5Ns) {
2347
+ sigRes = hybrid5Ns.sign(privU8, txSigningHashU8);
2348
+ if (sigRes && sigRes.error) return new SignResult(-916, null, null);
2349
+ verRes = hybrid5Ns.verify(pubU8, txSigningHashU8, sigRes.result);
2350
+ } else if (signingContext === 2 && hybridNs) {
2351
+ sigRes = hybridNs.sign(privU8, txSigningHashU8);
2352
+ if (sigRes && sigRes.error) return new SignResult(-917, null, null);
2353
+ verRes = hybridNs.verify(pubU8, txSigningHashU8, sigRes.result);
2354
+ } else {
2355
+ return new SignResult(-918, null, null);
2356
+ }
2357
+ if (verRes && verRes.error) return new SignResult(-919, null, null);
2358
+ if (verRes.result !== true) return new SignResult(-920, null, null);
2359
+ const quantumSig = sigRes.result instanceof Uint8Array ? Array.from(sigRes.result) : sigRes.result;
2360
+
2361
+ let txHashHex = transactionGetTransactionHash2(transactionSigningRequest.wallet.address, nonce, transactionSigningRequest.toAddress, valueInWeiHex, gasLimit, chainId, data, remarks, signingContext, transactionSigningRequest.wallet.publicKey, quantumSig);
2362
+ if (txHashHex == null) {
2363
+ return new SignResult(-921, null, null);
2364
+ }
2365
+
2366
+ let txnData = transactionGetData2(transactionSigningRequest.wallet.address, nonce, transactionSigningRequest.toAddress, valueInWeiHex, gasLimit, chainId, data, remarks, signingContext, transactionSigningRequest.wallet.publicKey, quantumSig);
2367
+ if (txnData == null) {
2368
+ return new SignResult(-922, null, null);
2369
+ }
2370
+
2371
+ return new SignResult(0, txHashHex, txnData);
2372
+ }
2373
+
2374
+ /**
2375
+ * Returns the gas price per unit of gas (per-gas-unit), in wei, for the signing context implied by keyType and fullSign.
2376
+ * The returned value is the price PER UNIT OF GAS, NOT the total transaction fee (total fee = gasPrice * gasLimit).
2377
+ * This mirrors the dynamic-fee gas price logic in quantum-coin-go core/types/dynamic_fee_tx.go.
2378
+ *
2379
+ * fullSign is IGNORED for keyType 5 (KEY_TYPE_HYBRIDEDMLDSASLHDSA5), which always uses signing context 1.
2380
+ * For keyType 3 (KEY_TYPE_HYBRIDEDMLDSASLHDSA), fullSign selects the scheme: false = compact (context 0), true = full (context 2).
2381
+ *
2382
+ * @function getGasPrice
2383
+ * @param {number} keyType - 3 (KEY_TYPE_HYBRIDEDMLDSASLHDSA) or 5 (KEY_TYPE_HYBRIDEDMLDSASLHDSA5).
2384
+ * @param {boolean|null} [fullSign] - Optional. Use full (non-compact) signing for keyType 3. Ignored for keyType 5. Defaults to false.
2385
+ * @returns {{ resultCode: number, gasPrice: string|null }} resultCode 0 and gasPrice as a decimal wei string (per gas unit) on success; resultCode -940 with gasPrice null for an invalid keyType.
2386
+ */
2387
+ function getGasPrice(keyType, fullSign) {
2388
+ const useFullSign = fullSign === true;
2389
+ let multiplier;
2390
+ if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA) {
2391
+ // signing context 0 (compact) or 2 (full)
2392
+ multiplier = useFullSign ? SIGNING_CONTEXT_LEVEL2_MULTIPLIER : 1n;
2393
+ } else if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA5) {
2394
+ // signing context 1; fullSign is not applicable for this key type
2395
+ multiplier = SIGNING_CONTEXT_LEVEL1_MULTIPLIER;
2396
+ } else {
2397
+ return { resultCode: -940, gasPrice: null };
2398
+ }
2399
+ const price = DYNAMIC_BASE_GAS_PRICE_WEI * multiplier;
2400
+ return { resultCode: 0, gasPrice: price.toString() };
2401
+ }
2402
+
2403
+ /**
2404
+ * Sign a message with a private key. Optional signingContext selects algorithm (same pattern as signRawTransaction); if null/omitted, derived from private key type.
2405
+ * @param {number[]|Uint8Array} privateKey - Private key bytes.
2406
+ * @param {number[]|Uint8Array} message - Message bytes (e.g. 32-byte hash).
2407
+ * @param {number|null} [signingContext] - Optional. 0 = hybridedmldsaslhdsa compact, 1 = hybridedmldsaslhdsa5, 2 = hybridedmldsaslhdsa full. If null/omitted, derived from private key type.
2408
+ * @returns {{ resultCode: number, signature: Uint8Array|null }} resultCode 0 on success, signature bytes; negative on error (e.g. -1000 not initialized, -700 invalid args, -701 unknown key type, -702/-703 CIRCL sign error, -704 unsupported key type or context).
2409
+ */
2410
+ function sign(privateKey, message, signingContext) {
2411
+ if (isInitialized === false) {
2412
+ return { resultCode: -1000, signature: null };
2413
+ }
2414
+ if (!isByteArray(privateKey) || !isByteArray(message)) {
2415
+ return { resultCode: -700, signature: null };
2416
+ }
2417
+ const privU8 = toUint8Array(privateKey);
2418
+ const messageU8 = toUint8Array(message);
2419
+ const hybridNs = circl && circl.hybridedmldsaslhdsa;
2420
+ const hybrid5Ns = circl && (circl.hybridedmldsaslhdsa5 || circl.hybridedmldsaslhdsa5);
2421
+ let sigRes;
2422
+ const ctx = signingContext === null || signingContext === undefined ? null : signingContext;
2423
+ if (ctx === null) {
2424
+ const keyType = getKeyTypeFromPrivateKey(privateKey);
2425
+ if (keyType == null) {
2426
+ return { resultCode: -701, signature: null };
2427
+ }
2428
+ if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA && hybridNs) {
2429
+ sigRes = hybridNs.signCompact(privU8, messageU8);
2430
+ if (sigRes && sigRes.error) return { resultCode: -702, signature: null };
2431
+ } else if (keyType === KEY_TYPE_HYBRIDEDMLDSASLHDSA5 && hybrid5Ns) {
2432
+ sigRes = hybrid5Ns.sign(privU8, messageU8);
2433
+ if (sigRes && sigRes.error) return { resultCode: -703, signature: null };
2434
+ } else {
2435
+ return { resultCode: -704, signature: null };
2436
+ }
2437
+ } else if (ctx === 0 && hybridNs) {
2438
+ sigRes = hybridNs.signCompact(privU8, messageU8);
2439
+ if (sigRes && sigRes.error) return { resultCode: -702, signature: null };
2440
+ } else if (ctx === 1 && hybrid5Ns) {
2441
+ sigRes = hybrid5Ns.sign(privU8, messageU8);
2442
+ if (sigRes && sigRes.error) return { resultCode: -703, signature: null };
2443
+ } else if (ctx === 2 && hybridNs) {
2444
+ sigRes = hybridNs.sign(privU8, messageU8);
2445
+ if (sigRes && sigRes.error) return { resultCode: -702, signature: null };
2446
+ } else {
2447
+ return { resultCode: -704, signature: null };
2448
+ }
2449
+ const sig = sigRes.result instanceof Uint8Array ? sigRes.result : new Uint8Array(sigRes.result);
2450
+ return { resultCode: 0, signature: sig };
2451
+ }
2452
+
2453
+ /**
2454
+ * Verify a signature over a message with a public key. Algorithm is determined by the first byte of the signature: 1=hybrideds verifyCompact, 2=hybrideds verify, 3=hybridedmldsaslhdsa verifyCompact, 4=hybridedmldsaslhdsa verify, 5=hybridedmldsaslhdsa5 verify.
2455
+ * @param {number[]|Uint8Array} publicKey - Public key bytes.
2456
+ * @param {number[]|Uint8Array} signature - Signature bytes from sign(); first byte selects verify function (1-5).
2457
+ * @param {number[]|Uint8Array} message - Message bytes (same as passed to sign).
2458
+ * @returns {{ resultCode: number, valid: boolean }} resultCode 0 and valid true if signature is valid; negative on error (e.g. -1000 not initialized, -715 invalid args, -717 CIRCL verify error, -719 signature invalid, -718 unknown signature type).
2459
+ */
2460
+ function verify(publicKey, signature, message) {
2461
+ if (isInitialized === false) {
2462
+ return { resultCode: -1000, valid: false };
2463
+ }
2464
+ if (!isByteArray(publicKey) || !isByteArray(signature) || !isByteArray(message)) {
2465
+ return { resultCode: -715, valid: false };
2466
+ }
2467
+ const sigLen = signature.byteLength !== undefined ? signature.byteLength : signature.length;
2468
+ if (sigLen < 1) {
2469
+ return { resultCode: -715, valid: false };
2470
+ }
2471
+ const sigType = signature[0];
2472
+ const pubU8 = toUint8Array(publicKey);
2473
+ const sigU8 = toUint8Array(signature);
2474
+ const messageU8 = toUint8Array(message);
2475
+ const hybridedsNs = circl && circl.hybrideds;
2476
+ const hybridNs = circl && circl.hybridedmldsaslhdsa;
2477
+ const hybrid5Ns = circl && (circl.hybridedmldsaslhdsa5 || circl.hybridedmldsaslhdsa5);
2478
+ let verRes;
2479
+ if (sigType === 1 && hybridedsNs) {
2480
+ verRes = hybridedsNs.verifyCompact(pubU8, messageU8, sigU8);
2481
+ } else if (sigType === 2 && hybridedsNs) {
2482
+ verRes = hybridedsNs.verify(pubU8, messageU8, sigU8);
2483
+ } else if (sigType === 3 && hybridNs) {
2484
+ verRes = hybridNs.verifyCompact(pubU8, messageU8, sigU8);
2485
+ } else if (sigType === 4 && hybridNs) {
2486
+ verRes = hybridNs.verify(pubU8, messageU8, sigU8);
2487
+ } else if (sigType === 5 && hybrid5Ns) {
2488
+ verRes = hybrid5Ns.verify(pubU8, messageU8, sigU8);
2489
+ } else {
2490
+ return { resultCode: -718, valid: false };
2491
+ }
2492
+ if (verRes && verRes.error) return { resultCode: -717, valid: false };
2493
+ if (verRes.result !== true) return { resultCode: -719, valid: false };
2494
+ return { resultCode: 0, valid: true };
2495
+ }
2496
+
2497
+ /**
2498
+ * The sendCoins function posts a send-coin transaction to the blockchain. The chainId used for signing should be provided in the initialize() function.
2499
+ * Since the gas fee for sending coins is fixed at 1000 coins, there is no option to set the gas fee explicitly.
2500
+ * It may take many seconds after submitting a transaction before the transaction is returned by the getTransactionDetails function.
2501
+ * Transactions are usually committed in less than 30 seconds.
2502
+ *
2503
+ * @deprecated Use signRawTransaction and postTransaction instead.
2504
+ * @async
2505
+ * @function sendCoins
2506
+ * @param {Wallet} wallet - A Wallet object from which the transaction has to be sent. The address corresponding to the Wallet should have enough coins to cover gas fees as well. A minimum of 1000 coins (1000000000000000000000 wei) are required for gas fees.
2507
+ * @param {string} toAddress - The address to which the coins should be sent.
2508
+ * @param {string} coins - The string representing the number of coins (in ether) to send. To convert between ethers and wei, see https://docs.ethers.org/v4/api-utils.html#ether-strings-and-wei
2509
+ * @param {number} nonce - The nonce of the account retrieved by invoking the getAccountDetails function. You have to carefully manage state of the nonce to avoid sending the coins multiple times, such as when retrying sendCoins after a network error.
2510
+ * @return {Promise<SendResult>} Returns a promise of type SendResult.
2511
+ */
2512
+ async function sendCoins(wallet, toAddress, coins, nonce) {
2513
+ if (isInitialized === false) {
2514
+ return -1000;
2515
+ }
2516
+
2517
+ if (wallet == null || toAddress == null || coins == null || nonce == null) {
2518
+ return new SendResult(-1, null, null, null);
2519
+ }
2520
+
2521
+ if (isAddressValid(toAddress) === false) {
2522
+ return new SendResult(-2, null, null, null);
2523
+ }
2524
+
2525
+ if (verifyWallet(wallet) === false) {
2526
+ return new SendResult(-3, null, null, null);
2527
+ }
2528
+
2529
+ if (isLargeNumber(coins) === false) {
2530
+ return new SendResult(-4, null, null, null);
2531
+ }
2532
+
2533
+ let tempNonce = parseInt(nonce);
2534
+ if (Number.isInteger(tempNonce) === false) {
2535
+ return new SendResult(-5, null, null, null);
2536
+ }
2537
+ nonce = tempNonce;
2538
+ if (nonce < 0) {
2539
+ return new SendResult(-6, null, null, null);
2540
+ }
2541
+
2542
+ let accountDetailsResult = await getAccountDetails(wallet.address);
2543
+ if (accountDetailsResult === null) {
2544
+ return new SendResult(-7, null, null, null);
2545
+ }
2546
+
2547
+ if (accountDetailsResult.resultCode !== 0) {
2548
+ return new SendResult(-7, null, null, null);
2549
+ }
2550
+
2551
+ if (accountDetailsResult.accountDetails.nonce !== nonce) {
2552
+ return new SendResult(-8, null, null, null);
2553
+ }
2554
+
2555
+ const contractData = null;
2556
+
2557
+ var txSigningHash = transactionGetSigningHash(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData);
2558
+ if (txSigningHash == null) {
2559
+ return new SendResult(-9, null, null, null);
2560
+ }
2561
+ const txSigningHashU8 = toUint8Array(txSigningHash);
2562
+ const hybridedsNs = circl && circl.hybrideds;
2563
+ if (!hybridedsNs) {
2564
+ return new SendResult(-10, null, null, null);
2565
+ }
2566
+ const sigRes = hybridedsNs.signCompact(toUint8Array(wallet.privateKey), txSigningHashU8);
2567
+ if (sigRes && sigRes.error) {
2568
+ return new SendResult(-10, null, null, null);
2569
+ }
2570
+ const verRes = hybridedsNs.verifyCompact(toUint8Array(wallet.publicKey), txSigningHashU8, sigRes.result);
2571
+ if (verRes && verRes.error) {
2572
+ return new SendResult(-10, null, null, null);
2573
+ }
2574
+ if (verRes.result !== true) {
2575
+ return new SendResult(-10, null, null, null);
2576
+ }
2577
+ const quantumSig = sigRes.result instanceof Uint8Array ? Array.from(sigRes.result) : sigRes.result;
2578
+
2579
+ var txHashHex = transactionGetTransactionHash(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData, wallet.publicKey, quantumSig);
2580
+ if (txHashHex == null) {
2581
+ return new SendResult(-11, null, null, null);
2582
+ }
2583
+
2584
+ var txnData = transactionGetData(wallet.address, nonce, toAddress, coins, DEFAULT_GAS, config.chainId, contractData, wallet.publicKey, quantumSig);
2585
+ if (txnData == null) {
2586
+ return new SendResult(-12, null, null, null);
2587
+ }
2588
+
2589
+ let sendResult = await postTransaction(txnData);
2590
+ sendResult.txnHash = txHashHex;
2591
+
2592
+ return sendResult;
2593
+ }
2594
+
2595
+ /**
2596
+ * The publicKeyFromSignature extracts the public key from a signature.
2597
+ *
2598
+ * @function publicKeyFromSignature
2599
+ * @param {number[]} digest - An array of bytes containing the digestHash. Should be of length 32.
2600
+ * @param {number[]} signature - An array of bytes containing the signature.
2601
+ * @return {string} - Returns the public key as a hex string. Returns null if the operation failed.
2602
+ */
2603
+ function publicKeyFromSignature(digest, signature) {
2604
+ if (isInitialized === false) {
2605
+ return -1000;
2606
+ }
2607
+
2608
+ if (digest === undefined || digest === null || digest.length === undefined || digest.length === null || digest.length !== 32) {
2609
+ return null;
2610
+ }
2611
+
2612
+ if (signature === undefined || signature === null || signature.length === undefined || signature.length === null) {
2613
+ return null;
2614
+ }
2615
+
2616
+ let publicKeyHex = PublicKeyFromSignature(digest, signature);
2617
+
2618
+ return publicKeyHex;
2619
+ }
2620
+
2621
+ /**
2622
+ * The publicKeyFromPrivateKey extracts the public key from a private key.
2623
+ *
2624
+ * @function publicKeyFromPrivateKey
2625
+ * @param {number[]} privateKey - An array of bytes containing the privateKey.
2626
+ * @return {string} - Returns the public key as a hex string. Returns null if the operation failed.
2627
+ */
2628
+ function publicKeyFromPrivateKey(privateKey) {
2629
+ if (isInitialized === false) {
2630
+ return -1000;
2631
+ }
2632
+
2633
+ if (privateKey === undefined || privateKey === null || privateKey.length === undefined || privateKey.length === null) {
2634
+ return null;
2635
+ }
2636
+
2637
+ let publicKeyHex = PublicKeyFromPrivateKey(privateKey);
2638
+
2639
+ return publicKeyHex;
2640
+ }
2641
+
2642
+ /**
2643
+ * The addressFromPublicKey returns the address corresponding to the public key.
2644
+ *
2645
+ * @function addressFromPublicKey
2646
+ * @param {number[]} publicKey - An array of bytes containing the public key.
2647
+ * @return {string} - Returns the address corresponding to the public key as a hex string. Returns null if the operation failed.
2648
+ */
2649
+ function addressFromPublicKey(publicKey) {
2650
+ if (isInitialized === false) {
2651
+ return -1000;
2652
+ }
2653
+
2654
+ if (publicKey === undefined || publicKey === null || publicKey.length === undefined || publicKey.length === null) {
2655
+ return null;
2656
+ }
2657
+
2658
+ return PublicKeyToAddress(publicKey);
2659
+ }
2660
+
2661
+ /**
2662
+ * The combinePublicKeySignature combines the public key and signature.
2663
+ *
2664
+ * @function combinePublicKeySignature
2665
+ * @param {number[]} publicKey - An array of bytes containing the public key.
2666
+ * @param {number[]} signature - An array of bytes containing the signature.
2667
+ * @return {string} - Returns a hex string corresponding to combined signature. Returns null if the operation failed.
2668
+ */
2669
+ function combinePublicKeySignature(publicKey, signature) {
2670
+ if (isInitialized === false) {
2671
+ return -1000;
2672
+ }
2673
+
2674
+ if (publicKey === undefined || publicKey === null || publicKey.length === undefined || publicKey.length === null) {
2675
+ return null;
2676
+ }
2677
+
2678
+ if (signature === undefined || signature === null || signature.length === undefined || signature.length === null) {
2679
+ return null;
2680
+ }
2681
+
2682
+ return CombinePublicKeySignature(publicKey, signature);
2683
+ }
2684
+
2685
+ /**
2686
+ * The packMethodData function packs a Solidity method call with the given ABI, method name, and arguments.
2687
+ * It returns the transaction data as a hex string that can be included in a transaction.
2688
+ *
2689
+ * @function packMethodData
2690
+ * @param {string} abiJSON - The Solidity ABI file content as a JSON string
2691
+ * @param {string} methodName - The name of the method to call
2692
+ * @param {...*} args - The parameters to pass to the method (variable arguments)
2693
+ * @return {PackUnpackResult} - Returns a PackUnpackResult object containing the error (if any) and the packed transaction data as a hex string.
2694
+ */
2695
+ function packMethodData(abiJSON, methodName, ...args) {
2696
+ if (isInitialized === false) {
2697
+ return new PackUnpackResult('SDK not initialized. Call initialize() first.', '');
2698
+ }
2699
+
2700
+ if (abiJSON === undefined || abiJSON === null || typeof abiJSON !== 'string') {
2701
+ return new PackUnpackResult('Invalid abiJSON parameter. Expected a string.', '');
2702
+ }
2703
+
2704
+ if (methodName === undefined || methodName === null || typeof methodName !== 'string') {
2705
+ return new PackUnpackResult('Invalid methodName parameter. Expected a string.', '');
2706
+ }
2707
+
2708
+ try {
2709
+ // Call WASM PackMethodData function
2710
+ // The WASM function expects: (abiJSON, methodName, ...args)
2711
+ const result = PackMethodData(abiJSON, methodName, ...args);
2712
+
2713
+ // Check if WASM returned an Error object
2714
+ if (result instanceof Error) {
2715
+ return new PackUnpackResult(result.message || 'Unknown error from WASM', '');
2716
+ }
2717
+
2718
+ if (result === null || result === undefined) {
2719
+ return new PackUnpackResult('PackMethodData returned null or undefined', '');
2720
+ }
2721
+
2722
+ // The WASM returns a string where each character is a byte
2723
+ // Convert to hex string
2724
+ let hex = '0x';
2725
+ for (let i = 0; i < result.length; i++) {
2726
+ const byte = result.charCodeAt(i);
2727
+ const hexByte = byte.toString(16);
2728
+ hex += hexByte.length === 1 ? '0' + hexByte : hexByte;
2729
+ }
2730
+
2731
+ return new PackUnpackResult('', hex);
2732
+ } catch (error) {
2733
+ const errorMessage = error instanceof Error ? error.message : String(error);
2734
+ return new PackUnpackResult(errorMessage, '');
2735
+ }
2736
+ }
2737
+
2738
+ /**
2739
+ * The unpackMethodData function unpacks the return values of a Solidity method call.
2740
+ * It returns the unpacked values as a JavaScript array or object.
2741
+ *
2742
+ * @function unpackMethodData
2743
+ * @param {string} abiJSON - The Solidity ABI file content as a JSON string
2744
+ * @param {string} methodName - The name of the method whose return values to unpack
2745
+ * @param {string} hexData - The hex-encoded return data (with or without 0x prefix)
2746
+ * @return {PackUnpackResult} - Returns a PackUnpackResult object containing the error (if any) and the unpacked return values as a JSON string.
2747
+ */
2748
+ function unpackMethodData(abiJSON, methodName, hexData) {
2749
+ if (isInitialized === false) {
2750
+ return new PackUnpackResult('SDK not initialized. Call initialize() first.', '');
2751
+ }
2752
+
2753
+ if (abiJSON === undefined || abiJSON === null || typeof abiJSON !== 'string') {
2754
+ return new PackUnpackResult('Invalid abiJSON parameter. Expected a string.', '');
2755
+ }
2756
+
2757
+ if (methodName === undefined || methodName === null || typeof methodName !== 'string') {
2758
+ return new PackUnpackResult('Invalid methodName parameter. Expected a string.', '');
2759
+ }
2760
+
2761
+ if (hexData === undefined || hexData === null || typeof hexData !== 'string') {
2762
+ return new PackUnpackResult('Invalid hexData parameter. Expected a string.', '');
2763
+ }
2764
+
2765
+ try {
2766
+ // Call WASM UnpackMethodData function
2767
+ const result = UnpackMethodData(abiJSON, methodName, hexData);
2768
+
2769
+ // Check if WASM returned an Error object
2770
+ if (result instanceof Error) {
2771
+ return new PackUnpackResult(result.message || 'Unknown error from WASM', '');
2772
+ }
2773
+
2774
+ if (result === null || result === undefined) {
2775
+ return new PackUnpackResult('UnpackMethodData returned null or undefined', '');
2776
+ }
2777
+
2778
+ // Return the JSON string result directly
2779
+ return new PackUnpackResult('', result);
2780
+ } catch (error) {
2781
+ const errorMessage = error instanceof Error ? error.message : String(error);
2782
+ return new PackUnpackResult(errorMessage, '');
2783
+ }
2784
+ }
2785
+
2786
+ /**
2787
+ * The packCreateContractData function packs constructor data for contract creation.
2788
+ * It combines the contract bytecode with the ABI-encoded constructor parameters.
2789
+ * This matches the Go pattern: Pack("", params...) and append(bytecode, input...)
2790
+ *
2791
+ * @function packCreateContractData
2792
+ * @param {string} abiJSON - The Solidity ABI file content as a JSON string
2793
+ * @param {string} bytecode - The contract bytecode as a hex string (with or without 0x prefix)
2794
+ * @param {...*} args - The constructor parameters (variable arguments, can be 0 or more)
2795
+ * @return {PackUnpackResult} - Returns a PackUnpackResult object containing the error (if any) and the packed contract creation data as a hex string.
2796
+ */
2797
+ function packCreateContractData(abiJSON, bytecode, ...args) {
2798
+ if (isInitialized === false) {
2799
+ return new PackUnpackResult('SDK not initialized. Call initialize() first.', '');
2800
+ }
2801
+
2802
+ if (abiJSON === undefined || abiJSON === null || typeof abiJSON !== 'string') {
2803
+ return new PackUnpackResult('Invalid abiJSON parameter. Expected a string.', '');
2804
+ }
2805
+
2806
+ if (bytecode === undefined || bytecode === null || typeof bytecode !== 'string') {
2807
+ return new PackUnpackResult('Invalid bytecode parameter. Expected a string.', '');
2808
+ }
2809
+
2810
+ try {
2811
+ // Call WASM PackCreateContractData function
2812
+ // The WASM function expects: (abiJSON, bytecode, ...args)
2813
+ const result = PackCreateContractData(abiJSON, bytecode, ...args);
2814
+
2815
+ // Check if WASM returned an Error object
2816
+ if (result instanceof Error) {
2817
+ return new PackUnpackResult(result.message || 'Unknown error from WASM', '');
2818
+ }
2819
+
2820
+ if (result === null || result === undefined) {
2821
+ return new PackUnpackResult('PackCreateContractData returned null or undefined', '');
2822
+ }
2823
+
2824
+ // The WASM returns a string where each character is a byte
2825
+ // Convert to hex string
2826
+ let hex = '0x';
2827
+ for (let i = 0; i < result.length; i++) {
2828
+ const byte = result.charCodeAt(i);
2829
+ const hexByte = byte.toString(16);
2830
+ hex += hexByte.length === 1 ? '0' + hexByte : hexByte;
2831
+ }
2832
+
2833
+ return new PackUnpackResult('', hex);
2834
+ } catch (error) {
2835
+ const errorMessage = error instanceof Error ? error.message : String(error);
2836
+ return new PackUnpackResult(errorMessage, '');
2837
+ }
2838
+ }
2839
+
2840
+ /**
2841
+ * The encodeEventLog function encodes event parameters into topics and data according to the ABI specification.
2842
+ * It returns the topics array and data hex string that can be used to create event logs.
2843
+ *
2844
+ * @function encodeEventLog
2845
+ * @param {string} abiJSON - The Solidity ABI file content as a JSON string
2846
+ * @param {string} eventName - The name of the event to encode
2847
+ * @param {...*} args - The event parameter values (variable arguments)
2848
+ * @return {EventLogEncodeResult} - Returns an EventLogEncodeResult object containing the error (if any) and the encoded event log with topics and data.
2849
+ */
2850
+ function encodeEventLog(abiJSON, eventName, ...args) {
2851
+ if (isInitialized === false) {
2852
+ return new EventLogEncodeResult('SDK not initialized. Call initialize() first.', null);
2853
+ }
2854
+
2855
+ if (abiJSON === undefined || abiJSON === null || typeof abiJSON !== 'string') {
2856
+ return new EventLogEncodeResult('Invalid abiJSON parameter. Expected a string.', null);
2857
+ }
2858
+
2859
+ if (eventName === undefined || eventName === null || typeof eventName !== 'string') {
2860
+ return new EventLogEncodeResult('Invalid eventName parameter. Expected a string.', null);
2861
+ }
2862
+
2863
+ try {
2864
+ // Call WASM EncodeEventLog function
2865
+ // The WASM function expects: (abiJSON, eventName, ...args)
2866
+ const result = EncodeEventLog(abiJSON, eventName, ...args);
2867
+
2868
+ // Check if WASM returned an Error object
2869
+ if (result instanceof Error) {
2870
+ return new EventLogEncodeResult(result.message || 'Unknown error from WASM', null);
2871
+ }
2872
+
2873
+ if (result === null || result === undefined) {
2874
+ return new EventLogEncodeResult('EncodeEventLog returned null or undefined', null);
2875
+ }
2876
+
2877
+ // The WASM returns a JavaScript object with topics (array) and data (hex string)
2878
+ // Extract topics array and data
2879
+ const topics = result.topics || [];
2880
+ const data = result.data || '0x';
2881
+
2882
+ // Ensure topics is an array and data is a string
2883
+ if (!Array.isArray(topics)) {
2884
+ return new EventLogEncodeResult('EncodeEventLog returned invalid topics (not an array)', null);
2885
+ }
2886
+
2887
+ if (typeof data !== 'string') {
2888
+ return new EventLogEncodeResult('EncodeEventLog returned invalid data (not a string)', null);
2889
+ }
2890
+
2891
+ return new EventLogEncodeResult('', { topics, data });
2892
+ } catch (error) {
2893
+ const errorMessage = error instanceof Error ? error.message : String(error);
2894
+ return new EventLogEncodeResult(errorMessage, null);
2895
+ }
2896
+ }
2897
+
2898
+ /**
2899
+ * The decodeEventLog function decodes event log topics and data back into event parameters.
2900
+ * It returns the decoded values as a JavaScript object.
2901
+ *
2902
+ * @function decodeEventLog
2903
+ * @param {string} abiJSON - The Solidity ABI file content as a JSON string
2904
+ * @param {string} eventName - The name of the event to decode
2905
+ * @param {string[]} topics - Array of topic hex strings (with or without 0x prefix)
2906
+ * @param {string} data - Hex-encoded data string (with or without 0x prefix)
2907
+ * @return {PackUnpackResult} - Returns a PackUnpackResult object containing the error (if any) and the decoded event parameters as a JSON string.
2908
+ */
2909
+ function decodeEventLog(abiJSON, eventName, topics, data) {
2910
+ if (isInitialized === false) {
2911
+ return new PackUnpackResult('SDK not initialized. Call initialize() first.', '');
2912
+ }
2913
+
2914
+ if (abiJSON === undefined || abiJSON === null || typeof abiJSON !== 'string') {
2915
+ return new PackUnpackResult('Invalid abiJSON parameter. Expected a string.', '');
2916
+ }
2917
+
2918
+ if (eventName === undefined || eventName === null || typeof eventName !== 'string') {
2919
+ return new PackUnpackResult('Invalid eventName parameter. Expected a string.', '');
2920
+ }
2921
+
2922
+ if (topics === undefined || topics === null || !Array.isArray(topics)) {
2923
+ return new PackUnpackResult('Invalid topics parameter. Expected an array of strings.', '');
2924
+ }
2925
+
2926
+ if (data === undefined || data === null || typeof data !== 'string') {
2927
+ return new PackUnpackResult('Invalid data parameter. Expected a string.', '');
2928
+ }
2929
+
2930
+ try {
2931
+ // Call WASM DecodeEventLog function
2932
+ const result = DecodeEventLog(abiJSON, eventName, topics, data);
2933
+
2934
+ // Check if WASM returned an Error object
2935
+ if (result instanceof Error) {
2936
+ return new PackUnpackResult(result.message || 'Unknown error from WASM', '');
2937
+ }
2938
+
2939
+ if (result === null || result === undefined) {
2940
+ return new PackUnpackResult('DecodeEventLog returned null or undefined', '');
2941
+ }
2942
+
2943
+ // The WASM returns a JSON string
2944
+ if (typeof result !== 'string') {
2945
+ return new PackUnpackResult('DecodeEventLog returned invalid result (not a string)', '');
2946
+ }
2947
+
2948
+ return new PackUnpackResult('', result);
2949
+ } catch (error) {
2950
+ const errorMessage = error instanceof Error ? error.message : String(error);
2951
+ return new PackUnpackResult(errorMessage, '');
2952
+ }
2953
+ }
2954
+
2955
+ /**
2956
+ * The encodeRlp function encodes a JavaScript value to RLP (Recursive Length Prefix) format.
2957
+ * Supports: strings, numbers, booleans, arrays, objects (maps), and hex-encoded bytes.
2958
+ * Returns a hex-encoded string of the RLP-encoded data.
2959
+ *
2960
+ * @function encodeRlp
2961
+ * @param {*} value - The value to encode (can be string, number, boolean, array, object, etc.)
2962
+ * @return {PackUnpackResult} - Returns a PackUnpackResult object containing the error (if any) and the RLP-encoded data as a hex string.
2963
+ */
2964
+ function encodeRlp(value) {
2965
+ if (isInitialized === false) {
2966
+ return new PackUnpackResult('SDK not initialized. Call initialize() first.', '');
2967
+ }
2968
+
2969
+ // Note: null and undefined are valid inputs and will be encoded as empty bytes
2970
+
2971
+ try {
2972
+ // Call WASM EncodeRlp function
2973
+ const result = EncodeRlp(value);
2974
+
2975
+ // Check if WASM returned an Error object
2976
+ if (result instanceof Error) {
2977
+ return new PackUnpackResult(result.message || 'Unknown error from WASM', '');
2978
+ }
2979
+
2980
+ if (result === null || result === undefined) {
2981
+ return new PackUnpackResult('EncodeRlp returned null or undefined', '');
2982
+ }
2983
+
2984
+ // The WASM returns a hex string
2985
+ if (typeof result !== 'string') {
2986
+ return new PackUnpackResult('EncodeRlp returned invalid result (not a string)', '');
2987
+ }
2988
+
2989
+ return new PackUnpackResult('', result);
2990
+ } catch (error) {
2991
+ const errorMessage = error instanceof Error ? error.message : String(error);
2992
+ return new PackUnpackResult(errorMessage, '');
2993
+ }
2994
+ }
2995
+
2996
+ /**
2997
+ * The decodeRlp function decodes RLP-encoded data back to a JavaScript-compatible value.
2998
+ * Takes a hex-encoded string and returns a JSON string representation of the decoded value.
2999
+ *
3000
+ * @function decodeRlp
3001
+ * @param {string} data - The hex-encoded RLP data (with or without 0x prefix)
3002
+ * @return {PackUnpackResult} - Returns a PackUnpackResult object containing the error (if any) and the decoded value as a JSON string.
3003
+ */
3004
+ function decodeRlp(data) {
3005
+ if (isInitialized === false) {
3006
+ return new PackUnpackResult('SDK not initialized. Call initialize() first.', '');
3007
+ }
3008
+
3009
+ if (data === undefined || data === null || typeof data !== 'string') {
3010
+ return new PackUnpackResult('Invalid data parameter. Expected a string.', '');
3011
+ }
3012
+
3013
+ try {
3014
+ // Call WASM DecodeRlp function
3015
+ const result = DecodeRlp(data);
3016
+
3017
+ // Check if WASM returned an Error object
3018
+ if (result instanceof Error) {
3019
+ return new PackUnpackResult(result.message || 'Unknown error from WASM', '');
3020
+ }
3021
+
3022
+ if (result === null || result === undefined) {
3023
+ return new PackUnpackResult('DecodeRlp returned null or undefined', '');
3024
+ }
3025
+
3026
+ // The WASM returns a JSON string
3027
+ if (typeof result !== 'string') {
3028
+ return new PackUnpackResult('DecodeRlp returned invalid result (not a string)', '');
3029
+ }
3030
+
3031
+ return new PackUnpackResult('', result);
3032
+ } catch (error) {
3033
+ const errorMessage = error instanceof Error ? error.message : String(error);
3034
+ return new PackUnpackResult(errorMessage, '');
3035
+ }
3036
+ }
3037
+
3038
+ /**
3039
+ * The createAddress function calculates the contract address that will be created by a transaction.
3040
+ * This uses the CREATE opcode address calculation: keccak256(RLP(sender, nonce))
3041
+ *
3042
+ * @function createAddress
3043
+ * @param {string} address - The address of the account that will create the contract (hex string with 0x prefix)
3044
+ * @param {number} nonce - The nonce of the account at the time of contract creation
3045
+ * @return {string|null} - Returns the contract address as a hex string, or null if an error occurred.
3046
+ */
3047
+ function createAddress(address, nonce) {
3048
+ if (isInitialized === false) {
3049
+ return null;
3050
+ }
3051
+
3052
+ if (address === undefined || address === null || typeof address !== 'string') {
3053
+ return null;
3054
+ }
3055
+
3056
+ if (nonce === undefined || nonce === null || typeof nonce !== 'number') {
3057
+ return null;
3058
+ }
3059
+
3060
+ try {
3061
+ // Call WASM CreateAddress function
3062
+ // The WASM function expects: (address, nonce as string)
3063
+ const result = CreateAddress(address, nonce.toString());
3064
+
3065
+ // Check if WASM returned an Error object
3066
+ if (result instanceof Error) {
3067
+ return null;
3068
+ }
3069
+
3070
+ if (result === null || result === undefined) {
3071
+ return null;
3072
+ }
3073
+
3074
+ // Return the address string directly
3075
+ return result;
3076
+ } catch (error) {
3077
+ return null;
3078
+ }
3079
+ }
3080
+
3081
+ /**
3082
+ * The createAddress2 function calculates the contract address using the CREATE2 opcode.
3083
+ * This allows deterministic contract address calculation: keccak256(0xff || sender || salt || keccak256(init_code))
3084
+ *
3085
+ * @function createAddress2
3086
+ * @param {string} address - The address of the account that will create the contract (hex string with 0x prefix)
3087
+ * @param {string} salt - A 32-byte salt value as a hex string (with 0x prefix)
3088
+ * @param {string} initHash - The keccak256 hash of the contract initialization code as a hex string (with 0x prefix)
3089
+ * @return {string|null} - Returns the contract address as a hex string, or null if an error occurred.
3090
+ */
3091
+ function createAddress2(address, salt, initHash) {
3092
+ if (isInitialized === false) {
3093
+ return null;
3094
+ }
3095
+
3096
+ if (address === undefined || address === null || typeof address !== 'string') {
3097
+ return null;
3098
+ }
3099
+
3100
+ if (salt === undefined || salt === null || typeof salt !== 'string') {
3101
+ return null;
3102
+ }
3103
+
3104
+ if (initHash === undefined || initHash === null || typeof initHash !== 'string') {
3105
+ return null;
3106
+ }
3107
+
3108
+ try {
3109
+ // Call WASM CreateAddress2 function
3110
+ // The WASM function expects: (address, salt, initHash)
3111
+ const result = CreateAddress2(address, salt, initHash);
3112
+
3113
+ // Check if WASM returned an Error object
3114
+ if (result instanceof Error) {
3115
+ return null;
3116
+ }
3117
+
3118
+ if (result === null || result === undefined) {
3119
+ return null;
3120
+ }
3121
+
3122
+ // Return the address string directly
3123
+ return result;
3124
+ } catch (error) {
3125
+ return null;
3126
+ }
3127
+ }
3128
+
3129
+ module.exports = {
3130
+ initialize,
3131
+ serializeWallet,
3132
+ deserializeWallet,
3133
+ serializeEncryptedWallet,
3134
+ serializeSeedAsEncryptedWallet,
3135
+ deserializeEncryptedWallet,
3136
+ verifyWallet,
3137
+ newWallet,
3138
+ sendCoins,
3139
+ getAccountDetails,
3140
+ getTransactionDetails,
3141
+ isAddressValid,
3142
+ getLatestBlockDetails,
3143
+ signSendCoinTransaction,
3144
+ listAccountTransactions,
3145
+ postTransaction,
3146
+ Config,
3147
+ Wallet,
3148
+ BlockDetails,
3149
+ LatestBlockDetailsResult,
3150
+ AccountDetails,
3151
+ AccountDetailsResult,
3152
+ SendResult,
3153
+ TransactionReceipt,
3154
+ TransactionDetails,
3155
+ TransactionDetailsResult,
3156
+ AccountTransactionsResult,
3157
+ ListAccountTransactionsResponse,
3158
+ AccountTransactionCompact,
3159
+ newWalletSeedWords,
3160
+ openWalletFromSeed,
3161
+ openWalletFromSeedWords,
3162
+ publicKeyFromSignature,
3163
+ publicKeyFromPrivateKey,
3164
+ addressFromPublicKey,
3165
+ combinePublicKeySignature,
3166
+ TransactionSigningRequest,
3167
+ signRawTransaction,
3168
+ getGasPrice,
3169
+ sign,
3170
+ verify,
3171
+ packMethodData,
3172
+ unpackMethodData,
3173
+ packCreateContractData,
3174
+ encodeEventLog,
3175
+ decodeEventLog,
3176
+ encodeRlp,
3177
+ decodeRlp,
3178
+ createAddress,
3179
+ createAddress2,
3180
+ PackUnpackResult,
3181
+ EventLogEncodeResult
3182
+ };