nexa-wallet-sdk 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/.parcel-cache/3e09f086f3c4d605-AssetGraph +0 -0
  2. package/.parcel-cache/5eac57ec674cdae8-AssetGraph +0 -0
  3. package/.parcel-cache/data.mdb +0 -0
  4. package/.parcel-cache/e43547b6c9167b58-RequestGraph +0 -0
  5. package/.parcel-cache/ecfe15d74834bbfd-BundleGraph +0 -0
  6. package/.parcel-cache/lock.mdb +0 -0
  7. package/.parcel-cache/snapshot-e43547b6c9167b58.txt +2 -0
  8. package/README.md +445 -0
  9. package/dist/browser/index.js +2456 -0
  10. package/dist/browser/index.js.map +1 -0
  11. package/dist/index.d.ts +918 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +2915 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/index.mjs +2456 -0
  16. package/dist/index.mjs.map +1 -0
  17. package/package.json +90 -0
  18. package/spec.md +257 -0
  19. package/src/index.ts +93 -0
  20. package/src/models/rostrum.entities.ts +159 -0
  21. package/src/models/transaction.entities.ts +46 -0
  22. package/src/models/wallet.entities.ts +42 -0
  23. package/src/network/RostrumProvider.ts +137 -0
  24. package/src/types.ts +0 -0
  25. package/src/utils/CommonUtils.ts +123 -0
  26. package/src/utils/TXUtils.ts +445 -0
  27. package/src/utils/TokenUtils.ts +75 -0
  28. package/src/utils/ValidationUtils.ts +86 -0
  29. package/src/utils/WalletUtils.ts +522 -0
  30. package/src/utils/WatchOnlyTXUtils.ts +275 -0
  31. package/src/wallet/Wallet.ts +397 -0
  32. package/src/wallet/WatchOnlyWallet.ts +169 -0
  33. package/src/wallet/accounts/AccountStore.ts +173 -0
  34. package/src/wallet/accounts/interfaces/BaseAccountInterface.ts +56 -0
  35. package/src/wallet/accounts/models/DappAccount.ts +80 -0
  36. package/src/wallet/accounts/models/DefaultAccount.ts +96 -0
  37. package/src/wallet/accounts/models/VaultAccount.ts +81 -0
  38. package/src/wallet/transactions/WalletTransactionCreator.ts +145 -0
  39. package/src/wallet/transactions/WatchOnlyTransactionCreator.ts +189 -0
  40. package/src/wallet/transactions/interfaces/TransactionCreator.ts +438 -0
  41. package/tests/core/tx/transactioncreator.test.ts +455 -0
  42. package/tests/core/tx/wallettransactioncreator.test.ts +362 -0
  43. package/tests/core/tx/watchonlytransactioncreator.test.ts +258 -0
  44. package/tests/core/wallet/accountstore.test.ts +341 -0
  45. package/tests/core/wallet/wallet.test.ts +69 -0
  46. package/tests/core/watchonlywallet/watchonlywallet.test.ts +251 -0
  47. package/tests/index.test.ts +12 -0
  48. package/tsconfig.json +113 -0
