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