@opendatalabs/vana-sdk 0.1.0-alpha.db07fe1 → 0.1.0-alpha.dc68f39

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