@quantabit/qbit-chain-sdk 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 QuantaBit Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,476 @@
1
+ # @quantabit/qbit-chain-sdk
2
+
3
+ > QBit Chain core interaction layer — production-grade blockchain SDK for QBit Chain (Solana-compatible).
4
+
5
+ ## Features
6
+
7
+ - **Connection Management** — Auto-retry (exponential backoff), Genesis Hash network validation, WebSocket auto-derivation, sdk-config sync
8
+ - **Key Management** — BIP44 (`m/44'/766'`) Ed25519 keypair generation, mnemonic backup, legacy path (`m/44'/766'`) compatibility
9
+ - **Transactions** — QBT transfer, SPL Token transfer (auto ATA creation), batch transfer, multi-signer support, sign/broadcast separation
10
+ - **SPL Token Lifecycle** — Create mint, mint, burn, approve/revoke, freeze/thaw, set authority, close account
11
+ - **Account Queries** — Balance, token holdings, mint info, ATA lookup, transaction history
12
+ - **Staking** — Create stake accounts, delegate/deactivate/withdraw, validator listing
13
+ - **RPC Utilities** — Health check, chain status summary, epoch info, supply, cluster nodes, block queries, performance samples, inflation, devnet airdrop
14
+ - **Error Handling** — 8 specialized error classes with structured codes for precise error recovery
15
+ - **Real-time Subscriptions** — WebSocket account monitoring, program logs, slot changes, signature confirmation
16
+ - **Token Registry** — Built-in metadata (QBT/USDC/USDT/wSOL), auto-discovery, amount formatting
17
+ - **Transaction Parser** — Decode raw transactions into structured events with human-readable summaries
18
+ - **Program Interaction** — PDA derivation, instruction builder, execution/simulation, Borsh serialization helpers
19
+ - **TypeScript** — Complete type definitions (600+ lines)
20
+
21
+ ## Installation
22
+
23
+ ```bash
24
+ npm install @quantabit/qbit-chain-sdk
25
+ ```
26
+
27
+ ## Quick Start
28
+
29
+ ```javascript
30
+ import { QBitConnection, QBitKeypair, QBitTransaction } from '@quantabit/qbit-chain-sdk';
31
+
32
+ // Connect to QBit mainnet
33
+ const conn = new QBitConnection(); // defaults to mainnet
34
+
35
+ // Validate network identity (Genesis Hash check)
36
+ const { valid } = await conn.validateNetwork();
37
+ console.log('Network valid:', valid);
38
+
39
+ // Generate a keypair (BIP44 path: m/44'/766'/0'/0')
40
+ const kp = await QBitKeypair.generate();
41
+ console.log('Address:', kp.address);
42
+ console.log('Mnemonic:', kp.mnemonic);
43
+
44
+ // Check balance
45
+ const balance = await conn.getBalanceQBT(kp.address);
46
+ console.log(`Balance: ${balance} QBT`);
47
+ ```
48
+
49
+ ## Networks
50
+
51
+ | Network | RPC Endpoint | Genesis Hash |
52
+ |---------|-------------|--------------|
53
+ | Mainnet | `https://api.mainnet.qbitchain.io/` | `HuM99k8A...` |
54
+ | Devnet | `https://api.devnet.qbitchain.io/` | `BmBSkzpt...` |
55
+
56
+ ```javascript
57
+ // Mainnet (default)
58
+ const conn = new QBitConnection();
59
+
60
+ // Devnet
61
+ const conn = new QBitConnection({ network: 'devnet' });
62
+
63
+ // Custom endpoint
64
+ const conn = new QBitConnection({ endpoint: 'https://my-rpc.example.com/' });
65
+
66
+ // Switch network at runtime
67
+ conn.switchNetwork('devnet');
68
+ ```
69
+
70
+ ## Key Management
71
+
72
+ ```javascript
73
+ import { QBitKeypair, generateMnemonic, validateMnemonic } from '@quantabit/qbit-chain-sdk';
74
+
75
+ // Generate new keypair with mnemonic (BIP44: m/44'/766'/0'/0')
76
+ const kp = await QBitKeypair.generate();
77
+
78
+ // Legacy path compatibility for existing wallets
79
+ const kpLegacy = await QBitKeypair.generate({ useLegacyPath: true }); // m/44'/766'/0'/0'
80
+
81
+ // Restore from mnemonic
82
+ const restored = await QBitKeypair.fromMnemonic('your twelve word mnemonic ...');
83
+
84
+ // Restore from private key
85
+ const fromKey = QBitKeypair.fromPrivateKey('base58PrivateKey...');
86
+
87
+ // Derive multiple accounts from one mnemonic
88
+ const accounts = await QBitKeypair.deriveMultiple(mnemonic, 5);
89
+
90
+ // Sign a message
91
+ const signature = kp.signBase58('Hello QBit');
92
+
93
+ // Clean up sensitive data
94
+ kp.destroy();
95
+ ```
96
+
97
+ ## Transactions
98
+
99
+ ### QBT Transfer
100
+
101
+ ```javascript
102
+ import { QBitTransaction, transferQBT } from '@quantabit/qbit-chain-sdk';
103
+
104
+ // Quick transfer
105
+ const result = await transferQBT(conn, myKeypair, 'ReceiverAddress', 1.5, {
106
+ memo: 'Payment',
107
+ });
108
+ console.log('Tx:', result.signature);
109
+
110
+ // Builder pattern
111
+ const tx = new QBitTransaction(conn);
112
+ tx.transfer(myKeypair.address, 'ReceiverAddress', 1.5);
113
+ tx.addMemo('Payment note');
114
+ const sig = await tx.sendAndConfirm(myKeypair);
115
+ ```
116
+
117
+ ### SPL Token Transfer
118
+
119
+ ```javascript
120
+ import { QBitTransaction, transferToken } from '@quantabit/qbit-chain-sdk';
121
+
122
+ // Auto-creates recipient ATA if needed
123
+ const result = await transferToken(
124
+ conn, myKeypair,
125
+ 'ReceiverAddress',
126
+ 'TokenMintAddress',
127
+ 1000000, // raw amount
128
+ 9, // decimals
129
+ );
130
+ ```
131
+
132
+ ### Batch Transfer
133
+
134
+ ```javascript
135
+ const tx = new QBitTransaction(conn);
136
+ tx.batchTransfer(myKeypair.address, [
137
+ { to: 'Address1', amountQBT: 1.0 },
138
+ { to: 'Address2', amountQBT: 2.0 },
139
+ { to: 'Address3', amountQBT: 3.0 },
140
+ ]);
141
+ await tx.sendAndConfirm(myKeypair);
142
+ ```
143
+
144
+ ### Transaction Simulation
145
+
146
+ ```javascript
147
+ const tx = new QBitTransaction(conn);
148
+ tx.transfer(from, to, 1.0);
149
+ const sim = await tx.simulate(myKeypair);
150
+ console.log('Fee:', sim.estimatedFee, 'Units:', sim.unitsConsumed);
151
+ console.log('Logs:', sim.logs);
152
+ ```
153
+
154
+ ## SPL Token Lifecycle
155
+
156
+ Beyond transfers, the SDK provides the full token lifecycle. All operations broadcast via HTTP polling confirmation (no WebSocket dependency).
157
+
158
+ ```javascript
159
+ import {
160
+ createMint, getOrCreateTokenAccount, mintTo, burn,
161
+ approve, revoke, freezeAccount, thawAccount,
162
+ setAuthority, closeTokenAccount,
163
+ } from '@quantabit/qbit-chain-sdk';
164
+
165
+ // Issue a new token (6 decimals). payer becomes mint + freeze authority by default.
166
+ const { mint } = await createMint(conn, payer, { decimals: 6 });
167
+
168
+ // Ensure a recipient has an associated token account
169
+ const { address } = await getOrCreateTokenAccount(conn, payer, mint, recipientAddress);
170
+
171
+ // Mint 1000 tokens (raw = 1000 * 10^6); recipient ATA is auto-created if missing
172
+ await mintTo(conn, mintAuthority, mint, recipientAddress, 1000 * 1e6);
173
+
174
+ // Burn tokens from the owner's ATA
175
+ await burn(conn, owner, mint, 500 * 1e6, { decimals: 6 });
176
+
177
+ // Delegate / revoke spending authority
178
+ await approve(conn, owner, mint, delegateAddress, 100 * 1e6);
179
+ await revoke(conn, owner, mint);
180
+
181
+ // Freeze / thaw (requires freeze authority)
182
+ await freezeAccount(conn, freezeAuthority, mint, ownerAddress);
183
+ await thawAccount(conn, freezeAuthority, mint, ownerAddress);
184
+
185
+ // Renounce mint authority permanently (newAuthority = null)
186
+ await setAuthority(conn, mintAuthority, mint, 'MintTokens', null);
187
+
188
+ // Close an empty token account and reclaim rent
189
+ await closeTokenAccount(conn, owner, mint, rentDestination);
190
+ ```
191
+
192
+ ## Multi-signer Transactions
193
+
194
+ ```javascript
195
+ const tx = new QBitTransaction(conn);
196
+ tx.addInstruction(someInstruction);
197
+ tx.addSigner(extraKeypair); // additional required signer
198
+ await tx.sendAndConfirm(payer, { feePayer: payer.address });
199
+ ```
200
+
201
+ ## Staking
202
+
203
+ ```javascript
204
+ import {
205
+ createStakeAccount, delegate, deactivate, withdrawStake,
206
+ getStakeActivation, getValidators,
207
+ } from '@quantabit/qbit-chain-sdk';
208
+
209
+ // List validators
210
+ const validators = await getValidators(conn);
211
+ console.log('Active validators:', validators.current.length);
212
+
213
+ // Create stake account and delegate
214
+ const stake = await createStakeAccount(conn, myKeypair, validatorVotePubkey, 10);
215
+ console.log('Stake account:', stake.stakeAccount);
216
+
217
+ // Check activation status
218
+ const activation = await getStakeActivation(conn, stake.stakeAccount);
219
+ console.log('State:', activation.state); // 'activating' -> 'active'
220
+
221
+ // Deactivate and withdraw
222
+ await deactivate(conn, myKeypair, stake.stakeAccount);
223
+ await withdrawStake(conn, myKeypair, stake.stakeAccount, myKeypair.address);
224
+ ```
225
+
226
+ ## Chain Status
227
+
228
+ ```javascript
229
+ import { getChainStatus, getChainHealth } from '@quantabit/qbit-chain-sdk';
230
+
231
+ // Quick health check
232
+ const health = await getChainHealth(); // 'ok'
233
+
234
+ // Full chain status (single call)
235
+ const status = await getChainStatus();
236
+ // {
237
+ // health: 'ok',
238
+ // network: 'mainnet',
239
+ // version: '4.0.0-beta.6',
240
+ // epoch: 13,
241
+ // blockHeight: 394991,
242
+ // totalSupplyQBT: 10000010011.175579,
243
+ // circulatingQBT: 10000010011.175579,
244
+ // slotProgress: '52.8%',
245
+ // }
246
+ ```
247
+
248
+ ## Connection Options
249
+
250
+ ```javascript
251
+ const conn = new QBitConnection({
252
+ network: 'mainnet', // 'mainnet' | 'devnet' | 'testnet'
253
+ endpoint: 'https://...', // custom RPC endpoint
254
+ commitment: 'confirmed', // 'processed' | 'confirmed' | 'finalized'
255
+ timeoutMs: 30000, // request timeout
256
+ autoValidate: true, // auto-validate Genesis Hash on connect
257
+ onConnect: ({ endpoint }) => {},
258
+ onDisconnect: ({ error }) => {},
259
+ onNetworkMismatch: ({ expected, actual }) => {},
260
+ });
261
+
262
+ // Network validation
263
+ const result = await conn.validateNetwork();
264
+ if (!result.valid) {
265
+ console.error('Wrong network!', result);
266
+ }
267
+ ```
268
+
269
+ ## Constants
270
+
271
+ ```javascript
272
+ import {
273
+ QBIT_COIN_TYPE, // 766
274
+ GENESIS_HASH, // { mainnet, devnet }
275
+ CHAIN_ENDPOINTS, // { mainnet, devnet, testnet }
276
+ CHAIN_PROGRAMS, // System, Token, Stake, Vote, DID, etc.
277
+ CHAIN_PARAMS, // slot duration, epoch size, token decimals
278
+ LAMPORTS_PER_QBT, // 1_000_000_000
279
+ } from '@quantabit/qbit-chain-sdk';
280
+ ```
281
+
282
+ ## Error Handling
283
+
284
+ Structured error hierarchy for precise error recovery:
285
+
286
+ ```javascript
287
+ import {
288
+ QBitError, // Base error
289
+ QBitRpcError, // RPC communication errors
290
+ QBitNetworkError, // Connection/timeout errors
291
+ QBitNetworkMismatchError, // Genesis Hash mismatch
292
+ QBitTransactionError, // Transaction build/sign/send errors
293
+ QBitInsufficientFundsError, // Balance too low
294
+ QBitAccountNotFoundError, // Account does not exist
295
+ QBitTokenError, // SPL Token errors
296
+ QBitKeypairError, // Invalid mnemonic/key
297
+ ERROR_CODES, // Error code constants
298
+ } from '@quantabit/qbit-chain-sdk';
299
+
300
+ try {
301
+ await transferQBT(conn, myKeypair, 'ReceiverAddress', 100);
302
+ } catch (err) {
303
+ if (err instanceof QBitInsufficientFundsError) {
304
+ console.log(`Need ${err.details.required}, have ${err.details.available}`);
305
+ } else if (err instanceof QBitNetworkError) {
306
+ console.log('Network issue, retrying...');
307
+ } else if (err instanceof QBitRpcError) {
308
+ console.log('RPC error:', err.rpcCode, err.method);
309
+ }
310
+ }
311
+ ```
312
+
313
+ ## Real-time Subscriptions
314
+
315
+ WebSocket-based event streaming:
316
+
317
+ ```javascript
318
+ import { QBitSubscription } from '@quantabit/qbit-chain-sdk';
319
+
320
+ const sub = new QBitSubscription(conn);
321
+
322
+ // Watch balance changes
323
+ const id1 = sub.onAccountChange('Address...', (info) => {
324
+ console.log('Balance changed:', info.lamports);
325
+ });
326
+
327
+ // Watch program logs (e.g., Token events)
328
+ const id2 = sub.onProgramLogs('TokenProgramId', (log) => {
329
+ console.log('Token event:', log.signature);
330
+ });
331
+
332
+ // Watch slot progression
333
+ sub.onSlotChange(({ slot }) => console.log('Slot:', slot));
334
+
335
+ // Track transaction confirmation
336
+ sub.onSignature('TxSignature...', (info) => {
337
+ console.log(info.confirmed ? 'Confirmed!' : 'Failed');
338
+ });
339
+
340
+ // Cleanup
341
+ sub.unsubscribe(id1); // cancel specific
342
+ sub.unsubscribeAll(); // cancel all
343
+ sub.destroy(); // alias for unsubscribeAll
344
+ ```
345
+
346
+ ## Token Registry
347
+
348
+ Built-in metadata for known tokens + auto-discovery:
349
+
350
+ ```javascript
351
+ import { TokenRegistry, getTokenRegistry, KNOWN_TOKENS } from '@quantabit/qbit-chain-sdk';
352
+
353
+ // Static reference
354
+ console.log(KNOWN_TOKENS.QBT.decimals); // 9
355
+ console.log(KNOWN_TOKENS.USDC.decimals); // 6
356
+
357
+ // Registry with chain connection (for auto-discovery)
358
+ const registry = getTokenRegistry(conn);
359
+
360
+ // Built-in tokens
361
+ const qbt = registry.getToken('native'); // { symbol: 'QBT', decimals: 9, ... }
362
+
363
+ // Auto-discover unknown token from chain
364
+ const info = await registry.resolveToken('MintAddress...');
365
+
366
+ // Register custom token
367
+ registry.register({
368
+ address: 'CustomMint...',
369
+ symbol: 'MYTOKEN',
370
+ name: 'My Token',
371
+ decimals: 8,
372
+ });
373
+
374
+ // Format amounts
375
+ registry.formatWithSymbol('native', 2000000000); // "2.0000 QBT"
376
+
377
+ // Search
378
+ const stables = registry.search('usd'); // [USDC, USDT]
379
+ ```
380
+
381
+ ## Transaction Parser
382
+
383
+ Decode on-chain transactions into human-readable events:
384
+
385
+ ```javascript
386
+ import { TransactionParser } from '@quantabit/qbit-chain-sdk';
387
+
388
+ const parser = new TransactionParser(conn);
389
+
390
+ // Parse single transaction
391
+ const parsed = await parser.parse('TxSignature...');
392
+ console.log(parsed.type); // 'transfer' | 'token_transfer' | 'stake_delegate' | ...
393
+ console.log(parsed.summary); // '转账 1.5 QBT → 8DjJ...DtMc'
394
+ console.log(parsed.fee); // fee in lamports
395
+ console.log(parsed.events); // structured event list
396
+ console.log(parsed.programs); // [{ address, name: 'System' }]
397
+
398
+ // Parse recent transactions for an address
399
+ const history = await parser.parseRecentForAddress('Address...', 20);
400
+ history.forEach(tx => {
401
+ console.log(`${tx.summary} | ${tx.success ? '✅' : '❌'}`);
402
+ });
403
+ ```
404
+
405
+ ## Program Interaction
406
+
407
+ DApp developer toolkit for custom program calls:
408
+
409
+ ```javascript
410
+ import { ProgramHelper } from '@quantabit/qbit-chain-sdk';
411
+
412
+ const helper = new ProgramHelper(conn, 'YourProgramId...');
413
+
414
+ // Find PDA
415
+ const [pda, bump] = helper.findPDA(['user', userPubkey.toBuffer()]);
416
+ console.log('PDA:', pda.toBase58(), 'bump:', bump);
417
+
418
+ // Build instruction
419
+ const ix = helper.buildInstruction(
420
+ Buffer.from([1, 0, 0, 0]), // instruction discriminator
421
+ [
422
+ { pubkey: userPubkey, isSigner: true, isWritable: true },
423
+ { pubkey: pda, isSigner: false, isWritable: true },
424
+ ]
425
+ );
426
+
427
+ // Simulate before sending
428
+ const sim = await helper.simulate(signer, [ix]);
429
+ console.log('Logs:', sim.logs, 'Error:', sim.err);
430
+
431
+ // Execute
432
+ const sig = await helper.execute(signer, [ix]);
433
+
434
+ // Query program accounts
435
+ const accounts = await helper.getAccounts({ dataSize: 128 });
436
+
437
+ // Borsh serialization helpers
438
+ const data = Buffer.concat([
439
+ ProgramHelper.encodeU32(1), // instruction index
440
+ ProgramHelper.encodeU64(1000000000n), // amount
441
+ ProgramHelper.encodeString('hello'), // string field
442
+ ]);
443
+ ```
444
+
445
+ ## API Summary
446
+
447
+ | Module | Exports |
448
+ |--------|---------|
449
+ | **Connection** | `QBitConnection`, `getDefaultConnection`, `resetDefaultConnection`, `withRetry` |
450
+ | **Keypair** | `QBitKeypair`, `generateMnemonic`, `mnemonicToKeypair`, `validateMnemonic`, `verifySignature` |
451
+ | **Transaction** | `QBitTransaction`, `transferQBT`, `transferToken`, `estimateTransactionFee` |
452
+ | **Token** | `createMint`, `getOrCreateTokenAccount`, `mintTo`, `burn`, `approve`, `revoke`, `freezeAccount`, `thawAccount`, `setAuthority`, `closeTokenAccount`, `getTokenAccountDelegation` |
453
+ | **Account** | `getAccountInfo`, `getBalance`, `getTokenAccounts`, `getTokenMintInfo`, `getAssociatedTokenAccount`, `getTransactionHistory`, `getStakeAccounts` |
454
+ | **Stake** | `createStakeAccount`, `delegate`, `deactivate`, `withdrawStake`, `getStakeActivation`, `getValidators` |
455
+ | **RPC** | `getChainHealth`, `getChainVersion`, `getBlockHeight`, `getSlot`, `getEpochInfo`, `getLatestBlockhash`, `getGenesisHash`, `getSupply`, `getClusterNodes`, `getVoteAccounts`, `getTransactionCount`, `getBlock`, `getBlockTime`, `getBlocks`, `getRecentPerformanceSamples`, `getInflationRate`, `requestAirdrop`, `validateNetwork`, `getChainStatus` |
456
+ | **Errors** | `QBitError`, `QBitRpcError`, `QBitNetworkError`, `QBitNetworkMismatchError`, `QBitTransactionError`, `QBitInsufficientFundsError`, `QBitAccountNotFoundError`, `QBitTokenError`, `QBitKeypairError`, `ERROR_CODES` |
457
+ | **Subscription** | `QBitSubscription` |
458
+ | **Token Registry** | `TokenRegistry`, `getTokenRegistry`, `KNOWN_TOKENS` |
459
+ | **TX Parser** | `TransactionParser` |
460
+ | **Program** | `ProgramHelper` |
461
+ | **Constants** | `CHAIN_ENDPOINTS`, `CHAIN_PROGRAMS`, `CHAIN_PARAMS`, `GENESIS_HASH`, `QBIT_COIN_TYPE`, `LAMPORTS_PER_QBT`, `DEFAULT_CONFIRM_OPTIONS`, `TIMEOUT`, `RETRY` |
462
+ | **Utils** | `qbtToLamports`, `lamportsToQbt`, `formatQbt`, `isValidAddress`, `shortenAddress`, `toPublicKey` |
463
+
464
+ ## License
465
+
466
+ MIT © QuantaBit Team
467
+
468
+
469
+ ---
470
+
471
+ ## 🌐 Brand & Links
472
+ - Official Mainnet: [QuantaBit Chain](https://qbitchain.io/)
473
+ - Developer Platform: [Developer Platform](https://developer.quantabit.io/)
474
+ - Open Platform: [Open Platform](https://open.quantabit.io/)
475
+ - Payment Platform: [Pay Platform](https://pay.qbitwallet.io/)
476
+ - Feedback: [Feedback](https://xwin.live/qbit)