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

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