quantumcoin 7.0.10 → 7.0.12

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 (171) hide show
  1. package/README-SDK.md +16 -5
  2. package/README.md +14 -3
  3. package/config.js +10 -2
  4. package/examples/example.js +0 -5
  5. package/examples/example.ts +0 -5
  6. package/examples/node_modules/.bin/esbuild +16 -0
  7. package/examples/node_modules/.bin/esbuild.cmd +17 -0
  8. package/examples/node_modules/.bin/esbuild.ps1 +28 -0
  9. package/examples/node_modules/.bin/sdkgen +16 -0
  10. package/examples/node_modules/.bin/sdkgen.cmd +17 -0
  11. package/examples/node_modules/.bin/sdkgen.ps1 +28 -0
  12. package/examples/node_modules/.bin/tsx +16 -0
  13. package/examples/node_modules/.bin/tsx.cmd +17 -0
  14. package/examples/node_modules/.bin/tsx.ps1 +28 -0
  15. package/examples/node_modules/.package-lock.json +144 -0
  16. package/examples/node_modules/@esbuild/win32-x64/README.md +3 -0
  17. package/examples/node_modules/@esbuild/win32-x64/esbuild.exe +0 -0
  18. package/examples/node_modules/@esbuild/win32-x64/package.json +20 -0
  19. package/examples/node_modules/esbuild/LICENSE.md +21 -0
  20. package/examples/node_modules/esbuild/README.md +3 -0
  21. package/examples/node_modules/esbuild/bin/esbuild +223 -0
  22. package/examples/node_modules/esbuild/install.js +289 -0
  23. package/examples/node_modules/esbuild/lib/main.d.ts +716 -0
  24. package/examples/node_modules/esbuild/lib/main.js +2532 -0
  25. package/examples/node_modules/esbuild/package.json +49 -0
  26. package/examples/node_modules/get-tsconfig/LICENSE +21 -0
  27. package/examples/node_modules/get-tsconfig/README.md +235 -0
  28. package/examples/node_modules/get-tsconfig/dist/index.cjs +7 -0
  29. package/examples/node_modules/get-tsconfig/dist/index.d.cts +2088 -0
  30. package/examples/node_modules/get-tsconfig/dist/index.d.mts +2088 -0
  31. package/examples/node_modules/get-tsconfig/dist/index.mjs +7 -0
  32. package/examples/node_modules/get-tsconfig/package.json +46 -0
  33. package/examples/node_modules/quantum-coin-js-sdk/LICENSE +21 -0
  34. package/examples/node_modules/quantum-coin-js-sdk/LICENSE-wasm_exec.js.txt +30 -0
  35. package/examples/node_modules/quantum-coin-js-sdk/README.md +1675 -0
  36. package/examples/node_modules/quantum-coin-js-sdk/example/README.md +14 -0
  37. package/examples/node_modules/quantum-coin-js-sdk/example/conversion-example.js +19 -0
  38. package/examples/node_modules/quantum-coin-js-sdk/example/example-create-contract.js +396 -0
  39. package/examples/node_modules/quantum-coin-js-sdk/example/example-encode-decode-rlp.js +225 -0
  40. package/examples/node_modules/quantum-coin-js-sdk/example/example-event-pack-unpack.js +391 -0
  41. package/examples/node_modules/quantum-coin-js-sdk/example/example-misc.js +101 -0
  42. package/examples/node_modules/quantum-coin-js-sdk/example/example-rpc-send-signRawTransaction.js +318 -0
  43. package/examples/node_modules/quantum-coin-js-sdk/example/example-rpc-send.js +116 -0
  44. package/examples/node_modules/quantum-coin-js-sdk/example/example-send.js +70 -0
  45. package/examples/node_modules/quantum-coin-js-sdk/example/example-token-pack-unpack.js +961 -0
  46. package/examples/node_modules/quantum-coin-js-sdk/example/example-wallet-version4.js +35 -0
  47. package/examples/node_modules/quantum-coin-js-sdk/example/example-wallet.js +43 -0
  48. package/examples/node_modules/quantum-coin-js-sdk/example/example.js +405 -0
  49. package/examples/node_modules/quantum-coin-js-sdk/example/package-lock.json +134 -0
  50. package/examples/node_modules/quantum-coin-js-sdk/example/package.json +15 -0
  51. package/examples/node_modules/quantum-coin-js-sdk/index.d.ts +1031 -0
  52. package/examples/node_modules/quantum-coin-js-sdk/index.js +3144 -0
  53. package/examples/node_modules/quantum-coin-js-sdk/package.json +34 -0
  54. package/examples/node_modules/quantum-coin-js-sdk/tests/encrypted-32.json +1 -0
  55. package/examples/node_modules/quantum-coin-js-sdk/tests/encrypted-36.json +1 -0
  56. package/examples/node_modules/quantum-coin-js-sdk/tests/encrypted-48.json +1 -0
  57. package/examples/node_modules/quantum-coin-js-sdk/tests/generate-verify-vectors.js +91 -0
  58. package/examples/node_modules/quantum-coin-js-sdk/tests/non-transactional.preinit.test.js +41 -0
  59. package/examples/node_modules/quantum-coin-js-sdk/tests/non-transactional.test.js +1389 -0
  60. package/examples/node_modules/quantum-coin-js-sdk/tests/sign-raw-keytype5-context-null.test.js +107 -0
  61. package/examples/node_modules/quantum-coin-js-sdk/tests/sign-raw-transaction.test.js +196 -0
  62. package/examples/node_modules/quantum-coin-js-sdk/tests/sign-verify.test.js +311 -0
  63. package/examples/node_modules/quantum-coin-js-sdk/tests/transactional.relay.test.js +131 -0
  64. package/examples/node_modules/quantum-coin-js-sdk/tests/transactional.rpc.test.js +103 -0
  65. package/examples/node_modules/quantum-coin-js-sdk/tests/verify-vectors.json +95035 -0
  66. package/examples/node_modules/quantum-coin-js-sdk/wasmBase64.d.ts +9 -0
  67. package/examples/node_modules/quantum-coin-js-sdk/wasmBase64.js +16 -0
  68. package/examples/node_modules/quantum-coin-js-sdk/wasm_exec.d.ts +0 -0
  69. package/examples/node_modules/quantum-coin-js-sdk/wasm_exec.js +587 -0
  70. package/examples/node_modules/resolve-pkg-maps/LICENSE +21 -0
  71. package/examples/node_modules/resolve-pkg-maps/README.md +216 -0
  72. package/examples/node_modules/resolve-pkg-maps/dist/index.cjs +1 -0
  73. package/examples/node_modules/resolve-pkg-maps/dist/index.d.cts +11 -0
  74. package/examples/node_modules/resolve-pkg-maps/dist/index.d.mts +11 -0
  75. package/examples/node_modules/resolve-pkg-maps/dist/index.mjs +1 -0
  76. package/examples/node_modules/resolve-pkg-maps/package.json +42 -0
  77. package/examples/node_modules/seed-words/.github/workflows/publish-npmjs.yaml +22 -0
  78. package/examples/node_modules/seed-words/BUILD.md +7 -0
  79. package/examples/node_modules/seed-words/LICENSE +121 -0
  80. package/examples/node_modules/seed-words/README.md +67 -0
  81. package/examples/node_modules/seed-words/dist/seedwords.d.ts +39 -0
  82. package/examples/node_modules/seed-words/package.json +27 -0
  83. package/examples/node_modules/seed-words/seedwords.js +315 -0
  84. package/examples/node_modules/seed-words/seedwords.txt +65536 -0
  85. package/examples/node_modules/seed-words/tsconfig.json +21 -0
  86. package/examples/node_modules/tsx/LICENSE +21 -0
  87. package/examples/node_modules/tsx/README.md +32 -0
  88. package/examples/node_modules/tsx/dist/cjs/api/index.cjs +1 -0
  89. package/examples/node_modules/tsx/dist/cjs/api/index.d.cts +35 -0
  90. package/examples/node_modules/tsx/dist/cjs/api/index.d.mts +35 -0
  91. package/examples/node_modules/tsx/dist/cjs/api/index.mjs +1 -0
  92. package/examples/node_modules/tsx/dist/cjs/index.cjs +1 -0
  93. package/examples/node_modules/tsx/dist/cjs/index.mjs +1 -0
  94. package/examples/node_modules/tsx/dist/cli.cjs +54 -0
  95. package/examples/node_modules/tsx/dist/cli.mjs +55 -0
  96. package/examples/node_modules/tsx/dist/client-BQVF1NaW.mjs +1 -0
  97. package/examples/node_modules/tsx/dist/client-D6NvIMSC.cjs +1 -0
  98. package/examples/node_modules/tsx/dist/esm/api/index.cjs +1 -0
  99. package/examples/node_modules/tsx/dist/esm/api/index.d.cts +35 -0
  100. package/examples/node_modules/tsx/dist/esm/api/index.d.mts +35 -0
  101. package/examples/node_modules/tsx/dist/esm/api/index.mjs +1 -0
  102. package/examples/node_modules/tsx/dist/esm/index.cjs +2 -0
  103. package/examples/node_modules/tsx/dist/esm/index.mjs +2 -0
  104. package/examples/node_modules/tsx/dist/get-pipe-path-BHW2eJdv.mjs +1 -0
  105. package/examples/node_modules/tsx/dist/get-pipe-path-BoR10qr8.cjs +1 -0
  106. package/examples/node_modules/tsx/dist/index-7AaEi15b.mjs +14 -0
  107. package/examples/node_modules/tsx/dist/index-BWFBUo6r.cjs +1 -0
  108. package/examples/node_modules/tsx/dist/index-gbaejti9.mjs +1 -0
  109. package/examples/node_modules/tsx/dist/index-gckBtVBf.cjs +14 -0
  110. package/examples/node_modules/tsx/dist/lexer-DQCqS3nf.mjs +3 -0
  111. package/examples/node_modules/tsx/dist/lexer-DgIbo0BU.cjs +3 -0
  112. package/examples/node_modules/tsx/dist/loader.cjs +1 -0
  113. package/examples/node_modules/tsx/dist/loader.mjs +1 -0
  114. package/examples/node_modules/tsx/dist/node-features-_8ZFwP_x.mjs +1 -0
  115. package/examples/node_modules/tsx/dist/node-features-roYmp9jK.cjs +1 -0
  116. package/examples/node_modules/tsx/dist/package-CeBgXWuR.mjs +1 -0
  117. package/examples/node_modules/tsx/dist/package-Dxt5kIHw.cjs +1 -0
  118. package/examples/node_modules/tsx/dist/patch-repl.cjs +1 -0
  119. package/examples/node_modules/tsx/dist/patch-repl.mjs +1 -0
  120. package/examples/node_modules/tsx/dist/preflight.cjs +1 -0
  121. package/examples/node_modules/tsx/dist/preflight.mjs +1 -0
  122. package/examples/node_modules/tsx/dist/register-2sWVXuRQ.cjs +1 -0
  123. package/examples/node_modules/tsx/dist/register-B7jrtLTO.mjs +1 -0
  124. package/examples/node_modules/tsx/dist/register-CFH5oNdT.mjs +4 -0
  125. package/examples/node_modules/tsx/dist/register-D46fvsV_.cjs +4 -0
  126. package/examples/node_modules/tsx/dist/repl.cjs +3 -0
  127. package/examples/node_modules/tsx/dist/repl.mjs +3 -0
  128. package/examples/node_modules/tsx/dist/require-D4F1Lv60.cjs +1 -0
  129. package/examples/node_modules/tsx/dist/require-DQxpCAr4.mjs +1 -0
  130. package/examples/node_modules/tsx/dist/suppress-warnings.cjs +1 -0
  131. package/examples/node_modules/tsx/dist/suppress-warnings.mjs +1 -0
  132. package/examples/node_modules/tsx/dist/temporary-directory-B83uKxJF.cjs +1 -0
  133. package/examples/node_modules/tsx/dist/temporary-directory-CwHp0_NW.mjs +1 -0
  134. package/examples/node_modules/tsx/dist/types-Cxp8y2TL.d.ts +5 -0
  135. package/examples/node_modules/tsx/package.json +68 -0
  136. package/examples/offline-signing.js +0 -2
  137. package/examples/offline-signing.ts +0 -1
  138. package/examples/package-lock.json +422 -73
  139. package/examples/package.json +1 -1
  140. package/examples/wallet-offline.js +1 -9
  141. package/examples/wallet-offline.ts +1 -9
  142. package/generate-sdk.js +5 -7
  143. package/package.json +2 -2
  144. package/src/abi/interface.js +13 -7
  145. package/src/abi/js-abi-coder.js +23 -18
  146. package/src/constants.d.ts +0 -5
  147. package/src/constants.js +0 -7
  148. package/src/contract/contract-factory.js +9 -3
  149. package/src/contract/contract.js +9 -3
  150. package/src/errors/index.js +12 -0
  151. package/src/index.d.ts +0 -3
  152. package/src/providers/extra-providers.js +20 -6
  153. package/src/providers/json-rpc-provider.js +15 -5
  154. package/src/providers/provider.d.ts +0 -2
  155. package/src/providers/provider.js +1 -3
  156. package/src/utils/address.d.ts +0 -14
  157. package/src/utils/address.js +12 -49
  158. package/src/utils/hashing.d.ts +0 -6
  159. package/src/utils/hashing.js +8 -23
  160. package/src/utils/index.d.ts +0 -3
  161. package/src/utils/rlp.js +7 -4
  162. package/src/wallet/wallet.d.ts +7 -13
  163. package/src/wallet/wallet.js +136 -97
  164. package/test/security/malformed-input.test.js +295 -1
  165. package/test/unit/address-wallet.test.js +329 -129
  166. package/test/unit/address-wallet.test.ts +328 -128
  167. package/test/unit/hashing.test.js +0 -11
  168. package/test/unit/hashing.test.ts +0 -11
  169. package/test/unit/providers.test.js +3 -1
  170. package/test/unit/providers.test.ts +3 -1
  171. package/SPEC.md +0 -3845
