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