@opendatalabs/vana-sdk 2.3.0 → 3.0.1

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 (623) hide show
  1. package/README.md +76 -92
  2. package/dist/auth/errors.cjs +54 -0
  3. package/dist/auth/errors.cjs.map +1 -0
  4. package/dist/auth/errors.d.ts +26 -0
  5. package/dist/auth/errors.js +28 -0
  6. package/dist/auth/errors.js.map +1 -0
  7. package/dist/auth/pkce.cjs +100 -0
  8. package/dist/auth/pkce.cjs.map +1 -0
  9. package/dist/auth/pkce.d.ts +55 -0
  10. package/dist/auth/pkce.js +71 -0
  11. package/dist/auth/pkce.js.map +1 -0
  12. package/dist/auth/token-store.cjs +59 -0
  13. package/dist/auth/token-store.cjs.map +1 -0
  14. package/dist/auth/token-store.d.ts +61 -0
  15. package/dist/auth/token-store.js +35 -0
  16. package/dist/auth/token-store.js.map +1 -0
  17. package/dist/auth/web3-signed-builder.cjs +70 -0
  18. package/dist/auth/web3-signed-builder.cjs.map +1 -0
  19. package/dist/auth/web3-signed-builder.d.ts +47 -0
  20. package/dist/auth/web3-signed-builder.js +45 -0
  21. package/dist/auth/web3-signed-builder.js.map +1 -0
  22. package/dist/auth/web3-signed.cjs +150 -0
  23. package/dist/auth/web3-signed.cjs.map +1 -0
  24. package/dist/auth/web3-signed.d.ts +59 -0
  25. package/dist/auth/web3-signed.js +129 -0
  26. package/dist/auth/web3-signed.js.map +1 -0
  27. package/dist/chains/definitions.cjs +2 -6
  28. package/dist/chains/definitions.cjs.map +1 -1
  29. package/dist/chains/definitions.d.ts +1 -7
  30. package/dist/chains/definitions.js +2 -6
  31. package/dist/chains/definitions.js.map +1 -1
  32. package/dist/config/chains.d.ts +18 -0
  33. package/dist/config/contracts.config.cjs +7 -95
  34. package/dist/config/contracts.config.cjs.map +1 -1
  35. package/dist/config/contracts.config.d.ts +0 -54
  36. package/dist/config/contracts.config.js +6 -93
  37. package/dist/config/contracts.config.js.map +1 -1
  38. package/dist/config/default-services.cjs +0 -10
  39. package/dist/config/default-services.cjs.map +1 -1
  40. package/dist/config/default-services.d.ts +1 -20
  41. package/dist/config/default-services.js +0 -9
  42. package/dist/config/default-services.js.map +1 -1
  43. package/dist/crypto/ecies/interface.cjs +2 -0
  44. package/dist/crypto/ecies/interface.cjs.map +1 -1
  45. package/dist/crypto/ecies/interface.js +2 -0
  46. package/dist/crypto/ecies/interface.js.map +1 -1
  47. package/dist/crypto/envelope/openpgp.cjs +59 -0
  48. package/dist/crypto/envelope/openpgp.cjs.map +1 -0
  49. package/dist/crypto/envelope/openpgp.d.ts +28 -0
  50. package/dist/crypto/envelope/openpgp.js +24 -0
  51. package/dist/crypto/envelope/openpgp.js.map +1 -0
  52. package/dist/crypto/keys/derive.cjs +65 -0
  53. package/dist/crypto/keys/derive.cjs.map +1 -0
  54. package/dist/crypto/keys/derive.d.ts +45 -0
  55. package/dist/crypto/keys/derive.js +38 -0
  56. package/dist/crypto/keys/derive.js.map +1 -0
  57. package/dist/errors.cjs +10 -0
  58. package/dist/errors.cjs.map +1 -1
  59. package/dist/errors.js +10 -0
  60. package/dist/errors.js.map +1 -1
  61. package/dist/generated/abi/index.cjs +2 -37
  62. package/dist/generated/abi/index.cjs.map +1 -1
  63. package/dist/generated/abi/index.d.ts +2683 -9296
  64. package/dist/generated/abi/index.js +2 -29
  65. package/dist/generated/abi/index.js.map +1 -1
  66. package/dist/generated/addresses.cjs +5 -107
  67. package/dist/generated/addresses.cjs.map +1 -1
  68. package/dist/generated/addresses.d.ts +5 -99
  69. package/dist/generated/addresses.js +5 -105
  70. package/dist/generated/addresses.js.map +1 -1
  71. package/dist/index.browser.d.ts +24 -140
  72. package/dist/index.browser.js +32258 -114
  73. package/dist/index.browser.js.map +7 -1
  74. package/dist/index.node.cjs +32980 -160
  75. package/dist/index.node.cjs.map +7 -1
  76. package/dist/index.node.d.ts +23 -210
  77. package/dist/index.node.js +32884 -133
  78. package/dist/index.node.js.map +7 -1
  79. package/dist/protocol/data-file.cjs +56 -0
  80. package/dist/protocol/data-file.cjs.map +1 -0
  81. package/dist/protocol/data-file.d.ts +20 -0
  82. package/dist/protocol/data-file.js +30 -0
  83. package/dist/protocol/data-file.js.map +1 -0
  84. package/dist/protocol/eip712.cjs +123 -0
  85. package/dist/protocol/eip712.cjs.map +1 -0
  86. package/dist/protocol/eip712.d.ts +117 -0
  87. package/dist/protocol/eip712.js +90 -0
  88. package/dist/protocol/eip712.js.map +1 -0
  89. package/dist/protocol/gateway.cjs +226 -0
  90. package/dist/protocol/gateway.cjs.map +1 -0
  91. package/dist/protocol/gateway.d.ts +120 -0
  92. package/dist/protocol/gateway.js +202 -0
  93. package/dist/protocol/gateway.js.map +1 -0
  94. package/dist/protocol/grants.cjs +146 -0
  95. package/dist/protocol/grants.cjs.map +1 -0
  96. package/dist/protocol/grants.d.ts +31 -0
  97. package/dist/protocol/grants.js +123 -0
  98. package/dist/protocol/grants.js.map +1 -0
  99. package/dist/protocol/scopes.cjs +78 -0
  100. package/dist/protocol/scopes.cjs.map +1 -0
  101. package/dist/protocol/scopes.d.ts +13 -0
  102. package/dist/protocol/scopes.js +50 -0
  103. package/dist/protocol/scopes.js.map +1 -0
  104. package/dist/{types/atomicStore.cjs → storage/default.cjs} +9 -8
  105. package/dist/storage/default.cjs.map +1 -0
  106. package/dist/storage/default.d.ts +4 -0
  107. package/dist/storage/default.js +8 -0
  108. package/dist/storage/default.js.map +1 -0
  109. package/dist/storage/index.cjs +11 -2
  110. package/dist/storage/index.cjs.map +1 -1
  111. package/dist/storage/index.d.ts +9 -0
  112. package/dist/storage/index.js +7 -1
  113. package/dist/storage/index.js.map +1 -1
  114. package/dist/storage/providers/callback-storage.cjs +1 -0
  115. package/dist/storage/providers/callback-storage.cjs.map +1 -1
  116. package/dist/storage/providers/callback-storage.js +1 -0
  117. package/dist/storage/providers/callback-storage.js.map +1 -1
  118. package/dist/storage/providers/dropbox.cjs +1 -0
  119. package/dist/storage/providers/dropbox.cjs.map +1 -1
  120. package/dist/storage/providers/dropbox.js +1 -0
  121. package/dist/storage/providers/dropbox.js.map +1 -1
  122. package/dist/storage/providers/google-drive.cjs +1 -0
  123. package/dist/storage/providers/google-drive.cjs.map +1 -1
  124. package/dist/storage/providers/google-drive.js +1 -0
  125. package/dist/storage/providers/google-drive.js.map +1 -1
  126. package/dist/storage/providers/ipfs.cjs +1 -0
  127. package/dist/storage/providers/ipfs.cjs.map +1 -1
  128. package/dist/storage/providers/ipfs.js +1 -0
  129. package/dist/storage/providers/ipfs.js.map +1 -1
  130. package/dist/storage/providers/pinata.cjs +1 -0
  131. package/dist/storage/providers/pinata.cjs.map +1 -1
  132. package/dist/storage/providers/pinata.js +1 -0
  133. package/dist/storage/providers/pinata.js.map +1 -1
  134. package/dist/storage/providers/r2.cjs +376 -0
  135. package/dist/storage/providers/r2.cjs.map +1 -0
  136. package/dist/storage/providers/r2.d.ts +91 -0
  137. package/dist/storage/providers/r2.js +354 -0
  138. package/dist/storage/providers/r2.js.map +1 -0
  139. package/dist/storage/providers/vana-storage.cjs +251 -0
  140. package/dist/storage/providers/vana-storage.cjs.map +1 -0
  141. package/dist/storage/providers/vana-storage.d.ts +100 -0
  142. package/dist/storage/providers/vana-storage.js +231 -0
  143. package/dist/storage/providers/vana-storage.js.map +1 -0
  144. package/dist/types/config.cjs +0 -34
  145. package/dist/types/config.cjs.map +1 -1
  146. package/dist/types/config.d.ts +1 -607
  147. package/dist/types/config.js +0 -22
  148. package/dist/types/config.js.map +1 -1
  149. package/dist/types/contracts.cjs.map +1 -1
  150. package/dist/types/contracts.d.ts +1 -1
  151. package/dist/types/index.cjs +2 -33
  152. package/dist/types/index.cjs.map +1 -1
  153. package/dist/types/index.d.ts +2 -33
  154. package/dist/types/index.js +1 -35
  155. package/dist/types/index.js.map +1 -1
  156. package/dist/types/ps-errors.cjs +91 -0
  157. package/dist/types/ps-errors.cjs.map +1 -0
  158. package/dist/types/ps-errors.d.ts +26 -0
  159. package/dist/types/ps-errors.js +66 -0
  160. package/dist/types/ps-errors.js.map +1 -0
  161. package/dist/types.cjs.map +1 -1
  162. package/dist/types.d.ts +0 -29
  163. package/dist/types.js.map +1 -1
  164. package/package.json +7 -25
  165. package/dist/client/enhancedResponse.cjs +0 -164
  166. package/dist/client/enhancedResponse.cjs.map +0 -1
  167. package/dist/client/enhancedResponse.d.ts +0 -120
  168. package/dist/client/enhancedResponse.js +0 -138
  169. package/dist/client/enhancedResponse.js.map +0 -1
  170. package/dist/controllers/__tests__/data-consistency-integration.test.d.ts +0 -7
  171. package/dist/controllers/base.cjs +0 -116
  172. package/dist/controllers/base.cjs.map +0 -1
  173. package/dist/controllers/base.d.ts +0 -94
  174. package/dist/controllers/base.js +0 -92
  175. package/dist/controllers/base.js.map +0 -1
  176. package/dist/controllers/data.cjs +0 -2633
  177. package/dist/controllers/data.cjs.map +0 -1
  178. package/dist/controllers/data.d.ts +0 -1067
  179. package/dist/controllers/data.js +0 -2626
  180. package/dist/controllers/data.js.map +0 -1
  181. package/dist/controllers/operations.cjs +0 -430
  182. package/dist/controllers/operations.cjs.map +0 -1
  183. package/dist/controllers/operations.d.ts +0 -229
  184. package/dist/controllers/operations.js +0 -406
  185. package/dist/controllers/operations.js.map +0 -1
  186. package/dist/controllers/permissions.cjs +0 -4368
  187. package/dist/controllers/permissions.cjs.map +0 -1
  188. package/dist/controllers/permissions.d.ts +0 -1411
  189. package/dist/controllers/permissions.js +0 -4344
  190. package/dist/controllers/permissions.js.map +0 -1
  191. package/dist/controllers/protocol.cjs +0 -183
  192. package/dist/controllers/protocol.cjs.map +0 -1
  193. package/dist/controllers/protocol.d.ts +0 -138
  194. package/dist/controllers/protocol.js +0 -163
  195. package/dist/controllers/protocol.js.map +0 -1
  196. package/dist/controllers/schemas.cjs +0 -678
  197. package/dist/controllers/schemas.cjs.map +0 -1
  198. package/dist/controllers/schemas.d.ts +0 -293
  199. package/dist/controllers/schemas.js +0 -654
  200. package/dist/controllers/schemas.js.map +0 -1
  201. package/dist/controllers/server.cjs +0 -643
  202. package/dist/controllers/server.cjs.map +0 -1
  203. package/dist/controllers/server.d.ts +0 -322
  204. package/dist/controllers/server.js +0 -624
  205. package/dist/controllers/server.js.map +0 -1
  206. package/dist/controllers/staking.cjs +0 -626
  207. package/dist/controllers/staking.cjs.map +0 -1
  208. package/dist/controllers/staking.d.ts +0 -457
  209. package/dist/controllers/staking.js +0 -602
  210. package/dist/controllers/staking.js.map +0 -1
  211. package/dist/core/__tests__/pollingManager.test.d.ts +0 -4
  212. package/dist/core/apiClient.cjs +0 -378
  213. package/dist/core/apiClient.cjs.map +0 -1
  214. package/dist/core/apiClient.d.ts +0 -286
  215. package/dist/core/apiClient.js +0 -359
  216. package/dist/core/apiClient.js.map +0 -1
  217. package/dist/core/generics.cjs +0 -417
  218. package/dist/core/generics.cjs.map +0 -1
  219. package/dist/core/generics.d.ts +0 -205
  220. package/dist/core/generics.js +0 -386
  221. package/dist/core/generics.js.map +0 -1
  222. package/dist/core/health.cjs +0 -289
  223. package/dist/core/health.cjs.map +0 -1
  224. package/dist/core/health.d.ts +0 -143
  225. package/dist/core/health.js +0 -265
  226. package/dist/core/health.js.map +0 -1
  227. package/dist/core/inMemoryNonceManager.cjs +0 -138
  228. package/dist/core/inMemoryNonceManager.cjs.map +0 -1
  229. package/dist/core/inMemoryNonceManager.d.ts +0 -69
  230. package/dist/core/inMemoryNonceManager.js +0 -114
  231. package/dist/core/inMemoryNonceManager.js.map +0 -1
  232. package/dist/core/nonceManager.cjs +0 -304
  233. package/dist/core/nonceManager.cjs.map +0 -1
  234. package/dist/core/nonceManager.d.ts +0 -116
  235. package/dist/core/nonceManager.js +0 -280
  236. package/dist/core/nonceManager.js.map +0 -1
  237. package/dist/core/pollingManager.cjs +0 -292
  238. package/dist/core/pollingManager.cjs.map +0 -1
  239. package/dist/core/pollingManager.d.ts +0 -120
  240. package/dist/core/pollingManager.js +0 -268
  241. package/dist/core/pollingManager.js.map +0 -1
  242. package/dist/core.cjs +0 -781
  243. package/dist/core.cjs.map +0 -1
  244. package/dist/core.d.ts +0 -496
  245. package/dist/core.js +0 -756
  246. package/dist/core.js.map +0 -1
  247. package/dist/diagnostics.cjs +0 -37
  248. package/dist/diagnostics.cjs.map +0 -1
  249. package/dist/diagnostics.d.ts +0 -24
  250. package/dist/diagnostics.js +0 -13
  251. package/dist/diagnostics.js.map +0 -1
  252. package/dist/generated/abi/DLPPerformanceImplementation.cjs +0 -1202
  253. package/dist/generated/abi/DLPPerformanceImplementation.cjs.map +0 -1
  254. package/dist/generated/abi/DLPPerformanceImplementation.d.ts +0 -914
  255. package/dist/generated/abi/DLPPerformanceImplementation.js +0 -1178
  256. package/dist/generated/abi/DLPPerformanceImplementation.js.map +0 -1
  257. package/dist/generated/abi/DLPRewardDeployerImplementation.cjs +0 -1112
  258. package/dist/generated/abi/DLPRewardDeployerImplementation.cjs.map +0 -1
  259. package/dist/generated/abi/DLPRewardDeployerImplementation.d.ts +0 -840
  260. package/dist/generated/abi/DLPRewardDeployerImplementation.js +0 -1088
  261. package/dist/generated/abi/DLPRewardDeployerImplementation.js.map +0 -1
  262. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.cjs +0 -612
  263. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.cjs.map +0 -1
  264. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.d.ts +0 -451
  265. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.js +0 -588
  266. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.js.map +0 -1
  267. package/dist/generated/abi/DLPRewardSwapImplementation.cjs +0 -939
  268. package/dist/generated/abi/DLPRewardSwapImplementation.cjs.map +0 -1
  269. package/dist/generated/abi/DLPRewardSwapImplementation.d.ts +0 -705
  270. package/dist/generated/abi/DLPRewardSwapImplementation.js +0 -915
  271. package/dist/generated/abi/DLPRewardSwapImplementation.js.map +0 -1
  272. package/dist/generated/abi/DLPRootImplementation.cjs +0 -1644
  273. package/dist/generated/abi/DLPRootImplementation.cjs.map +0 -1
  274. package/dist/generated/abi/DLPRootImplementation.d.ts +0 -1246
  275. package/dist/generated/abi/DLPRootImplementation.js +0 -1620
  276. package/dist/generated/abi/DLPRootImplementation.js.map +0 -1
  277. package/dist/generated/abi/DataLiquidityPoolImplementation.cjs +0 -985
  278. package/dist/generated/abi/DataLiquidityPoolImplementation.cjs.map +0 -1
  279. package/dist/generated/abi/DataLiquidityPoolImplementation.d.ts +0 -735
  280. package/dist/generated/abi/DataLiquidityPoolImplementation.js +0 -961
  281. package/dist/generated/abi/DataLiquidityPoolImplementation.js.map +0 -1
  282. package/dist/generated/abi/SwapHelperImplementation.cjs +0 -976
  283. package/dist/generated/abi/SwapHelperImplementation.cjs.map +0 -1
  284. package/dist/generated/abi/SwapHelperImplementation.d.ts +0 -728
  285. package/dist/generated/abi/SwapHelperImplementation.js +0 -952
  286. package/dist/generated/abi/SwapHelperImplementation.js.map +0 -1
  287. package/dist/generated/abi/TeePoolImplementation.cjs +0 -1313
  288. package/dist/generated/abi/TeePoolImplementation.cjs.map +0 -1
  289. package/dist/generated/abi/TeePoolImplementation.d.ts +0 -992
  290. package/dist/generated/abi/TeePoolImplementation.js +0 -1289
  291. package/dist/generated/abi/TeePoolImplementation.js.map +0 -1
  292. package/dist/generated/event-types.cjs +0 -17
  293. package/dist/generated/event-types.cjs.map +0 -1
  294. package/dist/generated/event-types.d.ts +0 -816
  295. package/dist/generated/event-types.js +0 -1
  296. package/dist/generated/event-types.js.map +0 -1
  297. package/dist/generated/eventRegistry.cjs +0 -4512
  298. package/dist/generated/eventRegistry.cjs.map +0 -1
  299. package/dist/generated/eventRegistry.d.ts +0 -14
  300. package/dist/generated/eventRegistry.js +0 -4487
  301. package/dist/generated/eventRegistry.js.map +0 -1
  302. package/dist/generated/server/server-exports.cjs +0 -45
  303. package/dist/generated/server/server-exports.cjs.map +0 -1
  304. package/dist/generated/server/server-exports.d.ts +0 -36
  305. package/dist/generated/server/server-exports.js +0 -19
  306. package/dist/generated/server/server-exports.js.map +0 -1
  307. package/dist/generated/server/server.cjs +0 -17
  308. package/dist/generated/server/server.cjs.map +0 -1
  309. package/dist/generated/server/server.d.ts +0 -907
  310. package/dist/generated/server/server.js +0 -1
  311. package/dist/generated/server/server.js.map +0 -1
  312. package/dist/generated/subgraph.cjs +0 -1440
  313. package/dist/generated/subgraph.cjs.map +0 -1
  314. package/dist/generated/subgraph.d.ts +0 -6113
  315. package/dist/generated/subgraph.js +0 -1404
  316. package/dist/generated/subgraph.js.map +0 -1
  317. package/dist/lib/__tests__/redisAtomicStore.test.d.ts +0 -1
  318. package/dist/lib/redisAtomicStore.cjs +0 -201
  319. package/dist/lib/redisAtomicStore.cjs.map +0 -1
  320. package/dist/lib/redisAtomicStore.d.ts +0 -120
  321. package/dist/lib/redisAtomicStore.js +0 -177
  322. package/dist/lib/redisAtomicStore.js.map +0 -1
  323. package/dist/server/relayerHandler.cjs +0 -452
  324. package/dist/server/relayerHandler.cjs.map +0 -1
  325. package/dist/server/relayerHandler.d.ts +0 -69
  326. package/dist/server/relayerHandler.js +0 -428
  327. package/dist/server/relayerHandler.js.map +0 -1
  328. package/dist/tests/abi.test.d.ts +0 -1
  329. package/dist/tests/chains-definitions.test.d.ts +0 -1
  330. package/dist/tests/core-encryption.test.d.ts +0 -1
  331. package/dist/tests/core-extended.test.d.ts +0 -1
  332. package/dist/tests/core-generics-coverage.test.d.ts +0 -1
  333. package/dist/tests/coverage-boost.test.d.ts +0 -1
  334. package/dist/tests/crypto-cross-platform-compatibility.test.d.ts +0 -1
  335. package/dist/tests/data-addfile-permissions-schema.test.d.ts +0 -1
  336. package/dist/tests/data-additional-methods.test.d.ts +0 -1
  337. package/dist/tests/data-controller-edge-cases.test.d.ts +0 -1
  338. package/dist/tests/data-ipfs-gateways.test.d.ts +0 -1
  339. package/dist/tests/data-relayer.test.d.ts +0 -1
  340. package/dist/tests/data-schema-validation.test.d.ts +0 -1
  341. package/dist/tests/data-simple-methods.test.d.ts +0 -1
  342. package/dist/tests/data-upload-owner-validation.test.d.ts +0 -1
  343. package/dist/tests/data.test.d.ts +0 -1
  344. package/dist/tests/demo-integration.test.d.ts +0 -1
  345. package/dist/tests/demo-trusted-server-integration.test.d.ts +0 -1
  346. package/dist/tests/download-relayer.test.d.ts +0 -1
  347. package/dist/tests/dual-mode-permissions.test.d.ts +0 -1
  348. package/dist/tests/dual-mode-trusted-servers.test.d.ts +0 -1
  349. package/dist/tests/encryption-correct-implementation.test.d.ts +0 -1
  350. package/dist/tests/encryption-coverage.test.d.ts +0 -1
  351. package/dist/tests/encryption-edge-cases.test.d.ts +0 -1
  352. package/dist/tests/encryption-utils-updated.test.d.ts +0 -1
  353. package/dist/tests/errors-coverage.test.d.ts +0 -1
  354. package/dist/tests/factories/mockFactory.d.ts +0 -316
  355. package/dist/tests/fakes/FakeStorageManager.d.ts +0 -200
  356. package/dist/tests/fakes/FakeStorageManager.test.d.ts +0 -1
  357. package/dist/tests/fakes/FakeWaitForTransactionEvents.d.ts +0 -170
  358. package/dist/tests/fakes/FakeWaitForTransactionEvents.test.d.ts +0 -1
  359. package/dist/tests/fakes/fake-pgp-port.d.ts +0 -13
  360. package/dist/tests/grantValidation-edge-cases.test.d.ts +0 -1
  361. package/dist/tests/grantValidation-unreachable-branch.test.d.ts +0 -1
  362. package/dist/tests/helper-methods.test.d.ts +0 -1
  363. package/dist/tests/helpers/typedMocks.d.ts +0 -64
  364. package/dist/tests/index-browser.test.d.ts +0 -1
  365. package/dist/tests/index-node.test.d.ts +0 -1
  366. package/dist/tests/index.test.d.ts +0 -1
  367. package/dist/tests/mocks/platformAdapter.d.ts +0 -12
  368. package/dist/tests/new-permissions-methods.test.d.ts +0 -1
  369. package/dist/tests/no-buffer-browser.test.d.ts +0 -1
  370. package/dist/tests/permissions-grantee.test.d.ts +0 -1
  371. package/dist/tests/permissions-revoke-relayer.test.d.ts +0 -1
  372. package/dist/tests/permissions-schema-validation.test.d.ts +0 -1
  373. package/dist/tests/permissions-server-files.test.d.ts +0 -1
  374. package/dist/tests/permissions-transaction-options.test.d.ts +0 -1
  375. package/dist/tests/permissions-trust-servers.test.d.ts +0 -1
  376. package/dist/tests/permissions.test.d.ts +0 -1
  377. package/dist/tests/personal.test.d.ts +0 -1
  378. package/dist/tests/platform-browser.test.d.ts +0 -1
  379. package/dist/tests/platform-crypto-expanded.test.d.ts +0 -1
  380. package/dist/tests/platform-crypto.test.d.ts +0 -1
  381. package/dist/tests/platform-index.test.d.ts +0 -1
  382. package/dist/tests/platform-node.test.d.ts +0 -1
  383. package/dist/tests/platform-shared-utils.test.d.ts +0 -1
  384. package/dist/tests/platform-updated.test.d.ts +0 -1
  385. package/dist/tests/protocol-additional-methods.test.d.ts +0 -1
  386. package/dist/tests/protocol.test.d.ts +0 -1
  387. package/dist/tests/read-only-mode.test.d.ts +0 -1
  388. package/dist/tests/relayer-integration.test.d.ts +0 -1
  389. package/dist/tests/relayer-unified.test.d.ts +0 -1
  390. package/dist/tests/schemas.test.d.ts +0 -1
  391. package/dist/tests/server-relayer-handler.test.d.ts +0 -1
  392. package/dist/tests/signatureFormatter.test.d.ts +0 -1
  393. package/dist/tests/staking.test.d.ts +0 -1
  394. package/dist/tests/trusted-server-queries.test.d.ts +0 -1
  395. package/dist/tests/typedDataConverter.test.d.ts +0 -1
  396. package/dist/tests/types-contracts.test.d.ts +0 -1
  397. package/dist/tests/types-data.test.d.ts +0 -1
  398. package/dist/tests/types-external-apis.test.d.ts +0 -1
  399. package/dist/tests/types-generics.test.d.ts +0 -1
  400. package/dist/tests/types-permissions.test.d.ts +0 -1
  401. package/dist/tests/types-upload-params.test.d.ts +0 -1
  402. package/dist/tests/types.test.d.ts +0 -1
  403. package/dist/tests/utils-formatters.test.d.ts +0 -1
  404. package/dist/tests/utils-grantFiles-edge-cases.test.d.ts +0 -1
  405. package/dist/tests/utils-grantFiles-validation.test.d.ts +0 -1
  406. package/dist/tests/utils-grantFiles.test.d.ts +0 -1
  407. package/dist/tests/utils-grantValidation-consolidated.test.d.ts +0 -1
  408. package/dist/tests/utils-grants.test.d.ts +0 -1
  409. package/dist/tests/utils-ipfs-additional.test.d.ts +0 -1
  410. package/dist/tests/utils-ipfs.test.d.ts +0 -4
  411. package/dist/tests/utils-schemaValidation.test.d.ts +0 -1
  412. package/dist/tests/vana.test.d.ts +0 -1
  413. package/dist/tests/wallet-crypto-compatibility.test.d.ts +0 -1
  414. package/dist/types/atomicStore.cjs.map +0 -1
  415. package/dist/types/atomicStore.d.ts +0 -236
  416. package/dist/types/atomicStore.js +0 -7
  417. package/dist/types/atomicStore.js.map +0 -1
  418. package/dist/types/blockchain.cjs +0 -17
  419. package/dist/types/blockchain.cjs.map +0 -1
  420. package/dist/types/blockchain.d.ts +0 -85
  421. package/dist/types/blockchain.js +0 -1
  422. package/dist/types/blockchain.js.map +0 -1
  423. package/dist/types/controller-context.cjs +0 -17
  424. package/dist/types/controller-context.cjs.map +0 -1
  425. package/dist/types/controller-context.d.ts +0 -68
  426. package/dist/types/controller-context.js +0 -1
  427. package/dist/types/controller-context.js.map +0 -1
  428. package/dist/types/data.cjs +0 -17
  429. package/dist/types/data.cjs.map +0 -1
  430. package/dist/types/data.d.ts +0 -763
  431. package/dist/types/data.js +0 -1
  432. package/dist/types/data.js.map +0 -1
  433. package/dist/types/external-apis.cjs +0 -61
  434. package/dist/types/external-apis.cjs.map +0 -1
  435. package/dist/types/external-apis.d.ts +0 -184
  436. package/dist/types/external-apis.js +0 -34
  437. package/dist/types/external-apis.js.map +0 -1
  438. package/dist/types/generics.cjs +0 -17
  439. package/dist/types/generics.cjs.map +0 -1
  440. package/dist/types/generics.d.ts +0 -518
  441. package/dist/types/generics.js +0 -1
  442. package/dist/types/generics.js.map +0 -1
  443. package/dist/types/operationStore.cjs +0 -17
  444. package/dist/types/operationStore.cjs.map +0 -1
  445. package/dist/types/operationStore.d.ts +0 -171
  446. package/dist/types/operationStore.js +0 -1
  447. package/dist/types/operationStore.js.map +0 -1
  448. package/dist/types/operations.cjs +0 -53
  449. package/dist/types/operations.cjs.map +0 -1
  450. package/dist/types/operations.d.ts +0 -204
  451. package/dist/types/operations.js +0 -26
  452. package/dist/types/operations.js.map +0 -1
  453. package/dist/types/options.cjs +0 -17
  454. package/dist/types/options.cjs.map +0 -1
  455. package/dist/types/options.d.ts +0 -308
  456. package/dist/types/options.js +0 -1
  457. package/dist/types/options.js.map +0 -1
  458. package/dist/types/permissions.cjs +0 -17
  459. package/dist/types/permissions.cjs.map +0 -1
  460. package/dist/types/permissions.d.ts +0 -955
  461. package/dist/types/permissions.js +0 -1
  462. package/dist/types/permissions.js.map +0 -1
  463. package/dist/types/personal.cjs +0 -17
  464. package/dist/types/personal.cjs.map +0 -1
  465. package/dist/types/personal.d.ts +0 -174
  466. package/dist/types/personal.js +0 -1
  467. package/dist/types/personal.js.map +0 -1
  468. package/dist/types/relayer.cjs +0 -17
  469. package/dist/types/relayer.cjs.map +0 -1
  470. package/dist/types/relayer.d.ts +0 -552
  471. package/dist/types/relayer.js +0 -1
  472. package/dist/types/relayer.js.map +0 -1
  473. package/dist/types/transactionResults.cjs +0 -17
  474. package/dist/types/transactionResults.cjs.map +0 -1
  475. package/dist/types/transactionResults.d.ts +0 -193
  476. package/dist/types/transactionResults.js +0 -1
  477. package/dist/types/transactionResults.js.map +0 -1
  478. package/dist/types/utils.cjs +0 -17
  479. package/dist/types/utils.cjs.map +0 -1
  480. package/dist/types/utils.d.ts +0 -771
  481. package/dist/types/utils.js +0 -1
  482. package/dist/types/utils.js.map +0 -1
  483. package/dist/utils/__tests__/chainQuery.test.d.ts +0 -1
  484. package/dist/utils/__tests__/parseTransaction.test.d.ts +0 -1
  485. package/dist/utils/__tests__/pojo-serialization.test.d.ts +0 -1
  486. package/dist/utils/__tests__/signatureCache.test.d.ts +0 -1
  487. package/dist/utils/__tests__/subgraphConsistency.test.d.ts +0 -4
  488. package/dist/utils/__tests__/subgraphPagination.test.d.ts +0 -4
  489. package/dist/utils/__tests__/transaction-edge-cases.test.d.ts +0 -1
  490. package/dist/utils/__tests__/transactionHelpers.test.d.ts +0 -1
  491. package/dist/utils/__tests__/urlResolver.test.d.ts +0 -4
  492. package/dist/utils/blockchain/registry.cjs +0 -81
  493. package/dist/utils/blockchain/registry.cjs.map +0 -1
  494. package/dist/utils/blockchain/registry.d.ts +0 -32
  495. package/dist/utils/blockchain/registry.js +0 -56
  496. package/dist/utils/blockchain/registry.js.map +0 -1
  497. package/dist/utils/blockchain/registry.test.d.ts +0 -1
  498. package/dist/utils/chainQuery.cjs +0 -107
  499. package/dist/utils/chainQuery.cjs.map +0 -1
  500. package/dist/utils/chainQuery.d.ts +0 -31
  501. package/dist/utils/chainQuery.js +0 -82
  502. package/dist/utils/chainQuery.js.map +0 -1
  503. package/dist/utils/download.cjs +0 -69
  504. package/dist/utils/download.cjs.map +0 -1
  505. package/dist/utils/download.d.ts +0 -40
  506. package/dist/utils/download.js +0 -45
  507. package/dist/utils/download.js.map +0 -1
  508. package/dist/utils/encryption.cjs +0 -176
  509. package/dist/utils/encryption.cjs.map +0 -1
  510. package/dist/utils/encryption.d.ts +0 -271
  511. package/dist/utils/encryption.js +0 -142
  512. package/dist/utils/encryption.js.map +0 -1
  513. package/dist/utils/formatters.cjs +0 -55
  514. package/dist/utils/formatters.cjs.map +0 -1
  515. package/dist/utils/formatters.d.ts +0 -118
  516. package/dist/utils/formatters.js +0 -28
  517. package/dist/utils/formatters.js.map +0 -1
  518. package/dist/utils/grantFiles.cjs +0 -181
  519. package/dist/utils/grantFiles.cjs.map +0 -1
  520. package/dist/utils/grantFiles.d.ts +0 -172
  521. package/dist/utils/grantFiles.js +0 -143
  522. package/dist/utils/grantFiles.js.map +0 -1
  523. package/dist/utils/grantValidation.cjs +0 -243
  524. package/dist/utils/grantValidation.cjs.map +0 -1
  525. package/dist/utils/grantValidation.d.ts +0 -226
  526. package/dist/utils/grantValidation.js +0 -201
  527. package/dist/utils/grantValidation.js.map +0 -1
  528. package/dist/utils/grants.cjs +0 -108
  529. package/dist/utils/grants.cjs.map +0 -1
  530. package/dist/utils/grants.d.ts +0 -148
  531. package/dist/utils/grants.js +0 -82
  532. package/dist/utils/grants.js.map +0 -1
  533. package/dist/utils/ipfs.cjs +0 -128
  534. package/dist/utils/ipfs.cjs.map +0 -1
  535. package/dist/utils/ipfs.d.ts +0 -88
  536. package/dist/utils/ipfs.js +0 -97
  537. package/dist/utils/ipfs.js.map +0 -1
  538. package/dist/utils/multicall.cjs +0 -233
  539. package/dist/utils/multicall.cjs.map +0 -1
  540. package/dist/utils/multicall.d.ts +0 -126
  541. package/dist/utils/multicall.js +0 -208
  542. package/dist/utils/multicall.js.map +0 -1
  543. package/dist/utils/parseTransactionPojo.cjs +0 -87
  544. package/dist/utils/parseTransactionPojo.cjs.map +0 -1
  545. package/dist/utils/parseTransactionPojo.d.ts +0 -31
  546. package/dist/utils/parseTransactionPojo.js +0 -63
  547. package/dist/utils/parseTransactionPojo.js.map +0 -1
  548. package/dist/utils/schemaValidation.cjs +0 -258
  549. package/dist/utils/schemaValidation.cjs.map +0 -1
  550. package/dist/utils/schemaValidation.d.ts +0 -168
  551. package/dist/utils/schemaValidation.js +0 -219
  552. package/dist/utils/schemaValidation.js.map +0 -1
  553. package/dist/utils/signatureCache.cjs +0 -192
  554. package/dist/utils/signatureCache.cjs.map +0 -1
  555. package/dist/utils/signatureCache.d.ts +0 -172
  556. package/dist/utils/signatureCache.js +0 -167
  557. package/dist/utils/signatureCache.js.map +0 -1
  558. package/dist/utils/signatureFormatter.cjs +0 -42
  559. package/dist/utils/signatureFormatter.cjs.map +0 -1
  560. package/dist/utils/signatureFormatter.d.ts +0 -36
  561. package/dist/utils/signatureFormatter.js +0 -18
  562. package/dist/utils/signatureFormatter.js.map +0 -1
  563. package/dist/utils/subgraphConsistency.cjs +0 -184
  564. package/dist/utils/subgraphConsistency.cjs.map +0 -1
  565. package/dist/utils/subgraphConsistency.d.ts +0 -65
  566. package/dist/utils/subgraphConsistency.js +0 -155
  567. package/dist/utils/subgraphConsistency.js.map +0 -1
  568. package/dist/utils/subgraphMetaCache.cjs +0 -101
  569. package/dist/utils/subgraphMetaCache.cjs.map +0 -1
  570. package/dist/utils/subgraphMetaCache.d.ts +0 -56
  571. package/dist/utils/subgraphMetaCache.js +0 -76
  572. package/dist/utils/subgraphMetaCache.js.map +0 -1
  573. package/dist/utils/subgraphPagination.cjs +0 -104
  574. package/dist/utils/subgraphPagination.cjs.map +0 -1
  575. package/dist/utils/subgraphPagination.d.ts +0 -78
  576. package/dist/utils/subgraphPagination.js +0 -78
  577. package/dist/utils/subgraphPagination.js.map +0 -1
  578. package/dist/utils/tests/multicall.test.d.ts +0 -1
  579. package/dist/utils/transactionHelpers.cjs +0 -54
  580. package/dist/utils/transactionHelpers.cjs.map +0 -1
  581. package/dist/utils/transactionHelpers.d.ts +0 -80
  582. package/dist/utils/transactionHelpers.js +0 -29
  583. package/dist/utils/transactionHelpers.js.map +0 -1
  584. package/dist/utils/typeGuards.cjs +0 -109
  585. package/dist/utils/typeGuards.cjs.map +0 -1
  586. package/dist/utils/typeGuards.d.ts +0 -138
  587. package/dist/utils/typeGuards.js +0 -74
  588. package/dist/utils/typeGuards.js.map +0 -1
  589. package/dist/utils/typedDataConverter.cjs +0 -43
  590. package/dist/utils/typedDataConverter.cjs.map +0 -1
  591. package/dist/utils/typedDataConverter.d.ts +0 -46
  592. package/dist/utils/typedDataConverter.js +0 -19
  593. package/dist/utils/typedDataConverter.js.map +0 -1
  594. package/dist/utils/urlResolver.cjs +0 -62
  595. package/dist/utils/urlResolver.cjs.map +0 -1
  596. package/dist/utils/urlResolver.d.ts +0 -56
  597. package/dist/utils/urlResolver.js +0 -37
  598. package/dist/utils/urlResolver.js.map +0 -1
  599. package/dist/utils/wallet.cjs +0 -63
  600. package/dist/utils/wallet.cjs.map +0 -1
  601. package/dist/utils/wallet.d.ts +0 -94
  602. package/dist/utils/wallet.js +0 -37
  603. package/dist/utils/wallet.js.map +0 -1
  604. package/dist/utils/withEvents.cjs +0 -44
  605. package/dist/utils/withEvents.cjs.map +0 -1
  606. package/dist/utils/withEvents.d.ts +0 -56
  607. package/dist/utils/withEvents.js +0 -18
  608. package/dist/utils/withEvents.js.map +0 -1
  609. /package/dist/{__tests__/waitForTransactionEvents.test.d.ts → auth/pkce.test.d.ts} +0 -0
  610. /package/dist/{client/__tests__/enhancedResponse.test.d.ts → auth/token-store.test.d.ts} +0 -0
  611. /package/dist/{controllers/__tests__/operations.processQueue.test.d.ts → auth/web3-signed.test.d.ts} +0 -0
  612. /package/dist/{controllers/__tests__/schemas-edge-cases.test.d.ts → crypto/envelope/openpgp.test.d.ts} +0 -0
  613. /package/dist/{controllers/data-error-handling.test.d.ts → crypto/keys/derive.test.d.ts} +0 -0
  614. /package/dist/{tests/errors.test.d.ts → errors.test.d.ts} +0 -0
  615. /package/dist/{controllers/server-additional.test.d.ts → protocol/data-file.test.d.ts} +0 -0
  616. /package/dist/{core/__tests__/health.test.d.ts → protocol/eip712.test.d.ts} +0 -0
  617. /package/dist/{core/__tests__/inMemoryNonceManager.test.d.ts → protocol/gateway.test.d.ts} +0 -0
  618. /package/dist/{core/__tests__/nonceManager.test.d.ts → protocol/grants.test.d.ts} +0 -0
  619. /package/dist/{core/core.test.d.ts → protocol/scopes.test.d.ts} +0 -0
  620. /package/dist/{core/tests/apiClient.test.d.ts → storage/tests/defaultStorage.test.d.ts} +0 -0
  621. /package/dist/{core/tests/client.test.d.ts → storage/tests/r2Storage.test.d.ts} +0 -0
  622. /package/dist/{core/tests/generics.test.d.ts → storage/tests/vanaStorage.test.d.ts} +0 -0
  623. /package/dist/{diagnostics.test.d.ts → types/ps-errors.test.d.ts} +0 -0