package/SPEC.md DELETED
@@ -1,3845 +0,0 @@
1
- > **CAUTION:** This is an experimental SDK. Use at your own risk.
2
-
3
- # QuantumCoin.js - Ethers.js v6 Compatible API Specification
4
-
5
- ## Overview
6
-
7
- This specification defines the requirements for implementing a QuantumCoin SDK that provides an ethers.js v6-compatible API. The implementation should follow the same object model pattern as ethers.js v6, while using quantum-coin-js-sdk for underlying functionality (ABI encoding/decoding, signing, address validation, etc.).
8
-
9
- ## Key Differences from Ethereum
10
-
11
- 1. **Address Format**: QuantumCoin addresses are 32 bytes (66 hex characters including 0x), not 20 bytes like Ethereum
12
- 2. **No HDWallet Support**: HDWallet functionality is not applicable for QuantumCoin
13
- 3. **RPC Endpoint**: Uses custom RPC endpoint format (stored in Config.rpcEndpoint)
14
- 4. **Chain ID**: Default chain ID is 123123 (mainnet)
15
-
16
- ## Core Principles
17
-
18
- - Use only built-in JavaScript/Node.js libraries (no external dependencies except quantum-coin-js-sdk)
19
- - Follow ethers.js v6 object model and API patterns
20
- - All cryptographic operations, signing, and address validation must use quantum-coin-js-sdk
21
- - Maintain compatibility with ethers.js v6 patterns for ease of migration
22
-
23
- ---
24
-
25
- ## Constants
26
-
27
- ### `version: string`
28
- The current version of the QuantumCoin.js library.
29
- - Type: `string`
30
- - Example: `"1.0.0"`
31
-
32
- ### `ZeroAddress: string`
33
- The zero address (all zeros).
34
- - Type: `string`
35
- - Value: `"0x0000000000000000000000000000000000000000000000000000000000000000"` (32 bytes, 66 hex characters)
36
- - **Note**: The API matches ethers.js v6 ZeroAddress. For QuantumCoin, this is a 32-byte address.
37
-
38
- ### `ZeroHash: string`
39
- The zero hash (all zeros).
40
- - Type: `string`
41
- - Value: `"0x0000000000000000000000000000000000000000000000000000000000000000"` (32 bytes, 66 hex characters)
42
- - **Note**: The API matches ethers.js v6 ZeroHash.
43
-
44
- ### `MaxUint256: bigint`
45
- The maximum value for a uint256.
46
- - Type: `bigint`
47
- - Value: `2n ** 256n - 1n`
48
- - **Note**: The API matches ethers.js v6 MaxUint256.
49
-
50
- ### `MaxUint160: bigint`
51
- The maximum value for a uint160.
52
- - Type: `bigint`
53
- - Value: `2n ** 160n - 1n`
54
- - **Note**: The API matches ethers.js v6 MaxUint160.
55
-
56
- ### `MinInt256: bigint`
57
- The minimum value for an int256.
58
- - Type: `bigint`
59
- - Value: `-(2n ** 255n)`
60
- - **Note**: The API matches ethers.js v6 MinInt256.
61
-
62
- ### `MaxInt256: bigint`
63
- The maximum value for an int256.
64
- - Type: `bigint`
65
- - Value: `2n ** 255n - 1n`
66
- - **Note**: The API matches ethers.js v6 MaxInt256.
67
-
68
- ### `NumericFault: string`
69
- Error code for numeric faults.
70
- - Type: `string`
71
- - Value: `"NUMERIC_FAULT"`
72
- - **Note**: The API matches ethers.js v6 NumericFault.
73
-
74
- ### `NumericFaultCode: string`
75
- Error code for numeric faults (alias).
76
- - Type: `string`
77
- - Value: `"NUMERIC_FAULT"`
78
- - **Note**: The API matches ethers.js v6 NumericFaultCode.
79
-
80
- ### `WeiPerEther: bigint`
81
- Wei per ether constant.
82
- - Type: `bigint`
83
- - Value: `1000000000000000000n` (1e18)
84
- - **Note**: The API matches ethers.js v6 WeiPerEther.
85
-
86
- ### `EtherSymbol: string`
87
- Symbol for Ether currency.
88
- - Type: `string`
89
- - Value: `"Ξ"`
90
- - **Note**: The API matches ethers.js v6 EtherSymbol.
91
-
92
- ### `N: bigint`
93
- BigNumber constant (exported as `N`).
94
- - Type: `bigint`
95
- - **Note**: The API matches ethers.js v6 N constant.
96
-
97
- ---
98
-
99
- ## Table of Contents
100
-
101
- - [Overview](#overview)
102
- - [Key Differences from Ethereum](#key-differences-from-ethereum)
103
- - [Core Principles](#core-principles)
104
- - [Constants](#constants)
105
- - [1. Provider Classes](#1-provider-classes)
106
- - [1.1 AbstractProvider](#11-abstractprovider)
107
- - [1.2 JsonRpcProvider](#12-jsonrpcprovider)
108
- - [1.3 Block](#13-block)
109
- - [1.4 TransactionRequest](#14-transactionrequest)
110
- - [1.5 TransactionResponse](#15-transactionresponse)
111
- - [1.6 TransactionReceipt](#16-transactionreceipt)
112
- - [1.7 Log](#17-log)
113
- - [1.8 Filter](#18-filter)
114
- - [1.9 PollingBlockTagSubscriber](#19-pollingblocktagsubscriber)
115
- - [1.10 WebSocketProvider](#110-websocketprovider)
116
- - [1.11 IpcSocketProvider](#111-ipcsocketprovider)
117
- - [1.12 FallbackProvider](#112-fallbackprovider)
118
- - [1.13 BrowserProvider](#113-browserprovider)
119
- - [1.14 FilterByBlockHash](#114-filterbyblockhash)
120
- - [2. Wallet Classes](#2-wallet-classes)
121
- - [2.1 AbstractSigner](#21-abstractsigner)
122
- - [2.2 BaseWallet](#22-basewallet)
123
- - [2.3 NonceManager](#23-noncemanager)
124
- - [2.4 Wallet](#24-wallet)
125
- - [2.5 JsonRpcSigner](#25-jsonrpcsigner)
126
- - [2.6 VoidSigner](#26-voidsigner)
127
- - [3. Contract Classes](#3-contract-classes)
128
- - [3.1 BaseContract](#31-basecontract)
129
- - [3.2 Contract](#32-contract)
130
- - [3.3 ContractFactory](#33-contractfactory)
131
- - [3.4 ContractTransactionResponse](#34-contracttransactionresponse)
132
- - [3.5 ContractTransactionReceipt](#35-contracttransactionreceipt)
133
- - [3.6 EventLog](#36-eventlog)
134
- - [4. Interface and ABI Classes](#4-interface-and-abi-classes)
135
- - [4.1 Interface](#41-interface)
136
- - [4.2 Fragment (Base Class)](#42-fragment-base-class)
137
- - [4.3 AbiFragment](#43-abifragment)
138
- - [4.4 FunctionFragment](#44-functionfragment)
139
- - [4.5 EventFragment](#45-eventfragment)
140
- - [4.6 AbiParameter](#46-abiparameter)
141
- - [4.7 TransactionDescription](#47-transactiondescription)
142
- - [4.8 LogDescription](#48-logdescription)
143
- - [4.9 ErrorFragment](#49-errorfragment)
144
- - [4.10 ErrorDescription](#410-errordescription)
145
- - [4.11 ConstructorFragment](#411-constructorfragment)
146
- - [4.12 ParamType](#412-paramtype)
147
- - [4.13 AbiCoder](#413-abicoder)
148
- - [4.14 StructFragment](#414-structfragment)
149
- - [4.15 FallbackFragment](#415-fallbackfragment)
150
- - [5. Utility Classes and Functions](#5-utility-classes-and-functions)
151
- - [5.1 Result](#51-result)
152
- - [5.2 BytesLike](#52-byteslike)
153
- - [5.3 BigNumberish](#53-bignumberish)
154
- - [5.3.1 AddressLike](#531-addresslike)
155
- - [5.3.2 Typed Values](#532-typed-values)
156
- - [5.3.3 BlockTag](#533-blocktag)
157
- - [5.3.4 ProviderEventFilter](#534-providereventfilter)
158
- - [5.3.5 EventFilter](#535-eventfilter)
159
- - [5.3.6 SigningKey](#536-signingkey)
160
- - [5.3.7 Signature](#537-signature)
161
- - [5.3.8 Transaction](#538-transaction)
162
- - [5.3.9 Indexed](#539-indexed)
163
- - [5.3.10 KeystoreAccount](#5310-keystoreaccount)
164
- - [5.4 Address Utilities](#54-address-utilities)
165
- - [5.4.1 Addressable Interface](#541-addressable-interface)
166
- - [5.5 Encoding/Decoding Utilities](#55-encodingdecoding-utilities)
167
- - [5.6 BigNumber Utilities](#56-bignumber-utilities)
168
- - [5.7 Hash Utilities](#57-hash-utilities)
169
- - [5.8 Random Utilities](#58-random-utilities)
170
- - [5.9 RLP Encoding](#59-rlp-encoding)
171
- - [5.10 Provider Utility Functions](#510-provider-utility-functions)
172
- - [5.11 JSON Wallet Utilities](#511-json-wallet-utilities)
173
- - [5.12 Mnemonic](#512-mnemonic)
174
- - [5.13 Wordlist](#513-wordlist)
175
- - [6. Network and Plugins](#6-network-and-plugins)
176
- - [6.1 Network](#61-network)
177
- - [6.2 Networkish](#62-networkish)
178
- - [6.3 NetworkPlugin (Base Interface)](#63-networkplugin-base-interface)
179
- - [6.4 GasCostPlugin](#64-gascostplugin)
180
- - [7. Error Classes](#7-error-classes)
181
- - [7.1 Error](#71-error)
182
- - [7.2 ProviderError](#72-providererror)
183
- - [7.3 TransactionError](#73-transactionerror)
184
- - [7.4 ContractError](#74-contracterror)
185
- - [8. Provider Types and Interfaces](#8-provider-types-and-interfaces)
186
- - [8.1 PreparedTransactionRequest](#81-preparedtransactionrequest)
187
- - [8.2 MinedBlock](#82-minedblock)
188
- - [8.3 MinedTransactionResponse](#83-minedtransactionresponse)
189
- - [8.4 FeeData](#84-feedata)
190
- - [8.5 WebSocketLike](#85-websocketlike)
191
- - [8.6 ProviderEvent](#86-providerevent)
192
- - [8.7 TopicFilter](#87-topicfilter)
193
- - [9. Provider Interface](#9-provider-interface)
194
- - [9.1 Provider (Abstract Base Class)](#91-provider-abstract-base-class)
195
- - [9.2 ContractRunner (Abstract Base Class/Interface)](#92-contractrunner-abstract-base-classinterface)
196
- - [9.3 Signer (Abstract Base Class)](#93-signer-abstract-base-class)
197
- - [10. Implementation Requirements](#10-implementation-requirements)
198
- - [10.1 Quantum-Coin-JS-SDK Integration](#101-quantum-coin-js-sdk-integration)
199
- - [10.2 Built-in Libraries Only](#102-built-in-libraries-only)
200
- - [10.3 Address Format Handling](#103-address-format-handling)
201
- - [10.4 Error Handling](#104-error-handling)
202
- - [10.5 Event Handling](#105-event-handling)
203
- - [10.6 Transaction Handling](#106-transaction-handling)
204
- - [10.7 ABI Handling](#107-abi-handling)
205
- - [10.8 Async/Await Pattern](#108-asyncawait-pattern)
206
- - [10.9 Type Safety](#109-type-safety)
207
- - [11. File Structure](#11-file-structure)
208
- - [12. Example Usage Patterns](#12-example-usage-patterns)
209
- - [12.1 Provider Usage](#121-provider-usage)
210
- - [12.2 Wallet Usage](#122-wallet-usage)
211
- - [12.3 Contract Usage](#123-contract-usage)
212
- - [12.4 Contract Deployment](#124-contract-deployment)
213
- - [13. Testing Requirements](#13-testing-requirements)
214
- - [14. Documentation Requirements](#14-documentation-requirements)
215
- - [15. Typed Contract Generator](#15-typed-contract-generator)
216
- - [Notes](#notes)
217
-
218
- ---
219
-
220
- ## 1. Provider Classes
221
-
222
- ### 1.1 AbstractProvider
223
-
224
- **Purpose**: Abstract base class for all providers
225
-
226
- **Extends**: Provider
227
-
228
- **Note**: This is an internal base class. All concrete providers (JsonRpcProvider, WebSocketProvider, etc.) extend this class. The API matches ethers.js v6 AbstractProvider.
229
-
230
- ---
231
-
232
- ### 1.2 JsonRpcProvider
233
-
234
- **Purpose**: Provides JSON-RPC interface to QuantumCoin blockchain
235
-
236
- **Extends**: AbstractProvider
237
-
238
- **Note**: The API matches ethers.js v6 JsonRpcProvider. All methods, properties, and behavior follow the same patterns as ethers.js v6.
239
-
240
- **Constructor**:
241
- ```javascript
242
- constructor(url?: string, chainId?: number)
243
- ```
244
- - `url`: RPC endpoint URL (defaults to Config.rpcEndpoint or "https://public.rpc.quantumcoinapi.com")
245
- - `chainId`: Chain ID (defaults to 123123)
246
-
247
- **Properties**:
248
- - `url`: string - RPC endpoint URL
249
- - `chainId`: number - Chain ID
250
-
251
- **Methods**:
252
-
253
- #### `getBlockNumber(): Promise<number>`
254
- Returns the latest block number.
255
-
256
- #### `getBlock(blockNumber: number | "latest"): Promise<Block>`
257
- Returns block information.
258
- - `blockNumber`: Block number or "latest"
259
-
260
- #### `getTransaction(txHash: string): Promise<TransactionResponse>`
261
- Returns transaction details.
262
- - `txHash`: Transaction hash (66 hex characters)
263
-
264
- #### `getTransactionReceipt(txHash: string): Promise<TransactionReceipt>`
265
- Returns transaction receipt.
266
- - `txHash`: Transaction hash
267
-
268
- #### `getBalance(address: string): Promise<bigint>`
269
- Returns account balance in wei.
270
- - `address`: 32-byte address (66 hex characters)
271
-
272
- #### `getTransactionCount(address: string, blockTag?: string): Promise<number>`
273
- Returns account nonce.
274
- - `address`: 32-byte address
275
- - `blockTag`: Optional block tag (default: "latest")
276
-
277
- #### `sendTransaction(tx: TransactionRequest): Promise<TransactionResponse>`
278
- Sends a signed transaction.
279
- - `tx`: Transaction request object
280
-
281
- #### `call(tx: TransactionRequest, blockTag?: string): Promise<string>`
282
- Executes a call without creating a transaction.
283
- - `tx`: Transaction request
284
- - `blockTag`: Optional block tag
285
-
286
- #### `estimateGas(tx: TransactionRequest): Promise<bigint>`
287
- Estimates gas for a transaction.
288
- - `tx`: Transaction request
289
-
290
- #### `getCode(address: string, blockTag?: string): Promise<string>`
291
- Returns contract bytecode.
292
- - `address`: Contract address
293
- - `blockTag`: Optional block tag
294
-
295
- #### `getStorageAt(address: string, position: bigint, blockTag?: string): Promise<string>`
296
- Returns storage value at position.
297
- - `address`: Contract address
298
- - `position`: Storage position
299
- - `blockTag`: Optional block tag
300
-
301
- #### `getLogs(filter: Filter): Promise<Log[]>`
302
- Returns event logs matching filter.
303
- - `filter`: Event filter object
304
-
305
- #### `on(event: string, callback: Function): void`
306
- Subscribes to events (block, pending, etc.).
307
- - `event`: Event name
308
- - `callback`: Callback function
309
-
310
- #### `once(event: string, callback: Function): void`
311
- Subscribes to event once.
312
- - `event`: Event name
313
- - `callback`: Callback function
314
-
315
- #### `removeListener(event: string, callback: Function): void`
316
- Removes event listener.
317
- - `event`: Event name
318
- - `callback`: Callback function
319
-
320
- #### `removeAllListeners(event?: string): void`
321
- Removes all listeners for event.
322
- - `event`: Optional event name
323
-
324
- ---
325
-
326
- ### 1.2.1 JsonRpcApiProvider
327
-
328
- **Purpose**: Base class for JSON-RPC API providers
329
-
330
- **Extends**: AbstractProvider
331
-
332
- **Note**: This is an internal base class that provides the core JSON-RPC API functionality. JsonRpcProvider extends this class. The API matches ethers.js v6 JsonRpcApiProvider.
333
-
334
- ---
335
-
336
- ### 1.3 Block
337
-
338
- **Properties**:
339
- - `number`: number - Block number
340
- - `hash`: string | null - Block hash (66 hex characters, null for pending blocks)
341
- - `timestamp`: number - Block timestamp
342
- - `transactions`: string[] | TransactionResponse[] - Array of transaction hashes or full transaction objects
343
- - `parentHash`: string - Parent block hash
344
- - `gasLimit`: bigint - Gas limit
345
- - `gasUsed`: bigint - Gas used
346
- - `miner`: string - Miner coinbase address (32 bytes, 66 hex characters)
347
- - `difficulty`: bigint - Difficulty target
348
- - `nonce`: string - Block nonce
349
- - `extraData`: string - Extra data included by validator
350
- - `receiptsRoot`: string | null - Hash of the transaction receipts trie
351
- - `date`: Date | null - Date object for block timestamp
352
- - `length`: number - Number of transactions in block
353
- - `provider: Provider | null` - Provider instance
354
-
355
- **Methods**:
356
-
357
- #### `getTransaction(indexOrHash: number | string): Promise<TransactionResponse | null>`
358
- Gets a transaction from the block.
359
- - `indexOrHash`: Transaction index or hash
360
- - Returns: TransactionResponse or null if not found
361
-
362
- #### `getTransactionReceipt(indexOrHash: number | string): Promise<TransactionReceipt | null>`
363
- Gets a transaction receipt from the block.
364
- - `indexOrHash`: Transaction index or hash
365
- - Returns: TransactionReceipt or null if not found
366
-
367
- #### `getPrefetchedTransactions(): TransactionResponse[]`
368
- Returns prefetched transaction objects (if available).
369
- - Returns: Array of TransactionResponse objects
370
-
371
- **Note**: Some properties may be null for pending blocks. The `transactions` property can be either an array of hashes (when fetched with `getBlock(blockNumber)`) or full transaction objects (when fetched with `getBlock(blockNumber, true)`).
372
-
373
- ---
374
-
375
- ### 1.4 TransactionRequest
376
-
377
- **Properties**:
378
- - `to`: string | null - Recipient address (null for contract creation)
379
- - `from`: string - Sender address
380
- - `value`: bigint | string - Value in wei
381
- - `data`: string - Transaction data (hex string)
382
- - `gasLimit`: bigint | string - Gas limit
383
- - `gasPrice`: bigint | string - Gas price
384
- - `nonce`: number - Transaction nonce
385
- - `chainId`: number - Chain ID
386
- - `remarks`: string | null - Optional hex string (including 0x) that represents a remark/comment. Maximum 32 bytes length (in bytes). Warning: do not store any sensitive information in this field as it will be public on the blockchain.
387
- - `signingContext`: number | null - Optional signing context (0, 1, 2, or null). Passed to quantum-coin-js-sdk's TransactionSigningRequest; default null. When null, the scheme is derived from the wallet key type.
388
- - `type?: number` - Transaction type
389
- - `accessList?: Array<{address: string, storageKeys: string[]}>` - Access list (EIP-2930)
390
-
391
- ---
392
-
393
- ### 1.5 TransactionResponse
394
-
395
- **Properties**:
396
- - `hash`: string - Transaction hash
397
- - `to`: string | null - Recipient address
398
- - `from`: string - Sender address
399
- - `value`: bigint - Value in wei
400
- - `data`: string - Transaction data
401
- - `gasLimit`: bigint - Gas limit
402
- - `gasPrice`: bigint | null - Gas price
403
- - `nonce`: number - Nonce
404
- - `chainId`: number - Chain ID
405
- - `remarks`: string | null - Optional hex string (including 0x) that represents a remark/comment. Maximum 32 bytes length (in bytes). Warning: do not store any sensitive information in this field as it will be public on the blockchain.
406
- - `blockNumber`: number | null - Block number
407
- - `blockHash`: string | null - Block hash
408
- - `provider: Provider | null` - Provider instance
409
- - `index: number | null` - Transaction index in block
410
- - `type: number | null` - Transaction type
411
- - `accessList: Array<{address: string, storageKeys: string[]}> | null` - Access list
412
-
413
- **Methods**:
414
-
415
- #### `wait(confirmations?: number, timeout?: number): Promise<TransactionReceipt>`
416
- Waits for transaction confirmation.
417
- - `confirmations`: Optional number of confirmations to wait for
418
- - `timeout`: Optional timeout in milliseconds
419
-
420
- ---
421
-
422
- ### 1.6 TransactionReceipt
423
-
424
- **Properties**:
425
- - `hash`: string - Transaction hash
426
- - `blockNumber`: number - Block number
427
- - `blockHash`: string - Block hash
428
- - `transactionIndex`: number - Transaction index in block
429
- - `from`: string - Sender address
430
- - `to`: string | null - Recipient address
431
- - `gasUsed`: bigint - Gas used
432
- - `effectiveGasPrice`: bigint - Effective gas price
433
- - `status`: number - Transaction status (1 = success, 0 = failure)
434
- - `remarks`: string | null - Optional hex string (including 0x) that represents a remark/comment from the transaction. Maximum 32 bytes length (in bytes). Warning: do not store any sensitive information in this field as it will be public on the blockchain.
435
- - `logs`: Log[] - Event logs
436
- - `logsBloom`: string - Logs bloom filter
437
- - `provider: Provider | null` - Provider instance
438
- - `contractAddress: string | null` - Contract address if transaction created a contract
439
- - `type: number | null` - Transaction type
440
- - `root: string | null` - State root (pre-Byzantium)
441
- - `cumulativeGasUsed: bigint` - Cumulative gas used in block
442
-
443
- ---
444
-
445
- ### 1.7 Log
446
-
447
- **Properties**:
448
- - `address`: string - Contract address
449
- - `topics`: string[] - Event topics
450
- - `data`: string - Log data
451
- - `blockNumber`: number - Block number
452
- - `blockHash`: string - Block hash
453
- - `transactionHash`: string - Transaction hash
454
- - `transactionIndex`: number - Transaction index
455
- - `logIndex`: number - Log index
456
- - `removed`: boolean - Whether log was removed
457
- - `provider: Provider | null` - Provider instance
458
-
459
- **Methods**:
460
-
461
- #### `getBlock(): Promise<Block | null>`
462
- Gets block containing log.
463
- - Returns: Block or null
464
-
465
- #### `getTransaction(): Promise<TransactionResponse | null>`
466
- Gets transaction containing log.
467
- - Returns: TransactionResponse or null
468
-
469
- #### `getTransactionReceipt(): Promise<TransactionReceipt | null>`
470
- Gets transaction receipt.
471
- - Returns: TransactionReceipt or null
472
-
473
- ---
474
-
475
- ### 1.8 Filter
476
-
477
- **Properties**:
478
- - `address`: string | string[] - Contract address(es)
479
- - `topics`: (string | string[] | null)[] - Event topics
480
- - `fromBlock`: number | string - Start block
481
- - `toBlock`: number | string - End block
482
-
483
- ---
484
-
485
- ### 1.9 PollingBlockTagSubscriber
486
-
487
- **Purpose**: Subscribes to block updates by polling the provider at regular intervals
488
-
489
- **Extends**: OnBlockSubscriber, Subscriber
490
-
491
- **Constructor**:
492
- ```javascript
493
- constructor(provider: Provider, tag: string)
494
- ```
495
- - `provider`: Provider instance
496
- - `tag`: Block tag to poll ("latest", "pending", etc.)
497
-
498
- **Methods**:
499
-
500
- #### `start(): void`
501
- Starts polling for block updates.
502
-
503
- #### `stop(): void`
504
- Stops polling for block updates.
505
-
506
- **Note**: This class provides a polling-based alternative to event subscriptions for environments where WebSocket subscriptions are not available.
507
-
508
- ---
509
-
510
- ### 1.9.1 SocketBlockSubscriber
511
-
512
- **Purpose**: Subscribes to block updates via WebSocket
513
-
514
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
515
-
516
- ---
517
-
518
- ### 1.9.2 SocketEventSubscriber
519
-
520
- **Purpose**: Subscribes to event logs via WebSocket
521
-
522
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
523
-
524
- ---
525
-
526
- ### 1.9.3 SocketPendingSubscriber
527
-
528
- **Purpose**: Subscribes to pending transactions via WebSocket
529
-
530
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
531
-
532
- ---
533
-
534
- ### 1.9.4 SocketSubscriber
535
-
536
- **Purpose**: Base class for WebSocket subscribers
537
-
538
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
539
-
540
- ---
541
-
542
- ### 1.9.5 UnmanagedSubscriber
543
-
544
- **Purpose**: Represents an unmanaged subscriber
545
-
546
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
547
-
548
- ---
549
-
550
- ### 1.10 WebSocketProvider
551
-
552
- **Purpose**: JSON-RPC provider backed by a WebSocket connection
553
-
554
- **Extends**: SocketProvider, JsonRpcProvider
555
-
556
- **Constructor**:
557
- ```javascript
558
- constructor(url: string | WebSocketLike | WebSocketCreator, chainId?: number, options?: JsonRpcApiProviderOptions)
559
- ```
560
- - `url`: WebSocket URL, WebSocketLike instance, or WebSocketCreator function
561
- - `chainId`: Chain ID (defaults to 123123)
562
- - `options`: Optional provider options
563
-
564
- **Properties**:
565
- - `websocket`: WebSocketLike - The WebSocket connection
566
- - `url`: string - WebSocket URL
567
- - `chainId`: number - Chain ID
568
-
569
- **Methods**:
570
- - Inherits all methods from JsonRpcProvider
571
- - Provides real-time event subscriptions via WebSocket
572
-
573
- **Note**: WebSockets provide instant access to events but require a persistent connection. Many third-party services charge additional fees for WebSocket endpoints.
574
-
575
- ---
576
-
577
- ### 1.11 IpcSocketProvider
578
-
579
- **Purpose**: JSON-RPC provider backed by an IPC socket (for local nodes)
580
-
581
- **Extends**: SocketProvider, JsonRpcProvider
582
-
583
- **Constructor**:
584
- ```javascript
585
- constructor(path: string, chainId?: number)
586
- ```
587
- - `path`: Path to IPC socket
588
- - `chainId`: Chain ID (defaults to 123123)
589
-
590
- **Properties**:
591
- - `path`: string - IPC socket path
592
- - `chainId`: number - Chain ID
593
-
594
- **Methods**:
595
- - Inherits all methods from JsonRpcProvider
596
- - Provides real-time event subscriptions via IPC
597
-
598
- **Note**: Used for connecting to local QuantumCoin nodes running on the same machine.
599
-
600
- ---
601
-
602
- ### 1.12 FallbackProvider
603
-
604
- **Purpose**: Provider that falls back to multiple providers for redundancy and reliability
605
-
606
- **Extends**: Provider
607
-
608
- **Constructor**:
609
- ```javascript
610
- constructor(providers: Array<{ provider: Provider, priority?: number, weight?: number }>, quorum?: number)
611
- ```
612
- - `providers`: Array of provider configurations with optional priority and weight
613
- - `quorum`: Optional quorum number (default: 1) - number of providers that must agree
614
-
615
- **Properties**:
616
- - `providers`: Provider[] - Array of providers
617
- - `quorum`: number - Quorum number
618
-
619
- **Methods**:
620
- - Inherits all methods from Provider
621
- - Automatically falls back to next provider on failure
622
- - For methods requiring quorum, waits for multiple providers to agree
623
-
624
- **Note**: Useful for high-availability applications where multiple RPC endpoints are available.
625
-
626
- ---
627
-
628
- ### 1.13 BrowserProvider
629
-
630
- **Purpose**: JSON-RPC provider backed by a browser-based EIP-1193 compatible provider (e.g., MetaMask, WalletConnect)
631
-
632
- **Extends**: JsonRpcProvider
633
-
634
- **Note**: The API matches ethers.js v6 BrowserProvider. This provider wraps EIP-1193 compatible providers that are injected into the browser (typically via `window.ethereum` or similar).
635
-
636
- **Constructor**:
637
- ```javascript
638
- constructor(ethereum: Eip1193Provider, chainId?: number)
639
- ```
640
- - `ethereum`: EIP-1193 compatible provider object (must implement the EIP-1193 interface)
641
- - `chainId`: Chain ID (defaults to 123123)
642
-
643
- **Properties**:
644
- - `provider`: Eip1193Provider - The wrapped EIP-1193 provider
645
- - `chainId`: number - Chain ID
646
-
647
- **Methods**:
648
- - Inherits all methods from JsonRpcProvider
649
- - Provides browser-based wallet integration
650
- - Automatically handles account changes and chain changes via EIP-1193 events
651
-
652
- **EIP-1193 Provider Interface**:
653
- The `ethereum` parameter must implement the EIP-1193 interface with the following methods:
654
- - `request({ method: string, params?: any[] }): Promise<any>` - Main RPC request method
655
- - `on(event: string, callback: Function): void` - Event subscription
656
- - `removeListener(event: string, callback: Function): void` - Event unsubscription
657
-
658
- **Events**:
659
- The BrowserProvider automatically listens to EIP-1193 events:
660
- - `accountsChanged` - Emitted when accounts change
661
- - `chainChanged` - Emitted when chain ID changes
662
- - `disconnect` - Emitted when provider disconnects
663
-
664
- **Note**: BrowserProvider is designed for browser environments. For Node.js environments, use JsonRpcProvider, WebSocketProvider, or IpcSocketProvider instead.
665
-
666
- ---
667
-
668
- ### 1.14 FilterByBlockHash
669
-
670
- **Properties**:
671
- - `blockHash`: string - Block hash to filter by (66 hex characters)
672
- - `address`: string | string[] - Contract address(es)
673
- - `topics`: (string | string[] | null)[] - Event topics
674
-
675
- **Note**: Alternative to Filter for querying logs by block hash instead of block number range. Allows querying potentially orphaned blocks without ambiguity.
676
-
677
- ---
678
-
679
- ## 2. Wallet Classes
680
-
681
- ### 2.1 AbstractSigner
682
-
683
- **Purpose**: Abstract base class for all signers
684
-
685
- **Extends**: Signer
686
-
687
- **Note**: This is an internal base class. All concrete signers (BaseWallet, Wallet, JsonRpcSigner, VoidSigner, etc.) extend this class. The API matches ethers.js v6 AbstractSigner.
688
-
689
- ---
690
-
691
- ### 2.2 BaseWallet
692
-
693
- **Purpose**: Streamlined implementation of a Signer that operates with a private key
694
-
695
- **Extends**: AbstractSigner
696
-
697
- **Constructor**:
698
- ```javascript
699
- constructor(privateKey: SigningKey, provider?: null | Provider)
700
- ```
701
- - `privateKey`: SigningKey instance
702
- - `provider`: Optional provider instance
703
-
704
- **Properties**:
705
- - `address`: string (read-only) - The wallet address
706
- - `privateKey`: string (read-only) - The private key for this wallet
707
- - `signingKey`: SigningKey (read-only) - The SigningKey used for signing payloads
708
- - `provider`: Provider | null - Provider instance
709
-
710
- **Methods**:
711
-
712
- #### `getAddress(): Promise<string>`
713
- Returns the wallet address.
714
- - Returns: Address string
715
-
716
- #### `signMessageSync(message: string | Uint8Array): string`
717
- Returns the signature for message signed with this wallet (synchronous).
718
- - `message`: Message to sign (string or bytes)
719
- - Returns: Signature string
720
- - **Implementation**: Uses quantum-coin-js-sdk for message signing
721
-
722
- #### `signTransaction(tx: TransactionRequest): Promise<string>`
723
- Signs a transaction and returns the signed transaction data.
724
- - `tx`: Transaction request
725
- - Returns: Signed transaction data
726
- - **Implementation**: Uses `signRawTransaction()` from quantum-coin-js-sdk
727
-
728
- #### `sendTransaction(tx: TransactionRequest): Promise<TransactionResponse>`
729
- Signs and sends a transaction.
730
- - `tx`: Transaction request
731
- - Returns: TransactionResponse
732
- - **Requires provider**: Throws error if `provider` is `null`.
733
-
734
- **Note**: BaseWallet provides the core signing functionality. Wallet extends BaseWallet and adds additional convenience methods.
735
-
736
- ---
737
-
738
- ### 2.3 NonceManager
739
-
740
- **Purpose**: Manages nonces for transactions to prevent conflicts and ensure proper ordering
741
-
742
- **Extends**: Signer
743
-
744
- **Constructor**:
745
- ```javascript
746
- constructor(signer: Signer)
747
- ```
748
- - `signer`: Signer instance to wrap
749
-
750
- **Properties**:
751
- - `signer`: Signer - The wrapped signer
752
- - `provider`: Provider | null - Provider instance (from wrapped signer)
753
-
754
- **Methods**:
755
-
756
- #### `getAddress(): Promise<string>`
757
- Returns the signer address.
758
- - Returns: Address string
759
-
760
- #### `getTransactionCount(blockTag?: string): Promise<number>`
761
- Gets the current transaction count (nonce).
762
- - `blockTag`: Optional block tag
763
- - Returns: Current nonce
764
-
765
- #### `sendTransaction(tx: TransactionRequest): Promise<TransactionResponse>`
766
- Sends a transaction with managed nonce.
767
- - `tx`: Transaction request (nonce will be auto-managed)
768
- - Returns: TransactionResponse
769
-
770
- #### `reset(): void`
771
- Resets the nonce manager, clearing cached nonce.
772
-
773
- #### `increment(): void`
774
- Increments the internal nonce counter.
775
-
776
- **Note**: NonceManager automatically manages nonces to prevent conflicts when sending multiple transactions. It tracks the nonce internally and increments it for each transaction.
777
-
778
- ---
779
-
780
- ### 2.4 Wallet
781
-
782
- **Purpose**: Represents a QuantumCoin wallet with signing capabilities
783
-
784
- **Extends**: BaseWallet
785
-
786
- **Constructor**:
787
- ```javascript
788
- constructor(key: string | Uint8Array | SigningKey, provider?: Provider)
789
- ```
790
- - `key`: Private key as hex string, byte array, or SigningKey instance
791
- - `provider`: Optional provider instance
792
-
793
- **Implementation Notes**:
794
- - The constructor should use quantum-coin-js-sdk functions to derive the wallet's public key and address:
795
- - Use `publicKeyFromPrivateKey()` from quantum-coin-js-sdk to get the public key from the private key
796
- - Use `addressFromPublicKey()` from quantum-coin-js-sdk to get the address from the public key
797
- - If either function returns null, throw an error
798
- - The private key should be converted to a byte array (number[]) if provided as a hex string for use with quantum-coin-js-sdk functions
799
- - If a SigningKey is provided, use it directly
800
-
801
- **Properties**:
802
- - `address`: string (read-only) - Wallet address (32 bytes, 66 hex characters)
803
- - `provider`: Provider | null - Provider instance (null if not provided in constructor)
804
- - `privateKey`: string (read-only) - Private key as hex string
805
- - `signingKey`: SigningKey (read-only) - The SigningKey used for signing payloads
806
-
807
- **Static Methods**:
808
-
809
- #### `createRandom(provider?: Provider): Wallet`
810
- Creates a new random wallet.
811
- - `provider`: Optional provider instance
812
- - Returns: New Wallet instance
813
- - **Implementation**: Uses `newWallet()` from quantum-coin-js-sdk internally. If `newWallet()` returns null, throw an error.
814
-
815
- #### `fromEncryptedJsonSync(json: string, password: string, provider?: Provider): Wallet`
816
- Creates a wallet from an encrypted JSON string (synchronous).
817
- - `json`: Encrypted wallet JSON string
818
- - `password`: Passphrase used to encrypt the wallet
819
- - `provider`: Optional provider instance
820
- - Returns: Wallet instance
821
- - **Implementation**: Uses `deserializeEncryptedWallet()` from quantum-coin-js-sdk internally. If `deserializeEncryptedWallet()` returns null, throw an error.
822
- - **Note**: This function can take up to a minute or so to execute. You should open wallets only from trusted sources.
823
-
824
- #### `fromPhrase(phrase: string | string[], provider?: Provider): Wallet`
825
- Creates a wallet from a seed phrase.
826
- - `phrase`: Either:
827
- - An array of seed words (string[])
828
- - A space or comma delimited string containing seed words
829
- - `provider`: Optional provider instance
830
- - Returns: Wallet instance
831
- - **Implementation**:
832
- - If `phrase` is a string, split it by spaces or commas to create an array of words
833
- - The resulting array must contain exactly 48 words
834
- - Uses `openWalletFromSeedWords()` from quantum-coin-js-sdk internally with the array
835
- - If `openWalletFromSeedWords()` returns null, throw an error
836
-
837
- **Provider Usage**:
838
- - The provider is optional in the constructor. If not provided, `provider` will be `null`.
839
- - Methods that require blockchain access (`getBalance()`, `getTransactionCount()`, `sendTransaction()`) will throw an error if `provider` is `null`.
840
- - Methods that only require signing (`signTransaction()`, `signMessageSync()`, `signTypedData()`) can work without a provider.
841
- - The provider can be set later using the `connect(provider)` method.
842
-
843
- **Methods**:
844
-
845
- #### `getAddress(): string`
846
- Returns the wallet address.
847
- - Does not require a provider.
848
-
849
- #### `getBalance(blockTag?: string): Promise<bigint>`
850
- Returns wallet balance.
851
- - `blockTag`: Optional block tag
852
- - **Requires provider**: Throws error if `provider` is `null`.
853
-
854
- #### `getTransactionCount(blockTag?: string): Promise<number>`
855
- Returns wallet nonce.
856
- - `blockTag`: Optional block tag
857
- - **Requires provider**: Throws error if `provider` is `null`.
858
-
859
- #### `sendTransaction(tx: TransactionRequest): Promise<TransactionResponse>`
860
- Signs and sends a transaction.
861
- - `tx`: Transaction request (from, nonce, gasLimit will be auto-filled if not provided)
862
- - **Requires provider**: Throws error if `provider` is `null`.
863
- - Note: The `remarks` field in TransactionRequest is optional and can be used to include a comment (max 32 bytes). Do not store sensitive information in remarks.
864
-
865
- #### `signTransaction(tx: TransactionRequest): Promise<string>`
866
- Signs a transaction and returns the signed transaction data.
867
- - `tx`: Transaction request
868
- - **Does not require provider**: Can sign transactions offline.
869
- - Note: The `remarks` field in TransactionRequest is optional and can be used to include a comment (max 32 bytes). Do not store sensitive information in remarks.
870
-
871
- #### `signMessageSync(message: string | Uint8Array): string`
872
- Signs a message and returns the signature (synchronous).
873
- - `message`: Message to sign (string or bytes)
874
- - Returns: Signature string
875
- - **Does not require provider**: Can sign messages offline.
876
- - **Implementation**: Uses quantum-coin-js-sdk for message signing
877
-
878
- #### `encryptSync(password: string | Uint8Array): string`
879
- Encrypts and serializes this wallet to a JSON string (synchronous).
880
- - `password`: Passphrase used to encrypt the wallet (should be at least 12 characters long)
881
- - Returns: Encrypted wallet JSON string
882
- - **Implementation**: Uses `serializeEncryptedWallet()` from quantum-coin-js-sdk internally. If `serializeEncryptedWallet()` returns null, throw an error.
883
- - **Note**: This method will block the event loop (freezing all UI) until it is complete, which may be a non-trivial duration. The encrypted JSON string is readable by Desktop/Mobile/Web/CLI wallet applications.
884
-
885
- #### `connect(provider: Provider): Wallet`
886
- Returns a new wallet instance connected to the provider.
887
- - `provider`: Provider instance
888
-
889
- ---
890
-
891
- ## 3. Contract Classes
892
-
893
- ### 3.2 Contract
894
-
895
- **Purpose**: Represents a smart contract instance
896
-
897
- **Extends**: BaseContract
898
-
899
- **Note**: The API matches ethers.js v6 Contract. All methods, properties, and behavior follow the same patterns as ethers.js v6.
900
-
901
- **Constructor**:
902
- ```javascript
903
- constructor(address: string, abi: Interface | AbiFragment[], providerOrSigner?: Provider | Signer, bytecode?: string)
904
- ```
905
- - `address`: Contract address (32 bytes)
906
- - `abi`: Contract ABI (Interface or array of fragments)
907
- - `providerOrSigner`: Provider or signer instance
908
- - `bytecode`: Optional contract bytecode
909
-
910
- **Properties**:
911
- - `address`: string - Contract address
912
- - `interface`: Interface - Contract interface
913
- - `provider`: Provider | null - Provider instance
914
- - `signer`: Signer | null - Signer instance
915
- - `target: string | Addressable` - Contract target (address or addressable)
916
- - `runner: ContractRunner | null` - Contract runner (provider or signer)
917
- - `deployTransaction: ContractTransactionResponse | null` - Deployment transaction
918
-
919
- **Methods**:
920
-
921
- #### `getAddress(): string`
922
- Returns contract address.
923
-
924
- #### `[methodName](...args): Promise<any>`
925
- Dynamic methods for each contract function.
926
- - For view functions: Returns decoded return values
927
- - For state-changing functions: Returns ContractTransactionResponse
928
-
929
- #### `queryFilter(event: EventFragment, fromBlock?: number | string, toBlock?: number | string): Promise<EventLog[]>`
930
- Queries event logs.
931
- - `event`: Event fragment
932
- - `fromBlock`: Start block
933
- - `toBlock`: End block
934
-
935
- #### `on(event: EventFragment | string, callback: Function): Contract`
936
- Subscribes to contract events.
937
- - `event`: Event fragment or name
938
- - `callback`: Callback function
939
-
940
- #### `once(event: EventFragment | string, callback: Function): Contract`
941
- Subscribes to event once.
942
- - `event`: Event fragment or name
943
- - `callback`: Callback function
944
-
945
- #### `removeListener(event: EventFragment | string, callback: Function): Contract`
946
- Removes event listener.
947
- - `event`: Event fragment or name
948
- - `callback`: Callback function
949
-
950
- #### `removeAllListeners(event?: EventFragment | string): Contract`
951
- Removes all listeners.
952
- - `event`: Optional event name
953
-
954
- #### `connect(signerOrProvider: Signer | Provider): Contract`
955
- Returns new contract instance connected to signer/provider.
956
- - `signerOrProvider`: Signer or provider
957
-
958
- #### `attach(address: string): Contract`
959
- Returns new contract instance at different address.
960
- - `address`: New contract address
961
-
962
- #### `deployTransaction(): TransactionResponse | null`
963
- Returns deployment transaction (if contract was deployed).
964
-
965
- #### `getTransactionReceipt(hash: string): Promise<ContractTransactionReceipt | null>`
966
- Gets contract transaction receipt.
967
- - `hash`: Transaction hash
968
- - Returns: ContractTransactionReceipt or null
969
-
970
- #### `waitForDeployment(): Promise<this>`
971
- Waits for contract deployment.
972
- - Returns: Contract instance (this)
973
-
974
- #### `getDeployedCode(): Promise<string | null>`
975
- Gets deployed contract code.
976
- - Returns: Contract bytecode or null if not deployed
977
-
978
- #### `static from(target: string | Addressable, abi: Interface | AbiFragment[], runner?: ContractRunner): Contract`
979
- Creates contract from target.
980
- - `target`: Contract address or addressable
981
- - `abi`: Contract ABI
982
- - `runner`: Optional contract runner
983
- - Returns: Contract instance
984
-
985
- ---
986
-
987
- ### 3.3 ContractFactory
988
-
989
- **Purpose**: Factory for deploying contracts
990
-
991
- **Note**: The API matches ethers.js v6 ContractFactory. All methods, properties, and behavior follow the same patterns as ethers.js v6.
992
-
993
- **Constructor**:
994
- ```javascript
995
- constructor(abi: Interface | AbiFragment[], bytecode: string | BytesLike, signer?: Signer)
996
- ```
997
- - `abi`: Contract ABI
998
- - `bytecode`: Contract bytecode
999
- - `signer`: Optional signer for deployment
1000
-
1001
- **Methods**:
1002
-
1003
- #### `getDeployTransaction(...args): TransactionRequest`
1004
- Returns deployment transaction request.
1005
- - `args`: Constructor arguments
1006
-
1007
- #### `deploy(...args): Promise<Contract>`
1008
- Deploys the contract.
1009
- - `args`: Constructor arguments
1010
- - Returns: Contract instance
1011
-
1012
- #### `attach(address: string): Contract`
1013
- Returns contract instance at address.
1014
- - `address`: Contract address
1015
-
1016
- #### `connect(signer: Signer): ContractFactory`
1017
- Returns new factory connected to signer.
1018
- - `signer`: Signer instance
1019
-
1020
- ---
1021
-
1022
- ### 3.4 ContractTransactionResponse
1023
-
1024
- **Extends**: TransactionResponse
1025
-
1026
- **Additional Methods**:
1027
-
1028
- #### `wait(confirmations?: number): Promise<ContractTransactionReceipt>`
1029
- Waits for transaction confirmation.
1030
- - `confirmations`: Optional confirmations to wait for
1031
-
1032
- ---
1033
-
1034
- ### 3.5 ContractTransactionReceipt
1035
-
1036
- **Extends**: TransactionReceipt
1037
-
1038
- **Additional Methods**:
1039
-
1040
- #### `getEvent(eventName: string): EventLog | null`
1041
- Gets event log by name.
1042
- - `eventName`: Event name
1043
-
1044
- #### `getEvents(eventName: string): EventLog[]`
1045
- Gets all event logs by name.
1046
- - `eventName`: Event name
1047
-
1048
- ---
1049
-
1050
- ### 3.6 EventLog
1051
-
1052
- **Extends**: Log
1053
-
1054
- **Additional Properties**:
1055
- - `eventName`: string - Event name
1056
- - `args`: Result - Decoded event arguments
1057
- - `fragment`: EventFragment - Event fragment
1058
-
1059
- ---
1060
-
1061
- ### 3.7 ContractEventPayload
1062
-
1063
- **Purpose**: Represents a contract event payload
1064
-
1065
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1066
-
1067
- ---
1068
-
1069
- ### 3.8 ContractUnknownEventPayload
1070
-
1071
- **Purpose**: Represents an unknown contract event payload
1072
-
1073
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1074
-
1075
- ---
1076
-
1077
- ### 3.9 EventPayload
1078
-
1079
- **Purpose**: Base class for event payloads
1080
-
1081
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1082
-
1083
- ---
1084
-
1085
- ### 3.10 UndecodedEventLog
1086
-
1087
- **Purpose**: Represents an undecoded event log
1088
-
1089
- **Extends**: Log
1090
-
1091
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1092
-
1093
- ---
1094
-
1095
- ## 4. Interface and ABI Classes
1096
-
1097
- ### 4.0 Fragment
1098
-
1099
- **Purpose**: Base class for ABI fragments
1100
-
1101
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference. In quantumcoin.js, `AbiFragment` serves as the base fragment class.
1102
-
1103
- ---
1104
-
1105
- ### 4.0.1 NamedFragment
1106
-
1107
- **Purpose**: Base class for named ABI fragments
1108
-
1109
- **Extends**: Fragment
1110
-
1111
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1112
-
1113
- ---
1114
-
1115
- ### 4.1 Interface
1116
-
1117
- **Purpose**: Represents contract ABI interface
1118
-
1119
- **Note**: The API matches ethers.js v6 Interface. All methods, properties, and behavior follow the same patterns as ethers.js v6.
1120
-
1121
- **Constructor**:
1122
- ```javascript
1123
- constructor(fragments: AbiFragment[] | string)
1124
- ```
1125
- - `fragments`: ABI fragments array or JSON string
1126
-
1127
- **Properties**:
1128
- - `fragments`: readonly AbiFragment[] - ABI fragments
1129
-
1130
- **Methods**:
1131
-
1132
- #### `getFunction(nameOrSignature: string): FunctionFragment`
1133
- Gets function fragment by name or signature.
1134
- - `nameOrSignature`: Function name or signature
1135
-
1136
- #### `getEvent(nameOrSignature: string): EventFragment`
1137
- Gets event fragment by name or signature.
1138
- - `nameOrSignature`: Event name or signature
1139
-
1140
- #### `encodeFunctionData(functionFragment: FunctionFragment | string, values: any[]): string`
1141
- Encodes function call data.
1142
- - `functionFragment`: Function fragment or signature
1143
- - `values`: Function arguments
1144
-
1145
- #### `decodeFunctionResult(functionFragment: FunctionFragment | string, data: string): Result`
1146
- Decodes function result.
1147
- - `functionFragment`: Function fragment or signature
1148
- - `data`: Encoded result data
1149
-
1150
- #### `encodeEventLog(eventFragment: EventFragment, values: any[]): { topics: string[], data: string }`
1151
- Encodes event log.
1152
- - `eventFragment`: Event fragment
1153
- - `values`: Event values
1154
- - **Implementation**: Uses `encodeEventLog()` from quantum-coin-js-sdk internally
1155
- - Returns: Object with `topics` (string[]) and `data` (string)
1156
-
1157
- #### `decodeEventLog(eventFragment: EventFragment, topics: string[], data: string): Result`
1158
- Decodes event log.
1159
- - `eventFragment`: Event fragment
1160
- - `topics`: Event topics
1161
- - `data`: Event data
1162
- - **Implementation**: Uses `decodeEventLog()` from quantum-coin-js-sdk internally
1163
- - Returns: Result object with decoded event arguments
1164
-
1165
- #### `parseTransaction(data: string): TransactionDescription`
1166
- Parses transaction data.
1167
- - `data`: Transaction data
1168
-
1169
- #### `parseLog(log: Log): LogDescription`
1170
- Parses log data.
1171
- - `log`: Log object
1172
- - Returns: LogDescription with decoded event information
1173
-
1174
- #### `getError(nameOrSignature: string): ErrorFragment`
1175
- Gets error fragment by name or signature.
1176
- - `nameOrSignature`: Error name or signature
1177
- - Returns: ErrorFragment instance
1178
-
1179
- #### `getConstructor(): ConstructorFragment | null`
1180
- Gets constructor fragment.
1181
- - Returns: ConstructorFragment instance or null if no constructor
1182
-
1183
- #### `getFallback(): FunctionFragment | null`
1184
- Gets fallback function fragment.
1185
- - Returns: FunctionFragment instance or null if no fallback function
1186
-
1187
- #### `getReceive(): FunctionFragment | null`
1188
- Gets receive function fragment.
1189
- - Returns: FunctionFragment instance or null if no receive function
1190
-
1191
- #### `parseError(data: string): ErrorDescription`
1192
- Parses error data.
1193
- - `data`: Error data (hex string)
1194
- - Returns: ErrorDescription with decoded error information
1195
-
1196
- #### `getSighash(fragment: FunctionFragment | ErrorFragment | string): string`
1197
- Gets function/error selector.
1198
- - `fragment`: Function or error fragment or signature string
1199
- - Returns: Function/error selector (4 bytes, 10 hex characters including 0x)
1200
-
1201
- #### `getEventTopic(fragment: EventFragment | string): string`
1202
- Gets event topic hash.
1203
- - `fragment`: Event fragment or signature string
1204
- - Returns: Event topic hash (32 bytes, 66 hex characters including 0x)
1205
-
1206
- #### `format(format?: string): string`
1207
- Formats interface as string.
1208
- - `format`: Optional format type
1209
- - Returns: Formatted interface string
1210
-
1211
- #### `formatJson(): string`
1212
- Formats interface as JSON string.
1213
- - Returns: JSON string representation of interface
1214
-
1215
- **Additional Properties**:
1216
- - `deploy: ConstructorFragment | null` - Constructor fragment
1217
- - `fallback: FallbackFragment | null` - Fallback function fragment
1218
- - `receive: boolean` - Whether contract has receive function
1219
-
1220
- ---
1221
-
1222
- ### 4.2 AbiFragment
1223
-
1224
- **Base Properties**:
1225
- - `type`: string - Fragment type ("function", "event", "constructor", "fallback", "receive", "error")
1226
- - `name`: string - Fragment name
1227
- - `inputs`: AbiParameter[] - Input parameters
1228
- - `outputs`: AbiParameter[] - Output parameters (for functions, not applicable for errors)
1229
- - `signature`: string - Full signature of the fragment (e.g., "transfer(address,uint256)")
1230
-
1231
- ---
1232
-
1233
- ### 4.4 FunctionFragment
1234
-
1235
- **Extends**: AbiFragment
1236
-
1237
- **Note**: The API matches ethers.js v6 FunctionFragment.
1238
-
1239
- **Additional Properties**:
1240
- - `stateMutability`: string - "pure", "view", "nonpayable", "payable"
1241
- - `constant`: boolean - Whether function is constant
1242
- - `payable`: boolean - Whether function is payable
1243
- - `selector`: string - Function selector (4 bytes, 10 hex characters including 0x)
1244
-
1245
- **Methods**:
1246
-
1247
- #### `format(format?: string): string`
1248
- Formats fragment as string.
1249
- - `format`: Optional format type
1250
-
1251
- ---
1252
-
1253
- ### 4.5 EventFragment
1254
-
1255
- **Extends**: AbiFragment
1256
-
1257
- **Note**: The API matches ethers.js v6 EventFragment.
1258
-
1259
- **Additional Properties**:
1260
- - `anonymous`: boolean - Whether event is anonymous
1261
- - `topicHash`: string - Event topic hash (32 bytes, 66 hex characters including 0x)
1262
-
1263
- **Methods**:
1264
-
1265
- #### `format(format?: string): string`
1266
- Formats fragment as string.
1267
- - `format`: Optional format type
1268
-
1269
- ---
1270
-
1271
- ### 4.6 AbiParameter
1272
-
1273
- **Note**: The API matches ethers.js v6 AbiParameter.
1274
-
1275
- **Properties**:
1276
- - `name`: string - Parameter name
1277
- - `type`: string - Parameter type
1278
- - `indexed`: boolean - Whether parameter is indexed (for events)
1279
- - `components`: AbiParameter[] - Components (for structs/tuples)
1280
-
1281
- ---
1282
-
1283
- ### 4.7 TransactionDescription
1284
-
1285
- **Note**: The API matches ethers.js v6 TransactionDescription.
1286
-
1287
- **Properties**:
1288
- - `name`: string - Function name
1289
- - `signature`: string - Function signature
1290
- - `args`: Result - Decoded arguments
1291
- - `fragment`: FunctionFragment - Function fragment
1292
-
1293
- ---
1294
-
1295
- ### 4.8 LogDescription
1296
-
1297
- **Note**: The API matches ethers.js v6 LogDescription.
1298
-
1299
- **Properties**:
1300
- - `name`: string - Event name
1301
- - `signature`: string - Event signature
1302
- - `args`: Result - Decoded arguments
1303
- - `fragment`: EventFragment - Event fragment
1304
-
1305
- ---
1306
-
1307
- ### 4.9 ErrorFragment
1308
-
1309
- **Extends**: AbiFragment
1310
-
1311
- **Note**: The API matches ethers.js v6 ErrorFragment.
1312
-
1313
- **Additional Properties**:
1314
- - `type`: "error" - Fragment type
1315
-
1316
- **Methods**:
1317
-
1318
- #### `format(format?: string): string`
1319
- Formats fragment as string.
1320
- - `format`: Optional format type
1321
-
1322
- ---
1323
-
1324
- ### 4.10 ErrorDescription
1325
-
1326
- **Note**: The API matches ethers.js v6 ErrorDescription.
1327
-
1328
- **Properties**:
1329
- - `name`: string - Error name
1330
- - `signature`: string - Error signature
1331
- - `args`: Result - Decoded error arguments
1332
- - `fragment`: ErrorFragment - Error fragment
1333
-
1334
- ---
1335
-
1336
- ### 4.11 ConstructorFragment
1337
-
1338
- **Extends**: AbiFragment
1339
-
1340
- **Note**: The API matches ethers.js v6 ConstructorFragment.
1341
-
1342
- **Additional Properties**:
1343
- - `type`: "constructor" - Fragment type
1344
- - `payable`: boolean - Whether constructor is payable
1345
-
1346
- **Methods**:
1347
-
1348
- #### `format(format?: string): string`
1349
- Formats fragment as string.
1350
- - `format`: Optional format type
1351
-
1352
- ---
1353
-
1354
- ### 4.11 ParamType
1355
-
1356
- **Purpose**: Represents a parameter type in an ABI
1357
-
1358
- **Constructor**:
1359
- ```javascript
1360
- constructor(fragment: string | ParamTypeLike)
1361
- ```
1362
- - `fragment`: Type string or ParamType-like object
1363
-
1364
- **Properties**:
1365
- - `type`: string - The base type (e.g., "uint256", "address", "tuple")
1366
- - `baseType`: string - The base type without array or tuple components
1367
- - `name`: string | null - Parameter name (if named)
1368
- - `indexed`: boolean - Whether parameter is indexed (for events)
1369
- - `components`: ParamType[] | null - Components for tuples/structs
1370
- - `arrayLength`: number | null - Array length (null for dynamic arrays)
1371
- - `arrayChildren`: ParamType | null - Type of array elements
1372
-
1373
- **Methods**:
1374
-
1375
- #### `format(format?: string): string`
1376
- Formats the type as a string.
1377
- - `format`: Optional format type ("full", "minimal", etc.)
1378
-
1379
- #### `walk(fn: (type: ParamType) => void): void`
1380
- Recursively walks the type tree, calling fn for each ParamType.
1381
-
1382
- ---
1383
-
1384
- ### 4.13 AbiCoder
1385
-
1386
- **Note**: The API matches ethers.js v6 AbiCoder.
1387
-
1388
- **Purpose**: Low-level ABI encoding and decoding utility
1389
-
1390
- **Constructor**:
1391
- ```javascript
1392
- constructor()
1393
- ```
1394
-
1395
- **Methods**:
1396
-
1397
- #### `encode(types: (string | ParamType)[], values: any[]): string`
1398
- Encodes an array of values according to their types.
1399
- - `types`: Array of type strings or ParamType instances
1400
- - `values`: Array of values to encode
1401
- - Returns: Encoded hex string
1402
- - **Implementation**: Uses `packMethodData()` from quantum-coin-js-sdk internally
1403
-
1404
- #### `decode(types: (string | ParamType)[], data: string, loose?: boolean): Result`
1405
- Decodes encoded data according to types.
1406
- - `types`: Array of type strings or ParamType instances
1407
- - `data`: Encoded hex string
1408
- - `loose`: Optional flag for loose decoding (handles older Solidity padding issues)
1409
- - Returns: Result object with decoded values
1410
- - **Implementation**: Uses `unpackMethodData()` from quantum-coin-js-sdk internally
1411
-
1412
- #### `getDefaultValue(types: (string | ParamType)[]): Result`
1413
- Returns the default values for the given types.
1414
- - `types`: Array of type strings or ParamType instances
1415
- - Returns: Result object with default values for each type
1416
-
1417
- ---
1418
-
1419
- ## 5. Utility Classes and Functions
1420
-
1421
- ### 5.1 Result
1422
-
1423
- **Purpose**: Represents decoded ABI data (array-like object with named properties)
1424
-
1425
- **Extends**: Array
1426
-
1427
- **Properties**:
1428
- - Array indices for positional access
1429
- - Named properties for named parameters
1430
-
1431
- **Static Methods**:
1432
-
1433
- #### `Result.fromItems(items: Array<any>, keys?: Array<null | string>): Result`
1434
- Creates a new Result for items with each entry also accessible by its corresponding name in keys.
1435
- - `items`: Array of values
1436
- - `keys`: Optional array of keys (null for unnamed entries)
1437
- - Returns: Result instance
1438
-
1439
- **Methods**:
1440
-
1441
- #### `getValue(name: string): any`
1442
- Returns the value for name.
1443
- - `name`: Property name
1444
- - Returns: The value for the named property
1445
- - **Note**: This method ensures all named values are accessible even if they conflict with Result methods or JavaScript keywords
1446
-
1447
- #### `toArray(deep?: boolean): any[]`
1448
- Converts to array.
1449
- - `deep`: Optional flag to recursively convert nested Result objects
1450
- - Returns: Normal array
1451
- - **Note**: Throws if there are any outstanding deferred errors
1452
-
1453
- #### `toObject(deep?: boolean): Record<string, any>`
1454
- Converts to object.
1455
- - `deep`: Optional flag to recursively convert nested Result objects
1456
- - Returns: Object with name-value pairs
1457
- - **Note**: Throws if any value is unnamed or if there are outstanding deferred errors
1458
-
1459
- #### `checkResultErrors(result: Result): Array<{ error: Error, path: Array<string | number> }>`
1460
- Returns all errors found in a Result.
1461
- - `result`: Result instance to check
1462
- - Returns: Array of error objects with error and path information
1463
- - **Note**: Certain errors encountered when creating a Result are deferred until accessed. This function allows checking for all errors upfront.
1464
-
1465
- ---
1466
-
1467
- ### 5.2 BytesLike
1468
-
1469
- **Type**: `string | Uint8Array | ArrayLike<number>`
1470
-
1471
- ---
1472
-
1473
- ### 5.3 BigNumberish
1474
-
1475
- **Type**: `string | number | bigint`
1476
-
1477
- ---
1478
-
1479
- ### 5.3.1 AddressLike
1480
-
1481
- **Type**: `string | Promise<string> | Addressable`
1482
-
1483
- **Purpose**: Anything that can be used to return or resolve an address.
1484
-
1485
- **Note**: For QuantumCoin, ENS (Ethereum Naming Service) is not applicable, so address resolution is limited to direct addresses and Addressable objects.
1486
-
1487
- ---
1488
-
1489
- ### 5.3.2 Typed Values
1490
-
1491
- **Purpose**: Typed values provide type-safe encoding and validation for ABI parameters.
1492
-
1493
- #### Typed (Base Class/Interface)
1494
-
1495
- **Purpose**: Base class for all typed values.
1496
-
1497
- **Static Methods**:
1498
-
1499
- #### `Typed.isTyped(value: any): boolean`
1500
- Returns true only if value is a Typed instance.
1501
- - `value`: Value to check
1502
- - Returns: `true` if value is a Typed instance
1503
-
1504
- #### `Typed.dereference(value: Typed | T, type: string): T`
1505
- If the value is a Typed instance, validates the underlying value and returns it, otherwise returns value directly.
1506
- - `value`: Typed instance or value
1507
- - `type`: Expected type string
1508
- - Returns: The underlying value if Typed, otherwise the value itself
1509
- - **Note**: Useful for functions that accept either a Typed object or values
1510
-
1511
- **Methods**:
1512
-
1513
- #### `format(): string`
1514
- Format the type as a Human-Readable type.
1515
- - Returns: Formatted type string
1516
-
1517
- #### `defaultValue(): string | number | bigint | Result`
1518
- The default value returned by this type.
1519
- - Returns: Default value for the type
1520
-
1521
- #### `isBigInt(): boolean`
1522
- Returns true and provides a type guard if this is a TypedBigInt.
1523
- - Returns: `true` if this is a TypedBigInt
1524
-
1525
- #### `isData(): boolean`
1526
- Returns true and provides a type guard if this is a TypedData.
1527
- - Returns: `true` if this is a TypedData
1528
-
1529
- #### `isString(): boolean`
1530
- Returns true and provides a type guard if this is a TypedString.
1531
- - Returns: `true` if this is a TypedString
1532
-
1533
- #### TypedBigInt Interface
1534
-
1535
- **Extends**: Typed
1536
-
1537
- **Purpose**: A Typed that represents a numeric value.
1538
-
1539
- **Properties**:
1540
- - `value`: bigint - The numeric value
1541
-
1542
- **Methods**:
1543
-
1544
- #### `defaultValue(): bigint`
1545
- The default value for all numeric types is 0.
1546
-
1547
- #### `maxValue(): bigint`
1548
- The maximum value for this type, accounting for bit-width.
1549
-
1550
- #### `minValue(): bigint`
1551
- The minimum value for this type, accounting for bit-width and signed-ness.
1552
-
1553
- **Static Methods**: Typed provides static methods for creating typed values:
1554
-
1555
- **Numeric Types**:
1556
- - `Typed.uint8(v: BigNumberish): Typed`
1557
- - `Typed.uint256(v: BigNumberish): Typed`
1558
- - `Typed.int8(v: BigNumberish): Typed`
1559
- - `Typed.int256(v: BigNumberish): Typed`
1560
- - And all other uint/int variants (uint8 through uint256, int8 through int256)
1561
-
1562
- **Other Types**:
1563
- - `Typed.address(v: string): Typed` - Creates a typed address
1564
- - `Typed.bool(v: boolean): Typed` - Creates a typed boolean
1565
- - `Typed.bytes(v: BytesLike, length?: number): Typed` - Creates typed bytes (length optional for dynamic bytes)
1566
- - `Typed.string(v: string): Typed` - Creates a typed string
1567
- - `Typed.array(v: any[], type: string): Typed` - Creates a typed array
1568
- - `Typed.tuple(v: any[], types: string[]): Typed` - Creates a typed tuple
1569
-
1570
- #### TypedData Interface
1571
-
1572
- **Extends**: Typed
1573
-
1574
- **Purpose**: A Typed that represents a binary sequence of data as bytes.
1575
-
1576
- **Properties**:
1577
- - `value`: string - The hex string value
1578
-
1579
- **Methods**:
1580
-
1581
- #### `defaultValue(): string`
1582
- The default value for this type (empty hex string "0x").
1583
-
1584
- #### TypedString Interface
1585
-
1586
- **Extends**: Typed
1587
-
1588
- **Purpose**: A Typed that represents a UTF-8 sequence of bytes.
1589
-
1590
- **Properties**:
1591
- - `value`: string - The string value
1592
-
1593
- **Methods**:
1594
-
1595
- #### `defaultValue(): string`
1596
- The default value for the string type is the empty string (i.e. "").
1597
-
1598
- **Note**: Typed values are primarily used for type-safe ABI encoding. For QuantumCoin, these should work with quantum-coin-js-sdk's ABI encoding functions.
1599
-
1600
- ---
1601
-
1602
- ### 5.3.3 BlockTag
1603
-
1604
- **Type**: `number | "latest" | "pending" | "earliest"`
1605
-
1606
- **Purpose**: Represents a block identifier for queries.
1607
-
1608
- **Values**:
1609
- - `number`: Specific block number
1610
- - `"latest"`: Latest block (default)
1611
- - `"pending"`: Pending block (mempool)
1612
- - `"earliest"`: Earliest block (genesis)
1613
-
1614
- ---
1615
-
1616
- ### 5.3.4 ProviderEventFilter
1617
-
1618
- **Type**: `{ address?: string | string[], topics?: (string | string[] | null)[] }`
1619
-
1620
- **Purpose**: Filter for provider events (blocks, transactions, logs).
1621
-
1622
- **Properties**:
1623
- - `address`: Optional contract address(es) to filter
1624
- - `topics`: Optional event topics to filter
1625
-
1626
- ---
1627
-
1628
- ### 5.3.5 EventFilter
1629
-
1630
- **Type**: `Filter`
1631
-
1632
- **Purpose**: Alias for Filter type, used for event filtering.
1633
-
1634
- **Note**: This is the same as the Filter type defined in Section 1.7.
1635
-
1636
- ---
1637
-
1638
- ### 5.3.6 SigningKey
1639
-
1640
- **Purpose**: Represents a signing key used for cryptographic operations
1641
-
1642
- **Constructor**:
1643
- ```javascript
1644
- constructor(privateKey: string | Uint8Array)
1645
- ```
1646
- - `privateKey`: Private key as hex string or byte array
1647
-
1648
- **Properties**:
1649
- - `privateKey`: string - Private key as hex string
1650
- - `publicKey`: string - Public key
1651
-
1652
- **Methods**:
1653
-
1654
- #### `sign(digest: BytesLike): Signature`
1655
- Signs a message digest.
1656
- - `digest`: Message digest to sign
1657
- - Returns: Signature object
1658
-
1659
- **Note**: SigningKey is used internally by BaseWallet and Wallet for signing operations. Can be created from a private key and used in Wallet constructor. The API matches ethers.js v6 SigningKey.
1660
-
1661
- ---
1662
-
1663
- ### 5.3.7 Signature
1664
-
1665
- **Purpose**: Represents a cryptographic signature
1666
-
1667
- **Properties**:
1668
- - `r`: string - R component of signature (hex string)
1669
- - `s`: string - S component of signature (hex string)
1670
- - `v`: number - Recovery ID (0 or 1)
1671
-
1672
- **Methods**:
1673
-
1674
- #### `serialize(): string`
1675
- Serializes signature to compact format.
1676
- - Returns: Serialized signature hex string
1677
-
1678
- **Static Methods**:
1679
-
1680
- #### `Signature.from(signature: string | SignatureLike): Signature`
1681
- Creates a Signature from various formats.
1682
- - `signature`: Signature string, object, or Signature instance
1683
- - Returns: Signature instance
1684
-
1685
- **Note**: The API matches ethers.js v6 Signature, with QuantumCoin-specific simplifications (removed network-specific fields and legacy conversion methods).
1686
-
1687
- ---
1688
-
1689
- ### 5.3.8 Transaction
1690
-
1691
- **Purpose**: Represents a transaction object
1692
-
1693
- **Type**: Interface/Class
1694
-
1695
- **Properties**:
1696
- - `to`: string | null - Recipient address (null for contract creation)
1697
- - `from`: string | null - Sender address (null if not specified)
1698
- - `nonce`: number | null - Transaction nonce
1699
- - `gasLimit`: bigint | null - Gas limit
1700
- - `gasPrice`: bigint | null - Gas price
1701
- - `value`: bigint | null - Transaction value in wei
1702
- - `data`: string | null - Transaction data (hex string)
1703
- - `chainId`: bigint | null - Chain ID
1704
- - `hash`: string | null - Transaction hash
1705
- - `type`: number | null - Transaction type
1706
- - `accessList`: Array<{ address: string, storageKeys: string[] }> | null - Access list (EIP-2930)
1707
-
1708
- **Methods**:
1709
-
1710
- #### `serialize(): string`
1711
- Serializes transaction to hex string.
1712
- - Returns: Serialized transaction hex string
1713
-
1714
- #### `unsignedHash(): string`
1715
- Computes hash of unsigned transaction.
1716
- - Returns: Transaction hash (32 bytes, 66 hex characters including 0x)
1717
-
1718
- **Static Methods**:
1719
-
1720
- #### `Transaction.from(tx: string | TransactionLike): Transaction`
1721
- Creates a Transaction from various formats.
1722
- - `tx`: Transaction string, object, or Transaction instance
1723
- - Returns: Transaction instance
1724
-
1725
- **Note**: The API matches ethers.js v6 Transaction. For QuantumCoin, transaction structure follows QuantumCoin conventions.
1726
-
1727
- ---
1728
-
1729
- ### 5.3.9 Indexed
1730
-
1731
- **Purpose**: Type guard/interface for indexed event parameters
1732
-
1733
- **Note**: This interface/type is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1734
-
1735
- ---
1736
-
1737
- ### 5.3.9.1 TypedDataEncoder
1738
-
1739
- **Purpose**: Encoder for EIP-712 typed data
1740
-
1741
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1742
-
1743
- **Type**: `{ indexed: true, hash?: string }`
1744
-
1745
- **Purpose**: Used to mark event parameters as indexed. When an event parameter is indexed, it is hashed and stored in the topics array of the log.
1746
-
1747
- **Note**: The API matches ethers.js v6 Indexed type. This is used in event filtering and decoding.
1748
-
1749
- ---
1750
-
1751
- ### 5.3.10 KeystoreAccount
1752
-
1753
- **Type**: `{ address: string, mnemonic?: { entropy: string }, privateKey: string }`
1754
-
1755
- **Purpose**: Contents of a JSON Keystore Wallet
1756
-
1757
- **Properties**:
1758
- - `address`: string - Wallet address
1759
- - `privateKey`: string - Private key as hex string
1760
- - `mnemonic?`: Optional object containing:
1761
- - `entropy`: string - Mnemonic entropy
1762
-
1763
- **Note**: Used by `encryptKeystoreJsonSync()` and `decryptKeystoreJsonSync()` functions. For QuantumCoin, the mnemonic field is optional and may contain entropy for 48-word phrases.
1764
-
1765
- ---
1766
-
1767
- ### 5.4 Address Utilities
1768
-
1769
- #### `isAddress(address: string): boolean`
1770
- Checks if string is a valid address (32 bytes, 66 hex characters).
1771
- - `address`: String to validate
1772
- - Returns: `true` if valid address, `false` otherwise
1773
-
1774
- #### `getAddress(address: string): string`
1775
- Returns checksummed address (normalized for QuantumCoin).
1776
- - `address`: Address string to normalize
1777
- - Returns: Normalized and checksummed address (32 bytes, 66 hex characters)
1778
- - **Note**: For QuantumCoin, address checksumming follows QuantumCoin conventions (not Ethereum EIP-55)
1779
-
1780
- #### `isAddressable(value: any): boolean`
1781
- Returns true if value is an object which implements the Addressable interface.
1782
- - `value`: Value to check
1783
- - Returns: `true` if value implements Addressable interface
1784
- - **Note**: Wallets, Signers, and Contracts implement Addressable
1785
-
1786
- #### `resolveAddress(target: AddressLike): string | Promise<string>`
1787
- Resolves to an address for the target, which may be any supported address type, an Addressable or a Promise which resolves to an address.
1788
- - `target`: Address string, Addressable object, or Promise resolving to address
1789
- - Returns: Address string (synchronously) or Promise resolving to address string
1790
- - **Note**: For QuantumCoin, ENS resolution is not supported. Only direct addresses and Addressable objects are supported.
1791
-
1792
- #### `getContractAddress(tx: { from: string, nonce: number }): string`
1793
- Calculates contract address from deployer and nonce.
1794
- - **Implementation**: Uses `createAddress()` from quantum-coin-js-sdk internally
1795
- - `tx.from`: Deployer address (32 bytes, 66 hex characters)
1796
- - `tx.nonce`: Deployer nonce (number)
1797
- - Returns: Contract address (32 bytes, 66 hex characters)
1798
-
1799
- #### `getCreateAddress(tx: { from: string, nonce: number }): string`
1800
- Gets CREATE address (alias for getContractAddress).
1801
- - `tx.from`: Deployer address
1802
- - `tx.nonce`: Deployer nonce
1803
- - Returns: Contract address
1804
-
1805
- #### `getCreate2Address(from: string, salt: string, initCodeHash: string): string`
1806
- Calculates CREATE2 contract address.
1807
- - **Implementation**: Uses `createAddress2()` from quantum-coin-js-sdk internally
1808
- - `from`: Deployer address (32 bytes, 66 hex characters)
1809
- - `salt`: Salt value (hex string)
1810
- - `initCodeHash`: Hash of initialization code (hex string)
1811
- - Returns: CREATE2 contract address (32 bytes, 66 hex characters)
1812
-
1813
- #### `computeAddress(key: string | Uint8Array): string`
1814
- Computes address from public key.
1815
- - `key`: Public key as hex string or byte array
1816
- - Returns: Computed address (32 bytes, 66 hex characters including 0x)
1817
- - **Implementation**: Uses quantum-coin-js-sdk's `addressFromPublicKey()` internally
1818
-
1819
- #### `verifyMessage(message: string | Uint8Array, signature: string): string`
1820
- Verifies a message signature and recovers the address.
1821
- - `message`: Message that was signed
1822
- - `signature`: Signature to verify (hex string)
1823
- - Returns: Address that signed the message
1824
- - **Implementation**: Uses quantum-coin-js-sdk for signature verification
1825
-
1826
- #### `recoverAddress(message: string | Uint8Array, signature: string): string`
1827
- Recovers the address from a message signature.
1828
- - `message`: Message that was signed
1829
- - `signature`: Signature (hex string)
1830
- - Returns: Address that signed the message
1831
- - **Implementation**: Uses quantum-coin-js-sdk for signature recovery
1832
-
1833
- ### 5.4.1 Addressable Interface
1834
-
1835
- **Purpose**: An interface for objects which have an address, and can resolve it asynchronously.
1836
-
1837
- **Methods**:
1838
-
1839
- #### `getAddress(): Promise<string>`
1840
- Get the object address.
1841
- - Returns: Promise resolving to the address string
1842
-
1843
- **Note**: Wallets, Signers, and Contracts implement this interface, allowing them to be used anywhere an address is expected.
1844
-
1845
- ---
1846
-
1847
- ### 5.5 Encoding/Decoding Utilities
1848
-
1849
- #### `toUtf8String(data: BytesLike): string`
1850
- Converts bytes to UTF-8 string.
1851
-
1852
- #### `toUtf8Bytes(str: string): Uint8Array`
1853
- Converts string to UTF-8 bytes.
1854
-
1855
- #### `toHex(data: BytesLike): string`
1856
- Converts data to hex string.
1857
-
1858
- #### `hexlify(data: BytesLike): string`
1859
- Converts data to hex string (alias for toHex).
1860
-
1861
- #### `arrayify(data: BytesLike): Uint8Array`
1862
- Converts data to byte array.
1863
-
1864
- #### `concat(items: BytesLike[]): string`
1865
- Concatenates byte arrays.
1866
-
1867
- #### `stripZerosLeft(data: BytesLike): string`
1868
- Strips leading zeros from hex string.
1869
-
1870
- #### `encodeBytes32String(text: string): string`
1871
- Encodes text as a Bytes32 string.
1872
- - `text`: Text string to encode
1873
- - Returns: Hex string (32 bytes, 66 hex characters including 0x)
1874
- - **Note**: Text is padded or truncated to exactly 32 bytes
1875
-
1876
- #### `decodeBytes32String(bytes: BytesLike): string`
1877
- Decodes the Bytes32-encoded bytes into a string.
1878
- - `bytes`: Bytes32-encoded data (hex string or bytes)
1879
- - Returns: Decoded text string
1880
- - **Note**: Removes null padding from the decoded string
1881
-
1882
- #### `decodeBase58(data: string): Uint8Array`
1883
- Decodes Base58-encoded data.
1884
-
1885
- **Note**: This function is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1886
-
1887
- ---
1888
-
1889
- #### `decodeBase64(data: string): Uint8Array`
1890
- Decodes Base64-encoded data.
1891
-
1892
- **Note**: This function is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1893
-
1894
- ---
1895
-
1896
- #### `encodeBase58(data: BytesLike): string`
1897
- Encodes data to Base58 string.
1898
-
1899
- **Note**: This function is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1900
-
1901
- ---
1902
-
1903
- #### `encodeBase64(data: BytesLike): string`
1904
- Encodes data to Base64 string.
1905
-
1906
- **Note**: This function is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1907
-
1908
- ---
1909
-
1910
- #### `toUtf8CodePoints(str: string): number[]`
1911
- Converts string to UTF-8 code points array.
1912
-
1913
- **Note**: This function is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
1914
-
1915
- ---
1916
-
1917
- #### `isHexString(value: any, length?: number): boolean`
1918
- Checks if value is a valid hex string.
1919
- - `value`: Value to check
1920
- - `length`: Optional expected length in bytes
1921
- - Returns: `true` if value is a valid hex string, `false` otherwise
1922
-
1923
- #### `isBytesLike(value: any): boolean`
1924
- Checks if value is bytes-like (string, Uint8Array, or ArrayLike<number>).
1925
- - `value`: Value to check
1926
- - Returns: `true` if value is bytes-like, `false` otherwise
1927
-
1928
- #### `zeroPad(value: BytesLike, length: number): string`
1929
- Zero-pads a value to the specified length.
1930
- - `value`: Value to pad
1931
- - `length`: Target length in bytes
1932
- - Returns: Zero-padded hex string
1933
-
1934
- #### `zeroPadValue(value: BytesLike, length: number): string`
1935
- Zero-pads a value to the specified length (left-pads).
1936
- - `value`: Value to pad
1937
- - `length`: Target length in bytes
1938
- - Returns: Zero-padded hex string
1939
-
1940
- #### `solidityPacked(types: string[], values: any[]): string`
1941
- Encodes values using Solidity's packed encoding (no padding, tightly packed).
1942
- - `types`: Array of Solidity type strings
1943
- - `values`: Array of values to encode
1944
- - Returns: Packed encoded hex string
1945
- - **Note**: This is different from ABI encoding - values are tightly packed without padding
1946
-
1947
- #### `solidityPackedKeccak256(types: string[], values: any[]): string`
1948
- Encodes values using Solidity's packed encoding and computes keccak256 hash.
1949
- - `types`: Array of Solidity type strings
1950
- - `values`: Array of values to encode
1951
- - Returns: Keccak256 hash of packed encoding (32 bytes, 66 hex characters including 0x)
1952
-
1953
- #### `solidityPackedSha256(types: string[], values: any[]): string`
1954
- Encodes values using Solidity's packed encoding and computes SHA-256 hash.
1955
- - `types`: Array of Solidity type strings
1956
- - `values`: Array of values to encode
1957
- - Returns: SHA-256 hash of packed encoding (32 bytes, 66 hex characters including 0x)
1958
-
1959
- ---
1960
-
1961
- ### 5.6 BigNumber Utilities
1962
-
1963
- #### `formatUnits(value: BigNumberish, decimals?: number): string`
1964
- Formats value with decimals.
1965
-
1966
- #### `parseUnits(value: string, decimals?: number): bigint`
1967
- Parses value with decimals.
1968
-
1969
- #### `formatEther(value: BigNumberish): string`
1970
- Formats wei to ether (18 decimals).
1971
-
1972
- #### `parseEther(value: string): bigint`
1973
- Parses ether to wei (18 decimals).
1974
-
1975
- ---
1976
-
1977
- ### 5.7 Hash Utilities
1978
-
1979
- #### `keccak256(data: BytesLike): string`
1980
- Computes Keccak-256 hash.
1981
- - `data`: Data to hash
1982
- - Returns: Hex string (32 bytes, 66 hex characters including 0x)
1983
-
1984
- #### `sha256(data: BytesLike): string`
1985
- Computes SHA-256 hash.
1986
- - `data`: Data to hash
1987
- - Returns: Hex string (32 bytes, 66 hex characters including 0x)
1988
-
1989
- #### `ripemd160(data: BytesLike): string`
1990
- Computes RIPEMD-160 hash.
1991
- - `data`: Data to hash
1992
- - Returns: Hex string (20 bytes, 42 hex characters including 0x)
1993
-
1994
- #### `id(text: string): string`
1995
- Creates a keccak256 hash of a string (commonly used for function selectors).
1996
- - `text`: Text string to hash
1997
- - Returns: Hex string (32 bytes, 66 hex characters including 0x)
1998
- - **Note**: This is equivalent to `keccak256(toUtf8Bytes(text))`
1999
-
2000
- #### `sha512(data: BytesLike): string`
2001
- Computes SHA-512 hash.
2002
- - `data`: Data to hash
2003
- - Returns: Hex string (64 bytes, 130 hex characters including 0x)
2004
-
2005
- ---
2006
-
2007
- ### 5.8 Random Utilities
2008
-
2009
- #### `randomBytes(length: number): Uint8Array`
2010
- Generates random bytes.
2011
- - `length`: Number of random bytes to generate
2012
- - Returns: Uint8Array containing random bytes
2013
- - **Implementation**: Uses Node.js `crypto.randomBytes()` for Node.js environments. For browser environments, uses `crypto.getRandomValues()` from the Web Crypto API.
2014
-
2015
- #### `computeHmac(algorithm: string, key: BytesLike, data: BytesLike): string`
2016
- Computes HMAC (Hash-based Message Authentication Code).
2017
- - `algorithm`: Hash algorithm to use (e.g., "sha256", "sha512")
2018
- - `key`: Secret key for HMAC computation
2019
- - `data`: Data to compute HMAC for
2020
- - Returns: HMAC as hex string
2021
- - **Implementation**: Uses Node.js `crypto.createHmac()` for Node.js environments. For browser environments, uses Web Crypto API's `crypto.subtle.sign()` with HMAC algorithm.
2022
- - **Supported algorithms**: "sha256", "sha512" (and other algorithms supported by the underlying crypto implementation)
2023
-
2024
- #### `pbkdf2(password: BytesLike, salt: BytesLike, iterations: number, keylen: number, algorithm?: string): string`
2025
- Derives a key using PBKDF2 (Password-Based Key Derivation Function 2).
2026
- - `password`: Password to derive key from
2027
- - `salt`: Salt value (should be random bytes)
2028
- - `iterations`: Number of iterations (higher is more secure but slower)
2029
- - `keylen`: Desired key length in bytes
2030
- - `algorithm`: Hash algorithm to use (default: "sha256")
2031
- - Returns: Derived key as hex string
2032
- - **Implementation**: Uses Node.js `crypto.pbkdf2Sync()` for Node.js environments. For browser environments, uses Web Crypto API's `crypto.subtle.deriveBits()` with PBKDF2 algorithm.
2033
- - **Note**: This is a synchronous function that may block the event loop for a significant duration depending on the number of iterations.
2034
-
2035
- #### `scrypt(password: BytesLike, salt: BytesLike, N: number, r: number, p: number, dkLen: number): string`
2036
- Derives a key using scrypt key derivation function.
2037
- - `password`: Password to derive key from
2038
- - `salt`: Salt value (should be random bytes)
2039
- - `N`: CPU/memory cost parameter (must be a power of 2, e.g., 16384, 32768)
2040
- - `r`: Block size parameter (typically 8)
2041
- - `p`: Parallelization parameter (typically 1)
2042
- - `dkLen`: Desired key length in bytes
2043
- - Returns: Derived key as hex string
2044
- - **Implementation**: Uses Node.js `crypto.scryptSync()` for Node.js environments. For browser environments, may require a polyfill or WebAssembly implementation as Web Crypto API does not support scrypt natively.
2045
- - **Note**: This is a synchronous function that may block the event loop for a significant duration depending on the parameters (especially N). scrypt is memory-hard and computationally expensive, making it resistant to hardware-accelerated attacks.
2046
-
2047
- #### `scryptSync(password: BytesLike, salt: BytesLike, N: number, r: number, p: number, dkLen: number): string`
2048
- Synchronous version of scrypt key derivation.
2049
-
2050
- **Note**: This function is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference. The `scrypt()` function in quantumcoin.js is already synchronous.
2051
-
2052
- ---
2053
-
2054
- ### 5.9 RLP Encoding
2055
-
2056
- #### `encodeRlp(value: any): string`
2057
- Encodes value using RLP.
2058
-
2059
- #### `decodeRlp(data: string): any`
2060
- Decodes RLP data.
2061
-
2062
- ---
2063
-
2064
- ### 5.10 Provider Utility Functions
2065
-
2066
- #### `copyRequest(req: TransactionRequest): PreparedTransactionRequest`
2067
- Returns a copy of req with all properties coerced to their strict types.
2068
- - `req`: Transaction request to copy
2069
- - Returns: PreparedTransactionRequest with normalized properties
2070
-
2071
- #### `getDefaultProvider(network?: Networkish, options?: any): FallbackProvider`
2072
- Gets default provider.
2073
- - `network`: Optional network identifier
2074
- - `options`: Optional provider options
2075
- - Returns: FallbackProvider instance
2076
-
2077
- #### `showThrottleMessage(): void`
2078
- Shows throttle message.
2079
- - **Note**: Internal utility for rate limiting messages
2080
-
2081
- #### `accessListify(accessList: any[]): Array<{address: string, storageKeys: string[]}>`
2082
- Normalizes access list.
2083
- - `accessList`: Access list to normalize
2084
- - Returns: Normalized access list
2085
-
2086
- ---
2087
-
2088
- ### 5.11 JSON Wallet Utilities
2089
-
2090
- #### `isKeystoreJson(json: string): boolean`
2091
- Returns true if json is a valid JSON Keystore Wallet.
2092
- - `json`: JSON string to validate
2093
- - Returns: `true` if valid keystore JSON, `false` otherwise
2094
-
2095
- #### `encryptKeystoreJsonSync(account: KeystoreAccount, password: string | Uint8Array): string`
2096
- Returns a JSON Keystore Wallet for account encrypted with password (synchronous).
2097
- - `account`: KeystoreAccount object with address, privateKey, and optional mnemonic
2098
- - `password`: Password for encryption
2099
- - Returns: Encrypted JSON Keystore Wallet string
2100
- - **Implementation**: Uses `serializeEncryptedWallet()` from quantum-coin-js-sdk internally
2101
- - **Note**: This method will block the event loop until encryption is complete. Uses default encryption parameters.
2102
-
2103
- #### `decryptKeystoreJsonSync(json: string, password: string | Uint8Array): KeystoreAccount`
2104
- Returns account details for JSON Keystore Wallet using password (synchronous).
2105
- - `json`: JSON Keystore Wallet string
2106
- - `password`: Password for decryption
2107
- - Returns: KeystoreAccount object with address, privateKey, and optional mnemonic
2108
- - **Implementation**: Uses `deserializeEncryptedWallet()` from quantum-coin-js-sdk internally
2109
- - **Note**: This method will block the event loop until decryption is complete, which may take some time.
2110
-
2111
- ---
2112
-
2113
- ### 5.12 Mnemonic
2114
-
2115
- **Purpose**: Wraps all properties required to compute seeds and convert between phrases and entropy
2116
-
2117
- **Properties**:
2118
- - `entropy`: string (read-only) - The underlying entropy which the mnemonic encodes
2119
- - `password`: string (read-only) - The password used for this mnemonic (empty string if no password)
2120
- - `phrase`: string (read-only) - The mnemonic phrase (48 words for QuantumCoin)
2121
- - `wordlist`: Wordlist (read-only) - The wordlist for this mnemonic
2122
- - **Note**: Wordlist is a type representing a list of words used for mnemonic generation. For QuantumCoin, a 48-word wordlist is used. The API matches ethers.js v6 Mnemonic, with QuantumCoin-specific simplifications (removed locale and path fields).
2123
-
2124
- ---
2125
-
2126
- ### 5.13 Wordlist
2127
-
2128
- **Purpose**: Represents a wordlist for mnemonic phrase generation
2129
-
2130
- **Note**: This is an abstract base class/interface. For QuantumCoin, the `seed-words` library (a dependency of quantum-coin-js-sdk) is used internally for wordlist operations.
2131
-
2132
- **Properties**:
2133
- - `locale`: string - Locale identifier for the wordlist
2134
-
2135
- **Methods**:
2136
-
2137
- #### `getWord(index: number): string`
2138
- Returns the word at the specified index.
2139
- - `index`: Word index (0-based)
2140
- - Returns: Word string
2141
-
2142
- #### `getWordIndex(word: string): number`
2143
- Returns the index of the specified word.
2144
- - `word`: Word to find
2145
- - Returns: Word index, or -1 if not found
2146
-
2147
- #### `split(mnemonic: string): Array<string>`
2148
- Splits a mnemonic phrase into individual words.
2149
- - `mnemonic`: Mnemonic phrase string
2150
- - Returns: Array of word strings
2151
-
2152
- #### `join(words: Array<string>): string`
2153
- Joins words into a mnemonic phrase.
2154
- - `words`: Array of word strings
2155
- - Returns: Mnemonic phrase string
2156
-
2157
- **Static Methods**:
2158
-
2159
- #### `Wordlist.check(wordlist: Wordlist): Wordlist`
2160
- Validates a wordlist.
2161
- - `wordlist`: Wordlist instance to validate
2162
- - Returns: Validated wordlist
2163
-
2164
- **Note**: The API matches ethers.js v6 Wordlist. For QuantumCoin, the `seed-words` library is used internally for all wordlist operations, including word lookup, validation, and phrase generation/parsing.
2165
-
2166
- ---
2167
-
2168
- ### 5.14 Number Utilities
2169
-
2170
- #### `fromTwos(value: bigint, width: number): bigint`
2171
- Converts from two's complement.
2172
- - `value`: Value to convert
2173
- - `width`: Bit width
2174
- - Returns: Converted value
2175
-
2176
- #### `toTwos(value: bigint, width: number): bigint`
2177
- Converts to two's complement.
2178
- - `value`: Value to convert
2179
- - `width`: Bit width
2180
- - Returns: Converted value
2181
-
2182
- #### `mask(value: bigint, bits: number): bigint`
2183
- Masks bits.
2184
- - `value`: Value to mask
2185
- - `bits`: Number of bits
2186
- - Returns: Masked value
2187
-
2188
- #### `getBigInt(value: any, name?: string): bigint`
2189
- Gets bigint value.
2190
- - `value`: Value to convert
2191
- - `name`: Optional parameter name for error messages
2192
- - Returns: Bigint value
2193
-
2194
- #### `getUint(value: any, name?: string): number`
2195
- Gets uint value.
2196
- - `value`: Value to convert
2197
- - `name`: Optional parameter name for error messages
2198
- - Returns: Unsigned integer value
2199
-
2200
- #### `getNumber(value: any, name?: string): number`
2201
- Gets number value.
2202
- - `value`: Value to convert
2203
- - `name`: Optional parameter name for error messages
2204
- - Returns: Number value
2205
-
2206
- #### `toBigInt(value: any): bigint`
2207
- Converts to bigint.
2208
- - `value`: Value to convert
2209
- - Returns: Bigint value
2210
-
2211
- #### `toNumber(value: any): number`
2212
- Converts to number.
2213
- - `value`: Value to convert
2214
- - Returns: Number value
2215
-
2216
- #### `toBeHex(value: any, width?: number): string`
2217
- Converts to hex with width.
2218
- - `value`: Value to convert
2219
- - `width`: Optional byte width
2220
- - Returns: Hex string
2221
-
2222
- #### `toBeArray(value: any, width?: number): Uint8Array`
2223
- Converts to array with width.
2224
- - `value`: Value to convert
2225
- - `width`: Optional byte width
2226
- - Returns: Byte array
2227
-
2228
- #### `toQuantity(value: any): string`
2229
- Converts to quantity format.
2230
- - `value`: Value to convert
2231
- - Returns: Quantity string
2232
-
2233
- ---
2234
-
2235
- ### 5.15 Bytes Utilities
2236
-
2237
- #### `getBytes(value: any, name?: string): Uint8Array`
2238
- Gets bytes.
2239
- - `value`: Value to convert
2240
- - `name`: Optional parameter name for error messages
2241
- - Returns: Byte array
2242
-
2243
- #### `getBytesCopy(value: any, name?: string): Uint8Array`
2244
- Gets bytes copy.
2245
- - `value`: Value to convert
2246
- - `name`: Optional parameter name for error messages
2247
- - Returns: Copy of byte array
2248
-
2249
- #### `dataLength(data: BytesLike): number`
2250
- Gets data length.
2251
- - `data`: Data to measure
2252
- - Returns: Length in bytes
2253
-
2254
- #### `dataSlice(data: BytesLike, start: number, end?: number): string`
2255
- Slices data.
2256
- - `data`: Data to slice
2257
- - `start`: Start position
2258
- - `end`: Optional end position
2259
- - Returns: Sliced hex string
2260
-
2261
- #### `zeroPadBytes(data: BytesLike, length: number): string`
2262
- Zero pads bytes.
2263
- - `data`: Data to pad
2264
- - `length`: Target length in bytes
2265
- - Returns: Zero-padded hex string
2266
-
2267
- ---
2268
-
2269
- ### 5.16 Error Utilities
2270
-
2271
- #### `isError(error: any, code?: string): boolean`
2272
- Checks if error with code.
2273
- - `error`: Error to check
2274
- - `code`: Optional error code to match
2275
- - Returns: true if error matches
2276
-
2277
- #### `isCallException(error: any): boolean`
2278
- Checks if call exception.
2279
- - `error`: Error to check
2280
- - Returns: true if call exception
2281
-
2282
- #### `makeError(message: string, code: string, info?: any): Error`
2283
- Makes error.
2284
- - `message`: Error message
2285
- - `code`: Error code
2286
- - `info`: Optional error info
2287
- - Returns: Error instance
2288
-
2289
- ---
2290
-
2291
- ### 5.17 Assertion Utilities
2292
-
2293
- #### `assert(check: boolean, message: string, code: string, info?: any): void`
2294
- Asserts condition.
2295
- - `check`: Condition to check
2296
- - `message`: Error message
2297
- - `code`: Error code
2298
- - `info`: Optional error info
2299
- - Throws: Error if check fails
2300
-
2301
- #### `assertArgument(check: boolean, message: string, name: string, value: any): void`
2302
- Asserts argument.
2303
- - `check`: Condition to check
2304
- - `message`: Error message
2305
- - `name`: Argument name
2306
- - `value`: Argument value
2307
- - Throws: Error if check fails
2308
-
2309
- #### `assertArgumentCount(count: number, expectedCount: number, message: string): void`
2310
- Asserts argument count.
2311
- - `count`: Actual count
2312
- - `expectedCount`: Expected count
2313
- - `message`: Error message
2314
- - Throws: Error if counts don't match
2315
-
2316
- #### `assertNormalize(form: string): void`
2317
- Asserts normalize form.
2318
- - `form`: Form to check
2319
- - Throws: Error if form invalid
2320
-
2321
- #### `assertPrivate(givenGuard: any, guard: symbol, className: string): void`
2322
- Asserts private access.
2323
- - `givenGuard`: Given guard value
2324
- - `guard`: Expected guard symbol
2325
- - `className`: Class name
2326
- - Throws: Error if guard doesn't match
2327
-
2328
- ---
2329
-
2330
- ### 5.18 Other Utilities
2331
-
2332
- #### `resolveProperties(value: Record<string, any>): Promise<Record<string, any>>`
2333
- Resolves properties.
2334
- - `value`: Object with potentially async values
2335
- - Returns: Promise resolving to object with all values resolved
2336
-
2337
- #### `defineProperties(target: any, values: Record<string, any>, types?: Record<string, string>): void`
2338
- Defines properties.
2339
- - `target`: Target object
2340
- - `values`: Property values
2341
- - `types`: Optional property types
2342
-
2343
- #### `lock(value: any): any`
2344
- Locks value.
2345
- - `value`: Value to lock
2346
- - Returns: Locked value
2347
-
2348
- #### `uuidV4(randomBytes: (length: number) => Uint8Array): string`
2349
- Generates UUID v4.
2350
- - `randomBytes`: Random bytes function
2351
- - Returns: UUID v4 string
2352
-
2353
- ---
2354
-
2355
- ### 5.19 Utility Classes (Not Implemented)
2356
-
2357
- The following utility classes are exported from ethers.js but not implemented in quantumcoin.js. They are listed here for API compatibility reference:
2358
-
2359
- #### `FixedNumber`
2360
-
2361
- **Purpose**: Represents fixed-point decimal numbers
2362
-
2363
- **Status**: Implemented in `src/utils/fixednumber.js`. Provides ethers.js v5/v6-compatible fixed-point arithmetic using native `bigint`, including `fromString`, `fromValue`, `fromBytes`, `from`, safe/unsafe/signal arithmetic, comparison, rounding, and format conversion. See `README-SDK.md` for full API documentation.
2364
-
2365
- ---
2366
-
2367
- #### `FetchRequest`
2368
-
2369
- **Purpose**: Represents an HTTP fetch request
2370
-
2371
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
2372
-
2373
- ---
2374
-
2375
- #### `FetchResponse`
2376
-
2377
- **Purpose**: Represents an HTTP fetch response
2378
-
2379
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
2380
-
2381
- ---
2382
-
2383
- #### `FetchCancelSignal`
2384
-
2385
- **Purpose**: Represents a cancellation signal for fetch requests
2386
-
2387
- **Note**: This class is exported from ethers.js but not implemented in quantumcoin.js. It is listed here for API compatibility reference.
2388
-
2389
- ---
2390
-
2391
- **Static Methods**:
2392
-
2393
- #### `Mnemonic.fromEntropy(entropy: BytesLike, password?: null | string, wordlist?: null | Wordlist): Mnemonic`
2394
- Create a new Mnemonic from the entropy.
2395
- - `entropy`: Entropy bytes
2396
- - `password`: Optional password (default: empty string)
2397
- - `wordlist`: Optional wordlist (default: QuantumCoin wordlist)
2398
- - Returns: Mnemonic instance
2399
- - **Note**: For QuantumCoin, the entropy should generate 48-word phrases
2400
-
2401
- #### `Mnemonic.fromPhrase(phrase: string, password?: null | string, wordlist?: null | Wordlist): Mnemonic`
2402
- Creates a new Mnemonic for the phrase.
2403
- - `phrase`: Mnemonic phrase string (48 words for QuantumCoin)
2404
- - `password`: Optional password (default: empty string)
2405
- - `wordlist`: Optional wordlist (default: QuantumCoin wordlist)
2406
- - Returns: Mnemonic instance
2407
-
2408
- #### `Mnemonic.entropyToPhrase(entropy: BytesLike, wordlist?: null | Wordlist): string`
2409
- Returns the phrase for the entropy.
2410
- - `entropy`: Entropy bytes
2411
- - `wordlist`: Optional wordlist (default: QuantumCoin wordlist)
2412
- - Returns: Mnemonic phrase string
2413
-
2414
- #### `Mnemonic.isValidMnemonic(phrase: string, wordlist?: null | Wordlist): boolean`
2415
- Returns true if phrase is a valid mnemonic phrase.
2416
- - `phrase`: Phrase to validate
2417
- - `wordlist`: Optional wordlist (default: QuantumCoin wordlist)
2418
- - Returns: `true` if valid mnemonic, `false` otherwise
2419
- - **Note**: Checks that all words belong to the wordlist, length is valid, and checksum is correct. For QuantumCoin, validates 48-word phrases.
2420
-
2421
- #### `Mnemonic.phraseToEntropy(phrase: string, wordlist?: null | Wordlist): string`
2422
- Returns the entropy for the phrase.
2423
- - `phrase`: Mnemonic phrase string
2424
- - `wordlist`: Optional wordlist (default: QuantumCoin wordlist)
2425
- - Returns: Entropy as hex string
2426
-
2427
- **Methods**:
2428
-
2429
- #### `computeSeed(): string`
2430
- Returns the seed for the mnemonic.
2431
- - Returns: Seed as hex string
2432
- - **Note**: Computes the seed from the mnemonic and password. For QuantumCoin, uses quantum-coin-js-sdk's seed computation.
2433
-
2434
- ---
2435
-
2436
- ## 6. Network and Plugins
2437
-
2438
- ### 6.1 Network
2439
-
2440
- **Purpose**: Encapsulates chain properties and allows plugin extensions
2441
-
2442
- **Note**: The API matches ethers.js v6 Network. All methods, properties, and behavior follow the same patterns as ethers.js v6.
2443
-
2444
- **Constructor**:
2445
- ```javascript
2446
- constructor(name: string, chainId: BigNumberish)
2447
- ```
2448
- - `name`: Network name
2449
- - `chainId`: Chain ID
2450
-
2451
- **Properties**:
2452
- - `name`: string - Network common name
2453
- - `chainId`: bigint - Network chain ID
2454
- - `plugins`: NetworkPlugin[] - Array of attached plugins (read-only)
2455
-
2456
- **Static Methods**:
2457
-
2458
- #### `Network.from(network?: Networkish): Network`
2459
- Returns a new Network for the network name or chainId.
2460
- - `network`: Network name, chainId, or Network object
2461
- - Returns: Network instance
2462
-
2463
- #### `Network.register(nameOrChainId: string | number | bigint, networkFunc: () => Network): void`
2464
- Registers a network name or chainId with a function that returns a Network instance.
2465
- - `nameOrChainId`: Network name or chain ID to register
2466
- - `networkFunc`: Function that returns a Network instance
2467
-
2468
- **Methods**:
2469
-
2470
- #### `attachPlugin(plugin: NetworkPlugin): this`
2471
- Attach a new plugin to this Network.
2472
- - `plugin`: NetworkPlugin instance
2473
- - Returns: this
2474
-
2475
- #### `clone(): Network`
2476
- Create a copy of this Network.
2477
- - Returns: New Network instance
2478
-
2479
- #### `computeIntrinsicGas(tx: TransactionLike): number`
2480
- Compute the intrinsic gas required for a transaction.
2481
- - `tx`: Transaction-like object
2482
- - Returns: Intrinsic gas amount
2483
- - **Note**: A GasCostPlugin can be attached to override default values
2484
-
2485
- #### `getPlugin<T extends NetworkPlugin>(name: string): null | T`
2486
- Return the plugin matching name exactly.
2487
- - `name`: Plugin name
2488
- - Returns: Plugin instance or null
2489
-
2490
- #### `getPlugins<T extends NetworkPlugin>(basename: string): T[]`
2491
- Gets all plugins that match basename (with or without fragment).
2492
- - `basename`: Plugin base name
2493
- - Returns: Array of matching plugins
2494
-
2495
- #### `matches(other: Networkish): boolean`
2496
- Returns true if other matches this network.
2497
- - `other`: Network name, chainId, or Network object
2498
- - Returns: true if chain IDs match (or names match if no chain ID)
2499
-
2500
- #### `toJSON(): any`
2501
- Returns a JSON-compatible representation of the Network.
2502
-
2503
- ---
2504
-
2505
- ### 6.2 Networkish
2506
-
2507
- **Type**: `Network | number | bigint | string | { chainId?: number, name?: string }`
2508
-
2509
- **Purpose**: Anything that can be used to identify or create a Network.
2510
-
2511
- ---
2512
-
2513
- ### 6.3 NetworkPlugin (Base Interface)
2514
-
2515
- **Purpose**: Base interface for network plugins
2516
-
2517
- **Properties**:
2518
- - `name`: string - Plugin name (must be unique per network)
2519
-
2520
- **Note**: All network plugins must implement this interface. Plugins can extend network functionality (gas costs, fee data, etc.).
2521
-
2522
- ---
2523
-
2524
- ### 6.4 GasCostPlugin
2525
-
2526
- **Extends**: NetworkPlugin
2527
-
2528
- **Purpose**: Plugin for computing gas costs
2529
-
2530
- **Properties**:
2531
- - `name`: "org.ethers.plugins.network.GasCost" - Plugin name
2532
- - `txAccessListAddress`: number - Gas cost for access list address
2533
- - `txAccessListStorageKey`: number - Gas cost for access list storage key
2534
- - `txBase`: number - Base transaction gas cost
2535
- - `txCreate`: number - Gas cost for contract creation
2536
- - `txDataNonzero`: number - Gas cost per non-zero data byte
2537
- - `txDataZero`: number - Gas cost per zero data byte
2538
-
2539
- **Methods**:
2540
-
2541
- #### `computeIntrinsicGas(tx: TransactionLike): number`
2542
- Compute the intrinsic gas required for a transaction using plugin parameters.
2543
- - `tx`: Transaction-like object
2544
- - Returns: Intrinsic gas amount
2545
-
2546
- ---
2547
-
2548
- ## 7. Error Classes
2549
-
2550
- ### 7.1 Error
2551
-
2552
- **Base error class**
2553
-
2554
- **Properties**:
2555
- - `message`: string - Error message
2556
- - `code`: string - Error code
2557
- - `data`: any - Error data
2558
-
2559
- ---
2560
-
2561
- ### 7.2 ProviderError
2562
-
2563
- **Extends**: Error
2564
-
2565
- **Additional Properties**:
2566
- - `statusCode`: number - HTTP status code
2567
- - `request`: any - Request object
2568
- - `response`: any - Response object
2569
-
2570
- ---
2571
-
2572
- ### 7.3 TransactionError
2573
-
2574
- **Extends**: Error
2575
-
2576
- **Additional Properties**:
2577
- - `transaction`: TransactionRequest - Transaction that failed
2578
- - `receipt`: TransactionReceipt | null - Transaction receipt (if available)
2579
-
2580
- ---
2581
-
2582
- ### 7.4 ContractError
2583
-
2584
- **Extends**: Error
2585
-
2586
- **Additional Properties**:
2587
- - `contractAddress`: string - Contract address
2588
- - `method`: string - Method name
2589
- - `args`: any[] - Method arguments
2590
-
2591
- ---
2592
-
2593
- ## 8. Provider Types and Interfaces
2594
-
2595
- ### 8.1 PreparedTransactionRequest
2596
-
2597
- **Purpose**: Transaction request with all properties coerced to strict types
2598
-
2599
- **Properties**:
2600
- - `to`: string | null - Recipient address
2601
- - `from`: string - Sender address
2602
- - `value`: bigint - Value in wei
2603
- - `data`: string - Transaction data (hex string)
2604
- - `gasLimit`: bigint - Gas limit
2605
- - `gasPrice`: bigint | null - Gas price
2606
- - `nonce`: number - Transaction nonce
2607
- - `chainId`: number - Chain ID
2608
- - `remarks`: string | null - Optional remarks field
2609
-
2610
- **Note**: Created by `copyRequest(req: TransactionRequest): PreparedTransactionRequest` to normalize a transaction request.
2611
-
2612
- ---
2613
-
2614
- ### 8.2 MinedBlock
2615
-
2616
- **Purpose**: Block that has been mined (extends Block)
2617
-
2618
- **Extends**: Block
2619
-
2620
- **Additional Properties**:
2621
- - All Block properties are guaranteed to be non-null (hash, number, etc.)
2622
-
2623
- **Note**: Type guard for blocks that have been mined. Pending blocks do not satisfy this type.
2624
-
2625
- ---
2626
-
2627
- ### 8.3 MinedTransactionResponse
2628
-
2629
- **Purpose**: Transaction response that has been mined
2630
-
2631
- **Extends**: TransactionResponse
2632
-
2633
- **Additional Properties**:
2634
- - `blockNumber`: number - Block number (guaranteed non-null)
2635
- - `blockHash`: string - Block hash (guaranteed non-null)
2636
-
2637
- **Methods**:
2638
-
2639
- #### `isMined(): boolean`
2640
- Returns true if this transaction has been mined.
2641
- - Returns: true (always true for MinedTransactionResponse)
2642
-
2643
- #### `getBlock(): Promise<Block>`
2644
- Resolves to the Block that this transaction was included in.
2645
- - Returns: Block instance
2646
-
2647
- #### `confirmations(): Promise<number>`
2648
- Resolves to the number of confirmations this transaction has.
2649
- - Returns: Number of confirmations
2650
-
2651
- **Note**: Type guard for transactions that have been included in a block.
2652
-
2653
- ---
2654
-
2655
- ### 8.4 FeeData
2656
-
2657
- **Purpose**: Represents fee data for transactions
2658
-
2659
- **Constructor**:
2660
- ```javascript
2661
- constructor(gasPrice: bigint | null)
2662
- ```
2663
- - `gasPrice`: Legacy gas price
2664
-
2665
- **Properties**:
2666
- - `gasPrice`: bigint | null - Gas price
2667
-
2668
- **Methods**:
2669
-
2670
- #### `toJSON(): any`
2671
- Converts to JSON.
2672
- - Returns: JSON representation of FeeData
2673
-
2674
- **Note**: For QuantumCoin, only `gasPrice` is used (EIP-1559 style transactions are not applicable).
2675
-
2676
- ---
2677
-
2678
- ### 8.5 WebSocketLike
2679
-
2680
- **Purpose**: Interface for WebSocket-like objects
2681
-
2682
- **Properties**:
2683
- - `readyState`: number - Connection state (0 = CONNECTING, 1 = OPEN, 2 = CLOSING, 3 = CLOSED)
2684
- - `onopen`: ((event: any) => void) | null - Open event handler
2685
- - `onmessage`: ((event: any) => void) | null - Message event handler
2686
- - `onerror`: ((event: any) => void) | null - Error event handler
2687
-
2688
- **Methods**:
2689
-
2690
- #### `send(payload: any): void`
2691
- Sends data through the WebSocket.
2692
- - `payload`: Data to send
2693
-
2694
- #### `close(code?: number, reason?: string): void`
2695
- Closes the WebSocket connection.
2696
- - `code`: Optional close code
2697
- - `reason`: Optional close reason
2698
-
2699
- **Note**: Generic interface for WebSocket compatibility, allowing different WebSocket implementations to be used.
2700
-
2701
- ---
2702
-
2703
- ### 8.6 ProviderEvent
2704
-
2705
- **Type**: `string | Array<string | Array<string>> | EventFilter | FilterByBlockHash`
2706
-
2707
- **Purpose**: Type for provider events that can be subscribed to
2708
-
2709
- **Values**:
2710
- - `"block"` - Emitted on each new block with block number
2711
- - `"error"` - Emitted on async errors
2712
- - `"debug"` - Emitted on debug events
2713
- - Transaction hash (string) - Emitted when transaction is mined
2714
- - Array of topics - Emitted on matching logs
2715
- - EventFilter - Emitted on matching logs
2716
- - FilterByBlockHash - Emitted on matching logs in specific block
2717
-
2718
- **Note**: Each provider may support additional event types.
2719
-
2720
- ---
2721
-
2722
- ### 8.7 TopicFilter
2723
-
2724
- **Type**: `Array<null | string | Array<string>>`
2725
-
2726
- **Purpose**: Structure for bloom-filter queries on event topics
2727
-
2728
- **Description**:
2729
- - Each field can be:
2730
- - `null` - Matches any value
2731
- - `string` - Must match exactly that value
2732
- - `Array<string>` - OR match (any one of those values must match)
2733
-
2734
- **Example**:
2735
- ```javascript
2736
- // Match any event from address 0x... with topic[0] = "0x123..." and any topic[1]
2737
- ["0x123...", null]
2738
-
2739
- // Match events with topic[0] = "0x123..." OR "0x456..."
2740
- [["0x123...", "0x456..."], null]
2741
- ```
2742
-
2743
- ---
2744
-
2745
- ## 9. Provider Interface
2746
-
2747
- ### 9.1 Provider (Abstract Base Class)
2748
-
2749
- **Properties**:
2750
- - `chainId`: Promise<number> - Chain ID
2751
-
2752
- **Methods**:
2753
-
2754
- #### `getBlockNumber(): Promise<number>`
2755
- Returns latest block number.
2756
-
2757
- #### `getBlock(blockNumber: number | string): Promise<Block>`
2758
- Returns block information.
2759
-
2760
- #### `getTransaction(txHash: string): Promise<TransactionResponse>`
2761
- Returns transaction.
2762
-
2763
- #### `getTransactionReceipt(txHash: string): Promise<TransactionReceipt>`
2764
- Returns transaction receipt.
2765
-
2766
- #### `getBalance(address: string, blockTag?: string): Promise<bigint>`
2767
- Returns balance.
2768
-
2769
- #### `getTransactionCount(address: string, blockTag?: string): Promise<number>`
2770
- Returns nonce.
2771
-
2772
- #### `sendTransaction(tx: string | TransactionRequest): Promise<TransactionResponse>`
2773
- Sends transaction.
2774
- - Note: If `tx` is a TransactionRequest, the `remarks` field is optional and can be used to include a comment (max 32 bytes). Do not store sensitive information in remarks.
2775
-
2776
- #### `call(tx: TransactionRequest, blockTag?: string): Promise<string>`
2777
- Executes call.
2778
-
2779
- #### `estimateGas(tx: TransactionRequest): Promise<bigint>`
2780
- Estimates gas.
2781
-
2782
- #### `getCode(address: string, blockTag?: string): Promise<string>`
2783
- Returns contract code.
2784
-
2785
- #### `getStorageAt(address: string, position: bigint, blockTag?: string): Promise<string>`
2786
- Returns storage value.
2787
-
2788
- #### `getLogs(filter: Filter): Promise<Log[]>`
2789
- Returns logs.
2790
-
2791
- #### `on(event: string, callback: Function): void`
2792
- Subscribes to events.
2793
-
2794
- #### `once(event: string, callback: Function): void`
2795
- Subscribes to event once.
2796
-
2797
- #### `removeListener(event: string, callback: Function): void`
2798
- Removes listener.
2799
-
2800
- #### `removeAllListeners(event?: string): void`
2801
- Removes all listeners.
2802
-
2803
- ---
2804
-
2805
- ## 9. Provider Interface
2806
-
2807
- ### 9.1 Provider (Abstract Base Class)
2808
-
2809
- **Purpose**: Abstract base class for blockchain providers
2810
-
2811
- **Note**: The API matches ethers.js v6 Provider. All methods, properties, and behavior follow the same patterns as ethers.js v6.
2812
-
2813
- **Properties**:
2814
- - `chainId`: Promise<number> - Chain ID
2815
- - `network: Network` - Network instance (read-only)
2816
- - `ready: Promise<Network>` - Promise that resolves when provider is ready
2817
-
2818
- **Methods**:
2819
-
2820
- #### `getBlockNumber(): Promise<number>`
2821
- Returns latest block number.
2822
-
2823
- #### `getBlock(blockTag: string | number): Promise<Block | null>`
2824
- Returns block information.
2825
-
2826
- #### `getTransaction(txHash: string): Promise<TransactionResponse | null>`
2827
- Returns transaction.
2828
-
2829
- #### `getTransactionReceipt(txHash: string): Promise<TransactionReceipt | null>`
2830
- Returns transaction receipt.
2831
-
2832
- #### `getBalance(address: string, blockTag?: string): Promise<bigint>`
2833
- Returns balance.
2834
-
2835
- #### `getTransactionCount(address: string, blockTag?: string): Promise<number>`
2836
- Returns nonce.
2837
-
2838
- #### `call(tx: TransactionRequest, blockTag?: string): Promise<string>`
2839
- Executes a call without creating a transaction.
2840
- - `tx`: Transaction request
2841
- - `blockTag`: Optional block tag
2842
- - Returns: Result data as hex string
2843
-
2844
- #### `estimateGas(tx: TransactionRequest): Promise<bigint>`
2845
- Estimates gas for a transaction.
2846
- - `tx`: Transaction request
2847
- - Returns: Estimated gas amount
2848
-
2849
- #### `getTransactionResult(txHash: string): Promise<null | string>`
2850
- Gets the result of a transaction execution.
2851
- - `txHash`: Transaction hash
2852
- - Returns: Result data or null if transaction failed
2853
-
2854
- #### `getNetwork(): Promise<Network>`
2855
- Gets network information.
2856
- - Returns: Network instance
2857
-
2858
- #### `getFeeData(): Promise<FeeData>`
2859
- Gets fee data (gas prices).
2860
- - Returns: FeeData instance
2861
-
2862
- #### `broadcastTransaction(signedTx: string): Promise<TransactionResponse>`
2863
- Broadcasts a signed transaction.
2864
- - `signedTx`: Signed transaction hex string
2865
- - Returns: TransactionResponse
2866
-
2867
- #### `waitForTransaction(txHash: string, confirms?: number, timeout?: number): Promise<TransactionReceipt>`
2868
- Waits for transaction confirmation.
2869
- - `txHash`: Transaction hash
2870
- - `confirms`: Optional number of confirmations to wait for
2871
- - `timeout`: Optional timeout in milliseconds
2872
- - Returns: TransactionReceipt
2873
-
2874
- **Note**: Both Provider and Signer implement this interface, allowing them to be used interchangeably for contract calls and gas estimation.
2875
-
2876
- ---
2877
-
2878
- ### 9.2 ContractRunner (Abstract Base Class/Interface)
2879
-
2880
- **Purpose**: Interface for contract execution (implemented by Provider and Signer)
2881
-
2882
- **Note**: The API matches ethers.js v6 ContractRunner. All methods, properties, and behavior follow the same patterns as ethers.js v6.
2883
-
2884
- **Properties**:
2885
- - `provider`: Provider | null - Provider instance
2886
-
2887
- **Methods**:
2888
-
2889
- #### `call(tx: TransactionRequest, blockTag?: string): Promise<string>`
2890
- Executes a call without creating a transaction.
2891
- - `tx`: Transaction request
2892
- - `blockTag`: Optional block tag
2893
- - Returns: Result data as hex string
2894
-
2895
- #### `estimateGas(tx: TransactionRequest): Promise<bigint>`
2896
- Estimates gas for a transaction.
2897
- - `tx`: Transaction request
2898
- - Returns: Estimated gas amount
2899
-
2900
- #### `getTransactionResult(txHash: string): Promise<null | string>`
2901
- Gets the result of a transaction execution.
2902
- - `txHash`: Transaction hash
2903
- - Returns: Result data or null if transaction failed
2904
-
2905
- **Note**: Both Provider and Signer implement this interface, allowing them to be used interchangeably for contract calls and gas estimation.
2906
-
2907
- ---
2908
-
2909
- ### 9.3 Signer (Abstract Base Class)
2910
-
2911
- **Note**: The API matches ethers.js v6 Signer. All methods, properties, and behavior follow the same patterns as ethers.js v6, except `signMessage()` is replaced with `signMessageSync()` for synchronous operation.
2912
-
2913
- **Properties**:
2914
- - `provider`: Provider | null - Provider instance
2915
- - `address: string` - Signer address (read-only)
2916
-
2917
- **Methods**:
2918
-
2919
- #### `getAddress(): Promise<string>`
2920
- Returns signer address.
2921
-
2922
- #### `getBalance(blockTag?: string): Promise<bigint>`
2923
- Returns balance.
2924
-
2925
- #### `getTransactionCount(blockTag?: string): Promise<number>`
2926
- Returns nonce.
2927
-
2928
- #### `sendTransaction(tx: TransactionRequest): Promise<TransactionResponse>`
2929
- Signs and sends transaction.
2930
- - Note: The `remarks` field in TransactionRequest is optional and can be used to include a comment (max 32 bytes). Do not store sensitive information in remarks.
2931
-
2932
- #### `signTransaction(tx: TransactionRequest): Promise<string>`
2933
- Signs transaction.
2934
- - Note: The `remarks` field in TransactionRequest is optional and can be used to include a comment (max 32 bytes). Do not store sensitive information in remarks.
2935
-
2936
- #### `signMessageSync(message: string | Uint8Array): string`
2937
- Signs message (synchronous).
2938
- - `message`: Message to sign (string or bytes)
2939
- - Returns: Signature string
2940
-
2941
- #### `connect(provider: Provider): Signer`
2942
- Connects to provider.
2943
-
2944
- #### `populateTransaction(tx: TransactionRequest): Promise<TransactionRequest>`
2945
- Populates transaction with defaults.
2946
- - `tx`: Transaction request
2947
- - Returns: Populated transaction request
2948
-
2949
- #### `populateCall(tx: TransactionRequest): Promise<TransactionRequest>`
2950
- Populates call transaction.
2951
- - `tx`: Transaction request
2952
- - Returns: Populated call transaction request
2953
-
2954
- #### `call(tx: TransactionRequest, blockTag?: BlockTag): Promise<string>`
2955
- Executes a call without creating a transaction.
2956
- - `tx`: Transaction request
2957
- - `blockTag`: Optional block tag
2958
- - Returns: Result data as hex string
2959
-
2960
- #### `estimateGas(tx: TransactionRequest): Promise<bigint>`
2961
- Estimates gas for a transaction.
2962
- - `tx`: Transaction request
2963
- - Returns: Estimated gas amount
2964
-
2965
- ---
2966
-
2967
- ## 10. Implementation Requirements
2968
-
2969
- ### 10.1 Quantum-Coin-JS-SDK Integration
2970
-
2971
- All implementations must use quantum-coin-js-sdk for:
2972
-
2973
- 1. **Address Validation**: Use `isAddressValid()` from quantum-coin-js-sdk
2974
- 2. **ABI Encoding/Decoding**: Use `packMethodData()` and `unpackMethodData()` from quantum-coin-js-sdk
2975
- 3. **Event Log Encoding/Decoding**: Use `encodeEventLog()` and `decodeEventLog()` from quantum-coin-js-sdk
2976
- 4. **Transaction Signing**: Use `signRawTransaction()` from quantum-coin-js-sdk (supports `remarks` field via TransactionSigningRequest)
2977
- 5. **Contract Address Calculation**: Use `createAddress()` and `createAddress2()` from quantum-coin-js-sdk
2978
- 6. **Wallet Operations**: Use Wallet class from quantum-coin-js-sdk for private key management
2979
- 7. **Wallet Address Derivation**: Use `publicKeyFromPrivateKey()` and `addressFromPublicKey()` from quantum-coin-js-sdk to derive the public key and address from the private key in the Wallet constructor
2980
- 8. **Random Wallet Creation**: Use `newWallet()` from quantum-coin-js-sdk in `Wallet.createRandom()` static method
2981
- 9. **Encrypted Wallet Deserialization**: Use `deserializeEncryptedWallet()` from quantum-coin-js-sdk in `Wallet.fromEncryptedJsonSync()` static method
2982
- 10. **Encrypted Wallet Serialization**: Use `serializeEncryptedWallet()` from quantum-coin-js-sdk in `Wallet.encryptSync()` instance method
2983
- 11. **Seed Words Wallet Creation**: Use `openWalletFromSeedWords()` from quantum-coin-js-sdk in `Wallet.fromPhrase()` static method (48 words required)
2984
- 12. **RPC Calls**: Use quantum-coin-js-sdk RPC functions (getAccountDetails, getTransactionDetails, etc.)
2985
- 13. **Transaction Remarks**: The `remarks` field is passed through to quantum-coin-js-sdk's TransactionSigningRequest.remarks field (optional, max 32 bytes, hex string with 0x prefix)
2986
- 14. **Transaction Signing Context**: The `signingContext` field is passed through to quantum-coin-js-sdk's TransactionSigningRequest.signingContext (optional, number | null; default null). Values 0, 1, 2 select the cryptographic scheme; null lets the SDK derive from wallet key type.
2987
-
2988
- **SDK Source Reference (for implementers)**:
2989
- - The `quantum-coin-js-sdk` code can be found under `node_modules/quantum-coin-js-sdk/`.
2990
- - The SDK entrypoint and the `initialize(...)` function can be found in `node_modules/quantum-coin-js-sdk/index.js`.
2991
-
2992
- ### 10.2 Built-in Libraries Only
2993
-
2994
- Use only built-in JavaScript/Node.js libraries:
2995
- - `crypto` - For hashing (SHA-256, RIPEMD-160), random bytes
2996
- - `Buffer` - For byte manipulation
2997
- - `http`/`https` - For RPC requests (if not using quantum-coin-js-sdk RPC)
2998
- - `util` - For utility functions
2999
- - `events` - For event emitters
3000
-
3001
- ### 10.3 Address Format Handling
3002
-
3003
- - All addresses must be validated as 32 bytes (66 hex characters including 0x)
3004
- - Address normalization should use quantum-coin-js-sdk validation
3005
- - Address checksumming (if applicable) should follow QuantumCoin conventions
3006
-
3007
- ### 10.4 Error Handling
3008
-
3009
- - All errors should extend appropriate error classes
3010
- - Error messages should be clear and descriptive
3011
- - Error codes should follow ethers.js patterns where applicable
3012
-
3013
- ### 10.5 Event Handling
3014
-
3015
- - Use Node.js EventEmitter for event subscriptions
3016
- - Support block events, transaction events, and contract events
3017
- - Implement proper cleanup for event listeners
3018
-
3019
- ### 10.6 Transaction Handling
3020
-
3021
- - Support both legacy and EIP-1559 style transactions (if applicable)
3022
- - Handle gas estimation and pricing
3023
- - Support transaction replacement (nonce management)
3024
- - Implement proper transaction confirmation waiting
3025
- - Support `remarks` field in transactions (optional, max 32 bytes, public on blockchain)
3026
- - Validate remarks field: must be hex string with 0x prefix, max 32 bytes when decoded
3027
- - Use quantum-coin-js-sdk's `signRawTransaction()` which accepts `remarks` and `signingContext` in TransactionSigningRequest
3028
-
3029
- ### 10.7 ABI Handling
3030
-
3031
- - Support all Solidity types (as defined in types.js)
3032
- - Handle complex types (arrays, structs, tuples)
3033
- - Support function overloading
3034
- - Support indexed and non-indexed event parameters
3035
-
3036
- ### 10.8 Async/Await Pattern
3037
-
3038
- - All provider methods should return Promises
3039
- - Use async/await throughout
3040
- - Handle errors with try/catch
3041
-
3042
- ### 10.9 Type Safety
3043
-
3044
- - Use JSDoc for type annotations
3045
- - Provide clear parameter and return type documentation
3046
- - Validate inputs at runtime
3047
-
3048
- ---
3049
-
3050
- ## 11. File Structure
3051
-
3052
- ```
3053
- quantumcoin.js/
3054
- ├── src/
3055
- │ ├── providers/
3056
- │ │ ├── provider.js # Base Provider class
3057
- │ │ ├── json-rpc-provider.js # JsonRpcProvider
3058
- │ │ └── index.js
3059
- │ ├── wallet/
3060
- │ │ ├── wallet.js # Wallet class
3061
- │ │ └── index.js
3062
- │ ├── contract/
3063
- │ │ ├── contract.js # Contract class
3064
- │ │ ├── contract-factory.js # ContractFactory
3065
- │ │ └── index.js
3066
- │ ├── abi/
3067
- │ │ ├── interface.js # Interface class
3068
- │ │ ├── fragments.js # Fragment classes
3069
- │ │ └── index.js
3070
- │ ├── utils/
3071
- │ │ ├── address.js # Address utilities
3072
- │ │ ├── encoding.js # Encoding utilities
3073
- │ │ ├── hashing.js # Hash utilities
3074
- │ │ ├── units.js # Unit conversion
3075
- │ │ └── index.js
3076
- │ ├── errors/
3077
- │ │ ├── index.js # Error classes
3078
- │ │ └── ...
3079
- │ └── index.js # Main entry point
3080
- ├── test/
3081
- │ ├── unit/ # Unit tests (no blockchain connectivity)
3082
- │ ├── integration/ # Integration tests (read-only blockchain)
3083
- │ ├── e2e/ # End-to-end tests (write access)
3084
- │ ├── security/ # Security tests (malformed input, etc.)
3085
- │ └── fixtures/ # Test fixtures and data
3086
- ├── config.js # Existing config
3087
- └── package.json
3088
- ```
3089
-
3090
- ---
3091
-
3092
- ## 12. Example Usage Patterns
3093
-
3094
- ### 12.1 Provider Usage
3095
-
3096
- ```javascript
3097
- const { JsonRpcProvider } = require('quantumcoin');
3098
- const provider = new JsonRpcProvider('https://public.rpc.quantumcoinapi.com', 123123);
3099
-
3100
- const balance = await provider.getBalance('0x...');
3101
- const blockNumber = await provider.getBlockNumber();
3102
- ```
3103
-
3104
- ### 12.2 Wallet Usage
3105
-
3106
- ```javascript
3107
- const { Wallet } = require('quantumcoin');
3108
-
3109
- // Create wallet from private key
3110
- const wallet = new Wallet('0x...privateKey...', provider);
3111
-
3112
- // Create random wallet
3113
- const randomWallet = Wallet.createRandom(provider);
3114
-
3115
- // Create wallet from encrypted JSON
3116
- const encryptedJson = '{"address":"...","crypto":{...}}';
3117
- const walletFromJson = Wallet.fromEncryptedJsonSync(encryptedJson, 'password123', provider);
3118
-
3119
- // Create wallet from seed phrase (48 words) - can be array or string
3120
- const seedPhraseArray = ['word1', 'word2', ..., 'word48'];
3121
- const walletFromPhrase1 = Wallet.fromPhrase(seedPhraseArray, provider);
3122
-
3123
- // Or as a space or comma delimited string
3124
- const seedPhraseString = 'word1 word2 ... word48'; // or 'word1,word2,...,word48'
3125
- const walletFromPhrase2 = Wallet.fromPhrase(seedPhraseString, provider);
3126
-
3127
- // Encrypt wallet to JSON string (instance method)
3128
- const encryptedJson = wallet.encryptSync('mySecurePassword123');
3129
- // Can be saved to file and opened in Desktop/Mobile/Web/CLI wallet applications
3130
-
3131
- // Sign message synchronously
3132
- const signature = wallet.signMessageSync('Hello, QuantumCoin!');
3133
-
3134
- const tx = await wallet.sendTransaction({
3135
- to: '0x...',
3136
- value: parseEther('1.0')
3137
- });
3138
- ```
3139
-
3140
- ### 12.3 Contract Usage
3141
-
3142
- ```javascript
3143
- const { Contract } = require('quantumcoin');
3144
- const abi = [...]; // ABI array
3145
- const contract = new Contract('0x...', abi, provider);
3146
-
3147
- const result = await contract.balanceOf('0x...');
3148
- const tx = await contract.transfer('0x...', parseEther('1.0'));
3149
- ```
3150
-
3151
- ### 12.4 Contract Deployment
3152
-
3153
- ```javascript
3154
- const { ContractFactory } = require('quantumcoin');
3155
- const factory = new ContractFactory(abi, bytecode, wallet);
3156
- const contract = await factory.deploy(...args);
3157
- ```
3158
-
3159
- ---
3160
-
3161
- ## 13. Testing Requirements
3162
-
3163
- ### 13.1 Test Organization
3164
-
3165
- Tests should be organized into the following folders:
3166
- - **`test/unit/`**: Unit tests that don't require blockchain connectivity
3167
- - **`test/integration/`**: Integration tests that require read-only blockchain connectivity
3168
- - **`test/e2e/`**: End-to-end tests that require write access (sending transactions)
3169
- - **`test/security/`**: Security tests with malformed input, edge cases, and attack vectors
3170
-
3171
- ### 13.2 Test Metadata
3172
-
3173
- Each test file must include metadata to specify test categories:
3174
-
3175
- ```javascript
3176
- /**
3177
- * @testCategory unit|integration|e2e|security
3178
- * @blockchainRequired false|readonly|write
3179
- * @description Brief description of what this test suite covers
3180
- */
3181
- ```
3182
-
3183
- **Test Categories:**
3184
- - **`unit`**: Tests that don't need blockchain connectivity (pure functions, utilities, encoding/decoding, etc.)
3185
- - **`integration`**: Tests that need read-only blockchain connectivity (querying blocks, transactions, contract reads, etc.)
3186
- - **`e2e`**: Tests that need write access (sending transactions, deploying contracts, etc.)
3187
- - **`security`**: Tests for security vulnerabilities, malformed input, edge cases, etc.
3188
-
3189
- **Blockchain Requirements:**
3190
- - **`false`**: No blockchain connectivity needed
3191
- - **`readonly`**: Read-only blockchain access (queries only)
3192
- - **`write`**: Write access required (sending transactions)
3193
-
3194
- ### 13.3 Test Configuration
3195
-
3196
- **RPC Endpoint**: `https://public.rpc.quantumcoinapi.com`
3197
- **Chain ID**: `123123`
3198
-
3199
- **Test Data Requirements:**
3200
- - For block-related tests: Use block numbers greater than `3000000`
3201
- - For transaction read-only tests: Use transactions between blocks `3385844` to `3387473` (inclusive)
3202
- - For smart contract read-only tests:
3203
- - Contract Address: `0x0000000000000000000000000000000000000000000000000000000000001000`
3204
- - ABI: Available at `https://raw.githubusercontent.com/quantumcoinproject/quantum-coin-go/refs/heads/dogep/systemcontracts/staking/stakingv2/StakingContract.abi`
3205
-
3206
- ### 13.4 Test Coverage Requirements
3207
-
3208
- #### 13.4.1 Comprehensive Test Coverage
3209
-
3210
- All tests must include:
3211
- - **Positive test cases**: Valid inputs and expected successful outcomes
3212
- - **Negative test cases**: Invalid inputs, error conditions, and edge cases
3213
- - **Optional parameter coverage**: Tests must cover all combinations of optional parameters to achieve 100% code coverage of the SDK
3214
- - Test with all optional parameters provided
3215
- - Test with no optional parameters (using defaults)
3216
- - Test with partial optional parameters (various combinations)
3217
-
3218
- #### 13.4.2 Unit Tests (No Blockchain Connectivity)
3219
-
3220
- Test areas:
3221
- - Address validation and conversion (32-byte addresses)
3222
- - Encoding/decoding utilities
3223
- - Hash functions
3224
- - Unit conversions
3225
- - Error classes and error handling
3226
- - Wallet creation and management (without sending transactions)
3227
- - Message signing (offline)
3228
- - ABI parsing and fragment handling
3229
- - Data encoding/decoding
3230
-
3231
- #### 13.4.3 Integration Tests (Read-Only Blockchain)
3232
-
3233
- Test areas:
3234
- - Provider initialization and connection
3235
- - Block queries (`getBlock`, `getBlockNumber`, etc.)
3236
- - Transaction queries (`getTransaction`, `getTransactionReceipt`, etc.)
3237
- - Balance queries (`getBalance`)
3238
- - Contract read operations (using the staking contract at `0x0000000000000000000000000000000000000000000000000000000000001000`)
3239
- - Event filtering and querying (read-only)
3240
- - Log queries
3241
- - Gas estimation (read-only operation)
3242
- - Network information queries
3243
-
3244
- **Test Data:**
3245
- - Blocks: Use block numbers > 3000000
3246
- - Transactions: Use transactions from blocks 3385844 to 3387473
3247
- - Contract: Use staking contract at `0x0000000000000000000000000000000000000000000000000000000000001000`
3248
-
3249
- #### 13.4.4 End-to-End Tests (Write Access)
3250
-
3251
- Test areas:
3252
- - Sending standard transactions
3253
- - Contract deployment
3254
- - Contract write operations
3255
- - Transaction confirmation and receipt handling
3256
- - Event listening and subscription
3257
- - Transaction replacement and cancellation
3258
-
3259
- **Test Wallet:**
3260
- - A hardcoded test wallet must be included in test files for sending transactions
3261
- - The test wallet should have sufficient balance for testing
3262
- - Private key should be stored securely in test configuration (not committed to version control in production)
3263
-
3264
- **IERC20 Contract Tests:**
3265
- - Deploy a standard IERC20 contract
3266
- - Test all IERC20 operations:
3267
- - `transfer(to, amount)`
3268
- - `transferFrom(from, to, amount)`
3269
- - `approve(spender, amount)`
3270
- - `balanceOf(account)`
3271
- - `allowance(owner, spender)`
3272
- - `totalSupply()`
3273
- - Test events: `Transfer`, `Approval`
3274
- - Test with various parameter combinations and optional parameters
3275
-
3276
- #### 13.4.5 Security Tests
3277
-
3278
- Test areas:
3279
- - **Malformed input handling**:
3280
- - Invalid addresses (wrong length, invalid characters, etc.)
3281
- - Invalid transaction data
3282
- - Invalid ABI formats
3283
- - Invalid block numbers and tags
3284
- - Invalid hex strings
3285
- - Invalid numeric values (negative, overflow, etc.)
3286
- - **Edge cases**:
3287
- - Empty strings and null/undefined values
3288
- - Very large numbers (overflow scenarios)
3289
- - Zero values
3290
- - Boundary conditions
3291
- - **Attack vectors**:
3292
- - SQL injection attempts in string parameters
3293
- - Buffer overflow attempts
3294
- - Reentrancy scenarios (where applicable)
3295
- - Invalid signature handling
3296
- - Invalid transaction replay attempts
3297
-
3298
- ### 13.5 Code Coverage Goal
3299
-
3300
- The test suite must achieve **100% code coverage** of the SDK. This includes:
3301
- - All public methods
3302
- - All private/internal methods
3303
- - All error paths
3304
- - All optional parameter combinations
3305
- - All conditional branches
3306
- - All edge cases
3307
-
3308
- ### 13.6 Test Examples
3309
-
3310
- #### Example: Unit Test Structure
3311
-
3312
- ```javascript
3313
- /**
3314
- * @testCategory unit
3315
- * @blockchainRequired false
3316
- * @description Tests for address utilities
3317
- */
3318
- describe('Address Utilities', () => {
3319
- describe('isAddress', () => {
3320
- it('should return true for valid 32-byte address', () => {
3321
- // Positive test case
3322
- });
3323
-
3324
- it('should return false for invalid address', () => {
3325
- // Negative test case
3326
- });
3327
-
3328
- it('should handle optional checksum parameter', () => {
3329
- // Optional parameter test
3330
- });
3331
- });
3332
- });
3333
- ```
3334
-
3335
- #### Example: Integration Test Structure
3336
-
3337
- ```javascript
3338
- /**
3339
- * @testCategory integration
3340
- * @blockchainRequired readonly
3341
- * @description Tests for block queries
3342
- */
3343
- describe('Block Queries', () => {
3344
- const provider = new JsonRpcProvider('https://public.rpc.quantumcoinapi.com', 123123);
3345
-
3346
- describe('getBlock', () => {
3347
- it('should get block by number > 3000000', async () => {
3348
- // Test with block number
3349
- });
3350
-
3351
- it('should get block with "latest" tag', async () => {
3352
- // Test with optional block tag
3353
- });
3354
-
3355
- it('should get block without optional parameters', async () => {
3356
- // Test default behavior
3357
- });
3358
- });
3359
- });
3360
- ```
3361
-
3362
- #### Example: E2E Test Structure
3363
-
3364
- ```javascript
3365
- /**
3366
- * @testCategory e2e
3367
- * @blockchainRequired write
3368
- * @description Tests for IERC20 contract deployment and interaction
3369
- */
3370
- describe('IERC20 Contract', () => {
3371
- const provider = new JsonRpcProvider('https://public.rpc.quantumcoinapi.com', 123123);
3372
- const wallet = new Wallet(TEST_WALLET_PRIVATE_KEY, provider);
3373
-
3374
- describe('Contract Deployment', () => {
3375
- it('should deploy IERC20 contract', async () => {
3376
- // Deploy contract
3377
- });
3378
- });
3379
-
3380
- describe('Contract Interactions', () => {
3381
- it('should transfer tokens', async () => {
3382
- // Test transfer with all parameters
3383
- });
3384
-
3385
- it('should transfer tokens with default gas settings', async () => {
3386
- // Test with optional parameters omitted
3387
- });
3388
- });
3389
- });
3390
- ```
3391
-
3392
- #### Example: Security Test Structure
3393
-
3394
- ```javascript
3395
- /**
3396
- * @testCategory security
3397
- * @blockchainRequired false
3398
- * @description Security tests for malformed input
3399
- */
3400
- describe('Security: Malformed Input', () => {
3401
- describe('Address Validation', () => {
3402
- it('should reject addresses with invalid length', () => {
3403
- // Security test
3404
- });
3405
-
3406
- it('should reject addresses with SQL injection attempts', () => {
3407
- // Security test
3408
- });
3409
- });
3410
- });
3411
- ```
3412
-
3413
- ### 13.7 Test Execution
3414
-
3415
- Tests should be organized to allow selective execution:
3416
- - Run only unit tests (fast, no network)
3417
- - Run only integration tests (read-only, requires network)
3418
- - Run only e2e tests (write access, requires network and test funds)
3419
- - Run only security tests
3420
- - Run all tests
3421
-
3422
- ### 13.8 Additional Requirements
3423
-
3424
- - All tests must be deterministic and repeatable
3425
- - Tests should clean up after themselves (where applicable)
3426
- - Tests should not interfere with each other
3427
- - Use appropriate test timeouts for network operations
3428
- - Mock external dependencies where appropriate (for unit tests)
3429
- - Use real blockchain data for integration and e2e tests
3430
-
3431
- ### 13.9 Implementation Gate: Non-Transaction Tests Must Pass
3432
-
3433
- After the rest of this specification is implemented (i.e., once the SDK APIs described in this document exist), the implementation MUST run **all tests that do not require sending transactions** and ensure they succeed.
3434
-
3435
- - **Included**: all test suites marked `@blockchainRequired false` or `@blockchainRequired readonly`
3436
- - **Excluded**: any test suites marked `@blockchainRequired write` (i.e., tests that send transactions)
3437
-
3438
- If any included test fails:
3439
- - **Diagnose** whether the failure is due to a **test bug** or a **SDK implementation bug**
3440
- - **Fix** the test (if the test is incorrect) or fix the SDK code (if the SDK is incorrect)
3441
- - **Re-run** the included test set and **repeat** until all included tests pass
3442
-
3443
- ---
3444
-
3445
- ## 14. Documentation Requirements
3446
-
3447
- - **Code and Documentation Comments**: All code must include detailed comments and documentation. Code comments should explain the logic, purpose, and implementation details. Documentation comments (JSDoc) should be comprehensive and clear, enabling both readers of the code and users of the SDK to understand functionality, parameters, return values, and usage patterns. Doc-level comments must appear in the SDK code itself (as JSDoc comments), not just in separate documentation files, so that they are available to SDK users through IDE tooltips and documentation generation tools.
3448
- - JSDoc comments for all public methods
3449
- - Usage examples for each major class
3450
- - Migration guide from ethers.js
3451
- - API reference documentation
3452
- - Troubleshooting guide
3453
-
3454
- ---
3455
-
3456
- ## 15. Typed Contract Generator
3457
-
3458
- ### 15.1 Overview
3459
-
3460
- A typed contract generator tool that creates fully-typed contract classes from ABI and bytecode. This generator produces TypeScript/JavaScript classes with proper types, methods, and deployment factories based on the provided contract ABI and binary code.
3461
-
3462
- ### 15.2 Generator Input
3463
-
3464
- The generator accepts the following inputs:
3465
- - **Contract ABI**: JSON array containing the contract's Application Binary Interface
3466
- - **Contract Bytecode (bin)**: Hexadecimal string containing the compiled contract bytecode
3467
-
3468
- ### 15.3 Interactive Setup Process
3469
-
3470
- #### 15.3.1 Package Creation Prompt
3471
-
3472
- When invoked, the generator first asks:
3473
- ```
3474
- Do you want to create a new package? (Y/N)
3475
- ```
3476
-
3477
- #### 15.3.2 New Package Creation (Y)
3478
-
3479
- If the user selects **Yes**, the generator prompts for:
3480
-
3481
- 1. **Package Location**:
3482
- - Prompt: `Enter the folder path where the package should be created:`
3483
- - User provides absolute or relative path
3484
-
3485
- 2. **Package Name**:
3486
- - Prompt: `Enter package name:`
3487
- - Must be valid npm package name
3488
-
3489
- 3. **Package Description**:
3490
- - Prompt: `Enter package description:`
3491
- - Brief description of the generated contract package
3492
-
3493
- 4. **Author**:
3494
- - Prompt: `Enter author name:`
3495
- - Author information for package.json
3496
-
3497
- 5. **License**:
3498
- - Prompt: `Enter license (default: MIT):`
3499
- - Default: `MIT` (if user presses Enter without input)
3500
- - User can specify custom license
3501
-
3502
- 6. **Version**:
3503
- - Prompt: `Enter version (default: 0.0.1):`
3504
- - Default: `0.0.1` (if user presses Enter without input)
3505
- - Must follow semantic versioning
3506
-
3507
- **Dependencies**: The generator automatically adds all dependencies from `quantumcoin.js` package.json to the generated package's dependencies.
3508
-
3509
- #### 15.3.3 Existing Package Integration (N)
3510
-
3511
- If the user selects **No**, the generator prompts for:
3512
-
3513
- 1. **Target Location**:
3514
- - Prompt: `Enter the location in your existing package (relative to package root):`
3515
- - User provides path where contract files should be generated
3516
- - Example: `src/contracts` or `contracts`
3517
-
3518
- ### 15.4 Generated Code Structure
3519
-
3520
- #### 15.4.1 Contract Class
3521
-
3522
- The generator creates a typed contract class with the following features:
3523
-
3524
- **Class Name**: Based on contract name from ABI (if available) or derived from package name
3525
-
3526
- **Constructor**:
3527
- ```typescript
3528
- constructor(address: string, runner?: ContractRunner, _deployTx?: TransactionResponse)
3529
- ```
3530
- - `address`: Contract address (32-byte QuantumCoin address)
3531
- - `runner`: Optional ContractRunner (Provider or Signer)
3532
- - `_deployTx`: Optional deployment transaction (for newly deployed contracts)
3533
-
3534
- **Typed Methods**:
3535
- - **Read-only functions**: Return typed results using types from quantumcoin.js
3536
- - **State-changing functions**: Return `ContractTransactionResponse` from quantumcoin.js
3537
- - **View functions**: Return typed values based on ABI return types
3538
- - **Pure functions**: Return typed values based on ABI return types
3539
-
3540
- **Method Signatures**:
3541
- - All method parameters are typed based on ABI input types
3542
- - All return types use quantumcoin.js types (e.g., `bigint`, `string`, `AddressLike`, etc.)
3543
- - Optional parameters are properly marked
3544
- - Overloads are generated for functions with optional parameters
3545
-
3546
- **Event Handling**:
3547
- - Typed event filters and listeners
3548
- - Event types match quantumcoin.js `EventLog` structure
3549
- - Indexed and non-indexed parameters are properly typed
3550
-
3551
- **Error Handling**:
3552
- - Custom error classes for contract-specific errors
3553
- - Error types match quantumcoin.js error patterns
3554
-
3555
- #### 15.4.2 Contract Factory
3556
-
3557
- The generator creates a `ContractFactory` class for deployment:
3558
-
3559
- **Class Name**: `{ContractName}__factory`
3560
-
3561
- **Static Methods**:
3562
- ```typescript
3563
- static connect(address: string, runner?: ContractRunner): {ContractName}
3564
- ```
3565
- - Creates a contract instance at the given address
3566
-
3567
- **Instance Methods**:
3568
- ```typescript
3569
- deploy(...constructorArgs: TypedArgs[]): Promise<{ContractName}>
3570
- ```
3571
- - Deploys the contract with typed constructor arguments
3572
- - Returns a contract instance with the deployment transaction attached
3573
-
3574
- **Properties**:
3575
- - `bytecode`: The contract bytecode
3576
- - `interface`: The contract ABI interface
3577
- - `abi`: The contract ABI array
3578
-
3579
- #### 15.4.3 Type Definitions
3580
-
3581
- The generator creates TypeScript type definitions for:
3582
- - Function parameters (input types)
3583
- - Function return values (output types)
3584
- - Event parameters
3585
- - Struct types (if present in ABI)
3586
- - Tuple types (if present in ABI)
3587
-
3588
- All types use quantumcoin.js type system:
3589
- - `bigint` for uint/int types
3590
- - `string` for addresses (32-byte)
3591
- - `BytesLike` for bytes types
3592
- - Custom struct types for complex data structures
3593
-
3594
- #### 15.4.4 Code Comments
3595
-
3596
- All generated code includes comprehensive JSDoc comments:
3597
-
3598
- **Class Comments**:
3599
- ```typescript
3600
- /**
3601
- * {ContractName} - A typed contract interface for {ContractName}
3602
- *
3603
- * @description {Description from ABI or package description}
3604
- * @example
3605
- * ```typescript
3606
- * const contract = new {ContractName}(address, provider);
3607
- * const result = await contract.someMethod(...args);
3608
- * ```
3609
- */
3610
- ```
3611
-
3612
- **Method Comments**:
3613
- ```typescript
3614
- /**
3615
- * {methodName} - {Description from ABI}
3616
- *
3617
- * @param {paramName} - {Type and description}
3618
- * @returns {Return type description}
3619
- * @throws {Error conditions}
3620
- *
3621
- * @example
3622
- * ```typescript
3623
- * const result = await contract.{methodName}(...args);
3624
- * ```
3625
- */
3626
- ```
3627
-
3628
- **Transaction Methods**:
3629
- ```typescript
3630
- /**
3631
- * {methodName} - Sends a transaction to {methodName}
3632
- *
3633
- * @param {paramName} - {Type and description}
3634
- * @param overrides - Optional transaction overrides (gas, value, etc.)
3635
- * @returns Promise<ContractTransactionResponse> - Transaction response object
3636
- *
3637
- * @example
3638
- * ```typescript
3639
- * const tx = await contract.{methodName}(...args, {
3640
- * gasLimit: 100000n,
3641
- * value: parseEther("1.0")
3642
- * });
3643
- * await tx.wait();
3644
- * ```
3645
- */
3646
- ```
3647
-
3648
- ### 15.5 Generated File Structure
3649
-
3650
- #### 15.5.1 New Package Structure
3651
-
3652
- ```
3653
- {package-name}/
3654
- ├── package.json # Generated with dependencies
3655
- ├── tsconfig.json # TypeScript configuration
3656
- ├── README.md # Generated README
3657
- ├── src/
3658
- │ ├── {ContractName}.ts # Main contract class
3659
- │ ├── {ContractName}__factory.ts # Contract factory
3660
- │ ├── types.ts # Type definitions
3661
- │ └── index.ts # Main exports
3662
- └── examples/
3663
- ├── deploy.ts # Deployment example
3664
- ├── read-operations.ts # Read-only operations example
3665
- ├── write-operations.ts # Transaction examples
3666
- └── events.ts # Event listening examples
3667
- ```
3668
-
3669
- #### 15.5.2 Existing Package Structure
3670
-
3671
- ```
3672
- {existing-package}/
3673
- └── {target-location}/
3674
- ├── {ContractName}.ts
3675
- ├── {ContractName}__factory.ts
3676
- ├── types.ts
3677
- └── index.ts
3678
- ```
3679
-
3680
- ### 15.6 Example Generation
3681
-
3682
- #### 15.6.1 Example Files
3683
-
3684
- The generator creates example files in the `examples/` folder:
3685
-
3686
- **deploy.ts**:
3687
- ```typescript
3688
- import { JsonRpcProvider, Wallet } from 'quantumcoin';
3689
- import { {ContractName}, {ContractName}__factory } from '../src';
3690
-
3691
- async function deploy() {
3692
- const provider = new JsonRpcProvider('https://public.rpc.quantumcoinapi.com', 123123);
3693
- const wallet = new Wallet('0x...privateKey...', provider);
3694
-
3695
- const factory = new {ContractName}__factory(wallet);
3696
- const contract = await factory.deploy(...constructorArgs);
3697
-
3698
- console.log('Contract deployed at:', contract.target);
3699
- console.log('Deployment transaction:', contract.deploymentTransaction()?.hash);
3700
-
3701
- await contract.deploymentTransaction()?.wait();
3702
- console.log('Contract deployed and confirmed!');
3703
- }
3704
-
3705
- deploy().catch(console.error);
3706
- ```
3707
-
3708
- **read-operations.ts**:
3709
- ```typescript
3710
- import { JsonRpcProvider } from 'quantumcoin';
3711
- import { {ContractName} } from '../src';
3712
-
3713
- async function readOperations() {
3714
- const provider = new JsonRpcProvider('https://public.rpc.quantumcoinapi.com', 123123);
3715
- const contract = {ContractName}.connect('0x...contractAddress...', provider);
3716
-
3717
- // Example read operations based on ABI
3718
- const result = await contract.someViewFunction(...args);
3719
- console.log('Result:', result);
3720
- }
3721
-
3722
- readOperations().catch(console.error);
3723
- ```
3724
-
3725
- **write-operations.ts**:
3726
- ```typescript
3727
- import { JsonRpcProvider, Wallet, parseEther } from 'quantumcoin';
3728
- import { {ContractName} } from '../src';
3729
-
3730
- async function writeOperations() {
3731
- const provider = new JsonRpcProvider('https://public.rpc.quantumcoinapi.com', 123123);
3732
- const wallet = new Wallet('0x...privateKey...', provider);
3733
- const contract = {ContractName}.connect('0x...contractAddress...', wallet);
3734
-
3735
- // Example transaction operations based on ABI
3736
- const tx = await contract.someStateChangingFunction(...args, {
3737
- gasLimit: 100000n
3738
- });
3739
- console.log('Transaction hash:', tx.hash);
3740
-
3741
- const receipt = await tx.wait();
3742
- console.log('Transaction confirmed in block:', receipt.blockNumber);
3743
- }
3744
-
3745
- writeOperations().catch(console.error);
3746
- ```
3747
-
3748
- **events.ts**:
3749
- ```typescript
3750
- import { JsonRpcProvider } from 'quantumcoin';
3751
- import { {ContractName} } from '../src';
3752
-
3753
- async function listenToEvents() {
3754
- const provider = new JsonRpcProvider('https://public.rpc.quantumcoinapi.com', 123123);
3755
- const contract = {ContractName}.connect('0x...contractAddress...', provider);
3756
-
3757
- // Example event listening based on ABI
3758
- contract.on('SomeEvent', (event) => {
3759
- console.log('Event received:', event);
3760
- });
3761
-
3762
- // Filter events
3763
- const filter = contract.filters.SomeEvent(...args);
3764
- const events = await contract.queryFilter(filter, fromBlock, toBlock);
3765
- console.log('Filtered events:', events);
3766
- }
3767
-
3768
- listenToEvents().catch(console.error);
3769
- ```
3770
-
3771
- ### 15.7 Transaction Return Types
3772
-
3773
- Methods that send transactions must return the appropriate transaction object from quantumcoin.js:
3774
-
3775
- - **Return Type**: `Promise<ContractTransactionResponse>`
3776
- - **Properties**: All properties from `ContractTransactionResponse`:
3777
- - `hash`: Transaction hash
3778
- - `to`: Recipient address
3779
- - `from`: Sender address
3780
- - `value`: Transaction value
3781
- - `data`: Transaction data
3782
- - `gasLimit`: Gas limit
3783
- - `gasPrice`: Gas price
3784
- - `nonce`: Transaction nonce
3785
- - `chainId`: Chain ID
3786
- - `wait()`: Method to wait for confirmation
3787
- - `getTransaction()`: Get full transaction details
3788
- - `getReceipt()`: Get transaction receipt
3789
-
3790
- ### 15.8 Type Mapping
3791
-
3792
- The generator maps Solidity types to quantumcoin.js types:
3793
-
3794
- | Solidity Type | quantumcoin.js Type |
3795
- |--------------|---------------------|
3796
- | `address` | `string` (32-byte address) |
3797
- | `uint8` to `uint256` | `bigint` |
3798
- | `int8` to `int256` | `bigint` |
3799
- | `bool` | `boolean` |
3800
- | `bytes1` to `bytes32` | `BytesLike` |
3801
- | `bytes` | `BytesLike` |
3802
- | `string` | `string` |
3803
- | `tuple` | Custom type or object |
3804
- | Arrays | `Array<Type>` |
3805
- | Mappings | Not directly accessible (use getter functions) |
3806
-
3807
- ### 15.9 Generator Implementation Requirements
3808
-
3809
- 1. **ABI Parsing**: Parse ABI JSON to extract functions, events, errors, and constructor
3810
- 2. **Type Inference**: Infer TypeScript types from ABI parameter types
3811
- 3. **Method Generation**: Generate typed methods for all functions in ABI
3812
- 4. **Event Generation**: Generate typed event filters and listeners
3813
- 5. **Error Generation**: Generate custom error classes for contract errors
3814
- 6. **Factory Generation**: Generate ContractFactory with deployment support
3815
- 7. **Example Generation**: Generate comprehensive examples for all operations
3816
- 8. **Documentation**: Generate JSDoc comments for all generated code
3817
- 9. **Package Setup**: Create package.json with proper dependencies
3818
- 10. **Type Safety**: Ensure all generated code is fully typed
3819
-
3820
- ### 15.10 Usage
3821
-
3822
- The generator should be invoked as a command-line tool or script:
3823
-
3824
- ```bash
3825
- # As a CLI tool
3826
- npx sdkgen --abi path/to/abi.json --bin path/to/bytecode.bin
3827
-
3828
- # Or as a Node.js script
3829
- node generate-sdk.js --abi path/to/abi.json --bin path/to/bytecode.bin
3830
- ```
3831
-
3832
- The generator should support:
3833
- - Interactive mode (prompts for all inputs)
3834
- - Non-interactive mode (all inputs via command-line arguments)
3835
- - Configuration file input (JSON/YAML config file)
3836
-
3837
- ---
3838
-
3839
- ## Notes
3840
-
3841
- 1. This specification is based on ethers.js v6 patterns but adapted for QuantumCoin
3842
- 2. All address-related operations must account for 32-byte addresses
3843
- 3. HDWallet functionality is explicitly excluded
3844
- 4. All cryptographic operations must use quantum-coin-js-sdk
3845
- 5. The implementation should be as compatible as possible with ethers.js v6 for ease of migration