@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,486 +1,486 @@
1
- /**
2
- * Cross-Context Permission Service
3
- *
4
- * Manages cross-context access permissions for the Personal Data Wallet.
5
- * Enables apps to request and manage access to data from other app contexts.
6
- */
7
-
8
- import { Transaction } from '@mysten/sui/transactions';
9
- import { normalizeSuiAddress } from '@mysten/sui/utils';
10
- import type { SuiClient } from '@mysten/sui/client';
11
- import type { Signer } from '@mysten/sui/cryptography';
12
-
13
- export interface CrossContextPermissionConfig {
14
- packageId: string;
15
- accessRegistryId: string;
16
- }
17
-
18
- export interface RegisterContextWalletOptions {
19
- contextWallet: string;
20
- derivationIndex: number;
21
- appHint?: string;
22
- }
23
-
24
- export interface GrantWalletAllowlistOptions {
25
- requestingWallet: string;
26
- targetWallet: string;
27
- scope?: string;
28
- accessLevel: 'read' | 'write';
29
- expiresAt: number; // Unix timestamp in milliseconds
30
- }
31
-
32
- export interface RevokeWalletAllowlistOptions {
33
- requestingWallet: string;
34
- targetWallet: string;
35
- scope?: string;
36
- }
37
-
38
- export interface WalletAllowlistPermission {
39
- requestingWallet: string;
40
- targetWallet: string;
41
- scope: string;
42
- accessLevel: string;
43
- grantedAt: number;
44
- expiresAt: number;
45
- grantedBy: string;
46
- }
47
-
48
- export interface WalletAllowlistHistoryEvent {
49
- timestamp: number;
50
- action: 'grant' | 'revoke';
51
- requestingWallet: string;
52
- targetWallet: string;
53
- scope: string;
54
- accessLevel: string;
55
- expiresAt: number;
56
- grantedBy: string;
57
- }
58
-
59
- export interface WalletAllowlistHistoryFilter {
60
- requestingWallet?: string;
61
- targetWallet?: string;
62
- }
63
-
64
- export interface CheckWalletAccessOptions {
65
- requestingWallet: string;
66
- targetWallet?: string;
67
- scope?: string;
68
- }
69
-
70
- interface WalletAllowlistEvent {
71
- key: string;
72
- requestingWallet: string;
73
- targetWallet: string;
74
- scope: string;
75
- accessLevel: string;
76
- granted: boolean;
77
- expiresAt: number;
78
- grantedAt: number;
79
- grantedBy: string;
80
- }
81
-
82
- /**
83
- * Service for managing cross-context permissions
84
- */
85
- export class CrossContextPermissionService {
86
- private packageId: string;
87
- private accessRegistryId: string;
88
- private client: SuiClient;
89
-
90
- constructor(config: CrossContextPermissionConfig, client: SuiClient) {
91
- this.packageId = config.packageId;
92
- this.accessRegistryId = config.accessRegistryId;
93
- this.client = client;
94
- }
95
-
96
- /**
97
- * Register a new context wallet for an app
98
- *
99
- * @param options - Context registration options
100
- * @param signer - Transaction signer
101
- * @returns Transaction digest
102
- */
103
- async registerContextWallet(
104
- options: RegisterContextWalletOptions,
105
- signer: Signer
106
- ): Promise<string> {
107
- const tx = this.buildRegisterContextWalletTransaction(options);
108
-
109
- const result = await this.client.signAndExecuteTransaction({
110
- transaction: tx,
111
- signer,
112
- options: {
113
- showEffects: true,
114
- showEvents: true,
115
- },
116
- });
117
-
118
- // Wait for transaction to be finalized to prevent gas coin version conflicts
119
- if (result.digest) {
120
- await this.client.waitForTransaction({ digest: result.digest });
121
- }
122
-
123
- if (result.effects?.status?.status !== 'success') {
124
- throw new Error(`Failed to register context: ${result.effects?.status?.error}`);
125
- }
126
-
127
- return result.digest;
128
- }
129
-
130
- /**
131
- * Build transaction to register a context wallet
132
- *
133
- * @param options - Context registration options
134
- * @returns Transaction object
135
- */
136
- buildRegisterContextWalletTransaction(options: RegisterContextWalletOptions): Transaction {
137
- const tx = new Transaction();
138
-
139
- tx.moveCall({
140
- target: `${this.packageId}::capability::register_context_wallet`,
141
- arguments: [
142
- tx.object(this.accessRegistryId),
143
- tx.pure.address(normalizeSuiAddress(options.contextWallet)),
144
- tx.pure.u64(options.derivationIndex),
145
- tx.pure.string(options.appHint ?? ''),
146
- tx.object('0x6'), // Clock object
147
- ],
148
- });
149
-
150
- return tx;
151
- }
152
-
153
- /**
154
- * Grant cross-context access permission
155
- *
156
- * @param options - Permission grant options
157
- * @param signer - Transaction signer
158
- * @returns Transaction digest
159
- */
160
- async grantWalletAllowlistAccess(
161
- options: GrantWalletAllowlistOptions,
162
- signer: Signer
163
- ): Promise<string> {
164
- const tx = this.buildGrantWalletAllowlistTransaction(options);
165
-
166
- const result = await this.client.signAndExecuteTransaction({
167
- transaction: tx,
168
- signer,
169
- options: {
170
- showEffects: true,
171
- showEvents: true,
172
- },
173
- });
174
-
175
- // Wait for transaction to be finalized to prevent gas coin version conflicts
176
- if (result.digest) {
177
- await this.client.waitForTransaction({ digest: result.digest });
178
- }
179
-
180
- if (result.effects?.status?.status !== 'success') {
181
- throw new Error(`Failed to grant access: ${result.effects?.status?.error}`);
182
- }
183
-
184
- return result.digest;
185
- }
186
-
187
- /**
188
- * Build transaction to grant cross-context access
189
- *
190
- * @param options - Permission grant options
191
- * @returns Transaction object
192
- */
193
- buildGrantWalletAllowlistTransaction(
194
- options: GrantWalletAllowlistOptions
195
- ): Transaction {
196
- const tx = new Transaction();
197
-
198
- tx.moveCall({
199
- target: `${this.packageId}::capability::grant_wallet_allowlist_access`,
200
- arguments: [
201
- tx.object(this.accessRegistryId),
202
- tx.pure.address(normalizeSuiAddress(options.requestingWallet)),
203
- tx.pure.address(normalizeSuiAddress(options.targetWallet)),
204
- tx.pure.string(options.scope ?? 'read'),
205
- tx.pure.string(options.accessLevel),
206
- tx.pure.u64(options.expiresAt),
207
- tx.object('0x6'), // Clock object
208
- ],
209
- });
210
-
211
- return tx;
212
- }
213
-
214
- /**
215
- * Revoke cross-context access permission
216
- *
217
- * @param options - Permission revocation options
218
- * @param signer - Transaction signer
219
- * @returns Transaction digest
220
- */
221
- async revokeWalletAllowlistAccess(
222
- options: RevokeWalletAllowlistOptions,
223
- signer: Signer
224
- ): Promise<string> {
225
- const tx = this.buildRevokeWalletAllowlistTransaction(options);
226
-
227
- const result = await this.client.signAndExecuteTransaction({
228
- transaction: tx,
229
- signer,
230
- options: {
231
- showEffects: true,
232
- showEvents: true,
233
- },
234
- });
235
-
236
- // Wait for transaction to be finalized to prevent gas coin version conflicts
237
- if (result.digest) {
238
- await this.client.waitForTransaction({ digest: result.digest });
239
- }
240
-
241
- if (result.effects?.status?.status !== 'success') {
242
- throw new Error(`Failed to revoke access: ${result.effects?.status?.error}`);
243
- }
244
-
245
- return result.digest;
246
- }
247
-
248
- /**
249
- * Build transaction to revoke cross-context access
250
- *
251
- * @param options - Permission revocation options
252
- * @returns Transaction object
253
- */
254
- buildRevokeWalletAllowlistTransaction(
255
- options: RevokeWalletAllowlistOptions
256
- ): Transaction {
257
- const tx = new Transaction();
258
-
259
- tx.moveCall({
260
- target: `${this.packageId}::capability::revoke_wallet_allowlist_access`,
261
- arguments: [
262
- tx.object(this.accessRegistryId),
263
- tx.pure.address(normalizeSuiAddress(options.requestingWallet)),
264
- tx.pure.address(normalizeSuiAddress(options.targetWallet)),
265
- tx.pure.string(options.scope ?? 'read'),
266
- ],
267
- });
268
-
269
- return tx;
270
- }
271
-
272
- /**
273
- * Build seal_approve transaction using capability module
274
- *
275
- * Uses pdw::capability::seal_approve which requires:
276
- * - id: vector<u8> - SEAL key identifier (MUST be first parameter!)
277
- * - cap: &MemoryCap - Reference to the capability object
278
- *
279
- * IMPORTANT: SEAL key server extracts 'id' from the FIRST PTB argument
280
- *
281
- * @param keyId - SEAL key ID bytes (computed from owner + nonce)
282
- * @param memoryCapId - MemoryCap object ID on Sui
283
- * @returns Transaction object
284
- */
285
- buildSealApproveTransaction(
286
- keyId: Uint8Array,
287
- memoryCapId: string
288
- ): Transaction {
289
- const tx = new Transaction();
290
-
291
- // CRITICAL: key_id MUST be first argument!
292
- // SEAL key server extracts 'id' from the FIRST PTB argument for decryption approval.
293
- tx.moveCall({
294
- target: `${this.packageId}::capability::seal_approve`,
295
- arguments: [
296
- tx.pure.vector('u8', Array.from(keyId)), // Arg 1: key_id bytes (SEAL key server requirement!)
297
- tx.object(memoryCapId), // Arg 2: MemoryCap reference
298
- ],
299
- });
300
-
301
- return tx;
302
- }
303
-
304
- /**
305
- * Build seal_approve transaction (legacy - for backward compatibility)
306
- * @deprecated Use buildSealApproveTransaction with memoryCapId instead
307
- */
308
- buildSealApproveTransactionLegacy(
309
- contentId: Uint8Array,
310
- requestingWallet: string
311
- ): Transaction {
312
- const tx = new Transaction();
313
-
314
- tx.moveCall({
315
- target: `${this.packageId}::capability::seal_approve`,
316
- arguments: [
317
- tx.pure.vector('u8', Array.from(contentId)),
318
- tx.pure.address(normalizeSuiAddress(requestingWallet)),
319
- tx.object(this.accessRegistryId),
320
- tx.object('0x6'), // Clock object
321
- ],
322
- });
323
-
324
- return tx;
325
- }
326
-
327
- /**
328
- * Query wallet allowlist permissions filtered by requester, target, or scope
329
- */
330
- async queryWalletPermissions(options: Partial<CheckWalletAccessOptions>): Promise<WalletAllowlistPermission[]> {
331
- const events = await this.fetchWalletAllowlistEvents();
332
- const state = this.reduceWalletAllowlistEvents(events);
333
-
334
- const normalizedRequester = options.requestingWallet ? normalizeSuiAddress(options.requestingWallet) : undefined;
335
- const normalizedTarget = options.targetWallet ? normalizeSuiAddress(options.targetWallet) : undefined;
336
- const scopeFilter = options.scope ?? undefined;
337
-
338
- return Array.from(state.values())
339
- .filter((permission) => {
340
- if (normalizedRequester && permission.requestingWallet !== normalizedRequester) {
341
- return false;
342
- }
343
- if (normalizedTarget && permission.targetWallet !== normalizedTarget) {
344
- return false;
345
- }
346
- if (scopeFilter && permission.scope !== scopeFilter) {
347
- return false;
348
- }
349
- return true;
350
- });
351
- }
352
-
353
- async listGrantsByTarget(targetWallet: string, scope?: string): Promise<WalletAllowlistPermission[]> {
354
- return this.queryWalletPermissions({ targetWallet, scope });
355
- }
356
-
357
- async listGrantsByRequester(requestingWallet: string, scope?: string): Promise<WalletAllowlistPermission[]> {
358
- return this.queryWalletPermissions({ requestingWallet, scope });
359
- }
360
-
361
- /**
362
- * Determine whether a wallet currently has allowlist permission
363
- */
364
- async hasWalletPermission(options: CheckWalletAccessOptions): Promise<boolean> {
365
- const permissions = await this.queryWalletPermissions(options);
366
- const now = Date.now();
367
-
368
- return permissions.some(permission => {
369
- const expiry = permission.expiresAt;
370
- return expiry === 0 || expiry > now;
371
- });
372
- }
373
-
374
- /**
375
- * List target wallets this requester can access for an optional scope
376
- */
377
- async getAccessibleWallets(requestingWallet: string, scope: string = 'read'): Promise<string[]> {
378
- const permissions = await this.queryWalletPermissions({ requestingWallet, scope });
379
- const now = Date.now();
380
-
381
- return permissions
382
- .filter(permission => permission.expiresAt === 0 || permission.expiresAt > now)
383
- .map(permission => permission.targetWallet);
384
- }
385
-
386
- async getWalletAllowlistHistory(
387
- filter?: WalletAllowlistHistoryFilter,
388
- ): Promise<WalletAllowlistHistoryEvent[]> {
389
- const events = await this.fetchWalletAllowlistEvents();
390
- const normalizedRequester = filter?.requestingWallet
391
- ? normalizeSuiAddress(filter.requestingWallet)
392
- : undefined;
393
- const normalizedTarget = filter?.targetWallet
394
- ? normalizeSuiAddress(filter.targetWallet)
395
- : undefined;
396
-
397
- return events
398
- .filter((event) => {
399
- if (normalizedRequester && event.requestingWallet !== normalizedRequester) {
400
- return false;
401
- }
402
- if (normalizedTarget && event.targetWallet !== normalizedTarget) {
403
- return false;
404
- }
405
- return true;
406
- })
407
- .map<WalletAllowlistHistoryEvent>((event) => ({
408
- timestamp: event.grantedAt,
409
- action: event.granted ? 'grant' : 'revoke',
410
- requestingWallet: event.requestingWallet,
411
- targetWallet: event.targetWallet,
412
- scope: event.scope,
413
- accessLevel: event.accessLevel,
414
- expiresAt: event.expiresAt,
415
- grantedBy: event.grantedBy,
416
- }))
417
- .sort((a, b) => a.timestamp - b.timestamp);
418
- }
419
-
420
- private async fetchWalletAllowlistEvents(): Promise<WalletAllowlistEvent[]> {
421
- const response = await this.client.queryEvents({
422
- query: {
423
- MoveEventType: `${this.packageId}::capability::WalletAllowlistChanged`,
424
- },
425
- limit: 1000,
426
- order: 'ascending',
427
- });
428
-
429
- const events: WalletAllowlistEvent[] = [];
430
-
431
- for (const event of response.data) {
432
- const parsed = event.parsedJson as any;
433
- if (!parsed) {
434
- continue;
435
- }
436
-
437
- const requestingWallet = normalizeSuiAddress(String(parsed.requester_wallet));
438
- const targetWallet = normalizeSuiAddress(String(parsed.target_wallet));
439
- const scope = String(parsed.scope ?? 'read');
440
- const accessLevel = String(parsed.access_level ?? 'read');
441
- const granted = Boolean(parsed.granted);
442
- const expiresAt = Number(parsed.expires_at ?? 0);
443
- const grantedBy = normalizeSuiAddress(String(parsed.granted_by ?? requestingWallet));
444
- const grantedAt = Number(event.timestampMs ?? Date.now());
445
- const key = `${requestingWallet}-${targetWallet}-${scope}`;
446
-
447
- events.push({
448
- key,
449
- requestingWallet,
450
- targetWallet,
451
- scope,
452
- accessLevel,
453
- granted,
454
- expiresAt,
455
- grantedAt,
456
- grantedBy,
457
- });
458
- }
459
-
460
- return events;
461
- }
462
-
463
- private reduceWalletAllowlistEvents(events: WalletAllowlistEvent[]): Map<string, WalletAllowlistPermission> {
464
- const state = new Map<string, WalletAllowlistPermission>();
465
-
466
- const sorted = [...events].sort((a, b) => a.grantedAt - b.grantedAt);
467
-
468
- for (const event of sorted) {
469
- if (event.granted) {
470
- state.set(event.key, {
471
- requestingWallet: event.requestingWallet,
472
- targetWallet: event.targetWallet,
473
- scope: event.scope,
474
- accessLevel: event.accessLevel,
475
- grantedAt: event.grantedAt,
476
- expiresAt: event.expiresAt,
477
- grantedBy: event.grantedBy,
478
- });
479
- } else {
480
- state.delete(event.key);
481
- }
482
- }
483
-
484
- return state;
485
- }
486
- }
1
+ /**
2
+ * Cross-Context Permission Service
3
+ *
4
+ * Manages cross-context access permissions for the Personal Data Wallet.
5
+ * Enables apps to request and manage access to data from other app contexts.
6
+ */
7
+
8
+ import { Transaction } from '@mysten/sui/transactions';
9
+ import { normalizeSuiAddress } from '@mysten/sui/utils';
10
+ import type { SuiClient } from '@mysten/sui/client';
11
+ import type { Signer } from '@mysten/sui/cryptography';
12
+
13
+ export interface CrossContextPermissionConfig {
14
+ packageId: string;
15
+ accessRegistryId: string;
16
+ }
17
+
18
+ export interface RegisterContextWalletOptions {
19
+ contextWallet: string;
20
+ derivationIndex: number;
21
+ appHint?: string;
22
+ }
23
+
24
+ export interface GrantWalletAllowlistOptions {
25
+ requestingWallet: string;
26
+ targetWallet: string;
27
+ scope?: string;
28
+ accessLevel: 'read' | 'write';
29
+ expiresAt: number; // Unix timestamp in milliseconds
30
+ }
31
+
32
+ export interface RevokeWalletAllowlistOptions {
33
+ requestingWallet: string;
34
+ targetWallet: string;
35
+ scope?: string;
36
+ }
37
+
38
+ export interface WalletAllowlistPermission {
39
+ requestingWallet: string;
40
+ targetWallet: string;
41
+ scope: string;
42
+ accessLevel: string;
43
+ grantedAt: number;
44
+ expiresAt: number;
45
+ grantedBy: string;
46
+ }
47
+
48
+ export interface WalletAllowlistHistoryEvent {
49
+ timestamp: number;
50
+ action: 'grant' | 'revoke';
51
+ requestingWallet: string;
52
+ targetWallet: string;
53
+ scope: string;
54
+ accessLevel: string;
55
+ expiresAt: number;
56
+ grantedBy: string;
57
+ }
58
+
59
+ export interface WalletAllowlistHistoryFilter {
60
+ requestingWallet?: string;
61
+ targetWallet?: string;
62
+ }
63
+
64
+ export interface CheckWalletAccessOptions {
65
+ requestingWallet: string;
66
+ targetWallet?: string;
67
+ scope?: string;
68
+ }
69
+
70
+ interface WalletAllowlistEvent {
71
+ key: string;
72
+ requestingWallet: string;
73
+ targetWallet: string;
74
+ scope: string;
75
+ accessLevel: string;
76
+ granted: boolean;
77
+ expiresAt: number;
78
+ grantedAt: number;
79
+ grantedBy: string;
80
+ }
81
+
82
+ /**
83
+ * Service for managing cross-context permissions
84
+ */
85
+ export class CrossContextPermissionService {
86
+ private packageId: string;
87
+ private accessRegistryId: string;
88
+ private client: SuiClient;
89
+
90
+ constructor(config: CrossContextPermissionConfig, client: SuiClient) {
91
+ this.packageId = config.packageId;
92
+ this.accessRegistryId = config.accessRegistryId;
93
+ this.client = client;
94
+ }
95
+
96
+ /**
97
+ * Register a new context wallet for an app
98
+ *
99
+ * @param options - Context registration options
100
+ * @param signer - Transaction signer
101
+ * @returns Transaction digest
102
+ */
103
+ async registerContextWallet(
104
+ options: RegisterContextWalletOptions,
105
+ signer: Signer
106
+ ): Promise<string> {
107
+ const tx = this.buildRegisterContextWalletTransaction(options);
108
+
109
+ const result = await this.client.signAndExecuteTransaction({
110
+ transaction: tx,
111
+ signer,
112
+ options: {
113
+ showEffects: true,
114
+ showEvents: true,
115
+ },
116
+ });
117
+
118
+ // Wait for transaction to be finalized to prevent gas coin version conflicts
119
+ if (result.digest) {
120
+ await this.client.waitForTransaction({ digest: result.digest });
121
+ }
122
+
123
+ if (result.effects?.status?.status !== 'success') {
124
+ throw new Error(`Failed to register context: ${result.effects?.status?.error}`);
125
+ }
126
+
127
+ return result.digest;
128
+ }
129
+
130
+ /**
131
+ * Build transaction to register a context wallet
132
+ *
133
+ * @param options - Context registration options
134
+ * @returns Transaction object
135
+ */
136
+ buildRegisterContextWalletTransaction(options: RegisterContextWalletOptions): Transaction {
137
+ const tx = new Transaction();
138
+
139
+ tx.moveCall({
140
+ target: `${this.packageId}::capability::register_context_wallet`,
141
+ arguments: [
142
+ tx.object(this.accessRegistryId),
143
+ tx.pure.address(normalizeSuiAddress(options.contextWallet)),
144
+ tx.pure.u64(options.derivationIndex),
145
+ tx.pure.string(options.appHint ?? ''),
146
+ tx.object('0x6'), // Clock object
147
+ ],
148
+ });
149
+
150
+ return tx;
151
+ }
152
+
153
+ /**
154
+ * Grant cross-context access permission
155
+ *
156
+ * @param options - Permission grant options
157
+ * @param signer - Transaction signer
158
+ * @returns Transaction digest
159
+ */
160
+ async grantWalletAllowlistAccess(
161
+ options: GrantWalletAllowlistOptions,
162
+ signer: Signer
163
+ ): Promise<string> {
164
+ const tx = this.buildGrantWalletAllowlistTransaction(options);
165
+
166
+ const result = await this.client.signAndExecuteTransaction({
167
+ transaction: tx,
168
+ signer,
169
+ options: {
170
+ showEffects: true,
171
+ showEvents: true,
172
+ },
173
+ });
174
+
175
+ // Wait for transaction to be finalized to prevent gas coin version conflicts
176
+ if (result.digest) {
177
+ await this.client.waitForTransaction({ digest: result.digest });
178
+ }
179
+
180
+ if (result.effects?.status?.status !== 'success') {
181
+ throw new Error(`Failed to grant access: ${result.effects?.status?.error}`);
182
+ }
183
+
184
+ return result.digest;
185
+ }
186
+
187
+ /**
188
+ * Build transaction to grant cross-context access
189
+ *
190
+ * @param options - Permission grant options
191
+ * @returns Transaction object
192
+ */
193
+ buildGrantWalletAllowlistTransaction(
194
+ options: GrantWalletAllowlistOptions
195
+ ): Transaction {
196
+ const tx = new Transaction();
197
+
198
+ tx.moveCall({
199
+ target: `${this.packageId}::capability::grant_wallet_allowlist_access`,
200
+ arguments: [
201
+ tx.object(this.accessRegistryId),
202
+ tx.pure.address(normalizeSuiAddress(options.requestingWallet)),
203
+ tx.pure.address(normalizeSuiAddress(options.targetWallet)),
204
+ tx.pure.string(options.scope ?? 'read'),
205
+ tx.pure.string(options.accessLevel),
206
+ tx.pure.u64(options.expiresAt),
207
+ tx.object('0x6'), // Clock object
208
+ ],
209
+ });
210
+
211
+ return tx;
212
+ }
213
+
214
+ /**
215
+ * Revoke cross-context access permission
216
+ *
217
+ * @param options - Permission revocation options
218
+ * @param signer - Transaction signer
219
+ * @returns Transaction digest
220
+ */
221
+ async revokeWalletAllowlistAccess(
222
+ options: RevokeWalletAllowlistOptions,
223
+ signer: Signer
224
+ ): Promise<string> {
225
+ const tx = this.buildRevokeWalletAllowlistTransaction(options);
226
+
227
+ const result = await this.client.signAndExecuteTransaction({
228
+ transaction: tx,
229
+ signer,
230
+ options: {
231
+ showEffects: true,
232
+ showEvents: true,
233
+ },
234
+ });
235
+
236
+ // Wait for transaction to be finalized to prevent gas coin version conflicts
237
+ if (result.digest) {
238
+ await this.client.waitForTransaction({ digest: result.digest });
239
+ }
240
+
241
+ if (result.effects?.status?.status !== 'success') {
242
+ throw new Error(`Failed to revoke access: ${result.effects?.status?.error}`);
243
+ }
244
+
245
+ return result.digest;
246
+ }
247
+
248
+ /**
249
+ * Build transaction to revoke cross-context access
250
+ *
251
+ * @param options - Permission revocation options
252
+ * @returns Transaction object
253
+ */
254
+ buildRevokeWalletAllowlistTransaction(
255
+ options: RevokeWalletAllowlistOptions
256
+ ): Transaction {
257
+ const tx = new Transaction();
258
+
259
+ tx.moveCall({
260
+ target: `${this.packageId}::capability::revoke_wallet_allowlist_access`,
261
+ arguments: [
262
+ tx.object(this.accessRegistryId),
263
+ tx.pure.address(normalizeSuiAddress(options.requestingWallet)),
264
+ tx.pure.address(normalizeSuiAddress(options.targetWallet)),
265
+ tx.pure.string(options.scope ?? 'read'),
266
+ ],
267
+ });
268
+
269
+ return tx;
270
+ }
271
+
272
+ /**
273
+ * Build seal_approve transaction using capability module
274
+ *
275
+ * Uses pdw::capability::seal_approve which requires:
276
+ * - id: vector<u8> - SEAL key identifier (MUST be first parameter!)
277
+ * - cap: &MemoryCap - Reference to the capability object
278
+ *
279
+ * IMPORTANT: SEAL key server extracts 'id' from the FIRST PTB argument
280
+ *
281
+ * @param keyId - SEAL key ID bytes (computed from owner + nonce)
282
+ * @param memoryCapId - MemoryCap object ID on Sui
283
+ * @returns Transaction object
284
+ */
285
+ buildSealApproveTransaction(
286
+ keyId: Uint8Array,
287
+ memoryCapId: string
288
+ ): Transaction {
289
+ const tx = new Transaction();
290
+
291
+ // CRITICAL: key_id MUST be first argument!
292
+ // SEAL key server extracts 'id' from the FIRST PTB argument for decryption approval.
293
+ tx.moveCall({
294
+ target: `${this.packageId}::capability::seal_approve`,
295
+ arguments: [
296
+ tx.pure.vector('u8', Array.from(keyId)), // Arg 1: key_id bytes (SEAL key server requirement!)
297
+ tx.object(memoryCapId), // Arg 2: MemoryCap reference
298
+ ],
299
+ });
300
+
301
+ return tx;
302
+ }
303
+
304
+ /**
305
+ * Build seal_approve transaction (legacy - for backward compatibility)
306
+ * @deprecated Use buildSealApproveTransaction with memoryCapId instead
307
+ */
308
+ buildSealApproveTransactionLegacy(
309
+ contentId: Uint8Array,
310
+ requestingWallet: string
311
+ ): Transaction {
312
+ const tx = new Transaction();
313
+
314
+ tx.moveCall({
315
+ target: `${this.packageId}::capability::seal_approve`,
316
+ arguments: [
317
+ tx.pure.vector('u8', Array.from(contentId)),
318
+ tx.pure.address(normalizeSuiAddress(requestingWallet)),
319
+ tx.object(this.accessRegistryId),
320
+ tx.object('0x6'), // Clock object
321
+ ],
322
+ });
323
+
324
+ return tx;
325
+ }
326
+
327
+ /**
328
+ * Query wallet allowlist permissions filtered by requester, target, or scope
329
+ */
330
+ async queryWalletPermissions(options: Partial<CheckWalletAccessOptions>): Promise<WalletAllowlistPermission[]> {
331
+ const events = await this.fetchWalletAllowlistEvents();
332
+ const state = this.reduceWalletAllowlistEvents(events);
333
+
334
+ const normalizedRequester = options.requestingWallet ? normalizeSuiAddress(options.requestingWallet) : undefined;
335
+ const normalizedTarget = options.targetWallet ? normalizeSuiAddress(options.targetWallet) : undefined;
336
+ const scopeFilter = options.scope ?? undefined;
337
+
338
+ return Array.from(state.values())
339
+ .filter((permission) => {
340
+ if (normalizedRequester && permission.requestingWallet !== normalizedRequester) {
341
+ return false;
342
+ }
343
+ if (normalizedTarget && permission.targetWallet !== normalizedTarget) {
344
+ return false;
345
+ }
346
+ if (scopeFilter && permission.scope !== scopeFilter) {
347
+ return false;
348
+ }
349
+ return true;
350
+ });
351
+ }
352
+
353
+ async listGrantsByTarget(targetWallet: string, scope?: string): Promise<WalletAllowlistPermission[]> {
354
+ return this.queryWalletPermissions({ targetWallet, scope });
355
+ }
356
+
357
+ async listGrantsByRequester(requestingWallet: string, scope?: string): Promise<WalletAllowlistPermission[]> {
358
+ return this.queryWalletPermissions({ requestingWallet, scope });
359
+ }
360
+
361
+ /**
362
+ * Determine whether a wallet currently has allowlist permission
363
+ */
364
+ async hasWalletPermission(options: CheckWalletAccessOptions): Promise<boolean> {
365
+ const permissions = await this.queryWalletPermissions(options);
366
+ const now = Date.now();
367
+
368
+ return permissions.some(permission => {
369
+ const expiry = permission.expiresAt;
370
+ return expiry === 0 || expiry > now;
371
+ });
372
+ }
373
+
374
+ /**
375
+ * List target wallets this requester can access for an optional scope
376
+ */
377
+ async getAccessibleWallets(requestingWallet: string, scope: string = 'read'): Promise<string[]> {
378
+ const permissions = await this.queryWalletPermissions({ requestingWallet, scope });
379
+ const now = Date.now();
380
+
381
+ return permissions
382
+ .filter(permission => permission.expiresAt === 0 || permission.expiresAt > now)
383
+ .map(permission => permission.targetWallet);
384
+ }
385
+
386
+ async getWalletAllowlistHistory(
387
+ filter?: WalletAllowlistHistoryFilter,
388
+ ): Promise<WalletAllowlistHistoryEvent[]> {
389
+ const events = await this.fetchWalletAllowlistEvents();
390
+ const normalizedRequester = filter?.requestingWallet
391
+ ? normalizeSuiAddress(filter.requestingWallet)
392
+ : undefined;
393
+ const normalizedTarget = filter?.targetWallet
394
+ ? normalizeSuiAddress(filter.targetWallet)
395
+ : undefined;
396
+
397
+ return events
398
+ .filter((event) => {
399
+ if (normalizedRequester && event.requestingWallet !== normalizedRequester) {
400
+ return false;
401
+ }
402
+ if (normalizedTarget && event.targetWallet !== normalizedTarget) {
403
+ return false;
404
+ }
405
+ return true;
406
+ })
407
+ .map<WalletAllowlistHistoryEvent>((event) => ({
408
+ timestamp: event.grantedAt,
409
+ action: event.granted ? 'grant' : 'revoke',
410
+ requestingWallet: event.requestingWallet,
411
+ targetWallet: event.targetWallet,
412
+ scope: event.scope,
413
+ accessLevel: event.accessLevel,
414
+ expiresAt: event.expiresAt,
415
+ grantedBy: event.grantedBy,
416
+ }))
417
+ .sort((a, b) => a.timestamp - b.timestamp);
418
+ }
419
+
420
+ private async fetchWalletAllowlistEvents(): Promise<WalletAllowlistEvent[]> {
421
+ const response = await this.client.queryEvents({
422
+ query: {
423
+ MoveEventType: `${this.packageId}::capability::WalletAllowlistChanged`,
424
+ },
425
+ limit: 1000,
426
+ order: 'ascending',
427
+ });
428
+
429
+ const events: WalletAllowlistEvent[] = [];
430
+
431
+ for (const event of response.data) {
432
+ const parsed = event.parsedJson as any;
433
+ if (!parsed) {
434
+ continue;
435
+ }
436
+
437
+ const requestingWallet = normalizeSuiAddress(String(parsed.requester_wallet));
438
+ const targetWallet = normalizeSuiAddress(String(parsed.target_wallet));
439
+ const scope = String(parsed.scope ?? 'read');
440
+ const accessLevel = String(parsed.access_level ?? 'read');
441
+ const granted = Boolean(parsed.granted);
442
+ const expiresAt = Number(parsed.expires_at ?? 0);
443
+ const grantedBy = normalizeSuiAddress(String(parsed.granted_by ?? requestingWallet));
444
+ const grantedAt = Number(event.timestampMs ?? Date.now());
445
+ const key = `${requestingWallet}-${targetWallet}-${scope}`;
446
+
447
+ events.push({
448
+ key,
449
+ requestingWallet,
450
+ targetWallet,
451
+ scope,
452
+ accessLevel,
453
+ granted,
454
+ expiresAt,
455
+ grantedAt,
456
+ grantedBy,
457
+ });
458
+ }
459
+
460
+ return events;
461
+ }
462
+
463
+ private reduceWalletAllowlistEvents(events: WalletAllowlistEvent[]): Map<string, WalletAllowlistPermission> {
464
+ const state = new Map<string, WalletAllowlistPermission>();
465
+
466
+ const sorted = [...events].sort((a, b) => a.grantedAt - b.grantedAt);
467
+
468
+ for (const event of sorted) {
469
+ if (event.granted) {
470
+ state.set(event.key, {
471
+ requestingWallet: event.requestingWallet,
472
+ targetWallet: event.targetWallet,
473
+ scope: event.scope,
474
+ accessLevel: event.accessLevel,
475
+ grantedAt: event.grantedAt,
476
+ expiresAt: event.expiresAt,
477
+ grantedBy: event.grantedBy,
478
+ });
479
+ } else {
480
+ state.delete(event.key);
481
+ }
482
+ }
483
+
484
+ return state;
485
+ }
486
+ }