package/spec.md ADDED
@@ -0,0 +1,257 @@
1
+ # Nexa SDK Technical Specification (Draft)
2
+
3
+ ## Motivation
4
+
5
+ Currently, Nexa lacks an easy-to-use wallet management SDK tailored for client-side web applications. Developers repeatedly face challenges re-implementing wallet functionalities. This SDK aims to simplify integration, standardize common wallet features, and encourage adoption of Nexa by lowering barriers to entry.
6
+
7
+ ## Objectives
8
+
9
+ * Provide wallet and network management utilities.
10
+ * Simplify transaction signing and verification.
11
+ * Offer seamless dApp ↔ wallet communication.
12
+ * Facilitate interactions with Rostrum (Electrum-based network provider).
13
+ * Abstract away lower-level complexities provided by `libnexa-ts`.
14
+
15
+ ## Dependencies
16
+
17
+ * `libnexa-ts`: Core Nexa blockchain utilities.
18
+ * `electrum-cash`: Integration with Rostrum for network provider functionality.
19
+
20
+ ## Project Files Structure
21
+
22
+ ```
23
+ src/
24
+ ├── wallet/
25
+ │ ├── Wallet.ts # Wallet instance creation and management
26
+ │ ├── AccountStore.ts # DefaultAccount management (create, import, export)
27
+ │ └── UTXOStore.ts # UTXO management (fetching, selection)
28
+ ├── network/
29
+ │ ├── NetworkProvider.ts # Interface for network providers
30
+ │ └── RostrumProvider.ts # Implementation of Rostrum provider
31
+ ├── dapp/
32
+ │ └── DAppConnector.ts # dApp communication utilities
33
+ ├── utils/
34
+ │ ├── CryptoUtils.ts # Cryptographic operations
35
+ │ └── WalletUtils.ts # Wallet helpers
36
+ ├── index.ts # SDK entry point
37
+ └── types.ts # Shared types and interfaces
38
+ ```
39
+
40
+ ## Core Components
41
+
42
+ ### 1. Wallet Management (`wallet/`)
43
+
44
+ * **Wallet.ts**
45
+
46
+ * Create, import, and manage wallet instances
47
+ * HD wallets, transaction signing, message signing, broadcasting
48
+
49
+ * **AccountStore.ts**
50
+
51
+ * Multiple account handling within wallets
52
+
53
+ * **UTXOStore.ts**
54
+
55
+ * UTXO fetching, caching, selection, and consolidation
56
+
57
+ ### 2. Network Interaction (`network/`)
58
+
59
+ * **NetworkProvider.ts**
60
+
61
+ * Interface defining required network methods
62
+
63
+ * **RostrumProvider.ts**
64
+
65
+ * Rostrum-specific implementation
66
+ * Connection handling and network interaction management
67
+
68
+ ### 3. dApp Communication (`dapp/`)
69
+
70
+ * **DAppConnector.ts**
71
+
72
+ * dApp ↔ wallet interaction management
73
+
74
+ ### 4. Utilities (`utils/`)
75
+
76
+ * **CryptoUtils.ts**
77
+
78
+ * Cryptographic tools (hashing, encoding)
79
+
80
+ * **WalletUtils.ts**
81
+
82
+ * Wallet tools
83
+
84
+ ## Example Usage
85
+
86
+ ### Initialize Network Provider
87
+
88
+ ```typescript
89
+ import { RostrumProvider } from 'nexa-sdk';
90
+
91
+ const provider = new RostrumProvider('wss://rostrum.example.com');
92
+ await provider.connect();
93
+ ```
94
+
95
+ ### Create and Initialize Wallet
96
+
97
+ ```typescript
98
+ import { Wallet } from 'nexa-sdk';
99
+
100
+ const wallet = Wallet.create();
101
+ await wallet.initialize(provider);
102
+ ```
103
+
104
+ ### Recover Wallet from Seed Phrase
105
+
106
+ ```typescript
107
+ import { Wallet } from 'nexa-sdk';
108
+
109
+ const recoveredWallet = Wallet.fromSeedPhrase('your seed phrase here');
110
+ await recoveredWallet.initialize(provider);
111
+ ```
112
+
113
+ ### Recover Wallet from Extended Private Key (xpriv)
114
+
115
+ ```typescript
116
+ import { Wallet } from 'nexa-sdk';
117
+
118
+ const xprivWallet = Wallet.fromXpriv('your xpriv here');
119
+ await xprivWallet.initialize(provider);
120
+ ```
121
+
122
+ ### Prepare, Sign, and Broadcast WalletTransactionCreator
123
+
124
+ ```typescript
125
+ const utxos = await wallet.utxoStore.getAvailableUTXOs();
126
+ const txDetails = wallet.prepareTransaction({
127
+ utxos,
128
+ outputs: [{ address: 'nexa:q....', amount: 1000 }],
129
+ });
130
+
131
+ const signedTx = wallet.signTransaction(txDetails);
132
+ await wallet.broadcastTransaction(signedTx);
133
+ ```
134
+
135
+ ### Send WalletTransactionCreator (Convenience Method)
136
+
137
+ ```typescript
138
+ await wallet.sendTransaction({
139
+ outputs: [{ address: 'nexa:q....', amount: 1000 }],
140
+ });
141
+ ```
142
+
143
+ ### Export Wallet Data
144
+
145
+ ```typescript
146
+ const exportedData = wallet.export();
147
+ ```
148
+
149
+ ## Component Designs
150
+
151
+ ### 1. Wallet.ts
152
+
153
+ #### Dependencies:
154
+
155
+ * AccountStore
156
+ * UTXOStore
157
+ * NetworkProvider (interface)
158
+ * CryptoUtils
159
+ * WalletUtils
160
+
161
+ #### Functions:
162
+
163
+ * `create(): Wallet`
164
+ * `fromSeedPhrase(phrase: string): Wallet`
165
+ * `fromXpriv(xpriv: string): Wallet`
166
+ * `initialize(provider: NetworkProvider): Promise<void>`
167
+ * `prepareTransaction(details: TransactionDetails): WalletTransactionCreator`
168
+ * `signTransaction(transaction: WalletTransactionCreator): SignedTransaction`
169
+ * `broadcastTransaction(signedTx: SignedTransaction): Promise<void>`
170
+ * `sendTransaction(details: TransactionDetails): Promise<void>`
171
+ * `signMessage(message: string): string`
172
+ * `verifyMessage(message: string, signature: string): boolean`
173
+ * `export(): WalletExport`
174
+
175
+ ### 2. AccountStore.ts
176
+
177
+ #### Dependencies:
178
+
179
+ * CryptoUtils
180
+
181
+ #### Functions:
182
+
183
+ * `createAccount(): DefaultAccount`
184
+ * `importAccount(accountData: AccountImport): DefaultAccount`
185
+ * `exportAccount(accountId: string): AccountExport`
186
+ * `removeAccount(accountId: string): void`
187
+ * `listAccounts(): DefaultAccount[]`
188
+
189
+ ### 3. UTXOStore.ts
190
+
191
+ #### Dependencies:
192
+
193
+ * NetworkProvider (interface)
194
+
195
+ #### Functions:
196
+
197
+ * `getAvailableUTXOs(): Promise<UTXO[]>`
198
+ * `selectUTXOs(amount: number): UTXO[]`
199
+ * `consolidateUTXOs(): WalletTransactionCreator`
200
+
201
+ ### 4. NetworkProvider.ts (Interface)
202
+
203
+ #### Interface Methods:
204
+
205
+ * `connect(): Promise<void>`
206
+ * `disconnect(): Promise<void>`
207
+ * `getUTXOs(addresses: string[]): Promise<UTXO[]>`
208
+ * `broadcastTransaction(signedTx: SignedTransaction): Promise<void>`
209
+ * `getTransactionHistory(address: string): Promise<TransactionHistory[]>`
210
+
211
+ ### 5. RostrumProvider.ts
212
+
213
+ #### Dependencies:
214
+
215
+ * NetworkProvider (interface)
216
+
217
+ #### Functions:
218
+
219
+ * Implements all methods defined in NetworkProvider interface
220
+
221
+ ### 6. DAppConnector.ts
222
+
223
+ #### Dependencies:
224
+
225
+ * CryptoUtils
226
+
227
+ #### Functions:
228
+
229
+ * `authorizeDApp(dAppId: string): Promise<boolean>`
230
+ * `signDAppTransaction(request: DAppTransactionRequest): Promise<SignedTransaction>`
231
+ * `listenToRequests(callback: (request: DAppRequest) => void): void`
232
+ * `respondToRequest(requestId: string, response: DAppResponse): void`
233
+
234
+
235
+ ## Dependency Graph
236
+
237
+ ```
238
+ Wallet.ts
239
+ ├── AccountStore.ts
240
+ │ └── CryptoUtils.ts
241
+ ├── UTXOStore.ts
242
+ │ └── NetworkProvider.ts (interface)
243
+ └── DAppConnector.ts
244
+
245
+ ValidationUtils.ts
246
+ └── CryptoUtils.ts
247
+ ```
248
+
249
+ ## Technical Considerations
250
+
251
+ * Use TypeScript for strong typing and clear interfaces.
252
+ * Implement robust error handling and clear exception messages.
253
+ * Follow modular design principles for easier maintenance and extendability.
254
+
255
+ ## Conclusion
256
+
257
+ The Nexa Wallet SDK provides a complete, developer-friendly toolkit that simplifies building web3 applications on Nexa. It addresses critical developer pain points, accelerates development cycles, and fosters broader adoption through streamlined wallet and network interactions.
package/src/index.ts ADDED
@@ -0,0 +1,93 @@
1
+ // @ts-ignore
2
+ import { version } from '../package.json';
3
+ import Wallet from "./wallet/Wallet";
4
+
5
+ /**
6
+ * Guards against multiple instances of the wallet SDK being loaded.
7
+ * This prevents conflicts and ensures only one version is active at a time.
8
+ * @param version - The version string to check
9
+ * @throws {Error} When multiple instances are detected
10
+ */
11
+ function versionGuard(version: string): void {
12
+ if (version !== undefined) {
13
+ let message = 'More than one instance of Wallet SDK' +
14
+ 'Please make sure to require Wallet SDK and check that submodules do' +
15
+ ' not also include their own Wallet SDK dependency.';
16
+ throw new Error(message);
17
+ }
18
+ }
19
+
20
+ versionGuard((global as any)._walletSdk_ver);
21
+ (global as any)._walletSdk_ver = `v${version}`;
22
+
23
+ /**
24
+ * Wallet SDK - A TypeScript SDK for the Nexa blockchain
25
+ *
26
+ * This SDK provides comprehensive wallet functionality including:
27
+ * - Creating and managing wallets from seed phrases or private keys
28
+ * - Account management with different account types
29
+ * - Transaction building and signing
30
+ * - Token operations and management
31
+ * - Message signing and verification
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * import { Wallet } from 'wallet-sdk-ts';
36
+ *
37
+ * // Create a new wallet
38
+ * const wallet = Wallet.create();
39
+ *
40
+ * // Or restore from seed phrase
41
+ * const wallet = Wallet.fromSeedPhrase('your seed phrase here');
42
+ *
43
+ * // Initialize and discover accounts
44
+ * await wallet.initialize();
45
+ * ```
46
+ */
47
+ const walletSdk = {
48
+ versionGuard,
49
+ version: `v${version}`,
50
+ Wallet
51
+ }
52
+
53
+ export default walletSdk
54
+
55
+ export { default as Wallet } from './wallet/Wallet'
56
+ export { default as WatchOnlyWallet } from './wallet/WatchOnlyWallet'
57
+
58
+ // Export utility enums and types
59
+ export { AccountType, TxTokenType } from './utils/WalletUtils'
60
+
61
+ // Export account interfaces and classes
62
+ export { BaseAccount } from './wallet/accounts/interfaces/BaseAccountInterface'
63
+ export { default as DefaultAccount } from './wallet/accounts/models/DefaultAccount'
64
+ export { default as DappAccount } from './wallet/accounts/models/DappAccount'
65
+ export { default as VaultAccount } from './wallet/accounts/models/VaultAccount'
66
+ export { default as AccountStore } from './wallet/accounts/AccountStore'
67
+
68
+ // Export transaction creators
69
+ export { default as WalletTransactionCreator } from './wallet/transactions/WalletTransactionCreator'
70
+ export { default as WatchOnlyTransactionCreator } from './wallet/transactions/WatchOnlyTransactionCreator'
71
+
72
+ // Export network provider
73
+ export { rostrumProvider } from './network/RostrumProvider'
74
+
75
+ // Export entity types and interfaces
76
+ export type {
77
+ AccountKeys,
78
+ AccountIndexes,
79
+ AddressKey,
80
+ Balance,
81
+ WatchOnlyAddress,
82
+ TxStatus,
83
+ HodlStatus
84
+ } from './models/wallet.entities'
85
+
86
+ export type {
87
+ TxEntityState,
88
+ TxTemplateData,
89
+ TxOptions,
90
+ TokenAction,
91
+ PermissionLabel,
92
+ TransactionEntity
93
+ } from './models/transaction.entities'
@@ -0,0 +1,159 @@
1
+ export type RostrumTransportScheme = 'ws' | 'wss';
2
+
3
+ export const RostrumScheme = {
4
+ WS: 'ws',
5
+ WSS: 'wss'
6
+ }
7
+
8
+ export interface RostrumParams {
9
+ scheme: RostrumTransportScheme;
10
+ host: string;
11
+ port: number;
12
+ }
13
+
14
+ export interface BlockTip {
15
+ height: number;
16
+ hex: string;
17
+ }
18
+
19
+ export interface IFirstUse {
20
+ block_hash: string;
21
+ block_height: number;
22
+ height: number;
23
+ tx_hash: string;
24
+ }
25
+
26
+ export interface ITokenGenesis {
27
+ decimal_places?: number,
28
+ document_hash?: string;
29
+ document_url?: string;
30
+ group: string;
31
+ height: number;
32
+ name?: string;
33
+ op_return?: string;
34
+ ticker?: string;
35
+ token_id_hex: string;
36
+ txid: string;
37
+ txidem: string;
38
+ op_return_id: number;
39
+ }
40
+
41
+ export interface ITokensBalance {
42
+ cursor?: any;
43
+ confirmed: Record<string, bigint | number>;
44
+ unconfirmed: Record<string, bigint | number>;
45
+ }
46
+
47
+ export interface ITokenListUnspent {
48
+ cursor?: any;
49
+ unspent: ITokenUtxo[];
50
+ }
51
+
52
+ export interface ITokenUtxo {
53
+ group: string;
54
+ height: number;
55
+ outpoint_hash: string;
56
+ token_amount: number | bigint;
57
+ token_id_hex: string;
58
+ tx_hash: string;
59
+ tx_pos: number;
60
+ value: number;
61
+ }
62
+
63
+ export interface IListUnspentRecord {
64
+ has_token: boolean;
65
+ height: number;
66
+ outpoint_hash: string;
67
+ tx_hash: string;
68
+ tx_pos: number;
69
+ value: number;
70
+ }
71
+
72
+ export interface IUtxo {
73
+ addresses: string[];
74
+ amount: number;
75
+ group: string;
76
+ group_authority: bigint | number;
77
+ group_quantity: bigint | number;
78
+ height: number;
79
+ scripthash: string;
80
+ scriptpubkey: string;
81
+ spent: ISpent;
82
+ status: string;
83
+ template_argumenthash: string;
84
+ template_scripthash: string;
85
+ token_id_hex: string;
86
+ tx_hash: string;
87
+ tx_idem: string;
88
+ tx_pos: number;
89
+ }
90
+
91
+ export interface ISpent {
92
+ height: number;
93
+ tx_hash: string;
94
+ tx_pos: number;
95
+ }
96
+
97
+ export interface ITransaction {
98
+ blockhash: string;
99
+ blocktime: number;
100
+ confirmations: number;
101
+ fee: number;
102
+ fee_satoshi: number;
103
+ hash: string;
104
+ height: number;
105
+ hex: string;
106
+ locktime: number;
107
+ size: number;
108
+ time: number;
109
+ txid: string;
110
+ txidem: string;
111
+ version: number;
112
+ vin: ITXInput[];
113
+ vout: ITXOutput[];
114
+ }
115
+
116
+ export interface ITXInput {
117
+ outpoint: string;
118
+ scriptSig: IScriptSig;
119
+ sequence: number;
120
+ value: number;
121
+ value_satoshi: bigint | number;
122
+ addresses: string[];
123
+ group: string;
124
+ groupAuthority: bigint | number;
125
+ groupQuantity: bigint | number;
126
+ }
127
+
128
+ export interface ITXOutput {
129
+ n: number;
130
+ outpoint_hash: string;
131
+ scriptPubKey: IScriptPubKey;
132
+ type: number;
133
+ value: number;
134
+ value_satoshi: bigint | number;
135
+ }
136
+
137
+ export interface IScriptSig {
138
+ asm: string;
139
+ hex: string;
140
+ }
141
+
142
+ export interface IScriptPubKey {
143
+ addresses: string[];
144
+ argHash: string;
145
+ asm: string;
146
+ group: string;
147
+ groupAuthority: bigint | number;
148
+ groupQuantity: bigint | number;
149
+ hex: string;
150
+ scriptHash: string;
151
+ token_id_hex?: string;
152
+ type: string;
153
+ }
154
+
155
+ export interface ITXHistory {
156
+ fee?: number;
157
+ height: number;
158
+ tx_hash: string;
159
+ }
@@ -0,0 +1,46 @@
1
+ import {PublicKey, Script} from "libnexa-ts";
2
+
3
+ export type PermissionLabel = 'authorise' | 'mint' | 'melt' | 'rescript' | 'subgroup';
4
+
5
+ export type TxEntityState = 'incoming' | 'outgoing' | 'both'
6
+
7
+ export interface TxTemplateData {
8
+ templateScript: Script;
9
+ constraintScript: Script;
10
+ visibleArgs: any[];
11
+ publicKey: PublicKey;
12
+ }
13
+
14
+ export interface TxOptions {
15
+ isConsolidate?: boolean;
16
+ toChange?: string;
17
+ templateData?: TxTemplateData;
18
+ feeFromAmount?: boolean;
19
+ }
20
+ export interface TokenAction {
21
+ token?: string
22
+ parentToken?: string
23
+ amount: bigint;
24
+ action: string;
25
+ extraData?: {
26
+ perms?: PermissionLabel[],
27
+ outpoint?: string
28
+ opReturnData?: string
29
+ address?: string
30
+ }
31
+ }
32
+
33
+ export interface TransactionEntity {
34
+ txIdem: string
35
+ txId: string
36
+ time: number
37
+ height: number
38
+ payTo: string
39
+ state: TxEntityState
40
+ value: string
41
+ fee: number
42
+ token: string
43
+ extraGroup: string
44
+ txGroupType: number
45
+ tokenAmount: string
46
+ }
@@ -0,0 +1,42 @@
1
+ import type bigDecimal from "js-big-decimal";
2
+ import type {HDPrivateKey, PublicKey} from "libnexa-ts"
3
+
4
+ export interface AccountKeys {
5
+ receiveKeys: AddressKey[];
6
+ changeKeys: AddressKey[];
7
+ }
8
+ export interface WatchOnlyAddress {
9
+ address: string,
10
+ xPub? :PublicKey,
11
+ derivationPath?: string
12
+ }
13
+
14
+ export interface AccountIndexes {
15
+ rIndex: number;
16
+ cIndex: number;
17
+ }
18
+
19
+ export interface TxStatus {
20
+ height: number;
21
+ }
22
+
23
+ export interface HodlStatus {
24
+ idx: number;
25
+ }
26
+
27
+ export interface AddressKey {
28
+ key: HDPrivateKey;
29
+ address: string;
30
+ balance: string;
31
+ tokensBalance: Record<string, Balance>;
32
+ }
33
+
34
+ export interface Balance {
35
+ confirmed: string | number;
36
+ unconfirmed: string | number;
37
+ }
38
+
39
+ export interface Price {
40
+ value: bigDecimal;
41
+ change: bigDecimal;
42
+ }