@opendatalabs/vana-sdk 0.1.0-alpha.f9cc6ed → 0.1.0-alpha.fd33fc9

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