@cmdoss/memwal-sdk 0.9.0 → 1.0.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.
Files changed (174) hide show
  1. package/README.md +157 -52
  2. package/dist/client/ClientMemoryManager.d.ts.map +1 -1
  3. package/dist/client/ClientMemoryManager.js +25 -8
  4. package/dist/client/ClientMemoryManager.js.map +1 -1
  5. package/dist/client/PersonalDataWallet.d.ts.map +1 -1
  6. package/dist/client/SimplePDWClient.d.ts +2 -1
  7. package/dist/client/SimplePDWClient.d.ts.map +1 -1
  8. package/dist/client/SimplePDWClient.js +23 -6
  9. package/dist/client/SimplePDWClient.js.map +1 -1
  10. package/dist/client/namespaces/MemoryNamespace.d.ts +6 -0
  11. package/dist/client/namespaces/MemoryNamespace.d.ts.map +1 -1
  12. package/dist/client/namespaces/MemoryNamespace.js +131 -18
  13. package/dist/client/namespaces/MemoryNamespace.js.map +1 -1
  14. package/dist/client/namespaces/consolidated/StorageNamespace.d.ts +3 -1
  15. package/dist/client/namespaces/consolidated/StorageNamespace.d.ts.map +1 -1
  16. package/dist/client/namespaces/consolidated/StorageNamespace.js.map +1 -1
  17. package/dist/config/ConfigurationHelper.js +61 -61
  18. package/dist/config/index.d.ts +1 -0
  19. package/dist/config/index.d.ts.map +1 -1
  20. package/dist/config/index.js +2 -0
  21. package/dist/config/index.js.map +1 -1
  22. package/dist/config/modelDefaults.d.ts +67 -0
  23. package/dist/config/modelDefaults.d.ts.map +1 -0
  24. package/dist/config/modelDefaults.js +91 -0
  25. package/dist/config/modelDefaults.js.map +1 -0
  26. package/dist/graph/GraphService.d.ts.map +1 -1
  27. package/dist/graph/GraphService.js +22 -21
  28. package/dist/graph/GraphService.js.map +1 -1
  29. package/dist/index.d.ts +1 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +1 -1
  32. package/dist/index.js.map +1 -1
  33. package/dist/langchain/createPDWRAG.js +30 -30
  34. package/dist/pipeline/MemoryPipeline.d.ts.map +1 -1
  35. package/dist/pipeline/MemoryPipeline.js +2 -1
  36. package/dist/pipeline/MemoryPipeline.js.map +1 -1
  37. package/dist/services/GeminiAIService.d.ts.map +1 -1
  38. package/dist/services/GeminiAIService.js +311 -310
  39. package/dist/services/GeminiAIService.js.map +1 -1
  40. package/dist/services/StorageService.d.ts +4 -1
  41. package/dist/services/StorageService.d.ts.map +1 -1
  42. package/dist/services/StorageService.js.map +1 -1
  43. package/dist/services/storage/QuiltBatchManager.d.ts +7 -0
  44. package/dist/services/storage/QuiltBatchManager.d.ts.map +1 -1
  45. package/dist/services/storage/QuiltBatchManager.js +24 -5
  46. package/dist/services/storage/QuiltBatchManager.js.map +1 -1
  47. package/dist/services/storage/WalrusStorageManager.d.ts +10 -1
  48. package/dist/services/storage/WalrusStorageManager.d.ts.map +1 -1
  49. package/dist/services/storage/WalrusStorageManager.js +53 -12
  50. package/dist/services/storage/WalrusStorageManager.js.map +1 -1
  51. package/dist/vector/BrowserHnswIndexService.js +2 -2
  52. package/dist/vector/BrowserHnswIndexService.js.map +1 -1
  53. package/dist/vector/NodeHnswService.js +4 -4
  54. package/dist/vector/NodeHnswService.js.map +1 -1
  55. package/dist/vector/createHnswService.d.ts +4 -0
  56. package/dist/vector/createHnswService.d.ts.map +1 -1
  57. package/dist/vector/createHnswService.js +15 -3
  58. package/dist/vector/createHnswService.js.map +1 -1
  59. package/package.json +1 -1
  60. package/src/access/PermissionService.ts +635 -635
  61. package/src/aggregation/AggregationService.ts +389 -389
  62. package/src/ai-sdk/PDWVectorStore.ts +715 -715
  63. package/src/ai-sdk/index.ts +65 -65
  64. package/src/ai-sdk/tools.ts +460 -460
  65. package/src/ai-sdk/types.ts +404 -404
  66. package/src/batch/BatchManager.ts +597 -597
  67. package/src/batch/BatchingService.ts +429 -429
  68. package/src/batch/MemoryProcessingCache.ts +492 -492
  69. package/src/batch/index.ts +30 -30
  70. package/src/browser.ts +200 -200
  71. package/src/client/ClientMemoryManager.ts +1004 -987
  72. package/src/client/PersonalDataWallet.ts +345 -345
  73. package/src/client/SimplePDWClient.ts +1387 -1369
  74. package/src/client/factory.ts +154 -154
  75. package/src/client/namespaces/AnalyticsNamespace.ts +377 -377
  76. package/src/client/namespaces/BatchNamespace.ts +356 -356
  77. package/src/client/namespaces/CacheNamespace.ts +123 -123
  78. package/src/client/namespaces/CapabilityNamespace.ts +217 -217
  79. package/src/client/namespaces/ClassifyNamespace.ts +169 -169
  80. package/src/client/namespaces/ContextNamespace.ts +297 -297
  81. package/src/client/namespaces/EncryptionNamespace.ts +221 -221
  82. package/src/client/namespaces/GraphNamespace.ts +468 -468
  83. package/src/client/namespaces/IndexNamespace.ts +364 -364
  84. package/src/client/namespaces/MemoryNamespace.ts +1704 -1569
  85. package/src/client/namespaces/PermissionsNamespace.ts +254 -254
  86. package/src/client/namespaces/PipelineNamespace.ts +220 -220
  87. package/src/client/namespaces/StorageNamespace.ts +458 -458
  88. package/src/client/namespaces/TxNamespace.ts +260 -260
  89. package/src/client/namespaces/WalletNamespace.ts +243 -243
  90. package/src/client/namespaces/consolidated/BlockchainNamespace.ts +607 -607
  91. package/src/client/namespaces/consolidated/SecurityNamespace.ts +648 -648
  92. package/src/client/namespaces/consolidated/StorageNamespace.ts +1143 -1141
  93. package/src/client/namespaces/consolidated/index.ts +41 -41
  94. package/src/client/signers/KeypairSigner.ts +108 -108
  95. package/src/client/signers/UnifiedSigner.ts +110 -110
  96. package/src/client/signers/WalletAdapterSigner.ts +159 -159
  97. package/src/client/signers/index.ts +26 -26
  98. package/src/config/ConfigurationHelper.ts +412 -412
  99. package/src/config/defaults.ts +56 -56
  100. package/src/config/index.ts +16 -9
  101. package/src/config/modelDefaults.ts +103 -0
  102. package/src/config/validation.ts +70 -70
  103. package/src/core/index.ts +14 -14
  104. package/src/core/interfaces/IService.ts +307 -307
  105. package/src/core/interfaces/index.ts +8 -8
  106. package/src/core/types/capability.ts +297 -297
  107. package/src/core/types/index.ts +874 -874
  108. package/src/core/types/wallet.ts +270 -270
  109. package/src/core/types.ts +9 -9
  110. package/src/core/wallet.ts +222 -222
  111. package/src/embedding/index.ts +19 -19
  112. package/src/embedding/types.ts +357 -357
  113. package/src/errors/index.ts +602 -602
  114. package/src/errors/recovery.ts +461 -461
  115. package/src/errors/validation.ts +567 -567
  116. package/src/generated/pdw/capability.ts +319 -319
  117. package/src/graph/GraphService.ts +888 -887
  118. package/src/graph/KnowledgeGraphManager.ts +728 -728
  119. package/src/graph/index.ts +25 -25
  120. package/src/index.ts +498 -498
  121. package/src/infrastructure/index.ts +22 -22
  122. package/src/infrastructure/seal/EncryptionService.ts +628 -628
  123. package/src/infrastructure/seal/SealService.ts +613 -613
  124. package/src/infrastructure/seal/index.ts +9 -9
  125. package/src/infrastructure/sui/BlockchainManager.ts +627 -627
  126. package/src/infrastructure/sui/SuiService.ts +888 -888
  127. package/src/infrastructure/sui/index.ts +9 -9
  128. package/src/infrastructure/walrus/StorageManager.ts +604 -604
  129. package/src/infrastructure/walrus/WalrusStorageService.ts +637 -637
  130. package/src/infrastructure/walrus/index.ts +9 -9
  131. package/src/langchain/createPDWRAG.ts +303 -303
  132. package/src/langchain/index.ts +47 -47
  133. package/src/permissions/ConsentRepository.browser.ts +249 -249
  134. package/src/permissions/ConsentRepository.ts +364 -364
  135. package/src/pipeline/MemoryPipeline.ts +863 -862
  136. package/src/pipeline/PipelineManager.ts +683 -683
  137. package/src/pipeline/index.ts +26 -26
  138. package/src/retrieval/AdvancedSearchService.ts +629 -629
  139. package/src/retrieval/MemoryAnalyticsService.ts +711 -711
  140. package/src/retrieval/MemoryDecryptionPipeline.ts +825 -825
  141. package/src/retrieval/index.ts +42 -42
  142. package/src/services/BatchService.ts +352 -352
  143. package/src/services/CapabilityService.ts +464 -464
  144. package/src/services/ClassifierService.ts +465 -465
  145. package/src/services/CrossContextPermissionService.ts +486 -486
  146. package/src/services/EmbeddingService.ts +796 -796
  147. package/src/services/EncryptionService.ts +712 -712
  148. package/src/services/GeminiAIService.ts +754 -753
  149. package/src/services/MemoryIndexService.ts +1009 -1009
  150. package/src/services/MemoryService.ts +369 -369
  151. package/src/services/QueryService.ts +890 -890
  152. package/src/services/StorageService.ts +1185 -1182
  153. package/src/services/TransactionService.ts +838 -838
  154. package/src/services/VectorService.ts +462 -462
  155. package/src/services/ViewService.ts +484 -484
  156. package/src/services/index.ts +25 -25
  157. package/src/services/storage/BlobAttributesManager.ts +333 -333
  158. package/src/services/storage/KnowledgeGraphManager.ts +425 -425
  159. package/src/services/storage/MemorySearchManager.ts +387 -387
  160. package/src/services/storage/QuiltBatchManager.ts +1157 -1130
  161. package/src/services/storage/WalrusMetadataManager.ts +268 -268
  162. package/src/services/storage/WalrusStorageManager.ts +333 -287
  163. package/src/services/storage/index.ts +57 -57
  164. package/src/types/index.ts +13 -13
  165. package/src/utils/index.ts +76 -76
  166. package/src/utils/memoryIndexOnChain.ts +507 -507
  167. package/src/vector/BrowserHnswIndexService.ts +758 -758
  168. package/src/vector/HnswWasmService.ts +731 -731
  169. package/src/vector/IHnswService.ts +233 -233
  170. package/src/vector/NodeHnswService.ts +833 -833
  171. package/src/vector/createHnswService.ts +147 -135
  172. package/src/vector/index.ts +56 -56
  173. package/src/wallet/ContextWalletService.ts +656 -656
  174. package/src/wallet/MainWalletService.ts +317 -317