@@ -1,2633 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var data_exports = {};
30
- __export(data_exports, {
31
- DataController: () => DataController
32
- });
33
- module.exports = __toCommonJS(data_exports);
34
- var import_viem = require("viem");
35
- var import_pollingManager = require("../core/pollingManager");
36
- var import_base = require("./base");
37
- var import_addresses = require("../generated/addresses");
38
- var import_abi = require("../generated/abi");
39
- var import_errors = require("../errors");
40
- var import_subgraph = require("../generated/subgraph");
41
- var import_graphql = require("graphql");
42
- var import_subgraphConsistency = require("../utils/subgraphConsistency");
43
- var import_subgraphPagination = require("../utils/subgraphPagination");
44
- var import_chainQuery = require("../utils/chainQuery");
45
- var import_encryption = require("../utils/encryption");
46
- var import_schemaValidation = require("../utils/schemaValidation");
47
- var import_multicall = require("../utils/multicall");
48
- class DataController extends import_base.BaseController {
49
- constructor(context) {
50
- super(context);
51
- }
52
- async upload(params) {
53
- this.assertWallet();
54
- const {
55
- content,
56
- filename,
57
- schemaId,
58
- permissions = [],
59
- encrypt = true,
60
- providerName,
61
- owner,
62
- schemaValidation = "strict"
63
- } = params;
64
- if (encrypt && owner && owner.toLowerCase() !== this.context.userAddress.toLowerCase()) {
65
- throw new import_errors.InvalidConfigurationError(
66
- "The 'owner' parameter cannot be different from the connected wallet's address when encryption is enabled. This would create an un-decryptable file."
67
- );
68
- }
69
- try {
70
- let isValid = true;
71
- let validationErrors = [];
72
- if (schemaId !== void 0 && schemaValidation !== "skip") {
73
- try {
74
- const { SchemaController } = await import("./schemas");
75
- const schemaController = new SchemaController(this.context);
76
- const schema = await schemaController.get(schemaId);
77
- let parsedContent;
78
- if (typeof content === "string") {
79
- try {
80
- parsedContent = JSON.parse(content);
81
- } catch {
82
- parsedContent = content;
83
- }
84
- } else if (content instanceof Blob) {
85
- const text = await content.text();
86
- try {
87
- parsedContent = JSON.parse(text);
88
- } catch {
89
- parsedContent = text;
90
- }
91
- } else {
92
- parsedContent = content;
93
- }
94
- (0, import_schemaValidation.validateDataAgainstSchema)(parsedContent, schema);
95
- } catch (error) {
96
- if (schemaValidation === "strict") {
97
- throw error;
98
- } else if (schemaValidation === "warn") {
99
- console.warn(
100
- '[Vana SDK] Schema validation failed, but continuing due to validation mode "warn"'
101
- );
102
- if (error instanceof Error) {
103
- console.warn(" Validation error:", error.message);
104
- if (typeof error === "object" && "errors" in error && Array.isArray(error.errors)) {
105
- console.warn(" Detailed errors:", error.errors);
106
- }
107
- }
108
- isValid = false;
109
- validationErrors = error instanceof Error ? [error.message] : ["Schema validation failed"];
110
- }
111
- }
112
- }
113
- const uploadResult = await this.uploadToStorage(
114
- content,
115
- filename,
116
- encrypt,
117
- providerName
118
- );
119
- const userAddress = owner ?? this.context.userAddress;
120
- let encryptedPermissions = [];
121
- if (permissions.length > 0 && encrypt) {
122
- this.assertWallet();
123
- const userEncryptionKey = await (0, import_encryption.generateEncryptionKey)(
124
- this.context.walletClient,
125
- this.context.platform,
126
- import_encryption.DEFAULT_ENCRYPTION_SEED
127
- );
128
- encryptedPermissions = await Promise.all(
129
- permissions.map(async (permission) => {
130
- const encryptedKey = await (0, import_encryption.encryptWithWalletPublicKey)(
131
- userEncryptionKey,
132
- permission.publicKey,
133
- this.context.platform
134
- );
135
- return {
136
- account: permission.account,
137
- key: encryptedKey
138
- };
139
- })
140
- );
141
- }
142
- let result;
143
- if (this.context.relayer) {
144
- const request = {
145
- type: "direct",
146
- operation: "submitFileAdditionComplete",
147
- params: {
148
- url: uploadResult.url,
149
- userAddress,
150
- permissions: encryptedPermissions,
151
- schemaId: schemaId ?? 0,
152
- ownerAddress: owner
153
- }
154
- };
155
- const response = await this.context.relayer(request);
156
- if (response.type === "error") {
157
- throw new Error(response.error);
158
- }
159
- if (response.type === "pending") {
160
- result = await this.pollRelayerForConfirmation(
161
- response.operationId,
162
- void 0
163
- // TODO: Add TransactionOptions to upload method signature
164
- );
165
- } else if (response.type === "direct" && typeof response.result === "object" && response.result !== null && "fileId" in response.result) {
166
- result = response.result;
167
- } else {
168
- throw new Error("Invalid response from relayer");
169
- }
170
- } else {
171
- const txResult = await this.addFileWithEncryptedPermissionsAndSchema(
172
- uploadResult.url,
173
- userAddress,
174
- encryptedPermissions,
175
- schemaId ?? 0
176
- );
177
- if (!this.context.waitForTransactionEvents) {
178
- throw new Error(
179
- "Cannot upload without relay: waitForTransactionEvents not configured"
180
- );
181
- }
182
- const eventResult = await this.context.waitForTransactionEvents(txResult);
183
- const fileAddedEvent = eventResult.expectedEvents.FileAdded;
184
- if (!fileAddedEvent) {
185
- throw new Error("FileAdded event not found in transaction");
186
- }
187
- result = {
188
- fileId: Number(fileAddedEvent.fileId),
189
- transactionHash: txResult.hash
190
- };
191
- }
192
- return {
193
- fileId: result.fileId,
194
- url: uploadResult.url,
195
- transactionHash: result.transactionHash,
196
- size: uploadResult.size,
197
- isValid,
198
- validationErrors: validationErrors.length > 0 ? validationErrors : void 0
199
- };
200
- } catch (error) {
201
- throw new Error(
202
- `Upload failed: ${error instanceof Error ? error.message : "Unknown error"}`
203
- );
204
- }
205
- }
206
- /**
207
- * Encrypts data using wallet-derived encryption.
208
- *
209
- * @remarks
210
- * This method provides secure, wallet-based encryption for data before uploading
211
- * to the Vana network. It's the counterpart to decryptFile for preparing data
212
- * for secure storage.
213
- *
214
- * The method automatically:
215
- * - Generates an encryption key from the user's wallet signature
216
- * - Converts the input data to a Blob if necessary
217
- * - Encrypts the data using the generated key
218
- * - Returns both the encrypted data and the encryption key
219
- *
220
- * The encryption key returned can be stored and later used for decryption,
221
- * or shared with others to grant them decryption access.
222
- *
223
- * @param data - The data to encrypt (Blob, string, or object)
224
- * @param options - Optional encryption configuration
225
- * @returns Promise resolving to encrypted data and the encryption key used
226
- * @throws {Error} When wallet is not connected or encryption fails
227
- * @example
228
- * ```typescript
229
- * // Encrypt a string
230
- * const { encryptedData, encryptionKey } = await vana.data.encryptFile(
231
- * "My secret data"
232
- * );
233
- *
234
- * // Encrypt JSON with custom MIME type
235
- * const { encryptedData, encryptionKey } = await vana.data.encryptFile(
236
- * { name: "Alice", age: 30 },
237
- * { mimeType: "application/json" }
238
- * );
239
- *
240
- * // With custom encryption seed
241
- * const { encryptedData, encryptionKey } = await vana.data.encryptFile(
242
- * "Secret message",
243
- * { seed: "My custom encryption seed" }
244
- * );
245
- *
246
- * // Upload the encrypted data
247
- * const result = await vana.data.uploadToStorage(encryptedData);
248
- * ```
249
- */
250
- async encryptFile(data, options) {
251
- this.assertWallet();
252
- try {
253
- const encryptionKey = await (0, import_encryption.generateEncryptionKey)(
254
- this.context.walletClient,
255
- this.context.platform,
256
- options?.seed ?? import_encryption.DEFAULT_ENCRYPTION_SEED
257
- );
258
- let blob;
259
- if (data instanceof Blob) {
260
- blob = data;
261
- } else if (typeof data === "string") {
262
- blob = new Blob([data], { type: options?.mimeType ?? "text/plain" });
263
- } else {
264
- blob = new Blob([JSON.stringify(data)], {
265
- type: options?.mimeType ?? "application/json"
266
- });
267
- }
268
- const encryptedData = await (0, import_encryption.encryptBlobWithSignedKey)(
269
- blob,
270
- encryptionKey,
271
- this.context.platform
272
- );
273
- return {
274
- encryptedData,
275
- encryptionKey
276
- };
277
- } catch (error) {
278
- throw new Error(
279
- `Failed to encrypt file: ${error instanceof Error ? error.message : "Unknown error"}`
280
- );
281
- }
282
- }
283
- /**
284
- * Decrypts a file using wallet-derived decryption key.
285
- *
286
- * @remarks
287
- * Counterpart to `upload()` for decrypting user files. Automatically
288
- * generates decryption key from wallet, fetches encrypted content,
289
- * and decrypts. Supports IPFS (with gateway fallback) and HTTP URLs.
290
- *
291
- * @param file - UserFile object from `getUserFiles()`
292
- * @param options - Decryption options
293
- * @param options.seed - Custom encryption seed.
294
- * Defaults to standard Vana seed.
295
- *
296
- * @returns Decrypted content as Blob
297
- *
298
- * @throws {Error} No wallet connected.
299
- * Connect wallet before decrypting.
300
- * @throws {Error} Network error accessing file.
301
- * Check CORS settings or server availability.
302
- * @throws {Error} File not found (404).
303
- * File no longer available at stored URL.
304
- * @throws {Error} Access denied (403).
305
- * No permission to access file.
306
- * @throws {Error} Invalid file format.
307
- * File not encrypted with Vana protocol.
308
- * @throws {Error} Wrong encryption key.
309
- * Verify seed matches upload or use default.
310
- *
311
- * @example
312
- * ```typescript
313
- * // Basic file decryption
314
- * const files = await vana.data.getUserFiles({ owner: userAddress });
315
- * const decryptedBlob = await vana.data.decryptFile(files[0]);
316
- *
317
- * // Convert to text
318
- * const text = await decryptedBlob.text();
319
- * console.log('Decrypted content:', text);
320
- *
321
- * // Convert to JSON
322
- * const json = JSON.parse(await decryptedBlob.text());
323
- * console.log('Decrypted data:', json);
324
- *
325
- * // With custom encryption seed
326
- * const decryptedBlob = await vana.data.decryptFile(
327
- * files[0],
328
- * "My custom encryption seed"
329
- * );
330
- *
331
- * // Save to file (in Node.js)
332
- * const buffer = await decryptedBlob.arrayBuffer();
333
- * fs.writeFileSync('decrypted-file.txt', Buffer.from(buffer));
334
- * ```
335
- */
336
- async decryptFile(file, options) {
337
- this.assertWallet();
338
- try {
339
- this.assertWallet();
340
- const encryptionKey = await (0, import_encryption.generateEncryptionKey)(
341
- this.context.walletClient,
342
- this.context.platform,
343
- options?.seed ?? import_encryption.DEFAULT_ENCRYPTION_SEED
344
- );
345
- let encryptedBlob;
346
- try {
347
- if (file.url.startsWith("ipfs://")) {
348
- encryptedBlob = await this.fetchFromIPFS(file.url);
349
- } else {
350
- encryptedBlob = await this.fetch(file.url);
351
- }
352
- } catch (fetchError) {
353
- const errorMessage = fetchError instanceof Error ? fetchError.message : "Unknown error";
354
- if (errorMessage.includes("Failed to fetch IPFS content") && errorMessage.includes("from all gateways")) {
355
- throw new Error(
356
- "Network error: Cannot access the file URL. The file may be stored on a server that's not accessible or has CORS restrictions."
357
- );
358
- } else if (errorMessage.includes("Empty response")) {
359
- throw new Error("File is empty or could not be retrieved");
360
- } else if (errorMessage.includes("Network error:") || errorMessage.includes("Failed to fetch")) {
361
- throw new Error(
362
- "Network error: Cannot access the file URL. The file may be stored on a server that's not accessible or has CORS restrictions."
363
- );
364
- } else if (errorMessage.includes("HTTP error!")) {
365
- const statusMatch = errorMessage.match(/status: (\d+)/);
366
- const status = statusMatch ? statusMatch[1] : "unknown";
367
- if (status === "500") {
368
- throw new Error(
369
- "Network error: Cannot access the file URL. The file may be stored on a server that's not accessible or has CORS restrictions."
370
- );
371
- } else if (status === "403") {
372
- throw new Error(
373
- "Access denied. You may not have permission to access this file"
374
- );
375
- } else if (status === "404") {
376
- throw new Error(
377
- "File not found: The encrypted file is no longer available at the stored URL."
378
- );
379
- } else {
380
- throw new Error(
381
- "Network error: Cannot access the file URL. The file may be stored on a server that's not accessible or has CORS restrictions."
382
- );
383
- }
384
- }
385
- throw fetchError;
386
- }
387
- if (encryptedBlob.size === 0) {
388
- throw new Error("File is empty or could not be retrieved");
389
- }
390
- let decryptedBlob;
391
- try {
392
- decryptedBlob = await (0, import_encryption.decryptBlobWithSignedKey)(
393
- encryptedBlob,
394
- encryptionKey,
395
- this.context.platform
396
- );
397
- } catch (decryptError) {
398
- const errorMessage = decryptError instanceof Error ? decryptError.message : "Unknown error";
399
- if (errorMessage.includes("not a valid OpenPGP message")) {
400
- throw new Error(
401
- "Invalid file format: This file doesn't appear to be encrypted with the Vana protocol"
402
- );
403
- } else if (errorMessage.includes("Session key decryption failed")) {
404
- throw new Error("Wrong encryption key");
405
- } else if (errorMessage.includes("Error decrypting message")) {
406
- throw new Error("Wrong encryption key");
407
- } else if (errorMessage.includes("File not found")) {
408
- throw new Error(
409
- "File not found: The encrypted file is no longer available"
410
- );
411
- } else {
412
- throw decryptError;
413
- }
414
- }
415
- return decryptedBlob;
416
- } catch (error) {
417
- if (error instanceof Error && (error.message.includes("Network error:") || error.message.includes("Invalid file format:") || error.message.includes("Wrong encryption key") || error.message.includes("Access denied") || error.message.includes("File not found:") || error.message.includes("File is empty"))) {
418
- throw error;
419
- }
420
- throw new Error(
421
- `Failed to decrypt file: ${error instanceof Error ? error.message : "Unknown error"}`
422
- );
423
- }
424
- }
425
- /**
426
- * Retrieves all files owned by a specific user address.
427
- *
428
- * @remarks
429
- * Queries the Vana subgraph for files owned by the specified address.
430
- * Automatically deduplicates by file ID, keeping the latest version
431
- * when duplicates exist from re-indexing or chain reorganizations.
432
- * Enriches results with DLP proof data when available.
433
- *
434
- * @param params - Query configuration
435
- * @param params.owner - Wallet address of the file owner
436
- * @param params.subgraphUrl - Subgraph endpoint override.
437
- * Defaults to context configuration.
438
- *
439
- * @returns Array of UserFile objects sorted by timestamp (newest first)
440
- *
441
- * @throws {Error} Subgraph URL not configured.
442
- * Provide `subgraphUrl` parameter or configure in Vana constructor.
443
- * @throws {Error} Subgraph request failed.
444
- * Check network connectivity and subgraph availability.
445
- * @throws {Error} Subgraph returned errors.
446
- * Review query parameters and subgraph logs.
447
- *
448
- * @example
449
- * ```typescript
450
- * const files = await vana.data.getUserFiles({
451
- * owner: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36"
452
- * });
453
- *
454
- * files.forEach(file => {
455
- * console.log(`File ${file.id}: ${file.url}`);
456
- * console.log(` Schema: ${file.schemaId}`);
457
- * console.log(` DLPs: ${file.dlpIds?.join(", ") || "none"}`);
458
- * });
459
- * ```
460
- */
461
- async getUserFiles(params, options) {
462
- const { owner, subgraphUrl } = params;
463
- let dataSource = options?.source === "chain" ? "chain" : "subgraph";
464
- if (options?.source === "auto" || !options?.source && options?.minBlock) {
465
- const endpoint2 = subgraphUrl ?? this.context.subgraphUrl;
466
- const currentBlock = await this.context.publicClient.getBlockNumber();
467
- let subgraphBlock;
468
- if (endpoint2) {
469
- try {
470
- const meta = await (0, import_subgraphConsistency.fetchSubgraphMeta)(endpoint2);
471
- subgraphBlock = meta.blockNumber;
472
- } catch {
473
- subgraphBlock = void 0;
474
- }
475
- }
476
- dataSource = (0, import_chainQuery.determineDataSource)(
477
- options?.source,
478
- options?.minBlock,
479
- currentBlock,
480
- subgraphBlock
481
- );
482
- }
483
- if (dataSource === "chain") {
484
- const publicClient = this.context.publicClient;
485
- const chainId = await publicClient.getChainId();
486
- const contractAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
487
- const files = await (0, import_chainQuery.getUserFilesFromChain)(
488
- publicClient,
489
- contractAddress,
490
- owner,
491
- options?.minBlock ? BigInt(options.minBlock) : void 0
492
- );
493
- const limit = options?.fetchAll ? files.length : options?.limit ?? 100;
494
- const offset = options?.offset ?? 0;
495
- return files.slice(offset, offset + limit);
496
- }
497
- const endpoint = subgraphUrl ?? this.context.subgraphUrl;
498
- if (!endpoint) {
499
- throw new Error(
500
- "subgraphUrl is required. Please provide a valid subgraph endpoint or configure it in Vana constructor."
501
- );
502
- }
503
- if (options?.minBlock || options?.waitForSync) {
504
- await (0, import_subgraphConsistency.checkSubgraphConsistency)(endpoint, options);
505
- }
506
- try {
507
- const orderByMap = {
508
- id: "id",
509
- addedAtBlock: "addedAtBlock",
510
- addedAtTimestamp: "addedAtTimestamp",
511
- url: "url",
512
- schemaId: "schemaId"
513
- };
514
- const allFiles = await (0, import_subgraphPagination.executePaginatedQuery)({
515
- endpoint,
516
- document: import_subgraph.GetUserFilesPaginatedDocument,
517
- baseVariables: {
518
- userId: owner.toLowerCase(),
519
- // Subgraph requires lowercase addresses
520
- orderBy: (0, import_subgraphPagination.mapOrderByToEnum)(
521
- options?.orderBy,
522
- orderByMap,
523
- "addedAtBlock"
524
- ),
525
- orderDirection: (0, import_subgraphPagination.mapOrderDirection)(
526
- options?.orderDirection,
527
- "asc",
528
- "desc"
529
- )
530
- },
531
- options,
532
- extractItems: (data) => data?.user?.files,
533
- transformItem: (file) => ({
534
- id: parseInt(file.id),
535
- url: file.url,
536
- ownerAddress: file.owner.id,
537
- addedAtBlock: BigInt(file.addedAtBlock),
538
- schemaId: parseInt(file.schemaId),
539
- addedAtTimestamp: BigInt(file.addedAtTimestamp),
540
- transactionHash: file.transactionHash
541
- })
542
- });
543
- if (allFiles.length > 0) {
544
- try {
545
- const fileIds = allFiles.map((f) => f.id);
546
- let proofMap;
547
- try {
548
- proofMap = await this._fetchProofsFromSubgraph(fileIds, endpoint);
549
- } catch (subgraphError) {
550
- console.debug(
551
- "Failed to fetch proofs from subgraph, trying chain:",
552
- subgraphError
553
- );
554
- proofMap = await this._fetchProofsFromChain(fileIds);
555
- }
556
- for (const file of allFiles) {
557
- const dlpIds = proofMap.get(file.id);
558
- if (dlpIds && dlpIds.length > 0) {
559
- file.dlpIds = dlpIds;
560
- }
561
- }
562
- } catch (error) {
563
- console.warn("Failed to fetch proof data for files:", error);
564
- }
565
- }
566
- return allFiles;
567
- } catch (error) {
568
- console.error("Failed to fetch user files from subgraph:", error);
569
- throw new Error(
570
- `Failed to fetch user files from subgraph: ${error instanceof Error ? error.message : "Unknown error"}`
571
- );
572
- }
573
- }
574
- /**
575
- * Fetches proof data for multiple files from the subgraph.
576
- *
577
- * @private
578
- * @param fileIds - Array of file IDs to fetch proofs for
579
- * @param subgraphUrl - The subgraph endpoint URL
580
- * @returns Map of file IDs to their associated DLP IDs
581
- */
582
- async _fetchProofsFromSubgraph(fileIds, subgraphUrl) {
583
- const response = await fetch(subgraphUrl, {
584
- method: "POST",
585
- headers: {
586
- "Content-Type": "application/json"
587
- },
588
- body: JSON.stringify({
589
- query: (0, import_graphql.print)(import_subgraph.GetFileProofsDocument),
590
- variables: {
591
- fileIds: fileIds.map((id) => id.toString())
592
- }
593
- })
594
- });
595
- if (!response.ok) {
596
- throw new Error(
597
- `Subgraph request failed: ${response.status} ${response.statusText}`
598
- );
599
- }
600
- const result = await response.json();
601
- if (result.errors) {
602
- throw new Error(
603
- `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
604
- );
605
- }
606
- const proofMap = /* @__PURE__ */ new Map();
607
- if (result.data?.dataRegistryProofs) {
608
- for (const proof of result.data.dataRegistryProofs) {
609
- if (proof.dlp?.id) {
610
- const fileId = parseInt(proof.fileId);
611
- const dlpId = parseInt(proof.dlp.id);
612
- let dlpIds = proofMap.get(fileId);
613
- if (!dlpIds) {
614
- dlpIds = [];
615
- proofMap.set(fileId, dlpIds);
616
- }
617
- if (!dlpIds.includes(dlpId)) {
618
- dlpIds.push(dlpId);
619
- }
620
- }
621
- }
622
- }
623
- return proofMap;
624
- }
625
- /**
626
- * Fetches proof data for multiple files from the blockchain.
627
- * Falls back to this when subgraph is unavailable.
628
- *
629
- * @private
630
- * @param fileIds - Array of file IDs to fetch proofs for
631
- * @returns Map of file IDs to their associated DLP IDs
632
- */
633
- async _fetchProofsFromChain(fileIds) {
634
- const chainId = this.context.publicClient.chain?.id;
635
- if (!chainId) {
636
- throw new Error("Chain ID not available");
637
- }
638
- const dataRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
639
- const dataRegistryAbi = (0, import_abi.getAbi)("DataRegistry");
640
- const proofMap = /* @__PURE__ */ new Map();
641
- for (const fileId of fileIds) {
642
- const dlpIds = [];
643
- let proofIndex = 0;
644
- let hasMoreProofs = true;
645
- while (hasMoreProofs) {
646
- try {
647
- const proof = await this.context.publicClient.readContract({
648
- address: dataRegistryAddress,
649
- abi: dataRegistryAbi,
650
- functionName: "fileProofs",
651
- args: [BigInt(fileId), BigInt(proofIndex)]
652
- });
653
- if (proof?.data?.dlpId) {
654
- const dlpId = Number(proof.data.dlpId);
655
- if (!dlpIds.includes(dlpId)) {
656
- dlpIds.push(dlpId);
657
- }
658
- }
659
- proofIndex++;
660
- } catch {
661
- hasMoreProofs = false;
662
- }
663
- }
664
- if (dlpIds.length > 0) {
665
- proofMap.set(fileId, dlpIds);
666
- }
667
- }
668
- return proofMap;
669
- }
670
- /**
671
- * Retrieves information about a specific Data Liquidity Pool (DLP).
672
- *
673
- * @remarks
674
- * DLPs are entities that process and verify data files in the Vana network.
675
- * This method fetches DLP metadata including name, status, and performance rating.
676
- * Uses subgraph first for efficiency, falls back to chain if unavailable.
677
- *
678
- * @param dlpId - The unique identifier of the DLP
679
- * @param options - Optional parameters
680
- * @param options.subgraphUrl - Custom subgraph URL to override default
681
- * @returns Promise resolving to DLP information
682
- * @throws {Error} When DLP cannot be found - "DLP not found: {dlpId}"
683
- * @throws {Error} When query fails - "Failed to fetch DLP: {error}"
684
- * @example
685
- * ```typescript
686
- * const dlp = await vana.data.getDLP(26);
687
- * console.log(`DLP ${dlp.name}: ${dlp.status}`);
688
- * ```
689
- */
690
- async getDLP(dlpId, options = {}) {
691
- const subgraphUrl = options.subgraphUrl ?? this.context.subgraphUrl;
692
- if (subgraphUrl && (options.minBlock || options.waitForSync)) {
693
- await (0, import_subgraphConsistency.checkSubgraphConsistency)(subgraphUrl, options);
694
- }
695
- if (subgraphUrl) {
696
- try {
697
- const response = await fetch(subgraphUrl, {
698
- method: "POST",
699
- headers: {
700
- "Content-Type": "application/json"
701
- },
702
- body: JSON.stringify({
703
- query: (0, import_graphql.print)(import_subgraph.GetDlpDocument),
704
- variables: {
705
- id: dlpId.toString()
706
- }
707
- })
708
- });
709
- if (!response.ok) {
710
- throw new Error(
711
- `Subgraph request failed: ${response.status} ${response.statusText}`
712
- );
713
- }
714
- const result = await response.json();
715
- if (result.errors) {
716
- throw new Error(
717
- `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
718
- );
719
- }
720
- if (!result.data?.dlp) {
721
- throw new Error(`DLP not found: ${dlpId}`);
722
- }
723
- return {
724
- id: parseInt(result.data.dlp.id),
725
- name: result.data.dlp.name ?? "",
726
- metadata: result.data.dlp.metadata ?? void 0,
727
- status: result.data.dlp.status ? parseInt(result.data.dlp.status) : void 0,
728
- address: result.data.dlp.address ? result.data.dlp.address : void 0,
729
- owner: result.data.dlp.owner ? result.data.dlp.owner : void 0
730
- };
731
- } catch (error) {
732
- console.debug("Subgraph query failed, falling back to chain:", error);
733
- }
734
- }
735
- try {
736
- const chainId = this.context.publicClient.chain?.id;
737
- if (!chainId) {
738
- throw new Error("Chain ID not available");
739
- }
740
- const dlpRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DLPRegistry");
741
- const dlpRegistryAbi = (0, import_abi.getAbi)("DLPRegistry");
742
- const dlpData = await this.context.publicClient.readContract({
743
- address: dlpRegistryAddress,
744
- abi: dlpRegistryAbi,
745
- functionName: "dlps",
746
- args: [BigInt(dlpId)]
747
- });
748
- if (!dlpData?.name) {
749
- throw new Error(`DLP not found: ${dlpId}`);
750
- }
751
- return {
752
- id: dlpId,
753
- name: dlpData.name,
754
- metadata: dlpData.metadata,
755
- status: dlpData.status,
756
- address: dlpData.dlpAddress,
757
- owner: dlpData.ownerAddress
758
- };
759
- } catch (error) {
760
- throw new Error(
761
- `Failed to fetch DLP: ${error instanceof Error ? error.message : "Unknown error"}`
762
- );
763
- }
764
- }
765
- /**
766
- * Lists all Data Liquidity Pools (DLPs) with optional pagination.
767
- *
768
- * @remarks
769
- * Fetches a paginated list of all DLPs registered in the network.
770
- * Uses subgraph for efficient querying with fallback to chain multicall.
771
- *
772
- * @param options - Optional parameters for pagination and filtering
773
- * @param options.limit - Maximum number of DLPs to return (default: 100)
774
- * @param options.offset - Number of DLPs to skip (default: 0)
775
- * @param options.subgraphUrl - Custom subgraph URL to override default
776
- * @returns Promise resolving to array of DLP information
777
- * @throws {Error} When query fails - "Failed to list DLPs: {error}"
778
- * @example
779
- * ```typescript
780
- * // Get first 10 DLPs
781
- * const dlps = await vana.data.listDLPs({ limit: 10 });
782
- * dlps.forEach(dlp => console.log(`${dlp.id}: ${dlp.name}`));
783
- *
784
- * // Get next page
785
- * const nextPage = await vana.data.listDLPs({ limit: 10, offset: 10 });
786
- * ```
787
- */
788
- async listDLPs(options = {}) {
789
- const { limit = 100, offset = 0 } = options;
790
- const subgraphUrl = options.subgraphUrl ?? this.context.subgraphUrl;
791
- if (subgraphUrl) {
792
- try {
793
- const query = `
794
- query ListDLPs($first: Int!, $skip: Int!) {
795
- dlps(first: $first, skip: $skip, orderBy: id) {
796
- id
797
- name
798
- metadata
799
- status
800
- address
801
- owner
802
- }
803
- }
804
- `;
805
- const response = await fetch(subgraphUrl, {
806
- method: "POST",
807
- headers: {
808
- "Content-Type": "application/json"
809
- },
810
- body: JSON.stringify({
811
- query,
812
- variables: {
813
- first: limit,
814
- skip: offset
815
- }
816
- })
817
- });
818
- if (!response.ok) {
819
- throw new Error(
820
- `Subgraph request failed: ${response.status} ${response.statusText}`
821
- );
822
- }
823
- const result = await response.json();
824
- if (result.errors) {
825
- throw new Error(
826
- `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
827
- );
828
- }
829
- const dlps = result.data?.dlps ?? [];
830
- return dlps.map((dlp) => ({
831
- id: parseInt(dlp.id),
832
- name: dlp.name ?? "",
833
- metadata: dlp.metadata,
834
- status: dlp.status ? parseInt(dlp.status) : void 0,
835
- address: dlp.address ? dlp.address : void 0,
836
- owner: dlp.owner ? dlp.owner : void 0
837
- }));
838
- } catch (error) {
839
- console.debug("Subgraph query failed, falling back to chain:", error);
840
- }
841
- }
842
- try {
843
- const chainId = this.context.publicClient.chain?.id;
844
- if (!chainId) {
845
- throw new Error("Chain ID not available");
846
- }
847
- const dlpRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DLPRegistry");
848
- const dlpRegistryAbi = (0, import_abi.getAbi)("DLPRegistry");
849
- const dlpCount = await this.context.publicClient.readContract({
850
- address: dlpRegistryAddress,
851
- abi: dlpRegistryAbi,
852
- functionName: "dlpsCount",
853
- args: []
854
- });
855
- const totalCount = Number(dlpCount);
856
- const start = offset;
857
- const end = Math.min(start + limit, totalCount);
858
- if (end <= start) {
859
- return [];
860
- }
861
- const calls = [];
862
- for (let i = start + 1; i <= end; i++) {
863
- calls.push({
864
- address: dlpRegistryAddress,
865
- abi: dlpRegistryAbi,
866
- functionName: "dlps",
867
- args: [BigInt(i)]
868
- });
869
- }
870
- const results = await (0, import_multicall.gasAwareMulticall)(this.context.publicClient, {
871
- contracts: calls,
872
- allowFailure: true,
873
- batchSize: 50
874
- });
875
- const dlps = [];
876
- for (let i = 0; i < results.length; i++) {
877
- const result = results[i];
878
- if (result.status === "success" && result.result) {
879
- const dlpData = result.result;
880
- if (dlpData.name) {
881
- dlps.push({
882
- id: start + i + 1,
883
- name: dlpData.name,
884
- metadata: dlpData.metadata,
885
- status: dlpData.status,
886
- address: dlpData.dlpAddress,
887
- owner: dlpData.ownerAddress
888
- });
889
- }
890
- }
891
- }
892
- return dlps;
893
- } catch (error) {
894
- throw new Error(
895
- `Failed to list DLPs: ${error instanceof Error ? error.message : "Unknown error"}`
896
- );
897
- }
898
- }
899
- /**
900
- * Retrieves a list of permissions granted by a user.
901
- *
902
- * This method supports automatic fallback between subgraph and RPC modes:
903
- * - If subgraph URL is available, tries subgraph query first
904
- * - Falls back to direct contract queries via RPC if subgraph fails
905
- * - RPC mode uses gasAwareMulticall for efficient batch queries
906
- *
907
- * @param params - Object containing the user address and optional subgraph URL
908
- * @param params.user - The wallet address of the user to query permissions for
909
- * @param params.subgraphUrl - Optional subgraph URL to override the default
910
- * @returns Promise resolving to an array of permission objects
911
- * @throws Error if both subgraph and RPC queries fail
912
- */
913
- async getUserPermissions(params, options) {
914
- const { user, subgraphUrl } = params;
915
- const endpoint = subgraphUrl ?? this.context.subgraphUrl;
916
- if (endpoint && (options?.minBlock || options?.waitForSync)) {
917
- await (0, import_subgraphConsistency.checkSubgraphConsistency)(endpoint, options);
918
- }
919
- if (endpoint) {
920
- try {
921
- const permissions = await this._getUserPermissionsViaSubgraph(
922
- {
923
- user,
924
- subgraphUrl: endpoint
925
- },
926
- options
927
- );
928
- return permissions;
929
- } catch (error) {
930
- console.warn("Subgraph query failed, falling back to RPC:", error);
931
- }
932
- }
933
- const allPermissions = await this._getUserPermissionsViaRpc({ user });
934
- if (options && !options.fetchAll) {
935
- const limit = options.limit ?? 100;
936
- const offset = options.offset ?? 0;
937
- return allPermissions.slice(offset, offset + limit);
938
- }
939
- return allPermissions;
940
- }
941
- /**
942
- * Internal method: Query user permissions via subgraph
943
- *
944
- * @param params - Query parameters object
945
- * @param params.user - The user address to query permissions for
946
- * @param params.subgraphUrl - The subgraph URL endpoint to query
947
- * @returns Promise resolving to an array of permission objects
948
- */
949
- async _getUserPermissionsViaSubgraph(params, options) {
950
- const { user, subgraphUrl } = params;
951
- try {
952
- const orderByMap = {
953
- id: "id",
954
- addedAtBlock: "addedAtBlock",
955
- addedAtTimestamp: "addedAtTimestamp",
956
- grant: "grant",
957
- nonce: "nonce",
958
- startBlock: "startBlock",
959
- endBlock: "endBlock"
960
- };
961
- const permissions = await (0, import_subgraphPagination.executePaginatedQuery)({
962
- endpoint: subgraphUrl,
963
- document: import_subgraph.GetUserPermissionsPaginatedDocument,
964
- baseVariables: {
965
- userId: user.toLowerCase(),
966
- orderBy: (0, import_subgraphPagination.mapOrderByToEnum)(
967
- options?.orderBy,
968
- orderByMap,
969
- "addedAtTimestamp"
970
- ),
971
- orderDirection: (0, import_subgraphPagination.mapOrderDirection)(
972
- options?.orderDirection,
973
- "desc",
974
- "asc"
975
- )
976
- },
977
- options,
978
- extractItems: (data) => data?.user?.permissions,
979
- transformItem: (permission) => ({
980
- id: permission.id,
981
- grant: permission.grant,
982
- nonce: BigInt(permission.nonce),
983
- signature: permission.signature,
984
- addedAtBlock: BigInt(permission.addedAtBlock),
985
- addedAtTimestamp: BigInt(permission.addedAtTimestamp),
986
- transactionHash: permission.transactionHash,
987
- user
988
- })
989
- });
990
- return permissions;
991
- } catch (error) {
992
- console.error("Failed to query user permissions from subgraph:", error);
993
- throw error;
994
- }
995
- }
996
- /**
997
- * Internal method: Query user permissions via direct RPC
998
- *
999
- * @param params - Query parameters object
1000
- * @param params.user - The user address to query permissions for
1001
- * @returns Promise resolving to an array of permission objects
1002
- */
1003
- async _getUserPermissionsViaRpc(params) {
1004
- const { user } = params;
1005
- try {
1006
- const chainId = this.context.publicClient.chain?.id;
1007
- if (!chainId) {
1008
- throw new Error("Chain ID not available");
1009
- }
1010
- const permissionsAddress = (0, import_addresses.getContractAddress)(
1011
- chainId,
1012
- "DataPortabilityPermissions"
1013
- );
1014
- const permissionsAbi = (0, import_abi.getAbi)("DataPortabilityPermissions");
1015
- const totalCount = await this.context.publicClient.readContract({
1016
- address: permissionsAddress,
1017
- abi: permissionsAbi,
1018
- functionName: "userPermissionIdsLength",
1019
- args: [user]
1020
- });
1021
- const total = Number(totalCount);
1022
- if (total === 0) {
1023
- return [];
1024
- }
1025
- const permissionIdCalls = [];
1026
- for (let i = 0; i < total; i++) {
1027
- permissionIdCalls.push({
1028
- address: permissionsAddress,
1029
- abi: permissionsAbi,
1030
- functionName: "userPermissionIdsAt",
1031
- args: [user, BigInt(i)]
1032
- });
1033
- }
1034
- const permissionIdResults = await (0, import_multicall.gasAwareMulticall)(this.context.publicClient, {
1035
- contracts: permissionIdCalls
1036
- });
1037
- const permissionIds = permissionIdResults.map((result) => result).filter((id) => id && id > 0n);
1038
- const permissionInfoCalls = permissionIds.map(
1039
- (permissionId) => ({
1040
- address: permissionsAddress,
1041
- abi: permissionsAbi,
1042
- functionName: "permissions",
1043
- args: [permissionId]
1044
- })
1045
- );
1046
- const permissionInfoResults = await (0, import_multicall.gasAwareMulticall)(this.context.publicClient, {
1047
- contracts: permissionInfoCalls,
1048
- allowFailure: true
1049
- });
1050
- const permissions = permissionInfoResults.map((result, index) => {
1051
- const permissionId = permissionIds[index];
1052
- if (result.status === "success" && result.result) {
1053
- const permissionInfo = result.result;
1054
- return {
1055
- id: permissionId.toString(),
1056
- grant: permissionInfo.grant,
1057
- nonce: permissionInfo.nonce,
1058
- signature: "",
1059
- // Not available from RPC, will be empty
1060
- addedAtBlock: permissionInfo.startBlock,
1061
- addedAtTimestamp: BigInt(0),
1062
- // Not available from RPC
1063
- transactionHash: "0x0000000000000000000000000000000000000000",
1064
- // Not available from RPC
1065
- user
1066
- };
1067
- } else {
1068
- return {
1069
- id: permissionId.toString(),
1070
- grant: "",
1071
- nonce: BigInt(0),
1072
- signature: "",
1073
- addedAtBlock: BigInt(0),
1074
- addedAtTimestamp: BigInt(0),
1075
- transactionHash: "0x0000000000000000000000000000000000000000",
1076
- user
1077
- };
1078
- }
1079
- }).filter((permission) => permission.grant !== "");
1080
- return permissions;
1081
- } catch (error) {
1082
- throw new Error(
1083
- `RPC query failed: ${error instanceof Error ? error.message : "Unknown error"}`
1084
- );
1085
- }
1086
- }
1087
- /**
1088
- * Retrieves a list of trusted servers for a user.
1089
- *
1090
- * This method supports automatic fallback between subgraph and RPC modes:
1091
- * - If subgraph URL is available, tries subgraph query first for fast results
1092
- * - Falls back to direct contract queries via RPC if subgraph fails
1093
- * - RPC mode uses gasAwareMulticall for efficient batch queries
1094
- *
1095
- * @param params - Query parameters including user address and optional pagination
1096
- * @param params.user - The wallet address of the user to query trusted servers for
1097
- * @param params.subgraphUrl - Optional subgraph URL to override the default
1098
- * @param params.limit - Maximum number of results to return (default: 50)
1099
- * @param params.offset - Number of results to skip for pagination (default: 0)
1100
- * @returns Promise resolving to an array of trusted server objects
1101
- * @throws Error if both subgraph and RPC queries fail
1102
- * @example
1103
- * ```typescript
1104
- * // Basic usage with automatic fallback
1105
- * const servers = await vana.data.getUserTrustedServers({
1106
- * user: '0x...'
1107
- * });
1108
- *
1109
- * // With pagination
1110
- * const servers = await vana.data.getUserTrustedServers({
1111
- * user: '0x...',
1112
- * limit: 10,
1113
- * offset: 20
1114
- * });
1115
- *
1116
- * // With custom subgraph URL
1117
- * const servers = await vana.data.getUserTrustedServers({
1118
- * user: '0x...',
1119
- * subgraphUrl: 'https://custom-subgraph.com/graphql'
1120
- * });
1121
- * ```
1122
- */
1123
- async getUserTrustedServers(params, options) {
1124
- const { user } = params;
1125
- const subgraphUrl = params.subgraphUrl ?? this.context.subgraphUrl;
1126
- if (subgraphUrl && (options?.minBlock || options?.waitForSync)) {
1127
- await (0, import_subgraphConsistency.checkSubgraphConsistency)(subgraphUrl, options);
1128
- }
1129
- if (subgraphUrl) {
1130
- try {
1131
- const servers = await this._getUserTrustedServersViaSubgraph(
1132
- {
1133
- user,
1134
- subgraphUrl
1135
- },
1136
- options
1137
- );
1138
- return servers;
1139
- } catch (error) {
1140
- console.warn("Subgraph query failed, falling back to RPC:", error);
1141
- }
1142
- }
1143
- const limit = options?.fetchAll ? Number.MAX_SAFE_INTEGER : options?.limit ?? 100;
1144
- const offset = options?.offset ?? 0;
1145
- const rpcResult = await this._getUserTrustedServersViaRpc({
1146
- user,
1147
- limit,
1148
- offset
1149
- });
1150
- return rpcResult.servers;
1151
- }
1152
- /**
1153
- * Internal method: Query trusted servers via subgraph
1154
- *
1155
- * @param params - Query parameters object
1156
- * @param params.user - The user address to query trusted servers for
1157
- * @param params.subgraphUrl - The subgraph URL endpoint to query
1158
- * @returns Promise resolving to an array of trusted server objects
1159
- */
1160
- async _getUserTrustedServersViaSubgraph(params, options) {
1161
- const { user, subgraphUrl } = params;
1162
- const graphqlEndpoint = subgraphUrl;
1163
- if (!graphqlEndpoint) {
1164
- throw new Error(
1165
- "subgraphUrl is required for subgraph mode. Please provide a valid subgraph endpoint or configure it in Vana constructor."
1166
- );
1167
- }
1168
- try {
1169
- const orderByMap = {
1170
- id: "id",
1171
- trustedAt: "trustedAt",
1172
- trustedAtBlock: "trustedAtBlock",
1173
- server: "server",
1174
- user: "user"
1175
- };
1176
- const serverTrusts = await (0, import_subgraphPagination.executePaginatedQuery)({
1177
- endpoint: graphqlEndpoint,
1178
- document: import_subgraph.GetUserTrustedServersPaginatedDocument,
1179
- baseVariables: {
1180
- userId: user.toLowerCase(),
1181
- // Subgraph requires lowercase addresses
1182
- orderBy: (0, import_subgraphPagination.mapOrderByToEnum)(
1183
- options?.orderBy,
1184
- orderByMap,
1185
- "trustedAtBlock"
1186
- ),
1187
- orderDirection: (0, import_subgraphPagination.mapOrderDirection)(
1188
- options?.orderDirection,
1189
- "desc",
1190
- "asc"
1191
- )
1192
- },
1193
- options,
1194
- extractItems: (data) => {
1195
- const trusts = data?.user?.serverTrusts ?? [];
1196
- return trusts.filter((trust) => !trust.untrustedAtBlock);
1197
- },
1198
- transformItem: (trust) => ({
1199
- id: trust.server.id,
1200
- serverAddress: trust.server.serverAddress,
1201
- serverUrl: trust.server.url,
1202
- trustedAt: BigInt(trust.trustedAt),
1203
- user,
1204
- name: ""
1205
- // Not available in new schema, will be empty
1206
- })
1207
- });
1208
- return serverTrusts;
1209
- } catch (error) {
1210
- console.error("Failed to query trusted servers from subgraph:", error);
1211
- throw error;
1212
- }
1213
- }
1214
- /**
1215
- * Internal method: Query trusted servers via direct RPC
1216
- *
1217
- * @param params - Query parameters object
1218
- * @param params.user - The user address to query trusted servers for
1219
- * @param params.limit - Maximum number of results to return
1220
- * @param params.offset - Number of results to skip for pagination
1221
- * @returns Promise resolving to pagination result with servers, total count, and hasMore flag
1222
- */
1223
- async _getUserTrustedServersViaRpc(params) {
1224
- const { user, limit, offset } = params;
1225
- try {
1226
- const chainId = this.context.publicClient.chain?.id;
1227
- if (!chainId) {
1228
- throw new Error("Chain ID not available");
1229
- }
1230
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
1231
- chainId,
1232
- "DataPortabilityServers"
1233
- );
1234
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
1235
- const totalCount = await this.context.publicClient.readContract({
1236
- address: DataPortabilityServersAddress,
1237
- abi: DataPortabilityServersAbi,
1238
- functionName: "userServerIdsLength",
1239
- args: [user]
1240
- });
1241
- const total = Number(totalCount);
1242
- if (total === 0 || offset >= total) {
1243
- return {
1244
- servers: [],
1245
- total,
1246
- hasMore: false
1247
- };
1248
- }
1249
- const endIndex = Math.min(offset + limit, total);
1250
- const serverIdCalls = [];
1251
- for (let i = offset; i < endIndex; i++) {
1252
- serverIdCalls.push({
1253
- address: DataPortabilityServersAddress,
1254
- abi: DataPortabilityServersAbi,
1255
- functionName: "userServerIdsAt",
1256
- args: [user, BigInt(i)]
1257
- });
1258
- }
1259
- const serverIdResults = await (0, import_multicall.gasAwareMulticall)(this.context.publicClient, {
1260
- contracts: serverIdCalls
1261
- });
1262
- const serverIds = serverIdResults.map((result) => result).filter((id) => id && id > 0n);
1263
- const serverInfoCalls = serverIds.map(
1264
- (serverId) => ({
1265
- address: DataPortabilityServersAddress,
1266
- abi: DataPortabilityServersAbi,
1267
- functionName: "servers",
1268
- args: [serverId]
1269
- })
1270
- );
1271
- const serverInfoResults = await (0, import_multicall.gasAwareMulticall)(this.context.publicClient, {
1272
- contracts: serverInfoCalls,
1273
- allowFailure: true
1274
- });
1275
- const servers = serverInfoResults.map((result, index) => {
1276
- const serverId = serverIds[index];
1277
- if (result.status === "success" && result.result) {
1278
- const serverInfo = result.result;
1279
- return {
1280
- id: `${user.toLowerCase()}-${serverId.toString()}`,
1281
- serverAddress: serverInfo.serverAddress,
1282
- serverUrl: serverInfo.url,
1283
- trustedAt: BigInt(Date.now()),
1284
- user,
1285
- trustIndex: offset + index
1286
- };
1287
- } else {
1288
- return {
1289
- id: `${user.toLowerCase()}-${serverId.toString()}`,
1290
- serverAddress: "0x0000000000000000000000000000000000000000",
1291
- serverUrl: "",
1292
- trustedAt: BigInt(Date.now()),
1293
- user,
1294
- trustIndex: offset + index
1295
- };
1296
- }
1297
- });
1298
- return {
1299
- servers,
1300
- total,
1301
- hasMore: offset + limit < total
1302
- };
1303
- } catch (error) {
1304
- throw new Error(
1305
- `RPC query failed: ${error instanceof Error ? error.message : "Unknown error"}`
1306
- );
1307
- }
1308
- }
1309
- /**
1310
- * Retrieves total file count from Data Registry.
1311
- *
1312
- * @remarks
1313
- * Queries blockchain for complete file count across all users.
1314
- * Useful for pagination and network statistics.
1315
- *
1316
- * @returns Total number of registered files
1317
- *
1318
- * @throws {Error} Chain ID not available.
1319
- * Ensure network connection.
1320
- * @throws {Error} Contract read failed.
1321
- * Check RPC availability.
1322
- *
1323
- * @example
1324
- * ```typescript
1325
- * const total = await vana.data.getTotalFilesCount();
1326
- * console.log(`Total files: ${total}`);
1327
- *
1328
- * // Calculate pagination
1329
- * const pages = Math.ceil(total / 20);
1330
- * ```
1331
- */
1332
- async getTotalFilesCount() {
1333
- try {
1334
- const chainId = this.context.publicClient.chain?.id;
1335
- if (!chainId) {
1336
- throw new Error("Chain ID not available");
1337
- }
1338
- const dataRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
1339
- const dataRegistryAbi = (0, import_abi.getAbi)("DataRegistry");
1340
- const dataRegistry = (0, import_viem.getContract)({
1341
- address: dataRegistryAddress,
1342
- abi: dataRegistryAbi,
1343
- client: this.context.publicClient
1344
- });
1345
- const count = await dataRegistry.read.filesCount();
1346
- return Number(count);
1347
- } catch (error) {
1348
- if (error instanceof Error && error.message === "Chain ID not available") {
1349
- throw error;
1350
- }
1351
- console.error("Failed to fetch total files count:", error);
1352
- return 0;
1353
- }
1354
- }
1355
- /**
1356
- * Retrieves file metadata by ID from the blockchain.
1357
- *
1358
- * @remarks
1359
- * Queries DataRegistry contract directly for file details.
1360
- * Works for any file ID regardless of ownership, enabling
1361
- * cross-user file discovery and verification.
1362
- *
1363
- * @param fileId - Numeric file ID to retrieve
1364
- *
1365
- * @returns UserFile object with metadata
1366
- *
1367
- * @throws {Error} Chain ID not available.
1368
- * Ensure proper network connection.
1369
- * @throws {Error} File not found.
1370
- * Verify file ID exists on-chain.
1371
- * @throws {Error} Contract call failed.
1372
- * Check network and RPC availability.
1373
- *
1374
- * @example
1375
- * ```typescript
1376
- * const file = await vana.data.getFileById(123);
1377
- * console.log(`File ${file.id}:`);
1378
- * console.log(` URL: ${file.url}`);
1379
- * console.log(` Owner: ${file.ownerAddress}`);
1380
- * console.log(` Block: ${file.addedAtBlock}`);
1381
- * ```
1382
- */
1383
- async getFileById(fileId) {
1384
- try {
1385
- const chainId = this.context.publicClient.chain?.id;
1386
- if (!chainId) {
1387
- throw new Error("Chain ID not available");
1388
- }
1389
- const dataRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
1390
- const dataRegistryAbi = (0, import_abi.getAbi)("DataRegistry");
1391
- const dataRegistry = (0, import_viem.getContract)({
1392
- address: dataRegistryAddress,
1393
- abi: dataRegistryAbi,
1394
- client: this.context.publicClient
1395
- });
1396
- const fileDetails = await dataRegistry.read.files([BigInt(fileId)]);
1397
- if (!fileDetails) {
1398
- throw new Error("File not found");
1399
- }
1400
- if (Array.isArray(fileDetails)) {
1401
- const [id, url, ownerAddress, addedAtBlock] = fileDetails;
1402
- if (id === BigInt(0)) {
1403
- throw new Error("File not found");
1404
- }
1405
- return {
1406
- id: Number(id),
1407
- url,
1408
- ownerAddress,
1409
- addedAtBlock: BigInt(addedAtBlock)
1410
- };
1411
- } else {
1412
- if (!fileDetails.id || fileDetails.id === BigInt(0)) {
1413
- throw new Error("File not found");
1414
- }
1415
- return {
1416
- id: Number(fileDetails.id),
1417
- ownerAddress: fileDetails.ownerAddress,
1418
- url: fileDetails.url,
1419
- addedAtBlock: BigInt(fileDetails.addedAtBlock)
1420
- };
1421
- }
1422
- } catch (error) {
1423
- console.error("Failed to fetch file by ID:", error);
1424
- throw new Error(
1425
- `Failed to fetch file ${fileId}: ${error instanceof Error ? error.message : "Unknown error"}`
1426
- );
1427
- }
1428
- }
1429
- /**
1430
- * Registers a file URL directly on the blockchain with a schema ID.
1431
- *
1432
- * @remarks
1433
- * This method registers an existing file URL on the DataRegistry contract
1434
- * with a schema ID, without uploading any data. Useful when you have already
1435
- * uploaded content to storage and just need to register it on-chain.
1436
- *
1437
- * @param url - The URL of the file to register (IPFS or HTTP/HTTPS)
1438
- * @param schemaId - The schema ID to associate with the file
1439
- * @returns Promise resolving to the file ID and transaction hash
1440
- * @throws {Error} When chain ID is not available - "Chain ID not available"
1441
- * @throws {Error} When wallet address is unavailable - "No addresses available"
1442
- * @throws {Error} When transaction fails - "Failed to register file with schema"
1443
- * @example
1444
- * ```typescript
1445
- * const { fileId, transactionHash } = await vana.data.registerFileWithSchema(
1446
- * "ipfs://QmXxx...",
1447
- * 1
1448
- * );
1449
- * console.log(`File ${fileId} registered with schema in tx ${transactionHash}`);
1450
- * ```
1451
- */
1452
- async registerFileWithSchema(url, schemaId, options) {
1453
- this.assertWallet();
1454
- try {
1455
- const chainId = this.context.publicClient.chain?.id;
1456
- if (!chainId) {
1457
- throw new Error("Chain ID not available");
1458
- }
1459
- this.assertWallet();
1460
- const dataRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
1461
- const dataRegistryAbi = (0, import_abi.getAbi)("DataRegistry");
1462
- const account = this.context.walletClient.account ?? this.context.userAddress;
1463
- const from = typeof account === "string" ? account : account.address;
1464
- const hash = await this.context.walletClient.writeContract({
1465
- address: dataRegistryAddress,
1466
- abi: dataRegistryAbi,
1467
- functionName: "addFileWithSchema",
1468
- args: [url, BigInt(schemaId)],
1469
- account,
1470
- chain: this.context.walletClient.chain ?? null,
1471
- ...this.spreadTransactionOptions(options)
1472
- });
1473
- const { tx } = await import("../utils/transactionHelpers");
1474
- return tx({
1475
- hash,
1476
- from,
1477
- contract: "DataRegistry",
1478
- fn: "addFileWithSchema"
1479
- });
1480
- } catch (error) {
1481
- console.error("Failed to register file with schema:", error);
1482
- throw new Error(
1483
- `Registration failed: ${error instanceof Error ? error.message : "Unknown error"}`
1484
- );
1485
- }
1486
- }
1487
- /**
1488
- * Gets the user's address from the wallet client.
1489
- *
1490
- * @returns Promise resolving to the user's wallet address
1491
- * @throws {Error} When no addresses are available in wallet client
1492
- */
1493
- /**
1494
- * Adds a file with permissions to the DataRegistry contract.
1495
- *
1496
- * @param url - The file URL to register
1497
- * @param ownerAddress - The address of the file owner
1498
- * @param permissions - Array of permissions to set for the file
1499
- * @returns Promise resolving to file ID and transaction hash
1500
- * @throws {Error} When chain ID is not available
1501
- * @throws {ContractError} When contract execution fails
1502
- * @throws {Error} When transaction receipt is not available
1503
- * @throws {Error} When FileAdded event cannot be parsed
1504
- *
1505
- * This method handles the core logic of registering a file
1506
- * with specific permissions on the DataRegistry contract. It can be used
1507
- * by both direct transactions and relayer services.
1508
- */
1509
- async addFileWithPermissions(url, ownerAddress, permissions = [], options) {
1510
- this.assertWallet();
1511
- try {
1512
- const chainId = this.context.publicClient.chain?.id;
1513
- if (!chainId) {
1514
- throw new Error("Chain ID not available");
1515
- }
1516
- this.assertWallet();
1517
- const dataRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
1518
- const dataRegistryAbi = (0, import_abi.getAbi)("DataRegistry");
1519
- const account = this.context.walletClient.account ?? ownerAddress;
1520
- const from = typeof account === "string" ? account : account.address;
1521
- const hash = await this.context.walletClient.writeContract({
1522
- address: dataRegistryAddress,
1523
- abi: dataRegistryAbi,
1524
- functionName: "addFileWithPermissions",
1525
- args: [url, ownerAddress, permissions],
1526
- account,
1527
- chain: this.context.walletClient.chain ?? null,
1528
- ...this.spreadTransactionOptions(options)
1529
- });
1530
- const { tx } = await import("../utils/transactionHelpers");
1531
- return tx({
1532
- hash,
1533
- from,
1534
- contract: "DataRegistry",
1535
- fn: "addFileWithPermissions"
1536
- });
1537
- } catch (error) {
1538
- console.error("Failed to add file with permissions:", error);
1539
- throw new Error(
1540
- `Failed to add file with permissions: ${error instanceof Error ? error.message : "Unknown error"}`
1541
- );
1542
- }
1543
- }
1544
- /**
1545
- * Adds a file to the registry with permissions and schema.
1546
- * This combines the functionality of addFileWithPermissions and schema validation.
1547
- *
1548
- * @remarks
1549
- * This method automatically encrypts permissions when a publicKey is provided.
1550
- * It generates the user's encryption key and encrypts it with each recipient's
1551
- * public key before registering on the blockchain.
1552
- *
1553
- * @param url - The URL of the file to register
1554
- * @param ownerAddress - The address of the file owner
1555
- * @param permissions - Array of permissions to grant, each with account and publicKey properties
1556
- * @param schemaId - The schema ID to associate with the file (0 for no schema)
1557
- * @returns Promise resolving to TransactionResult with fileId and transactionHash
1558
- * @throws {Error} "Chain ID not available" - When wallet chain is not configured
1559
- * @throws {Error} "Failed to generate encryption key" - When encryption key generation fails
1560
- * @throws {Error} "Permission for {account} must include 'publicKey'" - When publicKey is missing
1561
- * @throws {Error} "Failed to add file with permissions and schema: {error}" - When transaction fails
1562
- * @example
1563
- * ```typescript
1564
- * // Get server's public key
1565
- * const serverIdentity = await vana.server.getIdentity({
1566
- * userAddress: "0x..."
1567
- * });
1568
- *
1569
- * // Add file with permissions and schema
1570
- * const result = await vana.data.addFileWithPermissionsAndSchema(
1571
- * "ipfs://QmXxx...",
1572
- * ownerAddress,
1573
- * [{
1574
- * account: serverIdentity.address,
1575
- * publicKey: serverIdentity.publicKey
1576
- * }],
1577
- * schemaId
1578
- * );
1579
- *
1580
- * console.log(`File ${result.fileId} registered in tx ${result.hash}`);
1581
- * ```
1582
- */
1583
- async addFileWithPermissionsAndSchema(url, ownerAddress, permissions = [], schemaId = 0, options) {
1584
- this.assertWallet();
1585
- try {
1586
- let encryptedPermissions = [];
1587
- if (permissions.length > 0) {
1588
- this.assertWallet();
1589
- const userEncryptionKey = await (0, import_encryption.generateEncryptionKey)(
1590
- this.context.walletClient,
1591
- this.context.platform,
1592
- import_encryption.DEFAULT_ENCRYPTION_SEED
1593
- );
1594
- encryptedPermissions = await Promise.all(
1595
- permissions.map(async (permission) => {
1596
- if (!permission.publicKey) {
1597
- throw new Error(
1598
- `Permission for ${permission.account} must include 'publicKey'`
1599
- );
1600
- }
1601
- const encryptedKey = await (0, import_encryption.encryptWithWalletPublicKey)(
1602
- userEncryptionKey,
1603
- permission.publicKey,
1604
- this.context.platform
1605
- );
1606
- return {
1607
- account: permission.account,
1608
- key: encryptedKey
1609
- };
1610
- })
1611
- );
1612
- }
1613
- return await this.addFileWithEncryptedPermissionsAndSchema(
1614
- url,
1615
- ownerAddress,
1616
- encryptedPermissions,
1617
- schemaId,
1618
- options
1619
- );
1620
- } catch (error) {
1621
- console.error("Failed to add file with permissions and schema:", error);
1622
- throw new Error(
1623
- `Failed to add file with permissions and schema: ${error instanceof Error ? error.message : "Unknown error"}`
1624
- );
1625
- }
1626
- }
1627
- /**
1628
- * Adds a file with pre-encrypted permissions and schema to the DataRegistry.
1629
- *
1630
- * @remarks
1631
- * This method is designed for relay services and advanced use cases where permissions
1632
- * have already been encrypted client-side. Unlike `addFileWithPermissionsAndSchema()`,
1633
- * this method expects permissions in the encrypted format with a 'key' field instead
1634
- * of 'publicKey'.
1635
- *
1636
- * This is typically used by relay endpoints that receive pre-encrypted data from
1637
- * the client SDK's `upload()` method, avoiding double encryption.
1638
- *
1639
- * @param url - The storage URL of the file (e.g., IPFS URL)
1640
- * @param ownerAddress - The address that will own this file
1641
- * @param permissions - Array of pre-encrypted permissions with 'account' and 'key' fields
1642
- * @param schemaId - Optional schema ID for data validation (defaults to 0)
1643
- * @returns Promise resolving to transaction result with hash and contract details
1644
- * @throws {Error} When chain ID is not available
1645
- * @throws {Error} When wallet is not connected
1646
- * @throws {Error} When transaction fails
1647
- * @example
1648
- * ```typescript
1649
- * // In a relay endpoint that receives pre-encrypted permissions
1650
- * const result = await vana.data.addFileWithEncryptedPermissionsAndSchema(
1651
- * "ipfs://QmXxx...",
1652
- * ownerAddress,
1653
- * [
1654
- * {
1655
- * account: "0xServerAddress...",
1656
- * key: "encrypted_key_string" // Already encrypted by client
1657
- * }
1658
- * ],
1659
- * schemaId
1660
- * );
1661
- *
1662
- * console.log(`File registered in tx ${result.hash}`);
1663
- * ```
1664
- */
1665
- async addFileWithEncryptedPermissionsAndSchema(url, ownerAddress, permissions = [], schemaId = 0, options) {
1666
- try {
1667
- const chainId = this.context.publicClient.chain?.id;
1668
- if (!chainId) {
1669
- throw new Error("Chain ID not available");
1670
- }
1671
- this.assertWallet();
1672
- const dataRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
1673
- const dataRegistryAbi = (0, import_abi.getAbi)("DataRegistry");
1674
- const account = this.context.walletClient.account ?? ownerAddress;
1675
- const from = typeof account === "string" ? account : account.address;
1676
- const hash = await this.context.walletClient.writeContract({
1677
- address: dataRegistryAddress,
1678
- abi: dataRegistryAbi,
1679
- functionName: "addFileWithPermissionsAndSchema",
1680
- args: [url, ownerAddress, permissions, BigInt(schemaId)],
1681
- account,
1682
- chain: this.context.walletClient.chain ?? null,
1683
- ...this.spreadTransactionOptions(options)
1684
- });
1685
- const { tx } = await import("../utils/transactionHelpers");
1686
- return tx({
1687
- hash,
1688
- from,
1689
- contract: "DataRegistry",
1690
- fn: "addFileWithPermissionsAndSchema"
1691
- });
1692
- } catch (error) {
1693
- console.error("Failed to add file with permissions and schema:", error);
1694
- throw new Error(
1695
- `Failed to add file with permissions and schema: ${error instanceof Error ? error.message : "Unknown error"}`
1696
- );
1697
- }
1698
- }
1699
- /**
1700
- * Registers a data refiner for processing templates.
1701
- *
1702
- * @remarks
1703
- * Refiners define data transformation rules for DLPs.
1704
- * Associates schema, instructions, and processing logic.
1705
- *
1706
- * @param params - Refiner configuration
1707
- * @param params.dlpId - Data Liquidity Pool ID
1708
- * @param params.name - Refiner display name
1709
- * @param params.schemaId - Output schema ID.
1710
- * Obtain via `vana.schemas.list()`.
1711
- * @param params.refinementInstructionUrl - Processing instructions URL
1712
- *
1713
- * @returns Refiner ID and transaction hash
1714
- *
1715
- * @throws {Error} Chain ID not available.
1716
- * Ensure network connection.
1717
- * @throws {Error} Transaction failed.
1718
- * Check wallet balance and network status.
1719
- *
1720
- * @example
1721
- * ```typescript
1722
- * const result = await vana.data.addRefiner({
1723
- * dlpId: 1,
1724
- * name: "Sentiment Analyzer",
1725
- * schemaId: 42,
1726
- * refinementInstructionUrl: "ipfs://QmXxx..."
1727
- * });
1728
- * console.log(`Refiner ${result.refinerId} created`);
1729
- * ```
1730
- */
1731
- async addRefiner(params, options) {
1732
- this.assertWallet();
1733
- try {
1734
- const chainId = this.context.publicClient.chain?.id;
1735
- if (!chainId) {
1736
- throw new Error("Chain ID not available");
1737
- }
1738
- const dataRefinerRegistryAddress = (0, import_addresses.getContractAddress)(
1739
- chainId,
1740
- "DataRefinerRegistry"
1741
- );
1742
- const dataRefinerRegistryAbi = (0, import_abi.getAbi)("DataRefinerRegistry");
1743
- this.assertWallet();
1744
- const account = this.context.walletClient.account ?? this.context.userAddress;
1745
- const from = typeof account === "string" ? account : account.address;
1746
- const hash = await this.context.walletClient.writeContract({
1747
- address: dataRefinerRegistryAddress,
1748
- abi: dataRefinerRegistryAbi,
1749
- functionName: "addRefinerWithSchemaId",
1750
- args: [
1751
- BigInt(params.dlpId),
1752
- params.name,
1753
- BigInt(params.schemaId),
1754
- params.refinementInstructionUrl
1755
- ],
1756
- account,
1757
- chain: this.context.walletClient.chain ?? null,
1758
- ...this.spreadTransactionOptions(options)
1759
- });
1760
- const { tx } = await import("../utils/transactionHelpers");
1761
- const txResult = tx({
1762
- hash,
1763
- from,
1764
- contract: "DataRefinerRegistry",
1765
- fn: "addRefinerWithSchemaId"
1766
- });
1767
- if (!this.context.waitForTransactionEvents) {
1768
- throw new Error("waitForTransactionEvents not configured");
1769
- }
1770
- const result = await this.context.waitForTransactionEvents(txResult);
1771
- const event = result.expectedEvents.RefinerAdded;
1772
- if (!event) {
1773
- throw new Error("RefinerAdded event not found in transaction");
1774
- }
1775
- return {
1776
- refinerId: Number(event.refinerId),
1777
- transactionHash: hash
1778
- };
1779
- } catch (error) {
1780
- console.error("Failed to add refiner:", error);
1781
- throw new Error(
1782
- `Failed to add refiner: ${error instanceof Error ? error.message : "Unknown error"}`
1783
- );
1784
- }
1785
- }
1786
- /**
1787
- * Retrieves refiner configuration by ID.
1788
- *
1789
- * @remarks
1790
- * Queries DataRefinerRegistry for refiner details.
1791
- * Returns DLP association, schema, and processing instructions.
1792
- *
1793
- * @param refinerId - Numeric refiner ID
1794
- *
1795
- * @returns Refiner configuration object
1796
- *
1797
- * @throws {Error} Chain ID not available.
1798
- * Ensure network connection.
1799
- * @throws {Error} Refiner not found.
1800
- * Verify refiner ID exists.
1801
- * @throws {Error} Contract read failed.
1802
- * Check network and RPC status.
1803
- *
1804
- * @example
1805
- * ```typescript
1806
- * const refiner = await vana.data.getRefiner(1);
1807
- * console.log(`Refiner: ${refiner.name}`);
1808
- * console.log(`DLP: ${refiner.dlpId}`);
1809
- * console.log(`Schema: ${refiner.schemaId}`);
1810
- * ```
1811
- */
1812
- async getRefiner(refinerId) {
1813
- try {
1814
- const chainId = this.context.publicClient.chain?.id;
1815
- if (!chainId) {
1816
- throw new Error("Chain ID not available");
1817
- }
1818
- const dataRefinerRegistryAddress = (0, import_addresses.getContractAddress)(
1819
- chainId,
1820
- "DataRefinerRegistry"
1821
- );
1822
- const dataRefinerRegistryAbi = (0, import_abi.getAbi)("DataRefinerRegistry");
1823
- const dataRefinerRegistry = (0, import_viem.getContract)({
1824
- address: dataRefinerRegistryAddress,
1825
- abi: dataRefinerRegistryAbi,
1826
- client: this.context.publicClient
1827
- });
1828
- const refinerData = await dataRefinerRegistry.read.refiners([
1829
- BigInt(refinerId)
1830
- ]);
1831
- if (!refinerData) {
1832
- throw new Error("Refiner not found");
1833
- }
1834
- return {
1835
- id: refinerId,
1836
- dlpId: Number(refinerData.dlpId),
1837
- owner: refinerData.owner,
1838
- name: refinerData.name,
1839
- schemaId: Number(refinerData.schemaId),
1840
- refinementInstructionUrl: refinerData.refinementInstructionUrl
1841
- };
1842
- } catch (error) {
1843
- console.error("Failed to get refiner:", error);
1844
- throw new Error(
1845
- `Failed to get refiner ${refinerId}: ${error instanceof Error ? error.message : "Unknown error"}`
1846
- );
1847
- }
1848
- }
1849
- /**
1850
- * Validates schema ID existence.
1851
- *
1852
- * @remarks
1853
- * Verifies schema registration in DataRegistry.
1854
- * Check before using schemas for uploads.
1855
- *
1856
- * @param schemaId - Numeric schema ID to validate
1857
- *
1858
- * @returns True if schema exists, false otherwise
1859
- *
1860
- * @throws {Error} Chain ID not available.
1861
- * Ensure network connection.
1862
- * @throws {Error} Contract read failed.
1863
- * Check RPC availability.
1864
- *
1865
- * @example
1866
- * ```typescript
1867
- * const valid = await vana.data.isValidSchemaId(42);
1868
- * if (valid) {
1869
- * // Safe to use schema 42
1870
- * await vana.data.upload({ schemaId: 42, ... });
1871
- * }
1872
- * ```
1873
- */
1874
- async isValidSchemaId(schemaId) {
1875
- try {
1876
- const chainId = this.context.publicClient.chain?.id;
1877
- if (!chainId) {
1878
- throw new Error("Chain ID not available");
1879
- }
1880
- const dataRefinerRegistryAddress = (0, import_addresses.getContractAddress)(
1881
- chainId,
1882
- "DataRefinerRegistry"
1883
- );
1884
- const dataRefinerRegistryAbi = (0, import_abi.getAbi)("DataRefinerRegistry");
1885
- const dataRefinerRegistry = (0, import_viem.getContract)({
1886
- address: dataRefinerRegistryAddress,
1887
- abi: dataRefinerRegistryAbi,
1888
- client: this.context.publicClient
1889
- });
1890
- const isValid = await dataRefinerRegistry.read.isValidSchemaId([
1891
- BigInt(schemaId)
1892
- ]);
1893
- return isValid;
1894
- } catch (error) {
1895
- console.error("Failed to validate schema ID:", error);
1896
- return false;
1897
- }
1898
- }
1899
- /**
1900
- * Gets the total number of refiners in the registry.
1901
- *
1902
- * @remarks
1903
- * Queries the DataRefinerRegistry contract to get the total count of all
1904
- * registered refiners across all DLPs.
1905
- *
1906
- * @returns Promise resolving to the total refiner count
1907
- * @example
1908
- * ```typescript
1909
- * const count = await vana.data.getRefinersCount();
1910
- * console.log(`Total refiners registered: ${count}`);
1911
- * ```
1912
- */
1913
- async getRefinersCount() {
1914
- try {
1915
- const chainId = this.context.publicClient.chain?.id;
1916
- if (!chainId) {
1917
- throw new Error("Chain ID not available");
1918
- }
1919
- const dataRefinerRegistryAddress = (0, import_addresses.getContractAddress)(
1920
- chainId,
1921
- "DataRefinerRegistry"
1922
- );
1923
- const dataRefinerRegistryAbi = (0, import_abi.getAbi)("DataRefinerRegistry");
1924
- const dataRefinerRegistry = (0, import_viem.getContract)({
1925
- address: dataRefinerRegistryAddress,
1926
- abi: dataRefinerRegistryAbi,
1927
- client: this.context.publicClient
1928
- });
1929
- const count = await dataRefinerRegistry.read.refinersCount();
1930
- return Number(count);
1931
- } catch (error) {
1932
- console.error("Failed to get refiners count:", error);
1933
- return 0;
1934
- }
1935
- }
1936
- /**
1937
- * Updates the schema ID for an existing refiner.
1938
- *
1939
- * @remarks
1940
- * Allows the owner of a refiner to update its associated schema ID.
1941
- * This is useful when refiner output format needs to change.
1942
- *
1943
- * @param params - Update parameters
1944
- * @param params.refinerId - The refiner ID to update
1945
- * @param params.newSchemaId - The new schema ID to set
1946
- * @returns Promise resolving to the transaction hash
1947
- * @throws {Error} When chain ID is not available - "Chain ID not available"
1948
- * @throws {Error} When transaction fails - "Failed to update schema ID: {error}"
1949
- * @example
1950
- * ```typescript
1951
- * const result = await vana.data.updateSchemaId({
1952
- * refinerId: 1,
1953
- * newSchemaId: 55
1954
- * });
1955
- * console.log(`Schema updated in tx ${result.transactionHash}`);
1956
- * ```
1957
- */
1958
- async updateSchemaId(params, options) {
1959
- this.assertWallet();
1960
- try {
1961
- const chainId = this.context.publicClient.chain?.id;
1962
- if (!chainId) {
1963
- throw new Error("Chain ID not available");
1964
- }
1965
- const dataRefinerRegistryAddress = (0, import_addresses.getContractAddress)(
1966
- chainId,
1967
- "DataRefinerRegistry"
1968
- );
1969
- const dataRefinerRegistryAbi = (0, import_abi.getAbi)("DataRefinerRegistry");
1970
- this.assertWallet();
1971
- const account = this.context.walletClient.account ?? this.context.userAddress;
1972
- const hash = await this.context.walletClient.writeContract({
1973
- address: dataRefinerRegistryAddress,
1974
- abi: dataRefinerRegistryAbi,
1975
- functionName: "updateSchemaId",
1976
- args: [BigInt(params.refinerId), BigInt(params.newSchemaId)],
1977
- account,
1978
- chain: this.context.walletClient.chain ?? null,
1979
- ...this.spreadTransactionOptions(options)
1980
- });
1981
- await this.context.publicClient.waitForTransactionReceipt({ hash });
1982
- return {
1983
- transactionHash: hash
1984
- };
1985
- } catch (error) {
1986
- console.error("Failed to update schema ID:", error);
1987
- throw new Error(
1988
- `Failed to update schema ID: ${error instanceof Error ? error.message : "Unknown error"}`
1989
- );
1990
- }
1991
- }
1992
- /**
1993
- * Uploads an encrypted file and grants permission to a party with a public key.
1994
- *
1995
- * This method handles the complete workflow:
1996
- * 1. Encrypts the file with the user's encryption key
1997
- * 2. Uploads the encrypted file to storage
1998
- * 3. Encrypts the user's encryption key with the provided public key
1999
- * 4. Registers the file with permissions
2000
- *
2001
- * @param params - Upload parameters including data, permissions, and options
2002
- * @returns Promise resolving to upload result with file ID and storage URL
2003
- */
2004
- async uploadFileWithPermissions(params) {
2005
- this.assertWallet();
2006
- const { data, permissions, filename, providerName } = params;
2007
- try {
2008
- const uploadResult = await this.uploadToStorage(
2009
- data,
2010
- filename,
2011
- true,
2012
- // Always encrypt for uploadFileWithPermissions
2013
- providerName
2014
- );
2015
- const userAddress = this.context.userAddress;
2016
- const userEncryptionKey = await (0, import_encryption.generateEncryptionKey)(
2017
- this.context.walletClient,
2018
- this.context.platform,
2019
- import_encryption.DEFAULT_ENCRYPTION_SEED
2020
- );
2021
- const encryptedPermissions = await Promise.all(
2022
- permissions.map(async (permission) => {
2023
- const encryptedKey = await (0, import_encryption.encryptWithWalletPublicKey)(
2024
- userEncryptionKey,
2025
- permission.publicKey,
2026
- this.context.platform
2027
- );
2028
- return {
2029
- account: permission.account,
2030
- key: encryptedKey
2031
- };
2032
- })
2033
- );
2034
- if (this.context.relayer) {
2035
- const request = {
2036
- type: "direct",
2037
- operation: "submitFileAdditionWithPermissions",
2038
- params: {
2039
- url: uploadResult.url,
2040
- userAddress,
2041
- permissions: encryptedPermissions
2042
- }
2043
- };
2044
- const response = await this.context.relayer(request);
2045
- if (response.type === "error") {
2046
- throw new Error(response.error);
2047
- }
2048
- let result;
2049
- if (response.type === "pending") {
2050
- result = await this.pollRelayerForConfirmation(
2051
- response.operationId,
2052
- void 0
2053
- // TODO: Add TransactionOptions to upload method signature
2054
- );
2055
- } else if (response.type === "direct" && typeof response.result === "object" && response.result !== null && "fileId" in response.result) {
2056
- result = response.result;
2057
- } else {
2058
- throw new Error("Invalid response from relayer");
2059
- }
2060
- return {
2061
- fileId: result.fileId,
2062
- url: uploadResult.url,
2063
- size: uploadResult.size,
2064
- transactionHash: result.transactionHash
2065
- };
2066
- } else {
2067
- const txResult = await this.addFileWithPermissions(
2068
- uploadResult.url,
2069
- userAddress,
2070
- encryptedPermissions
2071
- );
2072
- if (!this.context.waitForTransactionEvents) {
2073
- throw new Error(
2074
- "Cannot upload without relay: waitForTransactionEvents not configured"
2075
- );
2076
- }
2077
- const eventResult = await this.context.waitForTransactionEvents(txResult);
2078
- const fileAddedEvent = eventResult.expectedEvents.FileAdded;
2079
- if (!fileAddedEvent) {
2080
- throw new Error("FileAdded event not found in transaction");
2081
- }
2082
- return {
2083
- fileId: Number(fileAddedEvent.fileId),
2084
- url: uploadResult.url,
2085
- size: uploadResult.size,
2086
- transactionHash: txResult.hash
2087
- };
2088
- }
2089
- } catch (error) {
2090
- console.error("Failed to upload file with permissions:", error);
2091
- throw new Error(
2092
- `Failed to upload file with permissions: ${error instanceof Error ? error.message : "Unknown error"}`
2093
- );
2094
- }
2095
- }
2096
- /**
2097
- * Uploads content to storage without registering it on the blockchain.
2098
- * This method only handles the storage upload and returns the file URL.
2099
- *
2100
- * @param content - The content to upload (string, Blob, Buffer, or object - objects will be JSON stringified)
2101
- * @param filename - Optional filename for the uploaded file (defaults to timestamp-based name)
2102
- * @param encrypt - Optional flag to encrypt the content before upload
2103
- * @param providerName - Optional specific storage provider to use
2104
- * @returns Promise resolving to the storage upload result with url, size, and contentType
2105
- */
2106
- async uploadToStorage(content, filename, encrypt = false, providerName) {
2107
- try {
2108
- let blob;
2109
- if (content instanceof Blob) {
2110
- blob = content;
2111
- } else if (typeof content === "string") {
2112
- blob = new Blob([content], { type: "text/plain" });
2113
- } else if (content instanceof Buffer) {
2114
- const arrayBuffer = content.buffer.slice(
2115
- content.byteOffset,
2116
- content.byteOffset + content.byteLength
2117
- );
2118
- blob = new Blob([arrayBuffer], { type: "application/octet-stream" });
2119
- } else {
2120
- blob = new Blob([JSON.stringify(content)], {
2121
- type: "application/json"
2122
- });
2123
- }
2124
- let finalBlob = blob;
2125
- if (encrypt) {
2126
- this.assertWallet();
2127
- const encryptionKey = await (0, import_encryption.generateEncryptionKey)(
2128
- this.context.walletClient,
2129
- this.context.platform,
2130
- import_encryption.DEFAULT_ENCRYPTION_SEED
2131
- );
2132
- finalBlob = await (0, import_encryption.encryptBlobWithSignedKey)(
2133
- blob,
2134
- encryptionKey,
2135
- this.context.platform
2136
- );
2137
- }
2138
- if (!this.context.storageManager) {
2139
- if (this.context.validateStorageRequired) {
2140
- this.context.validateStorageRequired();
2141
- throw new Error("Storage validation failed");
2142
- } else {
2143
- throw new Error(
2144
- "Storage manager not configured. Please provide storage providers in VanaConfig."
2145
- );
2146
- }
2147
- }
2148
- const finalFilename = (() => {
2149
- if (filename) {
2150
- if (encrypt && !filename.endsWith(".enc")) {
2151
- return `${filename}.enc`;
2152
- }
2153
- return filename;
2154
- }
2155
- return encrypt ? `upload-${Date.now()}.enc` : `upload-${Date.now()}.dat`;
2156
- })();
2157
- const uploadResult = await this.context.storageManager.upload(
2158
- finalBlob,
2159
- finalFilename,
2160
- providerName
2161
- );
2162
- return uploadResult;
2163
- } catch (error) {
2164
- throw new Error(
2165
- `Upload failed: ${error instanceof Error ? error.message : "Unknown error"}`
2166
- );
2167
- }
2168
- }
2169
- /**
2170
- * Adds a permission for a party to access an existing file.
2171
- *
2172
- * This method handles the complete workflow:
2173
- * 1. Gets the user's encryption key
2174
- * 2. Encrypts the user's encryption key with the provided public key
2175
- * 3. Adds the permission to the file
2176
- * 4. Returns the permission data from the blockchain event
2177
- *
2178
- * For advanced users who need more control over transaction timing,
2179
- * use `submitFilePermission()` instead.
2180
- *
2181
- * @param params - Parameters for adding file permission
2182
- * @param params.fileId - The ID of the file to grant permission for
2183
- * @param params.account - The recipient's wallet address that will access the file
2184
- * @param params.publicKey - The recipient's public key for encryption.
2185
- * Obtain via `vana.server.getIdentity(account).publicKey`
2186
- * @returns Promise resolving to permission data from PermissionGranted event
2187
- * @throws {Error} "No addresses available in wallet client" - When wallet is not connected
2188
- * @throws {Error} "Chain ID not available" - When wallet chain is not configured
2189
- * @throws {Error} "Failed to add permission to file: {error}" - When transaction fails or user doesn't own file
2190
- * @example
2191
- * ```typescript
2192
- * const result = await vana.data.addPermissionToFile({
2193
- * fileId: 123,
2194
- * account: "0xRecipientAddress...",
2195
- * publicKey: "0xRecipientPublicKey..."
2196
- * });
2197
- * console.log(`Permission granted to ${result.account} for file ${result.fileId}`);
2198
- * console.log(`Transaction: ${result.transactionHash}`);
2199
- * ```
2200
- */
2201
- async addPermissionToFile(params, options) {
2202
- this.assertWallet();
2203
- const { fileId, account, publicKey } = params;
2204
- return await this.submitFilePermission(fileId, account, publicKey, options);
2205
- }
2206
- /**
2207
- * Submits a file permission transaction to the blockchain.
2208
- *
2209
- * @remarks
2210
- * This method supports gasless transactions via relayer callbacks when configured.
2211
- * It encrypts the user's encryption key with the recipient's public key before submission.
2212
- * Use this when you want to handle transaction confirmation and event parsing separately.
2213
- *
2214
- * @param fileId - The ID of the file to grant permission for
2215
- * @param account - The recipient's wallet address that will access the file
2216
- * @param publicKey - The recipient's public key for encryption.
2217
- * Obtain via `vana.server.getIdentity(account).publicKey`
2218
- * @returns Promise resolving to TransactionResult for tracking the transaction
2219
- * @throws {Error} When chain ID is not available
2220
- * @throws {Error} When encryption key generation fails
2221
- * @throws {Error} When public key encryption fails
2222
- *
2223
- * @example
2224
- * ```typescript
2225
- * const tx = await vana.data.submitFilePermission(
2226
- * fileId,
2227
- * "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
2228
- * recipientPublicKey
2229
- * );
2230
- * const result = await tx.waitForEvents();
2231
- * console.log(`Permission granted with ID: ${result.permissionId}`);
2232
- * ```
2233
- */
2234
- async submitFilePermission(fileId, account, publicKey, options) {
2235
- this.assertWallet();
2236
- try {
2237
- const userEncryptionKey = await (0, import_encryption.generateEncryptionKey)(
2238
- this.context.walletClient,
2239
- this.context.platform,
2240
- import_encryption.DEFAULT_ENCRYPTION_SEED
2241
- );
2242
- const encryptedKey = await (0, import_encryption.encryptWithWalletPublicKey)(
2243
- userEncryptionKey,
2244
- publicKey,
2245
- this.context.platform
2246
- );
2247
- const chainId = this.context.publicClient.chain?.id;
2248
- if (!chainId) {
2249
- throw new Error("Chain ID not available");
2250
- }
2251
- const dataRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
2252
- const dataRegistryAbi = (0, import_abi.getAbi)("DataRegistry");
2253
- this.assertWallet();
2254
- const walletAccount = this.context.walletClient.account ?? this.context.userAddress;
2255
- const txHash = await this.context.walletClient.writeContract({
2256
- address: dataRegistryAddress,
2257
- abi: dataRegistryAbi,
2258
- functionName: "addFilePermission",
2259
- args: [BigInt(fileId), account, encryptedKey],
2260
- account: walletAccount,
2261
- chain: this.context.walletClient.chain ?? null,
2262
- ...this.spreadTransactionOptions(options)
2263
- });
2264
- const { tx } = await import("../utils/transactionHelpers");
2265
- return tx({
2266
- hash: txHash,
2267
- from: typeof walletAccount === "string" ? walletAccount : walletAccount.address,
2268
- contract: "DataRegistry",
2269
- fn: "addFilePermission"
2270
- });
2271
- } catch (error) {
2272
- console.error("Failed to add permission to file:", error);
2273
- throw new Error(
2274
- `Failed to add permission to file: ${error instanceof Error ? error.message : "Unknown error"}`
2275
- );
2276
- }
2277
- }
2278
- /**
2279
- * Gets the encrypted key for a specific account's permission to access a file.
2280
- *
2281
- * @param fileId - The ID of the file
2282
- * @param account - The account address to get the permission for
2283
- * @returns Promise resolving to the encrypted key for that account
2284
- */
2285
- async getFilePermission(fileId, account) {
2286
- try {
2287
- const chainId = this.context.publicClient.chain?.id;
2288
- if (!chainId) {
2289
- throw new Error("Chain ID not available");
2290
- }
2291
- const dataRegistryAddress = (0, import_addresses.getContractAddress)(chainId, "DataRegistry");
2292
- const dataRegistryAbi = (0, import_abi.getAbi)("DataRegistry");
2293
- const dataRegistry = (0, import_viem.getContract)({
2294
- address: dataRegistryAddress,
2295
- abi: dataRegistryAbi,
2296
- client: this.context.publicClient
2297
- });
2298
- const encryptedKey = await dataRegistry.read.filePermissions([
2299
- BigInt(fileId),
2300
- account
2301
- ]);
2302
- return encryptedKey;
2303
- } catch (error) {
2304
- console.error("Failed to get file permission:", error);
2305
- throw new Error(
2306
- `Failed to get file permission: ${error instanceof Error ? error.message : "Unknown error"}`
2307
- );
2308
- }
2309
- }
2310
- /**
2311
- * Decrypts a file that the user has permission to access using their private key.
2312
- *
2313
- * This method handles the complete workflow for servers or other permitted parties:
2314
- * 1. Gets the encrypted encryption key from file permissions
2315
- * 2. Decrypts the encryption key using the provided private key
2316
- * 3. Downloads and decrypts the file data
2317
- *
2318
- * @param file - The file to decrypt
2319
- * @param privateKey - The private key to decrypt the user's encryption key
2320
- * @param options - Optional decryption configuration
2321
- * @param options.account - The account address that has permission (defaults to current wallet account)
2322
- * @returns Promise resolving to the decrypted file data
2323
- */
2324
- async decryptFileWithPermission(file, privateKey, options) {
2325
- try {
2326
- const permissionAccount = options?.account ?? this.context.userAddress;
2327
- const encryptedKey = await this.getFilePermission(
2328
- file.id,
2329
- permissionAccount
2330
- );
2331
- if (!encryptedKey) {
2332
- throw new Error(
2333
- `No permission found for account ${permissionAccount} to access file ${file.id}`
2334
- );
2335
- }
2336
- const userEncryptionKey = await (0, import_encryption.decryptWithWalletPrivateKey)(
2337
- encryptedKey,
2338
- privateKey,
2339
- this.context.platform
2340
- );
2341
- let encryptedData;
2342
- if (file.url.startsWith("ipfs://")) {
2343
- encryptedData = await this.fetchFromIPFS(file.url);
2344
- } else {
2345
- encryptedData = await this.fetch(file.url);
2346
- }
2347
- const decryptedData = await (0, import_encryption.decryptBlobWithSignedKey)(
2348
- encryptedData,
2349
- userEncryptionKey,
2350
- this.context.platform
2351
- );
2352
- return decryptedData;
2353
- } catch (error) {
2354
- console.error("Failed to decrypt file with permission:", error);
2355
- throw new Error(
2356
- `Failed to decrypt file with permission: ${error instanceof Error ? error.message : "Unknown error"}`
2357
- );
2358
- }
2359
- }
2360
- /**
2361
- * Simple network-agnostic fetch utility for retrieving file content.
2362
- *
2363
- * @remarks
2364
- * This is a thin wrapper around the global fetch API that returns the response as a Blob.
2365
- * It provides a consistent interface for fetching encrypted content before decryption.
2366
- * For IPFS URLs, consider using fetchFromIPFS for better reliability.
2367
- *
2368
- * @param url - The URL to fetch content from
2369
- * @returns Promise resolving to the fetched content as a Blob
2370
- * @throws {Error} "HTTP error! status: {status} {statusText}" - When server returns error status
2371
- * @throws {Error} "Empty response" - When server returns no content
2372
- * @throws {Error} "Network error: Failed to fetch from {url}" - When network request fails
2373
- *
2374
- * @example
2375
- * ```typescript
2376
- * // Fetch and decrypt a file
2377
- * const encryptionKey = await generateEncryptionKey(walletClient);
2378
- * const encryptedBlob = await vana.data.fetch(file.url);
2379
- * const decryptedBlob = await decryptBlob(encryptedBlob, encryptionKey, platform);
2380
- *
2381
- * // With custom headers for authentication
2382
- * const response = await fetch(file.url, {
2383
- * headers: { 'Authorization': 'Bearer token' }
2384
- * });
2385
- * const encryptedBlob = await response.blob();
2386
- * ```
2387
- */
2388
- async fetch(url) {
2389
- try {
2390
- const { universalFetch } = await import("../utils/download");
2391
- const response = await universalFetch(url, this.context.downloadRelayer);
2392
- if (!response.ok) {
2393
- throw new Error(
2394
- `HTTP error! status: ${response.status} ${response.statusText}`
2395
- );
2396
- }
2397
- const blob = await response.blob();
2398
- if (blob.size === 0) {
2399
- throw new Error("Empty response");
2400
- }
2401
- return blob;
2402
- } catch (error) {
2403
- if (error instanceof TypeError && error.message.includes("fetch")) {
2404
- throw new Error(
2405
- `Network error: Failed to fetch from ${url}. The URL may be invalid or the server may not be accessible.`
2406
- );
2407
- }
2408
- throw error;
2409
- }
2410
- }
2411
- /**
2412
- * Specialized IPFS fetcher with gateway fallback mechanism.
2413
- *
2414
- * @remarks
2415
- * This method provides robust IPFS content fetching by trying multiple gateways
2416
- * in sequence until one succeeds. It supports both ipfs:// URLs and raw CIDs.
2417
- *
2418
- * The default gateway list includes public gateways, but you should provide
2419
- * your own gateways for production use to ensure reliability and privacy.
2420
- *
2421
- * @param url - The IPFS URL (ipfs://...) or CID to fetch
2422
- * @param options - Optional configuration
2423
- * @param options.gateways - Array of IPFS gateway URLs to try (must end with /)
2424
- * @returns Promise resolving to the fetched content as a Blob
2425
- * @throws {Error} "Invalid IPFS URL format" - When URL is not ipfs:// or valid CID
2426
- * @throws {Error} "Empty response" - When gateway returns no content
2427
- * @throws {Error} "HTTP error! status: {status}" - When gateway returns error status
2428
- * @throws {Error} "Failed to fetch IPFS content {cid} from all gateways" - When all gateways fail
2429
- *
2430
- * @example
2431
- * ```typescript
2432
- * // Fetch from IPFS with custom gateways
2433
- * const encryptedBlob = await vana.data.fetchFromIPFS(file.url, {
2434
- * gateways: [
2435
- * 'https://my-private-gateway.com/ipfs/',
2436
- * 'https://dweb.link/ipfs/',
2437
- * 'https://ipfs.io/ipfs/'
2438
- * ]
2439
- * });
2440
- *
2441
- * // Decrypt the fetched content
2442
- * const encryptionKey = await generateEncryptionKey(walletClient);
2443
- * const decryptedBlob = await decryptBlob(encryptedBlob, encryptionKey, platform);
2444
- *
2445
- * // With raw CID
2446
- * const blob = await vana.data.fetchFromIPFS('QmXxx...', {
2447
- * gateways: ['https://ipfs.io/ipfs/']
2448
- * });
2449
- * ```
2450
- */
2451
- async fetchFromIPFS(url, options) {
2452
- const defaultGateways = [
2453
- "https://dweb.link/ipfs/",
2454
- "https://ipfs.io/ipfs/"
2455
- ];
2456
- const gateways = options?.gateways ?? this.context.ipfsGateways ?? defaultGateways;
2457
- const { extractIpfsHash } = await import("../utils/ipfs");
2458
- const cid = extractIpfsHash(url);
2459
- if (!cid) {
2460
- throw new Error(
2461
- `Invalid IPFS URL format. Expected ipfs://... or a raw CID, got: ${url}`
2462
- );
2463
- }
2464
- const errors = [];
2465
- for (let i = 0; i < gateways.length; i++) {
2466
- const gateway = gateways[i];
2467
- const isLastGateway = i === gateways.length - 1;
2468
- const gatewayUrl = gateway.endsWith("/") ? `${gateway}${cid}` : `${gateway}/${cid}`;
2469
- try {
2470
- console.debug(`Trying IPFS gateway: ${gatewayUrl}`);
2471
- const response = await fetch(gatewayUrl);
2472
- if (response.ok) {
2473
- const blob = await response.blob();
2474
- if (blob.size > 0) {
2475
- console.debug(`Successfully fetched from gateway: ${gateway}`);
2476
- return blob;
2477
- } else {
2478
- if (isLastGateway) {
2479
- throw new Error("Empty response");
2480
- }
2481
- errors.push({
2482
- gateway,
2483
- error: "Empty response"
2484
- });
2485
- }
2486
- } else {
2487
- if (isLastGateway) {
2488
- if (response.status === 403) {
2489
- throw new Error(`HTTP error! status: 403 ${response.statusText}`);
2490
- } else if (response.status === 404) {
2491
- throw new Error(`HTTP error! status: 404 ${response.statusText}`);
2492
- } else {
2493
- throw new Error(
2494
- `HTTP error! status: ${response.status} ${response.statusText}`
2495
- );
2496
- }
2497
- }
2498
- errors.push({
2499
- gateway,
2500
- error: `HTTP ${response.status} ${response.statusText}`
2501
- });
2502
- }
2503
- } catch (error) {
2504
- if (isLastGateway && error instanceof Error && (error.message.includes("Empty response") || error.message.includes("HTTP error!"))) {
2505
- throw error;
2506
- }
2507
- errors.push({
2508
- gateway,
2509
- error: error instanceof Error ? error.message : "Unknown error"
2510
- });
2511
- }
2512
- }
2513
- if (this.context.downloadRelayer && gateways.length > 0) {
2514
- try {
2515
- const relayerUrl = gateways[0].endsWith("/") ? `${gateways[0]}${cid}` : `${gateways[0]}/${cid}`;
2516
- return await this.context.downloadRelayer.proxyDownload(relayerUrl);
2517
- } catch (relayerError) {
2518
- errors.push({
2519
- gateway: "download-relayer",
2520
- error: `Proxy failed: ${relayerError instanceof Error ? relayerError.message : "Unknown error"}`
2521
- });
2522
- }
2523
- }
2524
- const errorDetails = errors.map((e) => `${e.gateway}: ${e.error}`).join("\n ");
2525
- throw new Error(
2526
- `Failed to fetch IPFS content ${cid} from all gateways:
2527
- ${errorDetails}`
2528
- );
2529
- }
2530
- /**
2531
- * Validates a data schema definition against the Vana meta-schema.
2532
- *
2533
- * @param schema - The data schema definition to validate
2534
- * @returns The validated DataSchema
2535
- * @throws SchemaValidationError if invalid
2536
- * @example
2537
- * ```typescript
2538
- * const schema = {
2539
- * name: "User Profile",
2540
- * version: "1.0.0",
2541
- * dialect: "json",
2542
- * schema: {
2543
- * type: "object",
2544
- * properties: {
2545
- * name: { type: "string" },
2546
- * age: { type: "number" }
2547
- * }
2548
- * }
2549
- * };
2550
- *
2551
- * const validatedSchema = vana.data.validateDataSchemaAgainstMetaSchema(schema);
2552
- * ```
2553
- */
2554
- validateDataSchemaAgainstMetaSchema(schema) {
2555
- return (0, import_schemaValidation.validateDataSchemaAgainstMetaSchema)(schema);
2556
- }
2557
- /**
2558
- * Validates data against a JSON Schema from a data schema.
2559
- *
2560
- * @param data - The data to validate
2561
- * @param schema - The data schema containing the schema
2562
- * @returns Void (throws if validation fails)
2563
- * @throws SchemaValidationError if invalid
2564
- * @example
2565
- * ```typescript
2566
- * const schema = {
2567
- * name: "User Profile",
2568
- * version: "1.0.0",
2569
- * dialect: "json",
2570
- * schema: {
2571
- * type: "object",
2572
- * properties: {
2573
- * name: { type: "string" },
2574
- * age: { type: "number" }
2575
- * },
2576
- * required: ["name"]
2577
- * }
2578
- * };
2579
- *
2580
- * const userData = { name: "Alice", age: 30 };
2581
- * vana.data.validateDataAgainstSchema(userData, schema);
2582
- * ```
2583
- */
2584
- validateDataAgainstSchema(data, schema) {
2585
- (0, import_schemaValidation.validateDataAgainstSchema)(data, schema);
2586
- }
2587
- /**
2588
- * Fetches and validates a data schema from a URL, then returns the parsed data schema.
2589
- *
2590
- * @param url - The URL to fetch the data schema from
2591
- * @returns The validated data schema
2592
- * @throws SchemaValidationError if invalid or fetch fails
2593
- * @example
2594
- * ```typescript
2595
- * // Fetch and validate a schema from IPFS or HTTP
2596
- * const schema = await vana.data.fetchAndValidateSchema("https://example.com/schema.json");
2597
- * console.log(schema.name, schema.dialect);
2598
- *
2599
- * // Use the schema to validate user data
2600
- * if (schema.dialect === "json") {
2601
- * vana.data.validateDataAgainstSchema(userData, schema);
2602
- * }
2603
- * ```
2604
- */
2605
- async fetchAndValidateSchema(url) {
2606
- return (0, import_schemaValidation.fetchAndValidateSchema)(url);
2607
- }
2608
- /**
2609
- * Polls for confirmation of a relayer operation.
2610
- * @internal
2611
- */
2612
- async pollRelayerForConfirmation(operationId, options) {
2613
- if (!this.context.relayer) {
2614
- throw new Error("Relayer not configured for polling");
2615
- }
2616
- const pollingManager = new import_pollingManager.PollingManager(this.context.relayer);
2617
- const result = await pollingManager.startPolling(operationId, {
2618
- signal: options?.signal,
2619
- onStatusUpdate: options?.onStatusUpdate,
2620
- ...options?.pollingOptions
2621
- });
2622
- return {
2623
- fileId: 0,
2624
- // This would need to be extracted from transaction events
2625
- transactionHash: result.hash
2626
- };
2627
- }
2628
- }
2629
- // Annotate the CommonJS export names for ESM import in node:
2630
- 0 && (module.exports = {
2631
- DataController
2632
- });
2633
- //# sourceMappingURL=data.cjs.map