@@ -1,607 +1,607 @@
1
- /**
2
- * Blockchain Namespace - Consolidated Sui Blockchain Operations
3
- *
4
- * Merges functionality from:
5
- * - TxNamespace: Transaction building and execution
6
- * - WalletNamespace: Wallet operations and queries
7
- *
8
- * Provides a unified interface for all Sui blockchain interactions.
9
- *
10
- * @module client/namespaces/consolidated
11
- */
12
-
13
- import type { ServiceContainer } from '../../SimplePDWClient';
14
- import { Transaction } from '@mysten/sui/transactions';
15
- import type { TransactionResult } from '../../../types';
16
-
17
- // ============================================================================
18
- // Types
19
- // ============================================================================
20
-
21
- /**
22
- * Memory transaction options
23
- */
24
- export interface MemoryTxOptions {
25
- category: string;
26
- vectorId: number;
27
- blobId: string;
28
- importance: number;
29
- gasBudget?: number;
30
- }
31
-
32
- /**
33
- * Batch operation types supported by PTB
34
- */
35
- export type BatchOperationType = 'createMemory' | 'updateMemory' | 'deleteMemory' | 'createCap' | 'transferCap' | 'burnCap';
36
-
37
- /**
38
- * Batch operation definition
39
- */
40
- export interface BatchOperation {
41
- type: BatchOperationType;
42
- options: any;
43
- }
44
-
45
- /**
46
- * Wallet info
47
- */
48
- export interface WalletInfo {
49
- address: string;
50
- connected: boolean;
51
- network: string;
52
- }
53
-
54
- /**
55
- * Object info
56
- */
57
- export interface OwnedObject {
58
- id: string;
59
- type: string;
60
- version: string;
61
- digest: string;
62
- }
63
-
64
- // ============================================================================
65
- // Sub-Namespaces
66
- // ============================================================================
67
-
68
- /**
69
- * Transaction sub-namespace
70
- */
71
- class TxSubNamespace {
72
- constructor(private services: ServiceContainer) {}
73
-
74
- /**
75
- * Build transaction for creating memory record
76
- *
77
- * Automatically uses capability-based creation when encryption is enabled,
78
- * otherwise falls back to lightweight creation without capability.
79
- *
80
- * **Smart capability handling:**
81
- * - If `capId` provided → use it directly (V2)
82
- * - If encryption enabled + capability service available → auto get/create capability (V2)
83
- * - Otherwise → fallback to legacy mode (V1)
84
- *
85
- * @param options - Memory creation options (with optional capId for V2)
86
- * @returns Transaction object
87
- */
88
- async buildCreate(options: MemoryTxOptions & { capId?: string }): Promise<Transaction> {
89
- if (!this.services.tx) {
90
- throw new Error('Transaction service not configured.');
91
- }
92
-
93
- let capId = options.capId;
94
-
95
- // Auto get/create capability if encryption enabled and not explicitly provided
96
- if (!capId && this.services.capability && this.services.config.features?.enableEncryption) {
97
- try {
98
- console.log('🔐 Auto-creating capability for encryption...');
99
- const cap = await this.services.capability.getOrCreate(
100
- {
101
- appId: options.category,
102
- userAddress: this.services.config.userAddress
103
- },
104
- this.services.config.signer // Pass signer for transaction signing
105
- );
106
- capId = cap.id;
107
- console.log(`✅ Capability ready: ${capId}`);
108
- } catch (capError) {
109
- console.warn('⚠️ Failed to auto-create capability:', capError);
110
- // Continue without capability (fallback to legacy mode)
111
- }
112
- }
113
-
114
- // Use capability-based creation if capId available (V2 - RECOMMENDED for encryption)
115
- if (capId) {
116
- return this.services.tx.buildCreateMemoryRecordLightweightWithCap({
117
- category: options.category,
118
- vectorId: options.vectorId,
119
- blobId: options.blobId,
120
- importance: options.importance,
121
- gasBudget: options.gasBudget,
122
- capId: capId
123
- });
124
- }
125
-
126
- // Fallback to legacy lightweight creation (V1 - no encryption support)
127
- return this.services.tx.buildCreateMemoryRecordLightweight({
128
- category: options.category,
129
- vectorId: options.vectorId,
130
- blobId: options.blobId,
131
- importance: options.importance,
132
- gasBudget: options.gasBudget
133
- });
134
- }
135
-
136
- /**
137
- * Build transaction for updating memory metadata
138
- *
139
- * @param memoryId - Memory ID to update
140
- * @param metadataBlobId - New metadata blob ID
141
- * @returns Transaction object
142
- */
143
- buildUpdate(memoryId: string, metadataBlobId: string): Transaction {
144
- if (!this.services.tx) {
145
- throw new Error('Transaction service not configured.');
146
- }
147
- return this.services.tx.buildUpdateMemoryMetadata({
148
- memoryId,
149
- metadataBlobId,
150
- embeddingDimension: 3072
151
- });
152
- }
153
-
154
- /**
155
- * Build transaction for deleting memory record
156
- *
157
- * @param memoryId - Memory ID to delete
158
- * @returns Transaction object
159
- */
160
- buildDelete(memoryId: string): Transaction {
161
- if (!this.services.tx) {
162
- throw new Error('Transaction service not configured.');
163
- }
164
- return this.services.tx.buildDeleteMemoryRecord({ memoryId });
165
- }
166
-
167
- /**
168
- * Execute a transaction
169
- *
170
- * @param tx - Transaction to execute
171
- * @returns Transaction result with digest and status
172
- *
173
- * @example
174
- * ```typescript
175
- * const tx = pdw.blockchain.tx.buildCreate({ ... });
176
- * const result = await pdw.blockchain.tx.execute(tx);
177
- * console.log('Tx digest:', result.digest);
178
- * ```
179
- */
180
- async execute(tx: Transaction): Promise<TransactionResult> {
181
- const signer = this.services.config.signer;
182
-
183
- // Check if signer supports signAndExecuteTransaction (browser wallets like DappKitSigner)
184
- // Browser wallets cannot expose raw Signer for security reasons
185
- if ('signAndExecuteTransaction' in signer && typeof signer.signAndExecuteTransaction === 'function') {
186
- try {
187
- // Use the signer's signAndExecuteTransaction directly
188
- const result = await signer.signAndExecuteTransaction(tx);
189
-
190
- // Get full transaction details to extract created objects
191
- let createdObjects: Array<{ objectId: string; objectType: string }> | undefined;
192
- let mutatedObjects: Array<{ objectId: string; objectType: string }> | undefined;
193
-
194
- if (result.objectChanges && Array.isArray(result.objectChanges)) {
195
- createdObjects = result.objectChanges
196
- .filter((change: any) => change.type === 'created')
197
- .map((change: any) => ({
198
- objectId: change.objectId,
199
- objectType: change.objectType || 'unknown',
200
- }));
201
-
202
- mutatedObjects = result.objectChanges
203
- .filter((change: any) => change.type === 'mutated')
204
- .map((change: any) => ({
205
- objectId: change.objectId,
206
- objectType: change.objectType || 'unknown',
207
- }));
208
- }
209
-
210
- // Determine status from effects
211
- // dapp-kit may not return full effects structure unless custom execute is configured
212
- // We check multiple indicators:
213
- // 1. If effects.status.status explicitly says 'failure', it failed
214
- // 2. If effects.status.status says 'success', it succeeded
215
- // 3. If we have a digest but no effects status, assume success (tx was submitted and confirmed)
216
- let status: 'success' | 'failure';
217
- const effectsStatus = result.effects?.status?.status;
218
-
219
- if (effectsStatus === 'failure') {
220
- status = 'failure';
221
- } else if (effectsStatus === 'success') {
222
- status = 'success';
223
- } else if (result.digest) {
224
- // Has digest but no explicit status - DappKitSigner waits for confirmation
225
- // If we reach here without error, the transaction was successful
226
- status = 'success';
227
- } else {
228
- status = 'failure';
229
- }
230
-
231
- return {
232
- digest: result.digest,
233
- status,
234
- effects: result.effects,
235
- createdObjects,
236
- mutatedObjects,
237
- gasUsed: result.effects?.gasUsed?.computationCost
238
- ? Number(result.effects.gasUsed.computationCost)
239
- : undefined,
240
- error: status === 'failure' ? (result.effects?.status?.error || 'Transaction failed without digest') : undefined,
241
- };
242
- } catch (error) {
243
- console.error('Transaction execution failed:', error);
244
- return {
245
- digest: '',
246
- status: 'failure',
247
- error: error instanceof Error ? error.message : String(error),
248
- };
249
- }
250
- }
251
-
252
- // Fallback: Use TransactionService with raw Signer (Node.js/backend)
253
- if (!this.services.tx) {
254
- throw new Error('Transaction service not configured.');
255
- }
256
- return await this.services.tx.executeTransaction(
257
- tx,
258
- signer.getSigner()
259
- );
260
- }
261
-
262
- /**
263
- * Build batch transaction (combine multiple operations into single PTB)
264
- *
265
- * @param operations - Array of typed operations to batch
266
- * @returns Combined transaction with all move calls
267
- *
268
- * @example
269
- * ```typescript
270
- * const tx = pdw.blockchain.tx.buildBatch([
271
- * { type: 'createMemory', options: { ... } },
272
- * { type: 'createMemory', options: { ... } },
273
- * ]);
274
- * const result = await pdw.blockchain.tx.execute(tx);
275
- * ```
276
- */
277
- buildBatch(operations: BatchOperation[]): Transaction {
278
- if (!this.services.tx) {
279
- throw new Error('Transaction service not configured.');
280
- }
281
- return this.services.tx.buildBatchTransaction(operations);
282
- }
283
-
284
- /**
285
- * Build and execute batch transaction in one call
286
- *
287
- * @param operations - Array of typed operations to batch
288
- * @param gasBudget - Optional gas budget override
289
- * @returns Transaction result with digest and status
290
- */
291
- async executeBatch(operations: BatchOperation[], gasBudget?: number): Promise<TransactionResult> {
292
- if (!this.services.tx) {
293
- throw new Error('Transaction service not configured.');
294
- }
295
- return await this.services.tx.executeBatch(
296
- operations,
297
- this.services.config.signer.getSigner(),
298
- { gasBudget }
299
- );
300
- }
301
-
302
- /**
303
- * Estimate gas cost for transaction
304
- *
305
- * @param tx - Transaction to estimate
306
- * @returns Estimated gas cost
307
- */
308
- async estimateGas(tx: Transaction): Promise<number> {
309
- if (!this.services.tx) {
310
- throw new Error('Transaction service not configured.');
311
- }
312
- try {
313
- const dryRun = await this.services.config.sui.client.dryRunTransactionBlock({
314
- transactionBlock: await tx.build({ client: this.services.config.sui.client })
315
- });
316
- const gasUsed = dryRun.effects.gasUsed;
317
- return Number(gasUsed.computationCost) +
318
- Number(gasUsed.storageCost) -
319
- Number(gasUsed.storageRebate);
320
- } catch (error) {
321
- throw new Error(`Gas estimation failed: ${error instanceof Error ? error.message : String(error)}`);
322
- }
323
- }
324
-
325
- /**
326
- * Wait for transaction confirmation
327
- *
328
- * @param digest - Transaction digest
329
- * @returns Transaction effects
330
- */
331
- async waitForConfirmation(digest: string): Promise<TransactionResult> {
332
- if (!this.services.tx) {
333
- throw new Error('Transaction service not configured.');
334
- }
335
- try {
336
- const result = await this.services.config.sui.client.waitForTransaction({
337
- digest,
338
- options: {
339
- showEffects: true,
340
- showObjectChanges: true,
341
- showEvents: true
342
- }
343
- });
344
- return {
345
- digest: result.digest,
346
- status: result.effects?.status?.status === 'success' ? 'success' : 'failure',
347
- effects: result.effects,
348
- gasUsed: result.effects?.gasUsed?.computationCost
349
- ? Number(result.effects.gasUsed.computationCost)
350
- : undefined
351
- };
352
- } catch (error) {
353
- throw new Error(`Wait for confirmation failed: ${error instanceof Error ? error.message : String(error)}`);
354
- }
355
- }
356
- }
357
-
358
- /**
359
- * Wallet sub-namespace
360
- */
361
- class WalletSubNamespace {
362
- constructor(private services: ServiceContainer) {}
363
-
364
- /**
365
- * Get current wallet address
366
- *
367
- * @returns Wallet address
368
- *
369
- * @example
370
- * ```typescript
371
- * const address = await pdw.blockchain.wallet.getAddress();
372
- * ```
373
- */
374
- async getAddress(): Promise<string> {
375
- return this.services.config.userAddress;
376
- }
377
-
378
- /**
379
- * Check if wallet is connected/ready
380
- *
381
- * @returns Connection status
382
- */
383
- async isConnected(): Promise<boolean> {
384
- try {
385
- const address = await this.getAddress();
386
- return !!address && address.startsWith('0x');
387
- } catch {
388
- return false;
389
- }
390
- }
391
-
392
- /**
393
- * Get wallet info
394
- *
395
- * @returns Wallet information
396
- */
397
- async getInfo(): Promise<WalletInfo> {
398
- return {
399
- address: this.services.config.userAddress,
400
- connected: await this.isConnected(),
401
- network: this.services.config.sui?.network || 'testnet',
402
- };
403
- }
404
-
405
- /**
406
- * Get SUI balance
407
- *
408
- * @returns Balance in MIST (smallest unit)
409
- */
410
- async getBalance(): Promise<bigint> {
411
- const suiClient = this.services.config.sui?.client;
412
- if (!suiClient) {
413
- throw new Error('SuiClient not initialized');
414
- }
415
- const balance = await suiClient.getBalance({
416
- owner: this.services.config.userAddress,
417
- coinType: '0x2::sui::SUI',
418
- });
419
- return BigInt(balance.totalBalance);
420
- }
421
-
422
- /**
423
- * Get formatted SUI balance
424
- *
425
- * @returns Balance in SUI (human readable)
426
- *
427
- * @example
428
- * ```typescript
429
- * const balance = await pdw.blockchain.wallet.getFormattedBalance();
430
- * console.log('Balance:', balance); // "1.2345 SUI"
431
- * ```
432
- */
433
- async getFormattedBalance(): Promise<string> {
434
- const balanceMist = await this.getBalance();
435
- const balanceSui = Number(balanceMist) / 1_000_000_000;
436
- return `${balanceSui.toFixed(4)} SUI`;
437
- }
438
-
439
- /**
440
- * Get all owned objects of a specific type
441
- *
442
- * @param structType - Move struct type (e.g., "0x123::memory::Memory")
443
- * @returns Array of owned objects
444
- */
445
- async getOwnedObjects(structType: string): Promise<OwnedObject[]> {
446
- const suiClient = this.services.config.sui?.client;
447
- if (!suiClient) {
448
- throw new Error('SuiClient not initialized');
449
- }
450
- const response = await suiClient.getOwnedObjects({
451
- owner: this.services.config.userAddress,
452
- filter: { StructType: structType },
453
- options: { showContent: true, showType: true },
454
- });
455
- return response.data.map(obj => ({
456
- id: obj.data?.objectId || '',
457
- type: obj.data?.type || '',
458
- version: obj.data?.version || '',
459
- digest: obj.data?.digest || '',
460
- }));
461
- }
462
-
463
- /**
464
- * Get all MemoryCap objects owned by user
465
- *
466
- * @returns Array of MemoryCap object IDs
467
- */
468
- async getMemoryCaps(): Promise<OwnedObject[]> {
469
- const packageId = this.services.config.sui?.packageId;
470
- if (!packageId) {
471
- throw new Error('Package ID not configured');
472
- }
473
- return await this.getOwnedObjects(`${packageId}::capability::MemoryCap`);
474
- }
475
-
476
- /**
477
- * Get all Memory objects owned by user
478
- *
479
- * @returns Array of Memory object IDs
480
- */
481
- async getMemories(): Promise<OwnedObject[]> {
482
- const packageId = this.services.config.sui?.packageId;
483
- if (!packageId) {
484
- throw new Error('Package ID not configured');
485
- }
486
- return await this.getOwnedObjects(`${packageId}::memory::Memory`);
487
- }
488
-
489
- /**
490
- * Sign a message with the connected wallet
491
- *
492
- * @param message - Message to sign (string or bytes)
493
- * @returns Signature as hex string
494
- */
495
- async signMessage(message: string | Uint8Array): Promise<string> {
496
- const signer = this.services.config.signer;
497
- const messageBytes = typeof message === 'string'
498
- ? new TextEncoder().encode(message)
499
- : message;
500
- const result = await signer.signPersonalMessage(messageBytes);
501
- if (typeof result === 'string') {
502
- return result;
503
- }
504
- if (result && typeof result === 'object' && 'signature' in result) {
505
- return result.signature as string;
506
- }
507
- throw new Error('Unexpected signature format');
508
- }
509
-
510
- /**
511
- * Get object by ID
512
- *
513
- * @param objectId - Object ID to fetch
514
- * @returns Object data or null
515
- */
516
- async getObject(objectId: string): Promise<any | null> {
517
- const suiClient = this.services.config.sui?.client;
518
- if (!suiClient) {
519
- throw new Error('SuiClient not initialized');
520
- }
521
- try {
522
- const response = await suiClient.getObject({
523
- id: objectId,
524
- options: { showContent: true, showOwner: true, showType: true },
525
- });
526
- return response.data || null;
527
- } catch {
528
- return null;
529
- }
530
- }
531
- }
532
-
533
- // ============================================================================
534
- // Blockchain Namespace
535
- // ============================================================================
536
-
537
- /**
538
- * Blockchain Namespace - Unified Sui Operations
539
- *
540
- * Consolidates transaction building/execution and wallet operations.
541
- *
542
- * @example
543
- * ```typescript
544
- * // Transaction operations
545
- * const tx = pdw.blockchain.tx.buildCreate({ ... });
546
- * const result = await pdw.blockchain.tx.execute(tx);
547
- *
548
- * // Wallet operations
549
- * const address = await pdw.blockchain.wallet.getAddress();
550
- * const balance = await pdw.blockchain.wallet.getFormattedBalance();
551
- * ```
552
- */
553
- export class BlockchainNamespace {
554
- private _tx: TxSubNamespace;
555
- private _wallet: WalletSubNamespace;
556
-
557
- constructor(private services: ServiceContainer) {
558
- this._tx = new TxSubNamespace(services);
559
- this._wallet = new WalletSubNamespace(services);
560
- }
561
-
562
- /**
563
- * Transaction operations
564
- */
565
- get tx(): TxSubNamespace {
566
- return this._tx;
567
- }
568
-
569
- /**
570
- * Wallet operations
571
- */
572
- get wallet(): WalletSubNamespace {
573
- return this._wallet;
574
- }
575
-
576
- // ==========================================================================
577
- // Convenience Methods (Top-level shortcuts)
578
- // ==========================================================================
579
-
580
- /**
581
- * Get current wallet address (shortcut)
582
- *
583
- * @returns Wallet address
584
- */
585
- async getAddress(): Promise<string> {
586
- return this._wallet.getAddress();
587
- }
588
-
589
- /**
590
- * Get SUI balance (shortcut)
591
- *
592
- * @returns Balance in MIST
593
- */
594
- async getBalance(): Promise<bigint> {
595
- return this._wallet.getBalance();
596
- }
597
-
598
- /**
599
- * Execute a transaction (shortcut)
600
- *
601
- * @param tx - Transaction to execute
602
- * @returns Transaction result
603
- */
604
- async execute(tx: Transaction): Promise<TransactionResult> {
605
- return this._tx.execute(tx);
606
- }
607
- }
1
+ /**
2
+ * Blockchain Namespace - Consolidated Sui Blockchain Operations
3
+ *
4
+ * Merges functionality from:
5
+ * - TxNamespace: Transaction building and execution
6
+ * - WalletNamespace: Wallet operations and queries
7
+ *
8
+ * Provides a unified interface for all Sui blockchain interactions.
9
+ *
10
+ * @module client/namespaces/consolidated
11
+ */
12
+
13
+ import type { ServiceContainer } from '../../SimplePDWClient';
14
+ import { Transaction } from '@mysten/sui/transactions';
15
+ import type { TransactionResult } from '../../../types';
16
+
17
+ // ============================================================================
18
+ // Types
19
+ // ============================================================================
20
+
21
+ /**
22
+ * Memory transaction options
23
+ */
24
+ export interface MemoryTxOptions {
25
+ category: string;
26
+ vectorId: number;
27
+ blobId: string;
28
+ importance: number;
29
+ gasBudget?: number;
30
+ }
31
+
32
+ /**
33
+ * Batch operation types supported by PTB
34
+ */
35
+ export type BatchOperationType = 'createMemory' | 'updateMemory' | 'deleteMemory' | 'createCap' | 'transferCap' | 'burnCap';
36
+
37
+ /**
38
+ * Batch operation definition
39
+ */
40
+ export interface BatchOperation {
41
+ type: BatchOperationType;
42
+ options: any;
43
+ }
44
+
45
+ /**
46
+ * Wallet info
47
+ */
48
+ export interface WalletInfo {
49
+ address: string;
50
+ connected: boolean;
51
+ network: string;
52
+ }
53
+
54
+ /**
55
+ * Object info
56
+ */
57
+ export interface OwnedObject {
58
+ id: string;
59
+ type: string;
60
+ version: string;
61
+ digest: string;
62
+ }
63
+
64
+ // ============================================================================
65
+ // Sub-Namespaces
66
+ // ============================================================================
67
+
68
+ /**
69
+ * Transaction sub-namespace
70
+ */
71
+ class TxSubNamespace {
72
+ constructor(private services: ServiceContainer) {}
73
+
74
+ /**
75
+ * Build transaction for creating memory record
76
+ *
77
+ * Automatically uses capability-based creation when encryption is enabled,
78
+ * otherwise falls back to lightweight creation without capability.
79
+ *
80
+ * **Smart capability handling:**
81
+ * - If `capId` provided → use it directly (V2)
82
+ * - If encryption enabled + capability service available → auto get/create capability (V2)
83
+ * - Otherwise → fallback to legacy mode (V1)
84
+ *
85
+ * @param options - Memory creation options (with optional capId for V2)
86
+ * @returns Transaction object
87
+ */
88
+ async buildCreate(options: MemoryTxOptions & { capId?: string }): Promise<Transaction> {
89
+ if (!this.services.tx) {
90
+ throw new Error('Transaction service not configured.');
91
+ }
92
+
93
+ let capId = options.capId;
94
+
95
+ // Auto get/create capability if encryption enabled and not explicitly provided
96
+ if (!capId && this.services.capability && this.services.config.features?.enableEncryption) {
97
+ try {
98
+ console.log('🔐 Auto-creating capability for encryption...');
99
+ const cap = await this.services.capability.getOrCreate(
100
+ {
101
+ appId: options.category,
102
+ userAddress: this.services.config.userAddress
103
+ },
104
+ this.services.config.signer // Pass signer for transaction signing
105
+ );
106
+ capId = cap.id;
107
+ console.log(`✅ Capability ready: ${capId}`);
108
+ } catch (capError) {
109
+ console.warn('⚠️ Failed to auto-create capability:', capError);
110
+ // Continue without capability (fallback to legacy mode)
111
+ }
112
+ }
113
+
114
+ // Use capability-based creation if capId available (V2 - RECOMMENDED for encryption)
115
+ if (capId) {
116
+ return this.services.tx.buildCreateMemoryRecordLightweightWithCap({
117
+ category: options.category,
118
+ vectorId: options.vectorId,
119
+ blobId: options.blobId,
120
+ importance: options.importance,
121
+ gasBudget: options.gasBudget,
122
+ capId: capId
123
+ });
124
+ }
125
+
126
+ // Fallback to legacy lightweight creation (V1 - no encryption support)
127
+ return this.services.tx.buildCreateMemoryRecordLightweight({
128
+ category: options.category,
129
+ vectorId: options.vectorId,
130
+ blobId: options.blobId,
131
+ importance: options.importance,
132
+ gasBudget: options.gasBudget
133
+ });
134
+ }
135
+
136
+ /**
137
+ * Build transaction for updating memory metadata
138
+ *
139
+ * @param memoryId - Memory ID to update
140
+ * @param metadataBlobId - New metadata blob ID
141
+ * @returns Transaction object
142
+ */
143
+ buildUpdate(memoryId: string, metadataBlobId: string): Transaction {
144
+ if (!this.services.tx) {
145
+ throw new Error('Transaction service not configured.');
146
+ }
147
+ return this.services.tx.buildUpdateMemoryMetadata({
148
+ memoryId,
149
+ metadataBlobId,
150
+ embeddingDimension: 3072
151
+ });
152
+ }
153
+
154
+ /**
155
+ * Build transaction for deleting memory record
156
+ *
157
+ * @param memoryId - Memory ID to delete
158
+ * @returns Transaction object
159
+ */
160
+ buildDelete(memoryId: string): Transaction {
161
+ if (!this.services.tx) {
162
+ throw new Error('Transaction service not configured.');
163
+ }
164
+ return this.services.tx.buildDeleteMemoryRecord({ memoryId });
165
+ }
166
+
167
+ /**
168
+ * Execute a transaction
169
+ *
170
+ * @param tx - Transaction to execute
171
+ * @returns Transaction result with digest and status
172
+ *
173
+ * @example
174
+ * ```typescript
175
+ * const tx = pdw.blockchain.tx.buildCreate({ ... });
176
+ * const result = await pdw.blockchain.tx.execute(tx);
177
+ * console.log('Tx digest:', result.digest);
178
+ * ```
179
+ */
180
+ async execute(tx: Transaction): Promise<TransactionResult> {
181
+ const signer = this.services.config.signer;
182
+
183
+ // Check if signer supports signAndExecuteTransaction (browser wallets like DappKitSigner)
184
+ // Browser wallets cannot expose raw Signer for security reasons
185
+ if ('signAndExecuteTransaction' in signer && typeof signer.signAndExecuteTransaction === 'function') {
186
+ try {
187
+ // Use the signer's signAndExecuteTransaction directly
188
+ const result = await signer.signAndExecuteTransaction(tx);
189
+
190
+ // Get full transaction details to extract created objects
191
+ let createdObjects: Array<{ objectId: string; objectType: string }> | undefined;
192
+ let mutatedObjects: Array<{ objectId: string; objectType: string }> | undefined;
193
+
194
+ if (result.objectChanges && Array.isArray(result.objectChanges)) {
195
+ createdObjects = result.objectChanges
196
+ .filter((change: any) => change.type === 'created')
197
+ .map((change: any) => ({
198
+ objectId: change.objectId,
199
+ objectType: change.objectType || 'unknown',
200
+ }));
201
+
202
+ mutatedObjects = result.objectChanges
203
+ .filter((change: any) => change.type === 'mutated')
204
+ .map((change: any) => ({
205
+ objectId: change.objectId,
206
+ objectType: change.objectType || 'unknown',
207
+ }));
208
+ }
209
+
210
+ // Determine status from effects
211
+ // dapp-kit may not return full effects structure unless custom execute is configured
212
+ // We check multiple indicators:
213
+ // 1. If effects.status.status explicitly says 'failure', it failed
214
+ // 2. If effects.status.status says 'success', it succeeded
215
+ // 3. If we have a digest but no effects status, assume success (tx was submitted and confirmed)
216
+ let status: 'success' | 'failure';
217
+ const effectsStatus = result.effects?.status?.status;
218
+
219
+ if (effectsStatus === 'failure') {
220
+ status = 'failure';
221
+ } else if (effectsStatus === 'success') {
222
+ status = 'success';
223
+ } else if (result.digest) {
224
+ // Has digest but no explicit status - DappKitSigner waits for confirmation
225
+ // If we reach here without error, the transaction was successful
226
+ status = 'success';
227
+ } else {
228
+ status = 'failure';
229
+ }
230
+
231
+ return {
232
+ digest: result.digest,
233
+ status,
234
+ effects: result.effects,
235
+ createdObjects,
236
+ mutatedObjects,
237
+ gasUsed: result.effects?.gasUsed?.computationCost
238
+ ? Number(result.effects.gasUsed.computationCost)
239
+ : undefined,
240
+ error: status === 'failure' ? (result.effects?.status?.error || 'Transaction failed without digest') : undefined,
241
+ };
242
+ } catch (error) {
243
+ console.error('Transaction execution failed:', error);
244
+ return {
245
+ digest: '',
246
+ status: 'failure',
247
+ error: error instanceof Error ? error.message : String(error),
248
+ };
249
+ }
250
+ }
251
+
252
+ // Fallback: Use TransactionService with raw Signer (Node.js/backend)
253
+ if (!this.services.tx) {
254
+ throw new Error('Transaction service not configured.');
255
+ }
256
+ return await this.services.tx.executeTransaction(
257
+ tx,
258
+ signer.getSigner()
259
+ );
260
+ }
261
+
262
+ /**
263
+ * Build batch transaction (combine multiple operations into single PTB)
264
+ *
265
+ * @param operations - Array of typed operations to batch
266
+ * @returns Combined transaction with all move calls
267
+ *
268
+ * @example
269
+ * ```typescript
270
+ * const tx = pdw.blockchain.tx.buildBatch([
271
+ * { type: 'createMemory', options: { ... } },
272
+ * { type: 'createMemory', options: { ... } },
273
+ * ]);
274
+ * const result = await pdw.blockchain.tx.execute(tx);
275
+ * ```
276
+ */
277
+ buildBatch(operations: BatchOperation[]): Transaction {
278
+ if (!this.services.tx) {
279
+ throw new Error('Transaction service not configured.');
280
+ }
281
+ return this.services.tx.buildBatchTransaction(operations);
282
+ }
283
+
284
+ /**
285
+ * Build and execute batch transaction in one call
286
+ *
287
+ * @param operations - Array of typed operations to batch
288
+ * @param gasBudget - Optional gas budget override
289
+ * @returns Transaction result with digest and status
290
+ */
291
+ async executeBatch(operations: BatchOperation[], gasBudget?: number): Promise<TransactionResult> {
292
+ if (!this.services.tx) {
293
+ throw new Error('Transaction service not configured.');
294
+ }
295
+ return await this.services.tx.executeBatch(
296
+ operations,
297
+ this.services.config.signer.getSigner(),
298
+ { gasBudget }
299
+ );
300
+ }
301
+
302
+ /**
303
+ * Estimate gas cost for transaction
304
+ *
305
+ * @param tx - Transaction to estimate
306
+ * @returns Estimated gas cost
307
+ */
308
+ async estimateGas(tx: Transaction): Promise<number> {
309
+ if (!this.services.tx) {
310
+ throw new Error('Transaction service not configured.');
311
+ }
312
+ try {
313
+ const dryRun = await this.services.config.sui.client.dryRunTransactionBlock({
314
+ transactionBlock: await tx.build({ client: this.services.config.sui.client })
315
+ });
316
+ const gasUsed = dryRun.effects.gasUsed;
317
+ return Number(gasUsed.computationCost) +
318
+ Number(gasUsed.storageCost) -
319
+ Number(gasUsed.storageRebate);
320
+ } catch (error) {
321
+ throw new Error(`Gas estimation failed: ${error instanceof Error ? error.message : String(error)}`);
322
+ }
323
+ }
324
+
325
+ /**
326
+ * Wait for transaction confirmation
327
+ *
328
+ * @param digest - Transaction digest
329
+ * @returns Transaction effects
330
+ */
331
+ async waitForConfirmation(digest: string): Promise<TransactionResult> {
332
+ if (!this.services.tx) {
333
+ throw new Error('Transaction service not configured.');
334
+ }
335
+ try {
336
+ const result = await this.services.config.sui.client.waitForTransaction({
337
+ digest,
338
+ options: {
339
+ showEffects: true,
340
+ showObjectChanges: true,
341
+ showEvents: true
342
+ }
343
+ });
344
+ return {
345
+ digest: result.digest,
346
+ status: result.effects?.status?.status === 'success' ? 'success' : 'failure',
347
+ effects: result.effects,
348
+ gasUsed: result.effects?.gasUsed?.computationCost
349
+ ? Number(result.effects.gasUsed.computationCost)
350
+ : undefined
351
+ };
352
+ } catch (error) {
353
+ throw new Error(`Wait for confirmation failed: ${error instanceof Error ? error.message : String(error)}`);
354
+ }
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Wallet sub-namespace
360
+ */
361
+ class WalletSubNamespace {
362
+ constructor(private services: ServiceContainer) {}
363
+
364
+ /**
365
+ * Get current wallet address
366
+ *
367
+ * @returns Wallet address
368
+ *
369
+ * @example
370
+ * ```typescript
371
+ * const address = await pdw.blockchain.wallet.getAddress();
372
+ * ```
373
+ */
374
+ async getAddress(): Promise<string> {
375
+ return this.services.config.userAddress;
376
+ }
377
+
378
+ /**
379
+ * Check if wallet is connected/ready
380
+ *
381
+ * @returns Connection status
382
+ */
383
+ async isConnected(): Promise<boolean> {
384
+ try {
385
+ const address = await this.getAddress();
386
+ return !!address && address.startsWith('0x');
387
+ } catch {
388
+ return false;
389
+ }
390
+ }
391
+
392
+ /**
393
+ * Get wallet info
394
+ *
395
+ * @returns Wallet information
396
+ */
397
+ async getInfo(): Promise<WalletInfo> {
398
+ return {
399
+ address: this.services.config.userAddress,
400
+ connected: await this.isConnected(),
401
+ network: this.services.config.sui?.network || 'testnet',
402
+ };
403
+ }
404
+
405
+ /**
406
+ * Get SUI balance
407
+ *
408
+ * @returns Balance in MIST (smallest unit)
409
+ */
410
+ async getBalance(): Promise<bigint> {
411
+ const suiClient = this.services.config.sui?.client;
412
+ if (!suiClient) {
413
+ throw new Error('SuiClient not initialized');
414
+ }
415
+ const balance = await suiClient.getBalance({
416
+ owner: this.services.config.userAddress,
417
+ coinType: '0x2::sui::SUI',
418
+ });
419
+ return BigInt(balance.totalBalance);
420
+ }
421
+
422
+ /**
423
+ * Get formatted SUI balance
424
+ *
425
+ * @returns Balance in SUI (human readable)
426
+ *
427
+ * @example
428
+ * ```typescript
429
+ * const balance = await pdw.blockchain.wallet.getFormattedBalance();
430
+ * console.log('Balance:', balance); // "1.2345 SUI"
431
+ * ```
432
+ */
433
+ async getFormattedBalance(): Promise<string> {
434
+ const balanceMist = await this.getBalance();
435
+ const balanceSui = Number(balanceMist) / 1_000_000_000;
436
+ return `${balanceSui.toFixed(4)} SUI`;
437
+ }
438
+
439
+ /**
440
+ * Get all owned objects of a specific type
441
+ *
442
+ * @param structType - Move struct type (e.g., "0x123::memory::Memory")
443
+ * @returns Array of owned objects
444
+ */
445
+ async getOwnedObjects(structType: string): Promise<OwnedObject[]> {
446
+ const suiClient = this.services.config.sui?.client;
447
+ if (!suiClient) {
448
+ throw new Error('SuiClient not initialized');
449
+ }
450
+ const response = await suiClient.getOwnedObjects({
451
+ owner: this.services.config.userAddress,
452
+ filter: { StructType: structType },
453
+ options: { showContent: true, showType: true },
454
+ });
455
+ return response.data.map(obj => ({
456
+ id: obj.data?.objectId || '',
457
+ type: obj.data?.type || '',
458
+ version: obj.data?.version || '',
459
+ digest: obj.data?.digest || '',
460
+ }));
461
+ }
462
+
463
+ /**
464
+ * Get all MemoryCap objects owned by user
465
+ *
466
+ * @returns Array of MemoryCap object IDs
467
+ */
468
+ async getMemoryCaps(): Promise<OwnedObject[]> {
469
+ const packageId = this.services.config.sui?.packageId;
470
+ if (!packageId) {
471
+ throw new Error('Package ID not configured');
472
+ }
473
+ return await this.getOwnedObjects(`${packageId}::capability::MemoryCap`);
474
+ }
475
+
476
+ /**
477
+ * Get all Memory objects owned by user
478
+ *
479
+ * @returns Array of Memory object IDs
480
+ */
481
+ async getMemories(): Promise<OwnedObject[]> {
482
+ const packageId = this.services.config.sui?.packageId;
483
+ if (!packageId) {
484
+ throw new Error('Package ID not configured');
485
+ }
486
+ return await this.getOwnedObjects(`${packageId}::memory::Memory`);
487
+ }
488
+
489
+ /**
490
+ * Sign a message with the connected wallet
491
+ *
492
+ * @param message - Message to sign (string or bytes)
493
+ * @returns Signature as hex string
494
+ */
495
+ async signMessage(message: string | Uint8Array): Promise<string> {
496
+ const signer = this.services.config.signer;
497
+ const messageBytes = typeof message === 'string'
498
+ ? new TextEncoder().encode(message)
499
+ : message;
500
+ const result = await signer.signPersonalMessage(messageBytes);
501
+ if (typeof result === 'string') {
502
+ return result;
503
+ }
504
+ if (result && typeof result === 'object' && 'signature' in result) {
505
+ return result.signature as string;
506
+ }
507
+ throw new Error('Unexpected signature format');
508
+ }
509
+
510
+ /**
511
+ * Get object by ID
512
+ *
513
+ * @param objectId - Object ID to fetch
514
+ * @returns Object data or null
515
+ */
516
+ async getObject(objectId: string): Promise<any | null> {
517
+ const suiClient = this.services.config.sui?.client;
518
+ if (!suiClient) {
519
+ throw new Error('SuiClient not initialized');
520
+ }
521
+ try {
522
+ const response = await suiClient.getObject({
523
+ id: objectId,
524
+ options: { showContent: true, showOwner: true, showType: true },
525
+ });
526
+ return response.data || null;
527
+ } catch {
528
+ return null;
529
+ }
530
+ }
531
+ }
532
+
533
+ // ============================================================================
534
+ // Blockchain Namespace
535
+ // ============================================================================
536
+
537
+ /**
538
+ * Blockchain Namespace - Unified Sui Operations
539
+ *
540
+ * Consolidates transaction building/execution and wallet operations.
541
+ *
542
+ * @example
543
+ * ```typescript
544
+ * // Transaction operations
545
+ * const tx = pdw.blockchain.tx.buildCreate({ ... });
546
+ * const result = await pdw.blockchain.tx.execute(tx);
547
+ *
548
+ * // Wallet operations
549
+ * const address = await pdw.blockchain.wallet.getAddress();
550
+ * const balance = await pdw.blockchain.wallet.getFormattedBalance();
551
+ * ```
552
+ */
553
+ export class BlockchainNamespace {
554
+ private _tx: TxSubNamespace;
555
+ private _wallet: WalletSubNamespace;
556
+
557
+ constructor(private services: ServiceContainer) {
558
+ this._tx = new TxSubNamespace(services);
559
+ this._wallet = new WalletSubNamespace(services);
560
+ }
561
+
562
+ /**
563
+ * Transaction operations
564
+ */
565
+ get tx(): TxSubNamespace {
566
+ return this._tx;
567
+ }
568
+
569
+ /**
570
+ * Wallet operations
571
+ */
572
+ get wallet(): WalletSubNamespace {
573
+ return this._wallet;
574
+ }
575
+
576
+ // ==========================================================================
577
+ // Convenience Methods (Top-level shortcuts)
578
+ // ==========================================================================
579
+
580
+ /**
581
+ * Get current wallet address (shortcut)
582
+ *
583
+ * @returns Wallet address
584
+ */
585
+ async getAddress(): Promise<string> {
586
+ return this._wallet.getAddress();
587
+ }
588
+
589
+ /**
590
+ * Get SUI balance (shortcut)
591
+ *
592
+ * @returns Balance in MIST
593
+ */
594
+ async getBalance(): Promise<bigint> {
595
+ return this._wallet.getBalance();
596
+ }
597
+
598
+ /**
599
+ * Execute a transaction (shortcut)
600
+ *
601
+ * @param tx - Transaction to execute
602
+ * @returns Transaction result
603
+ */
604
+ async execute(tx: Transaction): Promise<TransactionResult> {
605
+ return this._tx.execute(tx);
606
+ }
607
+ }