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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (351) hide show
  1. package/dist/browser.cjs.map +1 -1
  2. package/dist/browser.d.ts +33 -1
  3. package/dist/browser.js.map +1 -1
  4. package/dist/chains/index.cjs.map +1 -1
  5. package/dist/chains/index.d.ts +30 -1
  6. package/dist/chains/index.js.map +1 -1
  7. package/dist/client/__tests__/enhancedResponse.test.d.ts +1 -0
  8. package/dist/client/enhancedResponse.cjs +164 -0
  9. package/dist/client/enhancedResponse.cjs.map +1 -0
  10. package/dist/client/enhancedResponse.d.ts +120 -0
  11. package/dist/client/enhancedResponse.js +138 -0
  12. package/dist/client/enhancedResponse.js.map +1 -0
  13. package/dist/config/chains.cjs.map +1 -1
  14. package/dist/config/chains.d.ts +99 -0
  15. package/dist/config/chains.js.map +1 -1
  16. package/dist/contracts/contractController.cjs.map +1 -1
  17. package/dist/contracts/contractController.d.ts +66 -10
  18. package/dist/contracts/contractController.js.map +1 -1
  19. package/dist/controllers/__tests__/data-consistency-integration.test.d.ts +7 -0
  20. package/dist/controllers/__tests__/operations.processQueue.test.d.ts +1 -0
  21. package/dist/controllers/base.cjs +33 -0
  22. package/dist/controllers/base.cjs.map +1 -1
  23. package/dist/controllers/base.d.ts +10 -0
  24. package/dist/controllers/base.js +33 -0
  25. package/dist/controllers/base.js.map +1 -1
  26. package/dist/controllers/data.cjs +417 -276
  27. package/dist/controllers/data.cjs.map +1 -1
  28. package/dist/controllers/data.d.ts +246 -193
  29. package/dist/controllers/data.js +430 -279
  30. package/dist/controllers/data.js.map +1 -1
  31. package/dist/controllers/operations.cjs +430 -0
  32. package/dist/controllers/operations.cjs.map +1 -0
  33. package/dist/controllers/operations.d.ts +229 -0
  34. package/dist/controllers/operations.js +406 -0
  35. package/dist/controllers/operations.js.map +1 -0
  36. package/dist/controllers/permissions.cjs +690 -209
  37. package/dist/controllers/permissions.cjs.map +1 -1
  38. package/dist/controllers/permissions.d.ts +196 -68
  39. package/dist/controllers/permissions.js +690 -209
  40. package/dist/controllers/permissions.js.map +1 -1
  41. package/dist/controllers/protocol.cjs.map +1 -1
  42. package/dist/controllers/protocol.d.ts +27 -28
  43. package/dist/controllers/protocol.js.map +1 -1
  44. package/dist/controllers/schemas.cjs +104 -25
  45. package/dist/controllers/schemas.cjs.map +1 -1
  46. package/dist/controllers/schemas.d.ts +88 -40
  47. package/dist/controllers/schemas.js +104 -25
  48. package/dist/controllers/schemas.js.map +1 -1
  49. package/dist/controllers/server.cjs +269 -58
  50. package/dist/controllers/server.cjs.map +1 -1
  51. package/dist/controllers/server.d.ts +157 -52
  52. package/dist/controllers/server.js +269 -58
  53. package/dist/controllers/server.js.map +1 -1
  54. package/dist/core/__tests__/health.test.d.ts +1 -0
  55. package/dist/core/__tests__/inMemoryNonceManager.test.d.ts +1 -0
  56. package/dist/core/__tests__/nonceManager.test.d.ts +1 -0
  57. package/dist/core/__tests__/pollingManager.test.d.ts +4 -0
  58. package/dist/core/apiClient.cjs +53 -3
  59. package/dist/core/apiClient.cjs.map +1 -1
  60. package/dist/core/apiClient.d.ts +132 -7
  61. package/dist/core/apiClient.js +53 -3
  62. package/dist/core/apiClient.js.map +1 -1
  63. package/dist/core/generics.cjs +30 -3
  64. package/dist/core/generics.cjs.map +1 -1
  65. package/dist/core/generics.d.ts +95 -6
  66. package/dist/core/generics.js +30 -3
  67. package/dist/core/generics.js.map +1 -1
  68. package/dist/core/health.cjs +289 -0
  69. package/dist/core/health.cjs.map +1 -0
  70. package/dist/core/health.d.ts +143 -0
  71. package/dist/core/health.js +265 -0
  72. package/dist/core/health.js.map +1 -0
  73. package/dist/core/inMemoryNonceManager.cjs +138 -0
  74. package/dist/core/inMemoryNonceManager.cjs.map +1 -0
  75. package/dist/core/inMemoryNonceManager.d.ts +69 -0
  76. package/dist/core/inMemoryNonceManager.js +114 -0
  77. package/dist/core/inMemoryNonceManager.js.map +1 -0
  78. package/dist/core/nonceManager.cjs +304 -0
  79. package/dist/core/nonceManager.cjs.map +1 -0
  80. package/dist/core/nonceManager.d.ts +116 -0
  81. package/dist/core/nonceManager.js +280 -0
  82. package/dist/core/nonceManager.js.map +1 -0
  83. package/dist/core/pollingManager.cjs +292 -0
  84. package/dist/core/pollingManager.cjs.map +1 -0
  85. package/dist/core/pollingManager.d.ts +120 -0
  86. package/dist/core/pollingManager.js +268 -0
  87. package/dist/core/pollingManager.js.map +1 -0
  88. package/dist/core.cjs +55 -1
  89. package/dist/core.cjs.map +1 -1
  90. package/dist/core.d.ts +54 -3
  91. package/dist/core.js +55 -1
  92. package/dist/core.js.map +1 -1
  93. package/dist/crypto/ecies/base.cjs +16 -3
  94. package/dist/crypto/ecies/base.cjs.map +1 -1
  95. package/dist/crypto/ecies/base.js +16 -3
  96. package/dist/crypto/ecies/base.js.map +1 -1
  97. package/dist/errors.cjs +29 -0
  98. package/dist/errors.cjs.map +1 -1
  99. package/dist/errors.d.ts +64 -0
  100. package/dist/errors.js +28 -0
  101. package/dist/errors.js.map +1 -1
  102. package/dist/generated/abi/ComputeInstructionRegistryImplementation.cjs.map +1 -1
  103. package/dist/generated/abi/ComputeInstructionRegistryImplementation.js.map +1 -1
  104. package/dist/generated/abi/DLPPerformanceImplementation.cjs +42 -0
  105. package/dist/generated/abi/DLPPerformanceImplementation.cjs.map +1 -1
  106. package/dist/generated/abi/DLPPerformanceImplementation.d.ts +32 -0
  107. package/dist/generated/abi/DLPPerformanceImplementation.js +42 -0
  108. package/dist/generated/abi/DLPPerformanceImplementation.js.map +1 -1
  109. package/dist/generated/abi/DLPRegistryImplementation.cjs +5 -5
  110. package/dist/generated/abi/DLPRegistryImplementation.cjs.map +1 -1
  111. package/dist/generated/abi/DLPRegistryImplementation.d.ts +4 -4
  112. package/dist/generated/abi/DLPRegistryImplementation.js +5 -5
  113. package/dist/generated/abi/DLPRegistryImplementation.js.map +1 -1
  114. package/dist/generated/abi/DLPRewardDeployerImplementation.cjs +166 -2
  115. package/dist/generated/abi/DLPRewardDeployerImplementation.cjs.map +1 -1
  116. package/dist/generated/abi/DLPRewardDeployerImplementation.d.ts +129 -2
  117. package/dist/generated/abi/DLPRewardDeployerImplementation.js +166 -2
  118. package/dist/generated/abi/DLPRewardDeployerImplementation.js.map +1 -1
  119. package/dist/generated/abi/DataPortabilityGranteesImplementation.cjs +167 -19
  120. package/dist/generated/abi/DataPortabilityGranteesImplementation.cjs.map +1 -1
  121. package/dist/generated/abi/DataPortabilityGranteesImplementation.d.ts +127 -14
  122. package/dist/generated/abi/DataPortabilityGranteesImplementation.js +167 -19
  123. package/dist/generated/abi/DataPortabilityGranteesImplementation.js.map +1 -1
  124. package/dist/generated/abi/DataPortabilityPermissionsImplementation.cjs +0 -19
  125. package/dist/generated/abi/DataPortabilityPermissionsImplementation.cjs.map +1 -1
  126. package/dist/generated/abi/DataPortabilityPermissionsImplementation.d.ts +0 -14
  127. package/dist/generated/abi/DataPortabilityPermissionsImplementation.js +0 -19
  128. package/dist/generated/abi/DataPortabilityPermissionsImplementation.js.map +1 -1
  129. package/dist/generated/abi/DataPortabilityServersImplementation.cjs +0 -19
  130. package/dist/generated/abi/DataPortabilityServersImplementation.cjs.map +1 -1
  131. package/dist/generated/abi/DataPortabilityServersImplementation.d.ts +0 -14
  132. package/dist/generated/abi/DataPortabilityServersImplementation.js +0 -19
  133. package/dist/generated/abi/DataPortabilityServersImplementation.js.map +1 -1
  134. package/dist/generated/abi/DataRegistryImplementation.cjs +0 -13
  135. package/dist/generated/abi/DataRegistryImplementation.cjs.map +1 -1
  136. package/dist/generated/abi/DataRegistryImplementation.d.ts +0 -10
  137. package/dist/generated/abi/DataRegistryImplementation.js +0 -13
  138. package/dist/generated/abi/DataRegistryImplementation.js.map +1 -1
  139. package/dist/generated/abi/SwapHelperImplementation.cjs +0 -43
  140. package/dist/generated/abi/SwapHelperImplementation.cjs.map +1 -1
  141. package/dist/generated/abi/SwapHelperImplementation.d.ts +0 -35
  142. package/dist/generated/abi/SwapHelperImplementation.js +0 -43
  143. package/dist/generated/abi/SwapHelperImplementation.js.map +1 -1
  144. package/dist/generated/abi/VanaEpochImplementation.cjs +195 -0
  145. package/dist/generated/abi/VanaEpochImplementation.cjs.map +1 -1
  146. package/dist/generated/abi/VanaEpochImplementation.d.ts +151 -0
  147. package/dist/generated/abi/VanaEpochImplementation.js +195 -0
  148. package/dist/generated/abi/VanaEpochImplementation.js.map +1 -1
  149. package/dist/generated/abi/VanaPoolEntityImplementation.cjs +22 -65
  150. package/dist/generated/abi/VanaPoolEntityImplementation.cjs.map +1 -1
  151. package/dist/generated/abi/VanaPoolEntityImplementation.d.ts +17 -51
  152. package/dist/generated/abi/VanaPoolEntityImplementation.js +22 -65
  153. package/dist/generated/abi/VanaPoolEntityImplementation.js.map +1 -1
  154. package/dist/generated/abi/VanaPoolStakingImplementation.cjs +113 -1
  155. package/dist/generated/abi/VanaPoolStakingImplementation.cjs.map +1 -1
  156. package/dist/generated/abi/VanaPoolStakingImplementation.d.ts +85 -1
  157. package/dist/generated/abi/VanaPoolStakingImplementation.js +113 -1
  158. package/dist/generated/abi/VanaPoolStakingImplementation.js.map +1 -1
  159. package/dist/generated/abi/index.d.ts +546 -146
  160. package/dist/generated/event-types.cjs.map +1 -1
  161. package/dist/generated/event-types.d.ts +14 -8
  162. package/dist/generated/eventRegistry.cjs +42 -18
  163. package/dist/generated/eventRegistry.cjs.map +1 -1
  164. package/dist/generated/eventRegistry.js +42 -18
  165. package/dist/generated/eventRegistry.js.map +1 -1
  166. package/dist/generated/server/server-exports.cjs +22 -0
  167. package/dist/generated/server/server-exports.cjs.map +1 -1
  168. package/dist/generated/server/server-exports.d.ts +27 -10
  169. package/dist/generated/server/server-exports.js +17 -0
  170. package/dist/generated/server/server-exports.js.map +1 -1
  171. package/dist/generated/server/server.cjs.map +1 -1
  172. package/dist/generated/server/server.d.ts +771 -402
  173. package/dist/generated/subgraph.cjs +797 -32
  174. package/dist/generated/subgraph.cjs.map +1 -1
  175. package/dist/generated/subgraph.d.ts +135 -0
  176. package/dist/generated/subgraph.js +792 -32
  177. package/dist/generated/subgraph.js.map +1 -1
  178. package/dist/index.browser.d.ts +2 -0
  179. package/dist/index.browser.js +10 -0
  180. package/dist/index.browser.js.map +1 -1
  181. package/dist/index.cjs.map +1 -1
  182. package/dist/index.js.map +1 -1
  183. package/dist/index.node.cjs +26 -0
  184. package/dist/index.node.cjs.map +1 -1
  185. package/dist/index.node.d.ts +49 -5
  186. package/dist/index.node.js +25 -1
  187. package/dist/index.node.js.map +1 -1
  188. package/dist/lib/__tests__/redisAtomicStore.test.d.ts +1 -0
  189. package/dist/lib/redisAtomicStore.cjs +201 -0
  190. package/dist/lib/redisAtomicStore.cjs.map +1 -0
  191. package/dist/lib/redisAtomicStore.d.ts +120 -0
  192. package/dist/lib/redisAtomicStore.js +177 -0
  193. package/dist/lib/redisAtomicStore.js.map +1 -0
  194. package/dist/node.cjs.map +1 -1
  195. package/dist/node.d.ts +39 -1
  196. package/dist/node.js.map +1 -1
  197. package/dist/platform/browser.cjs +160 -2
  198. package/dist/platform/browser.cjs.map +1 -1
  199. package/dist/platform/browser.d.ts +232 -12
  200. package/dist/platform/browser.js +160 -2
  201. package/dist/platform/browser.js.map +1 -1
  202. package/dist/platform/interface.cjs.map +1 -1
  203. package/dist/platform/interface.d.ts +283 -90
  204. package/dist/platform/node.cjs +163 -2
  205. package/dist/platform/node.cjs.map +1 -1
  206. package/dist/platform/node.d.ts +69 -6
  207. package/dist/platform/node.js +163 -2
  208. package/dist/platform/node.js.map +1 -1
  209. package/dist/server/relayerHandler.cjs +315 -81
  210. package/dist/server/relayerHandler.cjs.map +1 -1
  211. package/dist/server/relayerHandler.d.ts +35 -2
  212. package/dist/server/relayerHandler.js +315 -81
  213. package/dist/server/relayerHandler.js.map +1 -1
  214. package/dist/storage/index.cjs +3 -0
  215. package/dist/storage/index.cjs.map +1 -1
  216. package/dist/storage/index.d.ts +1 -0
  217. package/dist/storage/index.js +2 -0
  218. package/dist/storage/index.js.map +1 -1
  219. package/dist/storage/manager.cjs +108 -25
  220. package/dist/storage/manager.cjs.map +1 -1
  221. package/dist/storage/manager.d.ts +119 -25
  222. package/dist/storage/manager.js +108 -25
  223. package/dist/storage/manager.js.map +1 -1
  224. package/dist/storage/providers/callback-storage.cjs +86 -15
  225. package/dist/storage/providers/callback-storage.cjs.map +1 -1
  226. package/dist/storage/providers/callback-storage.d.ts +109 -20
  227. package/dist/storage/providers/callback-storage.js +86 -15
  228. package/dist/storage/providers/callback-storage.js.map +1 -1
  229. package/dist/storage/providers/dropbox.cjs +237 -0
  230. package/dist/storage/providers/dropbox.cjs.map +1 -0
  231. package/dist/storage/providers/dropbox.d.ts +39 -0
  232. package/dist/storage/providers/dropbox.js +215 -0
  233. package/dist/storage/providers/dropbox.js.map +1 -0
  234. package/dist/storage/providers/dropbox.test.d.ts +1 -0
  235. package/dist/storage/providers/pinata.cjs.map +1 -1
  236. package/dist/storage/providers/pinata.d.ts +12 -14
  237. package/dist/storage/providers/pinata.js.map +1 -1
  238. package/dist/tests/data-upload-owner-validation.test.d.ts +1 -0
  239. package/dist/tests/permissions-transaction-options.test.d.ts +1 -0
  240. package/dist/types/atomicStore.cjs +31 -0
  241. package/dist/types/atomicStore.cjs.map +1 -0
  242. package/dist/types/atomicStore.d.ts +236 -0
  243. package/dist/types/atomicStore.js +7 -0
  244. package/dist/types/atomicStore.js.map +1 -0
  245. package/dist/types/blockchain.cjs.map +1 -1
  246. package/dist/types/blockchain.d.ts +39 -11
  247. package/dist/types/chains.cjs.map +1 -1
  248. package/dist/types/chains.d.ts +74 -7
  249. package/dist/types/chains.js.map +1 -1
  250. package/dist/types/config.cjs.map +1 -1
  251. package/dist/types/config.d.ts +38 -4
  252. package/dist/types/config.js.map +1 -1
  253. package/dist/types/contracts.cjs.map +1 -1
  254. package/dist/types/contracts.d.ts +71 -7
  255. package/dist/types/controller-context.cjs.map +1 -1
  256. package/dist/types/controller-context.d.ts +4 -1
  257. package/dist/types/data.cjs.map +1 -1
  258. package/dist/types/data.d.ts +11 -10
  259. package/dist/types/generics.cjs.map +1 -1
  260. package/dist/types/generics.d.ts +81 -10
  261. package/dist/types/index.cjs.map +1 -1
  262. package/dist/types/index.d.ts +31 -3
  263. package/dist/types/index.js.map +1 -1
  264. package/dist/types/operationStore.cjs +17 -0
  265. package/dist/types/operationStore.cjs.map +1 -0
  266. package/dist/types/operationStore.d.ts +171 -0
  267. package/dist/types/operationStore.js +1 -0
  268. package/dist/types/operationStore.js.map +1 -0
  269. package/dist/types/operations.cjs +3 -15
  270. package/dist/types/operations.cjs.map +1 -1
  271. package/dist/types/operations.d.ts +131 -39
  272. package/dist/types/operations.js +2 -13
  273. package/dist/types/operations.js.map +1 -1
  274. package/dist/types/options.cjs +17 -0
  275. package/dist/types/options.cjs.map +1 -0
  276. package/dist/types/options.d.ts +308 -0
  277. package/dist/types/options.js +1 -0
  278. package/dist/types/options.js.map +1 -0
  279. package/dist/types/permissions.cjs.map +1 -1
  280. package/dist/types/permissions.d.ts +19 -20
  281. package/dist/types/personal.cjs.map +1 -1
  282. package/dist/types/personal.d.ts +150 -14
  283. package/dist/types/relayer.cjs.map +1 -1
  284. package/dist/types/relayer.d.ts +145 -24
  285. package/dist/types/storage.cjs.map +1 -1
  286. package/dist/types/storage.d.ts +9 -21
  287. package/dist/types/storage.js.map +1 -1
  288. package/dist/types/utils.cjs.map +1 -1
  289. package/dist/types/utils.d.ts +0 -45
  290. package/dist/utils/__tests__/chainQuery.test.d.ts +1 -0
  291. package/dist/utils/__tests__/subgraphConsistency.test.d.ts +4 -0
  292. package/dist/utils/__tests__/subgraphPagination.test.d.ts +4 -0
  293. package/dist/utils/chainQuery.cjs +107 -0
  294. package/dist/utils/chainQuery.cjs.map +1 -0
  295. package/dist/utils/chainQuery.d.ts +31 -0
  296. package/dist/utils/chainQuery.js +82 -0
  297. package/dist/utils/chainQuery.js.map +1 -0
  298. package/dist/utils/grantFiles.cjs +4 -1
  299. package/dist/utils/grantFiles.cjs.map +1 -1
  300. package/dist/utils/grantFiles.d.ts +10 -20
  301. package/dist/utils/grantFiles.js +4 -1
  302. package/dist/utils/grantFiles.js.map +1 -1
  303. package/dist/utils/grantValidation.cjs.map +1 -1
  304. package/dist/utils/grantValidation.d.ts +95 -16
  305. package/dist/utils/grantValidation.js.map +1 -1
  306. package/dist/utils/grants.cjs.map +1 -1
  307. package/dist/utils/grants.d.ts +93 -12
  308. package/dist/utils/grants.js.map +1 -1
  309. package/dist/utils/ipfs.cjs +2 -4
  310. package/dist/utils/ipfs.cjs.map +1 -1
  311. package/dist/utils/ipfs.d.ts +1 -1
  312. package/dist/utils/ipfs.js +2 -4
  313. package/dist/utils/ipfs.js.map +1 -1
  314. package/dist/utils/lazy-import.cjs.map +1 -1
  315. package/dist/utils/lazy-import.d.ts +32 -7
  316. package/dist/utils/lazy-import.js.map +1 -1
  317. package/dist/utils/signatureCache.cjs +8 -2
  318. package/dist/utils/signatureCache.cjs.map +1 -1
  319. package/dist/utils/signatureCache.d.ts +49 -8
  320. package/dist/utils/signatureCache.js +8 -2
  321. package/dist/utils/signatureCache.js.map +1 -1
  322. package/dist/utils/subgraphConsistency.cjs +184 -0
  323. package/dist/utils/subgraphConsistency.cjs.map +1 -0
  324. package/dist/utils/subgraphConsistency.d.ts +65 -0
  325. package/dist/utils/subgraphConsistency.js +155 -0
  326. package/dist/utils/subgraphConsistency.js.map +1 -0
  327. package/dist/utils/subgraphMetaCache.cjs +101 -0
  328. package/dist/utils/subgraphMetaCache.cjs.map +1 -0
  329. package/dist/utils/subgraphMetaCache.d.ts +56 -0
  330. package/dist/utils/subgraphMetaCache.js +76 -0
  331. package/dist/utils/subgraphMetaCache.js.map +1 -0
  332. package/dist/utils/subgraphPagination.cjs +104 -0
  333. package/dist/utils/subgraphPagination.cjs.map +1 -0
  334. package/dist/utils/subgraphPagination.d.ts +78 -0
  335. package/dist/utils/subgraphPagination.js +78 -0
  336. package/dist/utils/subgraphPagination.js.map +1 -0
  337. package/dist/utils/transactionHelpers.cjs.map +1 -1
  338. package/dist/utils/transactionHelpers.d.ts +12 -12
  339. package/dist/utils/transactionHelpers.js.map +1 -1
  340. package/dist/utils/typedDataConverter.cjs.map +1 -1
  341. package/dist/utils/typedDataConverter.d.ts +39 -3
  342. package/dist/utils/typedDataConverter.js.map +1 -1
  343. package/dist/utils/urlResolver.cjs +7 -0
  344. package/dist/utils/urlResolver.cjs.map +1 -1
  345. package/dist/utils/urlResolver.d.ts +22 -4
  346. package/dist/utils/urlResolver.js +7 -0
  347. package/dist/utils/urlResolver.js.map +1 -1
  348. package/dist/utils/wallet.cjs.map +1 -1
  349. package/dist/utils/wallet.d.ts +78 -16
  350. package/dist/utils/wallet.js.map +1 -1
  351. package/package.json +3 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/types/utils.ts"],"sourcesContent":["import type { Address, Hash } from \"viem\";\n\n/**\n * Makes all properties in T optional except for those in K\n *\n * @remarks\n * This utility type is useful when you want to create a variant of an interface\n * where most properties are optional, but specific properties remain required.\n * Commonly used for update operations where only certain fields must be provided.\n *\n * @example\n * ```typescript\n * interface User {\n * id: string;\n * name: string;\n * email: string;\n * age: number;\n * }\n *\n * // Only 'id' is required, all other properties are optional\n * type UserUpdate = PartialExcept<User, 'id'>;\n *\n * const update: UserUpdate = {\n * id: '123', // Required\n * name: 'John' // Optional\n * // email and age are also optional\n * };\n * ```\n * @category Reference\n */\nexport type PartialExcept<T, K extends keyof T> = Partial<T> & Pick<T, K>;\n\n/**\n * Makes all properties in T required except for those in K\n *\n * @remarks\n * This utility type is useful when you want to create a variant of an interface\n * where most properties are required, but specific properties remain optional.\n * Commonly used for creation operations where most fields are mandatory.\n *\n * @example\n * ```typescript\n * interface Config {\n * apiUrl: string;\n * timeout?: number;\n * retries?: number;\n * debug?: boolean;\n * }\n *\n * // All properties required except 'debug'\n * type StrictConfig = RequiredExcept<Config, 'debug'>;\n *\n * const config: StrictConfig = {\n * apiUrl: 'https://api.vana.com', // Required\n * timeout: 5000, // Required (was optional, now required)\n * retries: 3, // Required (was optional, now required)\n * // debug remains optional\n * };\n * ```\n * @category Reference\n */\nexport type RequiredExcept<T, K extends keyof T> = Required<T> &\n Partial<Pick<T, K>>;\n\n/**\n * Extracts the return type of a promise\n *\n * @remarks\n * This utility type unwraps the type contained within a Promise.\n * If the type is not a Promise, it returns the type unchanged.\n * Note: TypeScript 4.5+ includes a built-in Awaited type with similar functionality.\n *\n * @example\n * ```typescript\n * type AsyncString = Promise<string>;\n * type SyncString = string;\n *\n * // Extracts 'string' from Promise<string>\n * type Result1 = Awaited<AsyncString>; // string\n *\n * // Returns 'string' unchanged since it's not a Promise\n * type Result2 = Awaited<SyncString>; // string\n *\n * // Practical usage with async functions\n * async function fetchUser(): Promise<{ id: string; name: string }> {\n * // ...\n * }\n *\n * type User = Awaited<ReturnType<typeof fetchUser>>; // { id: string; name: string }\n * ```\n * @category Reference\n */\nexport type Awaited<T> = T extends Promise<infer U> ? U : T;\n\n/**\n * Creates a type that accepts either T or a Promise<T>\n *\n * @remarks\n * This utility type is useful for functions that can work with both\n * synchronous and asynchronous values. It allows flexible APIs that\n * can accept immediate values or promises that resolve to those values.\n *\n * @example\n * ```typescript\n * // Function that accepts either a value or a promise of that value\n * async function processData(data: MaybePromise<string>): Promise<string> {\n * // await works on both promises and regular values\n * const resolved = await data;\n * return resolved.toUpperCase();\n * }\n *\n * // Both calls are valid:\n * processData('hello'); // Synchronous value\n * processData(Promise.resolve('world')); // Asynchronous value\n *\n * // Common use case in SDK callbacks\n * interface StorageProvider {\n * // Provider can implement sync or async file reading\n * read(path: string): MaybePromise<Buffer>;\n * }\n * ```\n * @category Reference\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Creates a type that accepts either T or an array of T\n *\n * @remarks\n * This utility type is useful for functions that can accept either a single\n * value or an array of values, providing a more flexible API. The implementation\n * can normalize the input to always work with arrays internally.\n *\n * @example\n * ```typescript\n * // Function that accepts either a single ID or multiple IDs\n * function deleteItems(ids: MaybeArray<string>): void {\n * // Normalize to array\n * const idArray = Array.isArray(ids) ? ids : [ids];\n * idArray.forEach(id => console.log(`Deleting ${id}`));\n * }\n *\n * // Both calls are valid:\n * deleteItems('item-1'); // Single item\n * deleteItems(['item-1', 'item-2', 'item-3']); // Multiple items\n *\n * // Common use case in permissions\n * interface GrantPermissionsParams {\n * permissions: MaybeArray<Permission>;\n * }\n * ```\n * @category Reference\n */\nexport type MaybeArray<T> = T | T[];\n\n/**\n * Pagination parameters for controlling result set size and navigation.\n *\n * Used across SDK methods that return lists of items to control how many items\n * are returned and to navigate through large result sets efficiently.\n *\n * @category Reference\n * @example\n * ```typescript\n * const pagination: PaginationParams = {\n * limit: 20, // Return 20 items\n * offset: 40, // Skip first 40 items (page 3)\n * cursor: 'eyJpZCI6MTIzfQ==' // Or use cursor-based pagination\n * };\n *\n * const files = await vana.data.getUserFiles({\n * owner: userAddress,\n * pagination\n * });\n * ```\n */\nexport interface PaginationParams {\n /** Maximum number of items to return */\n limit?: number;\n /** Number of items to skip */\n offset?: number;\n /** Cursor for cursor-based pagination */\n cursor?: string;\n}\n\n/**\n * Pagination result containing items and metadata for navigating large datasets.\n *\n * @remarks\n * This interface standardizes paginated responses across the SDK, providing\n * consistent metadata for implementing pagination UI components and handling\n * multi-page data fetching. Supports both offset-based and cursor-based pagination.\n *\n * @example\n * ```typescript\n * // Fetching paginated user files\n * async function getAllUserFiles(userAddress: string): Promise<File[]> {\n * const allFiles: File[] = [];\n * let cursor: string | undefined;\n *\n * do {\n * const result: PaginationResult<File> = await vana.data.getUserFiles({\n * owner: userAddress,\n * pagination: { limit: 50, cursor }\n * });\n *\n * allFiles.push(...result.items);\n * cursor = result.nextCursor;\n *\n * console.log(`Fetched ${result.count} of ${result.total} files`);\n * } while (result.hasMore);\n *\n * return allFiles;\n * }\n * ```\n * @category Reference\n */\nexport interface PaginationResult<T> {\n /** Array of items */\n items: T[];\n /** Total number of items available */\n total: number;\n /** Number of items returned */\n count: number;\n /** Whether there are more items available */\n hasMore: boolean;\n /** Cursor for next page */\n nextCursor?: string;\n}\n\n/**\n * Block range parameters for filtering blockchain events and transactions.\n *\n * @remarks\n * Used to specify a range of blocks when querying blockchain data.\n * Both parameters are optional - omitting fromBlock starts from genesis,\n * omitting toBlock goes to the latest block. Be cautious with large ranges\n * as they may result in heavy RPC loads or timeouts.\n *\n * @example\n * ```typescript\n * // Get events from the last 1000 blocks\n * const currentBlock = await vana.protocol.getBlockNumber();\n * const events = await vana.protocol.getEvents({\n * blockRange: {\n * fromBlock: currentBlock - 1000n,\n * toBlock: currentBlock\n * }\n * });\n *\n * // Get all historical events (use with caution)\n * const allEvents = await vana.protocol.getEvents({\n * blockRange: {\n * fromBlock: 0n\n * // toBlock omitted = up to latest\n * }\n * });\n * ```\n * @category Reference\n */\nexport interface BlockRange {\n /** Starting block number */\n fromBlock?: bigint;\n /** Ending block number */\n toBlock?: bigint;\n}\n\n/**\n * Transaction options for customizing blockchain transaction parameters.\n *\n * @remarks\n * Provides fine-grained control over transaction execution. Supports both\n * legacy (gasPrice) and EIP-1559 (maxFeePerGas) transaction types. When\n * not specified, the SDK will use appropriate defaults based on network\n * conditions. Use these options to optimize for speed or cost.\n *\n * @example\n * ```typescript\n * // High priority transaction with EIP-1559 pricing\n * await vana.permissions.grant(params, {\n * maxFeePerGas: 100n * 10n ** 9n, // 100 gwei\n * maxPriorityFeePerGas: 2n * 10n ** 9n, // 2 gwei tip\n * });\n *\n * // Legacy transaction with specific gas limit\n * await vana.data.registerFile(params, {\n * gasLimit: 500000n,\n * gasPrice: 50n * 10n ** 9n // 50 gwei\n * });\n *\n * // Send ETH with the transaction\n * await vana.protocol.execute(params, {\n * value: 10n ** 18n, // 1 ETH\n * gasLimit: 21000n\n * });\n * ```\n * @category Reference\n */\nexport interface TransactionOptions {\n /** Gas limit */\n gasLimit?: bigint;\n /** Gas price */\n gasPrice?: bigint;\n /** Max fee per gas (EIP-1559) */\n maxFeePerGas?: bigint;\n /** Max priority fee per gas (EIP-1559) */\n maxPriorityFeePerGas?: bigint;\n /** Nonce */\n nonce?: number;\n /** Value to send with transaction */\n value?: bigint;\n}\n\n/**\n * Transaction receipt with additional metadata for tracking transaction results.\n *\n * @remarks\n * Provides comprehensive information about executed transactions including\n * gas usage, success status, and emitted events. Use the logs array to\n * decode events emitted by smart contracts during transaction execution.\n * The receipt is available after a transaction is mined and included in a block.\n *\n * @example\n * ```typescript\n * // Execute transaction and wait for receipt\n * const receipt = await vana.permissions.grant({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * dataId: 123\n * });\n *\n * // Check transaction success\n * if (receipt.status === 'success') {\n * console.log(`Gas used: ${receipt.gasUsed}`);\n * console.log(`Block: ${receipt.blockNumber}`);\n *\n * // Decode events from logs\n * receipt.logs.forEach(log => {\n * if (log.topics[0] === PERMISSION_GRANTED_TOPIC) {\n * console.log('Permission granted event detected');\n * }\n * });\n * } else {\n * console.error('Transaction reverted');\n * }\n * ```\n * @category Reference\n */\nexport interface TransactionReceipt {\n /** Transaction hash */\n transactionHash: Hash;\n /** Block number */\n blockNumber: bigint;\n /** Block hash */\n blockHash: Hash;\n /** Gas used */\n gasUsed: bigint;\n /** Transaction status */\n status: \"success\" | \"reverted\";\n /** Contract address if contract deployment */\n contractAddress?: Address;\n /** Event logs */\n logs: Array<{\n address: Address;\n topics: Hash[];\n data: string;\n }>;\n}\n\n/**\n * Response wrapper for API results providing consistent error handling.\n *\n * @remarks\n * Standardizes API responses across the SDK, making it easy to handle\n * both successful and failed requests. The generic type parameter T\n * represents the expected data type for successful responses. Check\n * the success flag before accessing data to ensure type safety.\n *\n * @example\n * ```typescript\n * // Handling API responses\n * async function fetchUserData(userId: string): Promise<User | null> {\n * const response: ApiResponse<User> = await api.getUser(userId);\n *\n * if (response.success) {\n * console.log('User fetched:', response.data.name);\n * // Access metadata if available\n * if (response.metadata?.cached) {\n * console.log('Data was cached');\n * }\n * return response.data;\n * } else {\n * console.error('Failed to fetch user:', response.error);\n * return null;\n * }\n * }\n *\n * // Type-safe error handling\n * interface UserData {\n * id: string;\n * name: string;\n * }\n *\n * const result: ApiResponse<UserData> = await api.call('/users/123');\n * if (result.success) {\n * // TypeScript knows result.data is UserData here\n * console.log(result.data.name);\n * }\n * ```\n * @category Reference\n */\nexport interface ApiResponse<T> {\n /** Response data */\n data: T;\n /** Success status */\n success: boolean;\n /** Error message if not successful */\n error?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Retry configuration for handling transient failures with exponential backoff.\n *\n * @remarks\n * Configures automatic retry behavior for operations that may fail due to\n * temporary issues like network problems or rate limits. Supports exponential\n * backoff to avoid overwhelming services. The shouldRetry function allows\n * custom logic to determine which errors warrant a retry attempt.\n *\n * @example\n * ```typescript\n * // Simple retry configuration\n * const basicRetry: RetryConfig = {\n * attempts: 3,\n * delay: 1000 // 1 second between retries\n * };\n *\n * // Exponential backoff configuration\n * const exponentialRetry: RetryConfig = {\n * attempts: 5,\n * delay: 1000,\n * backoffMultiplier: 2, // Double delay each time\n * maxDelay: 30000, // Cap at 30 seconds\n * shouldRetry: (error) => {\n * // Only retry network and timeout errors\n * return error.name === 'NetworkError' ||\n * error.message.includes('timeout');\n * }\n * };\n *\n * // Usage with SDK\n * const vana = new Vana({\n * retryConfig: exponentialRetry\n * });\n * ```\n * @category Reference\n */\nexport interface RetryConfig {\n /** Number of retry attempts */\n attempts: number;\n /** Delay between retries in milliseconds */\n delay: number;\n /** Backoff multiplier */\n backoffMultiplier?: number;\n /** Maximum delay in milliseconds */\n maxDelay?: number;\n /** Function to determine if error should be retried */\n shouldRetry?: (error: Error) => boolean;\n}\n\n/**\n * Cache configuration for optimizing repeated data fetches.\n *\n * @remarks\n * Configures in-memory caching behavior to reduce redundant API calls and\n * improve performance. The cache automatically evicts expired entries based\n * on TTL and removes least-recently-used items when maxSize is reached.\n * Use appropriate TTL values based on your data freshness requirements.\n *\n * @example\n * ```typescript\n * // Short-lived cache for frequently changing data\n * const userCache: CacheConfig = {\n * ttl: 60000, // 1 minute\n * maxSize: 100, // Store up to 100 users\n * prefix: 'user:' // Cache keys like 'user:123'\n * };\n *\n * // Long-lived cache for stable data\n * const schemaCache: CacheConfig = {\n * ttl: 3600000, // 1 hour\n * maxSize: 1000, // Store up to 1000 schemas\n * prefix: 'schema:'\n * };\n *\n * // Disable caching by setting TTL to 0\n * const noCache: CacheConfig = {\n * ttl: 0 // No caching\n * };\n * ```\n * @category Reference\n */\nexport interface CacheConfig {\n /** Cache TTL in milliseconds */\n ttl: number;\n /** Maximum cache size */\n maxSize?: number;\n /** Cache key prefix */\n prefix?: string;\n}\n\n/**\n * Validation result for data integrity checks and schema validation.\n *\n * @remarks\n * Provides detailed feedback about validation outcomes, distinguishing between\n * errors (which prevent processing) and warnings (which indicate potential issues).\n * Used throughout the SDK for validating permissions, file formats, schemas,\n * and API parameters before operations.\n *\n * @example\n * ```typescript\n * // Validating user input\n * function validateFileUpload(file: File): ValidationResult {\n * const errors: string[] = [];\n * const warnings: string[] = [];\n *\n * // Check file size\n * if (file.size > 100 * 1024 * 1024) {\n * errors.push('File size exceeds 100MB limit');\n * } else if (file.size > 50 * 1024 * 1024) {\n * warnings.push('Large file may take time to upload');\n * }\n *\n * // Check file type\n * if (!file.type.startsWith('image/')) {\n * errors.push('Only image files are allowed');\n * }\n *\n * return {\n * valid: errors.length === 0,\n * errors,\n * warnings\n * };\n * }\n *\n * // Using validation result\n * const result = validateFileUpload(file);\n * if (!result.valid) {\n * console.error('Validation failed:', result.errors.join(', '));\n * } else {\n * if (result.warnings.length > 0) {\n * console.warn('Warnings:', result.warnings.join(', '));\n * }\n * // Proceed with upload\n * }\n * ```\n * @category Reference\n */\nexport interface ValidationResult {\n /** Whether validation passed */\n valid: boolean;\n /** Validation errors */\n errors: string[];\n /** Validation warnings */\n warnings: string[];\n}\n\n/**\n * Status information for health checks and service monitoring.\n *\n * @remarks\n * Used to report the health status of various SDK components including\n * storage providers, RPC connections, and personal servers. The details\n * field can contain provider-specific information for debugging.\n * Timestamps use Unix epoch milliseconds.\n *\n * @example\n * ```typescript\n * // Checking storage provider health\n * const status: StatusInfo = await storage.getStatus();\n *\n * if (!status.healthy) {\n * console.error(`Storage unhealthy: ${status.message}`);\n * // Check how long the issue has persisted\n * const downtime = Date.now() - status.lastCheck;\n * if (downtime > 300000) { // 5 minutes\n * // Switch to backup provider\n * }\n * }\n *\n * // Detailed status with custom fields\n * const serverStatus: StatusInfo = {\n * healthy: true,\n * message: 'All systems operational',\n * lastCheck: Date.now(),\n * details: {\n * uptime: 3600000, // 1 hour\n * requestsServed: 1234,\n * avgResponseTime: 145, // ms\n * activeConnections: 23\n * }\n * };\n * ```\n * @category Reference\n */\nexport interface StatusInfo {\n /** Whether the service is healthy */\n healthy: boolean;\n /** Status message */\n message?: string;\n /** Last check timestamp */\n lastCheck: number;\n /** Additional status details */\n details?: Record<string, unknown>;\n}\n\n/**\n * Rate limit information for API throttling and quota management.\n *\n * @remarks\n * Provides visibility into rate limiting status to help applications\n * implement appropriate backoff strategies. Rate limits protect services\n * from overload and ensure fair resource usage. Use this information\n * to pace requests and avoid hitting limits.\n *\n * @example\n * ```typescript\n * // Check rate limit before making requests\n * const rateLimit: RateLimitInfo = await api.getRateLimit();\n *\n * console.log(`Requests: ${rateLimit.requests}/${rateLimit.limit}`);\n * console.log(`Resets in: ${rateLimit.resetTime} seconds`);\n *\n * // Implement backoff if approaching limit\n * if (rateLimit.requests >= rateLimit.limit * 0.9) {\n * console.warn('Approaching rate limit, slowing down');\n * await new Promise(resolve =>\n * setTimeout(resolve, rateLimit.resetTime * 1000)\n * );\n * }\n *\n * // Calculate requests per second allowed\n * const rps = rateLimit.limit / rateLimit.window;\n * console.log(`Max ${rps} requests per second allowed`);\n * ```\n * @category Reference\n */\nexport interface RateLimitInfo {\n /** Current request count */\n requests: number;\n /** Maximum requests allowed */\n limit: number;\n /** Time window in seconds */\n window: number;\n /** Time until reset in seconds */\n resetTime: number;\n}\n\n/**\n * File upload progress tracking for user feedback and monitoring.\n *\n * @remarks\n * Provides real-time progress information during file uploads, enabling\n * applications to show progress bars and estimated completion times.\n * The speed calculation is typically based on a rolling average to\n * smooth out network fluctuations.\n *\n * @example\n * ```typescript\n * // Upload with progress tracking\n * await vana.data.upload(file, {\n * onProgress: (progress: UploadProgress) => {\n * // Update progress bar\n * progressBar.style.width = `${progress.percentage}%`;\n *\n * // Show upload speed\n * const speedMBps = (progress.speed / 1024 / 1024).toFixed(2);\n * speedDisplay.textContent = `${speedMBps} MB/s`;\n *\n * // Show time remaining\n * const minutes = Math.floor(progress.estimatedTimeRemaining / 60);\n * const seconds = progress.estimatedTimeRemaining % 60;\n * timeDisplay.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;\n *\n * // Log progress milestones\n * if (progress.percentage === 25 ||\n * progress.percentage === 50 ||\n * progress.percentage === 75) {\n * console.log(`Upload ${progress.percentage}% complete`);\n * }\n * }\n * });\n * ```\n * @category Reference\n */\nexport interface UploadProgress {\n /** Bytes uploaded */\n loaded: number;\n /** Total bytes to upload */\n total: number;\n /** Upload percentage (0-100) */\n percentage: number;\n /** Upload speed in bytes per second */\n speed: number;\n /** Estimated time remaining in seconds */\n estimatedTimeRemaining: number;\n}\n\n/**\n * Network information for blockchain connectivity and monitoring.\n *\n * @remarks\n * Provides comprehensive details about the connected blockchain network,\n * including configuration URLs and real-time status. Use this information\n * to verify network connectivity, display network details to users, and\n * construct explorer links for transactions.\n *\n * @example\n * ```typescript\n * // Get current network info\n * const network: NetworkInfo = await vana.protocol.getNetworkInfo();\n *\n * console.log(`Connected to: ${network.chainName} (ID: ${network.chainId})`);\n * console.log(`Current block: ${network.currentBlock}`);\n *\n * // Check network health\n * if (network.status !== 'healthy') {\n * console.warn(`Network ${network.status}: consider switching RPC`);\n * }\n *\n * // Generate explorer link for transaction\n * function getExplorerLink(txHash: string): string {\n * if (!network.explorerUrl) {\n * return `Transaction: ${txHash}`;\n * }\n * return `${network.explorerUrl}/tx/${txHash}`;\n * }\n *\n * // Verify expected network\n * const EXPECTED_CHAIN_ID = 1337; // Vana testnet\n * if (network.chainId !== EXPECTED_CHAIN_ID) {\n * throw new Error(`Wrong network! Expected ${EXPECTED_CHAIN_ID}, got ${network.chainId}`);\n * }\n * ```\n * @category Reference\n */\nexport interface NetworkInfo {\n /** Chain ID */\n chainId: number;\n /** Chain name */\n chainName: string;\n /** RPC URL */\n rpcUrl: string;\n /** Block explorer URL */\n explorerUrl?: string;\n /** Current block number */\n currentBlock: bigint;\n /** Network status */\n status: \"healthy\" | \"degraded\" | \"down\";\n}\n\n/**\n * Gas estimate information for transaction cost prediction.\n *\n * @remarks\n * Provides detailed gas pricing estimates to help users understand transaction\n * costs before execution. Supports both legacy (gasPrice) and EIP-1559\n * (maxFeePerGas) pricing models. The estimatedCost is calculated based on\n * current network conditions and may vary by the time of actual execution.\n *\n * @example\n * ```typescript\n * // Get gas estimate before transaction\n * const estimate: GasEstimate = await vana.permissions.estimateGas({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * dataId: 123\n * });\n *\n * // Convert to human-readable format\n * const costInEth = Number(estimate.estimatedCost) / 1e18;\n * console.log(`Estimated cost: ${costInEth.toFixed(6)} ETH`);\n *\n * // Check if user has sufficient balance\n * const balance = await vana.protocol.getBalance(userAddress);\n * if (balance < estimate.estimatedCost) {\n * throw new Error(`Insufficient balance. Need ${costInEth} ETH`);\n * }\n *\n * // Use estimate for transaction with buffer\n * await vana.permissions.grant(params, {\n * gasLimit: estimate.gasLimit * 110n / 100n, // 10% buffer\n * maxFeePerGas: estimate.maxFeePerGas,\n * maxPriorityFeePerGas: estimate.maxPriorityFeePerGas\n * });\n * ```\n * @category Reference\n */\nexport interface GasEstimate {\n /** Gas limit */\n gasLimit: bigint;\n /** Gas price */\n gasPrice: bigint;\n /** Max fee per gas */\n maxFeePerGas?: bigint;\n /** Max priority fee per gas */\n maxPriorityFeePerGas?: bigint;\n /** Estimated cost in wei */\n estimatedCost: bigint;\n}\n\n/**\n * Time range parameters for filtering operations by time period.\n *\n * Used in various SDK methods to specify date/time ranges for queries,\n * analytics, and data filtering operations. Times are specified as Unix timestamps.\n *\n * @category Reference\n * @example\n * ```typescript\n * const lastWeek: TimeRange = {\n * from: Date.now() - (7 * 24 * 60 * 60 * 1000), // 7 days ago\n * to: Date.now()\n * };\n *\n * const permissions = await vana.permissions.getUserPermissions({\n * timeRange: lastWeek\n * });\n * ```\n */\nexport interface TimeRange {\n /** Start time (Unix timestamp) */\n from?: number;\n /** End time (Unix timestamp) */\n to?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
1
+ {"version":3,"sources":["../../src/types/utils.ts"],"sourcesContent":["import type { Address, Hash } from \"viem\";\n\n/**\n * Makes all properties in T optional except for those in K\n *\n * @remarks\n * This utility type is useful when you want to create a variant of an interface\n * where most properties are optional, but specific properties remain required.\n * Commonly used for update operations where only certain fields must be provided.\n *\n * @example\n * ```typescript\n * interface User {\n * id: string;\n * name: string;\n * email: string;\n * age: number;\n * }\n *\n * // Only 'id' is required, all other properties are optional\n * type UserUpdate = PartialExcept<User, 'id'>;\n *\n * const update: UserUpdate = {\n * id: '123', // Required\n * name: 'John' // Optional\n * // email and age are also optional\n * };\n * ```\n * @category Reference\n */\nexport type PartialExcept<T, K extends keyof T> = Partial<T> & Pick<T, K>;\n\n/**\n * Makes all properties in T required except for those in K\n *\n * @remarks\n * This utility type is useful when you want to create a variant of an interface\n * where most properties are required, but specific properties remain optional.\n * Commonly used for creation operations where most fields are mandatory.\n *\n * @example\n * ```typescript\n * interface Config {\n * apiUrl: string;\n * timeout?: number;\n * retries?: number;\n * debug?: boolean;\n * }\n *\n * // All properties required except 'debug'\n * type StrictConfig = RequiredExcept<Config, 'debug'>;\n *\n * const config: StrictConfig = {\n * apiUrl: 'https://api.vana.com', // Required\n * timeout: 5000, // Required (was optional, now required)\n * retries: 3, // Required (was optional, now required)\n * // debug remains optional\n * };\n * ```\n * @category Reference\n */\nexport type RequiredExcept<T, K extends keyof T> = Required<T> &\n Partial<Pick<T, K>>;\n\n/**\n * Extracts the return type of a promise\n *\n * @remarks\n * This utility type unwraps the type contained within a Promise.\n * If the type is not a Promise, it returns the type unchanged.\n * Note: TypeScript 4.5+ includes a built-in Awaited type with similar functionality.\n *\n * @example\n * ```typescript\n * type AsyncString = Promise<string>;\n * type SyncString = string;\n *\n * // Extracts 'string' from Promise<string>\n * type Result1 = Awaited<AsyncString>; // string\n *\n * // Returns 'string' unchanged since it's not a Promise\n * type Result2 = Awaited<SyncString>; // string\n *\n * // Practical usage with async functions\n * async function fetchUser(): Promise<{ id: string; name: string }> {\n * // ...\n * }\n *\n * type User = Awaited<ReturnType<typeof fetchUser>>; // { id: string; name: string }\n * ```\n * @category Reference\n */\nexport type Awaited<T> = T extends Promise<infer U> ? U : T;\n\n/**\n * Creates a type that accepts either T or a Promise<T>\n *\n * @remarks\n * This utility type is useful for functions that can work with both\n * synchronous and asynchronous values. It allows flexible APIs that\n * can accept immediate values or promises that resolve to those values.\n *\n * @example\n * ```typescript\n * // Function that accepts either a value or a promise of that value\n * async function processData(data: MaybePromise<string>): Promise<string> {\n * // await works on both promises and regular values\n * const resolved = await data;\n * return resolved.toUpperCase();\n * }\n *\n * // Both calls are valid:\n * processData('hello'); // Synchronous value\n * processData(Promise.resolve('world')); // Asynchronous value\n *\n * // Common use case in SDK callbacks\n * interface StorageProvider {\n * // Provider can implement sync or async file reading\n * read(path: string): MaybePromise<Buffer>;\n * }\n * ```\n * @category Reference\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * Creates a type that accepts either T or an array of T\n *\n * @remarks\n * This utility type is useful for functions that can accept either a single\n * value or an array of values, providing a more flexible API. The implementation\n * can normalize the input to always work with arrays internally.\n *\n * @example\n * ```typescript\n * // Function that accepts either a single ID or multiple IDs\n * function deleteItems(ids: MaybeArray<string>): void {\n * // Normalize to array\n * const idArray = Array.isArray(ids) ? ids : [ids];\n * idArray.forEach(id => console.log(`Deleting ${id}`));\n * }\n *\n * // Both calls are valid:\n * deleteItems('item-1'); // Single item\n * deleteItems(['item-1', 'item-2', 'item-3']); // Multiple items\n *\n * // Common use case in permissions\n * interface GrantPermissionsParams {\n * permissions: MaybeArray<Permission>;\n * }\n * ```\n * @category Reference\n */\nexport type MaybeArray<T> = T | T[];\n\n/**\n * Pagination parameters for controlling result set size and navigation.\n *\n * Used across SDK methods that return lists of items to control how many items\n * are returned and to navigate through large result sets efficiently.\n *\n * @category Reference\n * @example\n * ```typescript\n * const pagination: PaginationParams = {\n * limit: 20, // Return 20 items\n * offset: 40, // Skip first 40 items (page 3)\n * cursor: 'eyJpZCI6MTIzfQ==' // Or use cursor-based pagination\n * };\n *\n * const files = await vana.data.getUserFiles({\n * owner: userAddress,\n * pagination\n * });\n * ```\n */\nexport interface PaginationParams {\n /** Maximum number of items to return */\n limit?: number;\n /** Number of items to skip */\n offset?: number;\n /** Cursor for cursor-based pagination */\n cursor?: string;\n}\n\n/**\n * Pagination result containing items and metadata for navigating large datasets.\n *\n * @remarks\n * This interface standardizes paginated responses across the SDK, providing\n * consistent metadata for implementing pagination UI components and handling\n * multi-page data fetching. Supports both offset-based and cursor-based pagination.\n *\n * @example\n * ```typescript\n * // Fetching paginated user files\n * async function getAllUserFiles(userAddress: string): Promise<File[]> {\n * const allFiles: File[] = [];\n * let cursor: string | undefined;\n *\n * do {\n * const result: PaginationResult<File> = await vana.data.getUserFiles({\n * owner: userAddress,\n * pagination: { limit: 50, cursor }\n * });\n *\n * allFiles.push(...result.items);\n * cursor = result.nextCursor;\n *\n * console.log(`Fetched ${result.count} of ${result.total} files`);\n * } while (result.hasMore);\n *\n * return allFiles;\n * }\n * ```\n * @category Reference\n */\nexport interface PaginationResult<T> {\n /** Array of items */\n items: T[];\n /** Total number of items available */\n total: number;\n /** Number of items returned */\n count: number;\n /** Whether there are more items available */\n hasMore: boolean;\n /** Cursor for next page */\n nextCursor?: string;\n}\n\n/**\n * Block range parameters for filtering blockchain events and transactions.\n *\n * @remarks\n * Used to specify a range of blocks when querying blockchain data.\n * Both parameters are optional - omitting fromBlock starts from genesis,\n * omitting toBlock goes to the latest block. Be cautious with large ranges\n * as they may result in heavy RPC loads or timeouts.\n *\n * @example\n * ```typescript\n * // Get events from the last 1000 blocks\n * const currentBlock = await vana.protocol.getBlockNumber();\n * const events = await vana.protocol.getEvents({\n * blockRange: {\n * fromBlock: currentBlock - 1000n,\n * toBlock: currentBlock\n * }\n * });\n *\n * // Get all historical events (use with caution)\n * const allEvents = await vana.protocol.getEvents({\n * blockRange: {\n * fromBlock: 0n\n * // toBlock omitted = up to latest\n * }\n * });\n * ```\n * @category Reference\n */\nexport interface BlockRange {\n /** Starting block number */\n fromBlock?: bigint;\n /** Ending block number */\n toBlock?: bigint;\n}\n\n/**\n * Transaction receipt with additional metadata for tracking transaction results.\n *\n * @remarks\n * Provides comprehensive information about executed transactions including\n * gas usage, success status, and emitted events. Use the logs array to\n * decode events emitted by smart contracts during transaction execution.\n * The receipt is available after a transaction is mined and included in a block.\n *\n * @example\n * ```typescript\n * // Execute transaction and wait for receipt\n * const receipt = await vana.permissions.grant({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * dataId: 123\n * });\n *\n * // Check transaction success\n * if (receipt.status === 'success') {\n * console.log(`Gas used: ${receipt.gasUsed}`);\n * console.log(`Block: ${receipt.blockNumber}`);\n *\n * // Decode events from logs\n * receipt.logs.forEach(log => {\n * if (log.topics[0] === PERMISSION_GRANTED_TOPIC) {\n * console.log('Permission granted event detected');\n * }\n * });\n * } else {\n * console.error('Transaction reverted');\n * }\n * ```\n * @category Reference\n */\nexport interface TransactionReceipt {\n /** Transaction hash */\n transactionHash: Hash;\n /** Block number */\n blockNumber: bigint;\n /** Block hash */\n blockHash: Hash;\n /** Gas used */\n gasUsed: bigint;\n /** Transaction status */\n status: \"success\" | \"reverted\";\n /** Contract address if contract deployment */\n contractAddress?: Address;\n /** Event logs */\n logs: Array<{\n address: Address;\n topics: Hash[];\n data: string;\n }>;\n}\n\n/**\n * Response wrapper for API results providing consistent error handling.\n *\n * @remarks\n * Standardizes API responses across the SDK, making it easy to handle\n * both successful and failed requests. The generic type parameter T\n * represents the expected data type for successful responses. Check\n * the success flag before accessing data to ensure type safety.\n *\n * @example\n * ```typescript\n * // Handling API responses\n * async function fetchUserData(userId: string): Promise<User | null> {\n * const response: ApiResponse<User> = await api.getUser(userId);\n *\n * if (response.success) {\n * console.log('User fetched:', response.data.name);\n * // Access metadata if available\n * if (response.metadata?.cached) {\n * console.log('Data was cached');\n * }\n * return response.data;\n * } else {\n * console.error('Failed to fetch user:', response.error);\n * return null;\n * }\n * }\n *\n * // Type-safe error handling\n * interface UserData {\n * id: string;\n * name: string;\n * }\n *\n * const result: ApiResponse<UserData> = await api.call('/users/123');\n * if (result.success) {\n * // TypeScript knows result.data is UserData here\n * console.log(result.data.name);\n * }\n * ```\n * @category Reference\n */\nexport interface ApiResponse<T> {\n /** Response data */\n data: T;\n /** Success status */\n success: boolean;\n /** Error message if not successful */\n error?: string;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Retry configuration for handling transient failures with exponential backoff.\n *\n * @remarks\n * Configures automatic retry behavior for operations that may fail due to\n * temporary issues like network problems or rate limits. Supports exponential\n * backoff to avoid overwhelming services. The shouldRetry function allows\n * custom logic to determine which errors warrant a retry attempt.\n *\n * @example\n * ```typescript\n * // Simple retry configuration\n * const basicRetry: RetryConfig = {\n * attempts: 3,\n * delay: 1000 // 1 second between retries\n * };\n *\n * // Exponential backoff configuration\n * const exponentialRetry: RetryConfig = {\n * attempts: 5,\n * delay: 1000,\n * backoffMultiplier: 2, // Double delay each time\n * maxDelay: 30000, // Cap at 30 seconds\n * shouldRetry: (error) => {\n * // Only retry network and timeout errors\n * return error.name === 'NetworkError' ||\n * error.message.includes('timeout');\n * }\n * };\n *\n * // Usage with SDK\n * const vana = new Vana({\n * retryConfig: exponentialRetry\n * });\n * ```\n * @category Reference\n */\nexport interface RetryConfig {\n /** Number of retry attempts */\n attempts: number;\n /** Delay between retries in milliseconds */\n delay: number;\n /** Backoff multiplier */\n backoffMultiplier?: number;\n /** Maximum delay in milliseconds */\n maxDelay?: number;\n /** Function to determine if error should be retried */\n shouldRetry?: (error: Error) => boolean;\n}\n\n/**\n * Cache configuration for optimizing repeated data fetches.\n *\n * @remarks\n * Configures in-memory caching behavior to reduce redundant API calls and\n * improve performance. The cache automatically evicts expired entries based\n * on TTL and removes least-recently-used items when maxSize is reached.\n * Use appropriate TTL values based on your data freshness requirements.\n *\n * @example\n * ```typescript\n * // Short-lived cache for frequently changing data\n * const userCache: CacheConfig = {\n * ttl: 60000, // 1 minute\n * maxSize: 100, // Store up to 100 users\n * prefix: 'user:' // Cache keys like 'user:123'\n * };\n *\n * // Long-lived cache for stable data\n * const schemaCache: CacheConfig = {\n * ttl: 3600000, // 1 hour\n * maxSize: 1000, // Store up to 1000 schemas\n * prefix: 'schema:'\n * };\n *\n * // Disable caching by setting TTL to 0\n * const noCache: CacheConfig = {\n * ttl: 0 // No caching\n * };\n * ```\n * @category Reference\n */\nexport interface CacheConfig {\n /** Cache TTL in milliseconds */\n ttl: number;\n /** Maximum cache size */\n maxSize?: number;\n /** Cache key prefix */\n prefix?: string;\n}\n\n/**\n * Validation result for data integrity checks and schema validation.\n *\n * @remarks\n * Provides detailed feedback about validation outcomes, distinguishing between\n * errors (which prevent processing) and warnings (which indicate potential issues).\n * Used throughout the SDK for validating permissions, file formats, schemas,\n * and API parameters before operations.\n *\n * @example\n * ```typescript\n * // Validating user input\n * function validateFileUpload(file: File): ValidationResult {\n * const errors: string[] = [];\n * const warnings: string[] = [];\n *\n * // Check file size\n * if (file.size > 100 * 1024 * 1024) {\n * errors.push('File size exceeds 100MB limit');\n * } else if (file.size > 50 * 1024 * 1024) {\n * warnings.push('Large file may take time to upload');\n * }\n *\n * // Check file type\n * if (!file.type.startsWith('image/')) {\n * errors.push('Only image files are allowed');\n * }\n *\n * return {\n * valid: errors.length === 0,\n * errors,\n * warnings\n * };\n * }\n *\n * // Using validation result\n * const result = validateFileUpload(file);\n * if (!result.valid) {\n * console.error('Validation failed:', result.errors.join(', '));\n * } else {\n * if (result.warnings.length > 0) {\n * console.warn('Warnings:', result.warnings.join(', '));\n * }\n * // Proceed with upload\n * }\n * ```\n * @category Reference\n */\nexport interface ValidationResult {\n /** Whether validation passed */\n valid: boolean;\n /** Validation errors */\n errors: string[];\n /** Validation warnings */\n warnings: string[];\n}\n\n/**\n * Status information for health checks and service monitoring.\n *\n * @remarks\n * Used to report the health status of various SDK components including\n * storage providers, RPC connections, and personal servers. The details\n * field can contain provider-specific information for debugging.\n * Timestamps use Unix epoch milliseconds.\n *\n * @example\n * ```typescript\n * // Checking storage provider health\n * const status: StatusInfo = await storage.getStatus();\n *\n * if (!status.healthy) {\n * console.error(`Storage unhealthy: ${status.message}`);\n * // Check how long the issue has persisted\n * const downtime = Date.now() - status.lastCheck;\n * if (downtime > 300000) { // 5 minutes\n * // Switch to backup provider\n * }\n * }\n *\n * // Detailed status with custom fields\n * const serverStatus: StatusInfo = {\n * healthy: true,\n * message: 'All systems operational',\n * lastCheck: Date.now(),\n * details: {\n * uptime: 3600000, // 1 hour\n * requestsServed: 1234,\n * avgResponseTime: 145, // ms\n * activeConnections: 23\n * }\n * };\n * ```\n * @category Reference\n */\nexport interface StatusInfo {\n /** Whether the service is healthy */\n healthy: boolean;\n /** Status message */\n message?: string;\n /** Last check timestamp */\n lastCheck: number;\n /** Additional status details */\n details?: Record<string, unknown>;\n}\n\n/**\n * Rate limit information for API throttling and quota management.\n *\n * @remarks\n * Provides visibility into rate limiting status to help applications\n * implement appropriate backoff strategies. Rate limits protect services\n * from overload and ensure fair resource usage. Use this information\n * to pace requests and avoid hitting limits.\n *\n * @example\n * ```typescript\n * // Check rate limit before making requests\n * const rateLimit: RateLimitInfo = await api.getRateLimit();\n *\n * console.log(`Requests: ${rateLimit.requests}/${rateLimit.limit}`);\n * console.log(`Resets in: ${rateLimit.resetTime} seconds`);\n *\n * // Implement backoff if approaching limit\n * if (rateLimit.requests >= rateLimit.limit * 0.9) {\n * console.warn('Approaching rate limit, slowing down');\n * await new Promise(resolve =>\n * setTimeout(resolve, rateLimit.resetTime * 1000)\n * );\n * }\n *\n * // Calculate requests per second allowed\n * const rps = rateLimit.limit / rateLimit.window;\n * console.log(`Max ${rps} requests per second allowed`);\n * ```\n * @category Reference\n */\nexport interface RateLimitInfo {\n /** Current request count */\n requests: number;\n /** Maximum requests allowed */\n limit: number;\n /** Time window in seconds */\n window: number;\n /** Time until reset in seconds */\n resetTime: number;\n}\n\n/**\n * File upload progress tracking for user feedback and monitoring.\n *\n * @remarks\n * Provides real-time progress information during file uploads, enabling\n * applications to show progress bars and estimated completion times.\n * The speed calculation is typically based on a rolling average to\n * smooth out network fluctuations.\n *\n * @example\n * ```typescript\n * // Upload with progress tracking\n * await vana.data.upload(file, {\n * onProgress: (progress: UploadProgress) => {\n * // Update progress bar\n * progressBar.style.width = `${progress.percentage}%`;\n *\n * // Show upload speed\n * const speedMBps = (progress.speed / 1024 / 1024).toFixed(2);\n * speedDisplay.textContent = `${speedMBps} MB/s`;\n *\n * // Show time remaining\n * const minutes = Math.floor(progress.estimatedTimeRemaining / 60);\n * const seconds = progress.estimatedTimeRemaining % 60;\n * timeDisplay.textContent = `${minutes}:${seconds.toString().padStart(2, '0')}`;\n *\n * // Log progress milestones\n * if (progress.percentage === 25 ||\n * progress.percentage === 50 ||\n * progress.percentage === 75) {\n * console.log(`Upload ${progress.percentage}% complete`);\n * }\n * }\n * });\n * ```\n * @category Reference\n */\nexport interface UploadProgress {\n /** Bytes uploaded */\n loaded: number;\n /** Total bytes to upload */\n total: number;\n /** Upload percentage (0-100) */\n percentage: number;\n /** Upload speed in bytes per second */\n speed: number;\n /** Estimated time remaining in seconds */\n estimatedTimeRemaining: number;\n}\n\n/**\n * Network information for blockchain connectivity and monitoring.\n *\n * @remarks\n * Provides comprehensive details about the connected blockchain network,\n * including configuration URLs and real-time status. Use this information\n * to verify network connectivity, display network details to users, and\n * construct explorer links for transactions.\n *\n * @example\n * ```typescript\n * // Get current network info\n * const network: NetworkInfo = await vana.protocol.getNetworkInfo();\n *\n * console.log(`Connected to: ${network.chainName} (ID: ${network.chainId})`);\n * console.log(`Current block: ${network.currentBlock}`);\n *\n * // Check network health\n * if (network.status !== 'healthy') {\n * console.warn(`Network ${network.status}: consider switching RPC`);\n * }\n *\n * // Generate explorer link for transaction\n * function getExplorerLink(txHash: string): string {\n * if (!network.explorerUrl) {\n * return `Transaction: ${txHash}`;\n * }\n * return `${network.explorerUrl}/tx/${txHash}`;\n * }\n *\n * // Verify expected network\n * const EXPECTED_CHAIN_ID = 1337; // Vana testnet\n * if (network.chainId !== EXPECTED_CHAIN_ID) {\n * throw new Error(`Wrong network! Expected ${EXPECTED_CHAIN_ID}, got ${network.chainId}`);\n * }\n * ```\n * @category Reference\n */\nexport interface NetworkInfo {\n /** Chain ID */\n chainId: number;\n /** Chain name */\n chainName: string;\n /** RPC URL */\n rpcUrl: string;\n /** Block explorer URL */\n explorerUrl?: string;\n /** Current block number */\n currentBlock: bigint;\n /** Network status */\n status: \"healthy\" | \"degraded\" | \"down\";\n}\n\n/**\n * Gas estimate information for transaction cost prediction.\n *\n * @remarks\n * Provides detailed gas pricing estimates to help users understand transaction\n * costs before execution. Supports both legacy (gasPrice) and EIP-1559\n * (maxFeePerGas) pricing models. The estimatedCost is calculated based on\n * current network conditions and may vary by the time of actual execution.\n *\n * @example\n * ```typescript\n * // Get gas estimate before transaction\n * const estimate: GasEstimate = await vana.permissions.estimateGas({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * dataId: 123\n * });\n *\n * // Convert to human-readable format\n * const costInEth = Number(estimate.estimatedCost) / 1e18;\n * console.log(`Estimated cost: ${costInEth.toFixed(6)} ETH`);\n *\n * // Check if user has sufficient balance\n * const balance = await vana.protocol.getBalance(userAddress);\n * if (balance < estimate.estimatedCost) {\n * throw new Error(`Insufficient balance. Need ${costInEth} ETH`);\n * }\n *\n * // Use estimate for transaction with buffer\n * await vana.permissions.grant(params, {\n * gasLimit: estimate.gasLimit * 110n / 100n, // 10% buffer\n * maxFeePerGas: estimate.maxFeePerGas,\n * maxPriorityFeePerGas: estimate.maxPriorityFeePerGas\n * });\n * ```\n * @category Reference\n */\nexport interface GasEstimate {\n /** Gas limit */\n gasLimit: bigint;\n /** Gas price */\n gasPrice: bigint;\n /** Max fee per gas */\n maxFeePerGas?: bigint;\n /** Max priority fee per gas */\n maxPriorityFeePerGas?: bigint;\n /** Estimated cost in wei */\n estimatedCost: bigint;\n}\n\n/**\n * Time range parameters for filtering operations by time period.\n *\n * Used in various SDK methods to specify date/time ranges for queries,\n * analytics, and data filtering operations. Times are specified as Unix timestamps.\n *\n * @category Reference\n * @example\n * ```typescript\n * const lastWeek: TimeRange = {\n * from: Date.now() - (7 * 24 * 60 * 60 * 1000), // 7 days ago\n * to: Date.now()\n * };\n *\n * const permissions = await vana.permissions.getUserPermissions({\n * timeRange: lastWeek\n * });\n * ```\n */\nexport interface TimeRange {\n /** Start time (Unix timestamp) */\n from?: number;\n /** End time (Unix timestamp) */\n to?: number;\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA;AAAA;","names":[]}
@@ -255,51 +255,6 @@ export interface BlockRange {
255
255
  /** Ending block number */
256
256
  toBlock?: bigint;
257
257
  }
258
- /**
259
- * Transaction options for customizing blockchain transaction parameters.
260
- *
261
- * @remarks
262
- * Provides fine-grained control over transaction execution. Supports both
263
- * legacy (gasPrice) and EIP-1559 (maxFeePerGas) transaction types. When
264
- * not specified, the SDK will use appropriate defaults based on network
265
- * conditions. Use these options to optimize for speed or cost.
266
- *
267
- * @example
268
- * ```typescript
269
- * // High priority transaction with EIP-1559 pricing
270
- * await vana.permissions.grant(params, {
271
- * maxFeePerGas: 100n * 10n ** 9n, // 100 gwei
272
- * maxPriorityFeePerGas: 2n * 10n ** 9n, // 2 gwei tip
273
- * });
274
- *
275
- * // Legacy transaction with specific gas limit
276
- * await vana.data.registerFile(params, {
277
- * gasLimit: 500000n,
278
- * gasPrice: 50n * 10n ** 9n // 50 gwei
279
- * });
280
- *
281
- * // Send ETH with the transaction
282
- * await vana.protocol.execute(params, {
283
- * value: 10n ** 18n, // 1 ETH
284
- * gasLimit: 21000n
285
- * });
286
- * ```
287
- * @category Reference
288
- */
289
- export interface TransactionOptions {
290
- /** Gas limit */
291
- gasLimit?: bigint;
292
- /** Gas price */
293
- gasPrice?: bigint;
294
- /** Max fee per gas (EIP-1559) */
295
- maxFeePerGas?: bigint;
296
- /** Max priority fee per gas (EIP-1559) */
297
- maxPriorityFeePerGas?: bigint;
298
- /** Nonce */
299
- nonce?: number;
300
- /** Value to send with transaction */
301
- value?: bigint;
302
- }
303
258
  /**
304
259
  * Transaction receipt with additional metadata for tracking transaction results.
305
260
  *
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @file Tests for subgraph consistency utilities
3
+ */
4
+ export {};
@@ -0,0 +1,4 @@
1
+ /**
2
+ * @file Tests for subgraph pagination utilities
3
+ */
4
+ export {};
@@ -0,0 +1,107 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var chainQuery_exports = {};
20
+ __export(chainQuery_exports, {
21
+ determineDataSource: () => determineDataSource,
22
+ getUserFilesFromChain: () => getUserFilesFromChain
23
+ });
24
+ module.exports = __toCommonJS(chainQuery_exports);
25
+ var import_viem = require("viem");
26
+ async function getUserFilesFromChain(publicClient, contractAddress, owner, fromBlock, toBlock) {
27
+ const fileAddedV2Events = await publicClient.getLogs({
28
+ address: contractAddress,
29
+ event: (0, import_viem.parseAbiItem)(
30
+ "event FileAddedV2(uint256 indexed fileId, address indexed ownerAddress, string url, uint256 schemaId)"
31
+ ),
32
+ args: {
33
+ ownerAddress: owner
34
+ },
35
+ fromBlock: fromBlock ?? "earliest",
36
+ toBlock: toBlock ?? "latest"
37
+ });
38
+ const fileAddedEvents = await publicClient.getLogs({
39
+ address: contractAddress,
40
+ event: (0, import_viem.parseAbiItem)(
41
+ "event FileAdded(uint256 indexed fileId, address indexed ownerAddress, string url)"
42
+ ),
43
+ args: {
44
+ ownerAddress: owner
45
+ },
46
+ fromBlock: fromBlock ?? "earliest",
47
+ toBlock: toBlock ?? "latest"
48
+ });
49
+ const filesFromV2 = fileAddedV2Events.map((event) => ({
50
+ id: Number(event.args.fileId),
51
+ url: event.args.url,
52
+ ownerAddress: event.args.ownerAddress,
53
+ schemaId: Number(event.args.schemaId),
54
+ addedAtBlock: event.blockNumber,
55
+ addedAtTimestamp: BigInt(0),
56
+ // Would need to fetch block for timestamp
57
+ transactionHash: event.transactionHash
58
+ }));
59
+ const filesFromV1 = fileAddedEvents.map((event) => ({
60
+ id: Number(event.args.fileId),
61
+ url: event.args.url,
62
+ ownerAddress: event.args.ownerAddress,
63
+ schemaId: 0,
64
+ // No schema in V1
65
+ addedAtBlock: event.blockNumber,
66
+ addedAtTimestamp: BigInt(0),
67
+ // Would need to fetch block for timestamp
68
+ transactionHash: event.transactionHash
69
+ }));
70
+ const allFiles = [...filesFromV2];
71
+ const v2FileIds = new Set(filesFromV2.map((f) => f.id));
72
+ for (const v1File of filesFromV1) {
73
+ if (!v2FileIds.has(v1File.id)) {
74
+ allFiles.push(v1File);
75
+ }
76
+ }
77
+ allFiles.sort((a, b) => {
78
+ if (a.addedAtBlock > b.addedAtBlock) return -1;
79
+ if (a.addedAtBlock < b.addedAtBlock) return 1;
80
+ return 0;
81
+ });
82
+ return allFiles;
83
+ }
84
+ function determineDataSource(source, minBlock, currentBlock, subgraphBlock) {
85
+ if (source === "subgraph" || source === "chain") {
86
+ return source;
87
+ }
88
+ if (source === "auto" || source === void 0) {
89
+ if (!minBlock) {
90
+ return "subgraph";
91
+ }
92
+ if (!subgraphBlock || subgraphBlock < minBlock) {
93
+ const staleness = Number(currentBlock) - (subgraphBlock ?? 0);
94
+ if (staleness > 100) {
95
+ return "chain";
96
+ }
97
+ }
98
+ return "subgraph";
99
+ }
100
+ return "subgraph";
101
+ }
102
+ // Annotate the CommonJS export names for ESM import in node:
103
+ 0 && (module.exports = {
104
+ determineDataSource,
105
+ getUserFilesFromChain
106
+ });
107
+ //# sourceMappingURL=chainQuery.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/chainQuery.ts"],"sourcesContent":["/**\n * @file Utilities for querying data directly from the blockchain\n * @module vana-sdk/utils/chainQuery\n */\n\nimport type { Address, PublicClient } from \"viem\";\nimport { parseAbiItem } from \"viem\";\nimport type { UserFile } from \"../types\";\n\n/**\n * Query user files directly from the blockchain using events\n *\n * @remarks\n * This bypasses the subgraph entirely and queries events directly from the chain.\n * Slower than subgraph but guarantees real-time consistency.\n *\n * @param publicClient - Viem public client for chain interaction\n * @param contractAddress - DataRegistry contract address\n * @param owner - Owner address to query files for\n * @param fromBlock - Starting block number (optional)\n * @param toBlock - Ending block number (optional)\n * @returns Array of UserFile objects\n */\nexport async function getUserFilesFromChain(\n publicClient: PublicClient,\n contractAddress: Address,\n owner: Address,\n fromBlock?: bigint,\n toBlock?: bigint,\n): Promise<UserFile[]> {\n // Query FileAddedV2 events (has schema support)\n const fileAddedV2Events = await publicClient.getLogs({\n address: contractAddress,\n event: parseAbiItem(\n \"event FileAddedV2(uint256 indexed fileId, address indexed ownerAddress, string url, uint256 schemaId)\",\n ),\n args: {\n ownerAddress: owner,\n },\n fromBlock: fromBlock ?? \"earliest\",\n toBlock: toBlock ?? \"latest\",\n });\n\n // Also query older FileAdded events (no schema)\n const fileAddedEvents = await publicClient.getLogs({\n address: contractAddress,\n event: parseAbiItem(\n \"event FileAdded(uint256 indexed fileId, address indexed ownerAddress, string url)\",\n ),\n args: {\n ownerAddress: owner,\n },\n fromBlock: fromBlock ?? \"earliest\",\n toBlock: toBlock ?? \"latest\",\n });\n\n // Convert events to UserFile objects\n const filesFromV2 = fileAddedV2Events.map((event) => ({\n id: Number(event.args.fileId),\n url: event.args.url as string,\n ownerAddress: event.args.ownerAddress as Address,\n schemaId: Number(event.args.schemaId),\n addedAtBlock: event.blockNumber,\n addedAtTimestamp: BigInt(0), // Would need to fetch block for timestamp\n transactionHash: event.transactionHash,\n }));\n\n const filesFromV1 = fileAddedEvents.map((event) => ({\n id: Number(event.args.fileId),\n url: event.args.url as string,\n ownerAddress: event.args.ownerAddress as Address,\n schemaId: 0, // No schema in V1\n addedAtBlock: event.blockNumber,\n addedAtTimestamp: BigInt(0), // Would need to fetch block for timestamp\n transactionHash: event.transactionHash,\n }));\n\n // Combine and deduplicate (V2 takes precedence)\n const allFiles = [...filesFromV2];\n const v2FileIds = new Set(filesFromV2.map((f) => f.id));\n\n for (const v1File of filesFromV1) {\n if (!v2FileIds.has(v1File.id)) {\n allFiles.push(v1File);\n }\n }\n\n // Sort by block number descending (most recent first)\n allFiles.sort((a, b) => {\n if (a.addedAtBlock > b.addedAtBlock) return -1;\n if (a.addedAtBlock < b.addedAtBlock) return 1;\n return 0;\n });\n\n return allFiles;\n}\n\n/**\n * Determine optimal data source based on requirements\n *\n * @param source - Explicitly requested source\n * @param minBlock - Minimum required block\n * @param currentBlock - Current chain block\n * @param subgraphBlock - Current subgraph block\n * @returns The data source to use\n */\nexport function determineDataSource(\n source: \"subgraph\" | \"chain\" | \"auto\" | undefined,\n minBlock: number | undefined,\n currentBlock: bigint,\n subgraphBlock: number | undefined,\n): \"subgraph\" | \"chain\" {\n // If explicitly specified, use that\n if (source === \"subgraph\" || source === \"chain\") {\n return source;\n }\n\n // Auto mode or unspecified\n if (source === \"auto\" || source === undefined) {\n // If no consistency requirement, use subgraph (faster)\n if (!minBlock) {\n return \"subgraph\";\n }\n\n // If subgraph is unknown or too far behind, use chain\n if (!subgraphBlock || subgraphBlock < minBlock) {\n // Calculate staleness\n const staleness = Number(currentBlock) - (subgraphBlock ?? 0);\n\n // If more than 100 blocks behind, use chain\n if (staleness > 100) {\n return \"chain\";\n }\n }\n\n // Default to subgraph\n return \"subgraph\";\n }\n\n // Default fallback\n return \"subgraph\";\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAMA,kBAA6B;AAiB7B,eAAsB,sBACpB,cACA,iBACA,OACA,WACA,SACqB;AAErB,QAAM,oBAAoB,MAAM,aAAa,QAAQ;AAAA,IACnD,SAAS;AAAA,IACT,WAAO;AAAA,MACL;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,cAAc;AAAA,IAChB;AAAA,IACA,WAAW,aAAa;AAAA,IACxB,SAAS,WAAW;AAAA,EACtB,CAAC;AAGD,QAAM,kBAAkB,MAAM,aAAa,QAAQ;AAAA,IACjD,SAAS;AAAA,IACT,WAAO;AAAA,MACL;AAAA,IACF;AAAA,IACA,MAAM;AAAA,MACJ,cAAc;AAAA,IAChB;AAAA,IACA,WAAW,aAAa;AAAA,IACxB,SAAS,WAAW;AAAA,EACtB,CAAC;AAGD,QAAM,cAAc,kBAAkB,IAAI,CAAC,WAAW;AAAA,IACpD,IAAI,OAAO,MAAM,KAAK,MAAM;AAAA,IAC5B,KAAK,MA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ACT;","names":[]}
@@ -0,0 +1,31 @@
1
+ /**
2
+ * @file Utilities for querying data directly from the blockchain
3
+ * @module vana-sdk/utils/chainQuery
4
+ */
5
+ import type { Address, PublicClient } from "viem";
6
+ import type { UserFile } from "../types";
7
+ /**
8
+ * Query user files directly from the blockchain using events
9
+ *
10
+ * @remarks
11
+ * This bypasses the subgraph entirely and queries events directly from the chain.
12
+ * Slower than subgraph but guarantees real-time consistency.
13
+ *
14
+ * @param publicClient - Viem public client for chain interaction
15
+ * @param contractAddress - DataRegistry contract address
16
+ * @param owner - Owner address to query files for
17
+ * @param fromBlock - Starting block number (optional)
18
+ * @param toBlock - Ending block number (optional)
19
+ * @returns Array of UserFile objects
20
+ */
21
+ export declare function getUserFilesFromChain(publicClient: PublicClient, contractAddress: Address, owner: Address, fromBlock?: bigint, toBlock?: bigint): Promise<UserFile[]>;
22
+ /**
23
+ * Determine optimal data source based on requirements
24
+ *
25
+ * @param source - Explicitly requested source
26
+ * @param minBlock - Minimum required block
27
+ * @param currentBlock - Current chain block
28
+ * @param subgraphBlock - Current subgraph block
29
+ * @returns The data source to use
30
+ */
31
+ export declare function determineDataSource(source: "subgraph" | "chain" | "auto" | undefined, minBlock: number | undefined, currentBlock: bigint, subgraphBlock: number | undefined): "subgraph" | "chain";
@@ -0,0 +1,82 @@
1
+ import { parseAbiItem } from "viem";
2
+ async function getUserFilesFromChain(publicClient, contractAddress, owner, fromBlock, toBlock) {
3
+ const fileAddedV2Events = await publicClient.getLogs({
4
+ address: contractAddress,
5
+ event: parseAbiItem(
6
+ "event FileAddedV2(uint256 indexed fileId, address indexed ownerAddress, string url, uint256 schemaId)"
7
+ ),
8
+ args: {
9
+ ownerAddress: owner
10
+ },
11
+ fromBlock: fromBlock ?? "earliest",
12
+ toBlock: toBlock ?? "latest"
13
+ });
14
+ const fileAddedEvents = await publicClient.getLogs({
15
+ address: contractAddress,
16
+ event: parseAbiItem(
17
+ "event FileAdded(uint256 indexed fileId, address indexed ownerAddress, string url)"
18
+ ),
19
+ args: {
20
+ ownerAddress: owner
21
+ },
22
+ fromBlock: fromBlock ?? "earliest",
23
+ toBlock: toBlock ?? "latest"
24
+ });
25
+ const filesFromV2 = fileAddedV2Events.map((event) => ({
26
+ id: Number(event.args.fileId),
27
+ url: event.args.url,
28
+ ownerAddress: event.args.ownerAddress,
29
+ schemaId: Number(event.args.schemaId),
30
+ addedAtBlock: event.blockNumber,
31
+ addedAtTimestamp: BigInt(0),
32
+ // Would need to fetch block for timestamp
33
+ transactionHash: event.transactionHash
34
+ }));
35
+ const filesFromV1 = fileAddedEvents.map((event) => ({
36
+ id: Number(event.args.fileId),
37
+ url: event.args.url,
38
+ ownerAddress: event.args.ownerAddress,
39
+ schemaId: 0,
40
+ // No schema in V1
41
+ addedAtBlock: event.blockNumber,
42
+ addedAtTimestamp: BigInt(0),
43
+ // Would need to fetch block for timestamp
44
+ transactionHash: event.transactionHash
45
+ }));
46
+ const allFiles = [...filesFromV2];
47
+ const v2FileIds = new Set(filesFromV2.map((f) => f.id));
48
+ for (const v1File of filesFromV1) {
49
+ if (!v2FileIds.has(v1File.id)) {
50
+ allFiles.push(v1File);
51
+ }
52
+ }
53
+ allFiles.sort((a, b) => {
54
+ if (a.addedAtBlock > b.addedAtBlock) return -1;
55
+ if (a.addedAtBlock < b.addedAtBlock) return 1;
56
+ return 0;
57
+ });
58
+ return allFiles;
59
+ }
60
+ function determineDataSource(source, minBlock, currentBlock, subgraphBlock) {
61
+ if (source === "subgraph" || source === "chain") {
62
+ return source;
63
+ }
64
+ if (source === "auto" || source === void 0) {
65
+ if (!minBlock) {
66
+ return "subgraph";
67
+ }
68
+ if (!subgraphBlock || subgraphBlock < minBlock) {
69
+ const staleness = Number(currentBlock) - (subgraphBlock ?? 0);
70
+ if (staleness > 100) {
71
+ return "chain";
72
+ }
73
+ }
74
+ return "subgraph";
75
+ }
76
+ return "subgraph";
77
+ }
78
+ export {
79
+ determineDataSource,
80
+ getUserFilesFromChain
81
+ };
82
+ //# sourceMappingURL=chainQuery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/utils/chainQuery.ts"],"sourcesContent":["/**\n * @file Utilities for querying data directly from the blockchain\n * @module vana-sdk/utils/chainQuery\n */\n\nimport type { Address, PublicClient } from \"viem\";\nimport { parseAbiItem } from \"viem\";\nimport type { UserFile } from \"../types\";\n\n/**\n * Query user files directly from the blockchain using events\n *\n * @remarks\n * This bypasses the subgraph entirely and queries events directly from the chain.\n * Slower than subgraph but guarantees real-time consistency.\n *\n * @param publicClient - Viem public client for chain interaction\n * @param contractAddress - DataRegistry contract address\n * @param owner - Owner address to query files for\n * @param fromBlock - Starting block number (optional)\n * @param toBlock - Ending block number (optional)\n * @returns Array of UserFile objects\n */\nexport async function getUserFilesFromChain(\n publicClient: PublicClient,\n contractAddress: Address,\n owner: Address,\n fromBlock?: bigint,\n toBlock?: bigint,\n): Promise<UserFile[]> {\n // Query FileAddedV2 events (has schema support)\n const fileAddedV2Events = await publicClient.getLogs({\n address: contractAddress,\n event: parseAbiItem(\n \"event FileAddedV2(uint256 indexed fileId, address indexed ownerAddress, string url, uint256 schemaId)\",\n ),\n args: {\n ownerAddress: owner,\n },\n fromBlock: fromBlock ?? \"earliest\",\n toBlock: toBlock ?? \"latest\",\n });\n\n // Also query older FileAdded events (no schema)\n const fileAddedEvents = await publicClient.getLogs({\n address: contractAddress,\n event: parseAbiItem(\n \"event FileAdded(uint256 indexed fileId, address indexed ownerAddress, string url)\",\n ),\n args: {\n ownerAddress: owner,\n },\n fromBlock: fromBlock ?? \"earliest\",\n toBlock: toBlock ?? \"latest\",\n });\n\n // Convert events to UserFile objects\n const filesFromV2 = fileAddedV2Events.map((event) => ({\n id: Number(event.args.fileId),\n url: event.args.url as string,\n ownerAddress: event.args.ownerAddress as Address,\n schemaId: Number(event.args.schemaId),\n addedAtBlock: event.blockNumber,\n addedAtTimestamp: BigInt(0), // Would need to fetch block for timestamp\n transactionHash: event.transactionHash,\n }));\n\n const filesFromV1 = fileAddedEvents.map((event) => ({\n id: Number(event.args.fileId),\n url: event.args.url as string,\n ownerAddress: event.args.ownerAddress as Address,\n schemaId: 0, // No schema in V1\n addedAtBlock: event.blockNumber,\n addedAtTimestamp: BigInt(0), // Would need to fetch block for timestamp\n transactionHash: event.transactionHash,\n }));\n\n // Combine and deduplicate (V2 takes precedence)\n const allFiles = [...filesFromV2];\n const v2FileIds = new Set(filesFromV2.map((f) => f.id));\n\n for (const v1File of filesFromV1) {\n if (!v2FileIds.has(v1File.id)) {\n allFiles.push(v1File);\n }\n }\n\n // Sort by block number descending (most recent first)\n allFiles.sort((a, b) => {\n if (a.addedAtBlock > b.addedAtBlock) return -1;\n if (a.addedAtBlock < b.addedAtBlock) return 1;\n return 0;\n });\n\n return allFiles;\n}\n\n/**\n * Determine optimal data source based on requirements\n *\n * @param source - Explicitly requested source\n * @param minBlock - Minimum required block\n * @param currentBlock - Current chain block\n * @param subgraphBlock - Current subgraph block\n * @returns The data source to use\n */\nexport function determineDataSource(\n source: \"subgraph\" | \"chain\" | \"auto\" | undefined,\n minBlock: number | undefined,\n currentBlock: bigint,\n subgraphBlock: number | undefined,\n): \"subgraph\" | \"chain\" {\n // If explicitly specified, use that\n if (source === \"subgraph\" || source === \"chain\") {\n return source;\n }\n\n // Auto mode or unspecified\n if (source === \"auto\" || source === undefined) {\n // If no consistency requirement, use subgraph (faster)\n if (!minBlock) {\n return \"subgraph\";\n }\n\n // If subgraph is unknown or too far behind, use chain\n if (!subgraphBlock || subgraphBlock < minBlock) {\n // Calculate staleness\n const staleness = Number(currentBlock) - (subgraphBlock ?? 0);\n\n // If more than 100 blocks behind, use chain\n if (staleness > 100) {\n return \"chain\";\n }\n }\n\n // Default to subgraph\n return \"subgraph\";\n }\n\n // Default fallback\n return \"subgraph\";\n}\n"],"mappings":"AAMA,SAAS,oBAAoB;AAiB7B,eAAsB,sBACpB,cACA,iBACA,OACA,WACA,SACqB;AAErB,QAAM,oBAAoB,MAAM,aAAa,QAAQ;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,EAAE,eAAe,EAAE,aAAc,QAAO;AAC5C,QAAI,EAAE,eAAe,EAAE,aAAc,QAAO;AAC5C,WAAO;AAAA,EACT,CAAC;AAED,SAAO;AACT;AAWO,SAAS,oBACd,QACA,UACA,cACA,eACsB;AAEtB,MAAI,WAAW,cAAc,WAAW,SAAS;AAC/C,WAAO;AAAA,EACT;AAGA,MAAI,WAAW,UAAU,WAAW,QAAW;AAE7C,QAAI,CAAC,UAAU;AACb,aAAO;AAAA,IACT;AAGA,QAAI,CAAC,iBAAiB,gBAAgB,UAAU;AAE9C,YAAM,YAAY,OAAO,YAAY,KAAK,iBAAiB;AAG3D,UAAI,YAAY,KAAK;AACnB,eAAO;AAAA,MACT;AAAA,IACF;AAGA,WAAO;AAAA,EACT;AAGA,SAAO;AACT;","names":[]}
@@ -41,8 +41,11 @@ function createGrantFile(params) {
41
41
  const grantFile = {
42
42
  grantee: params.grantee,
43
43
  operation: params.operation,
44
- parameters: params.parameters
44
+ parameters: { ...params.parameters }
45
45
  };
46
+ if (params.filters) {
47
+ grantFile.parameters.filters = params.filters;
48
+ }
46
49
  if (params.expiresAt) {
47
50
  grantFile.expires = params.expiresAt;
48
51
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/grantFiles.ts"],"sourcesContent":["import { keccak256, toHex } from \"viem\";\nimport type { GrantFile, GrantPermissionParams } from \"../types/permissions\";\nimport { SerializationError, NetworkError } from \"../errors\";\n\ninterface GrantFileStorageResponse {\n success: boolean;\n error?: string;\n url?: string;\n}\n\n/**\n * Creates a grant file structure from permission parameters.\n *\n * @remarks\n * This function constructs the JSON structure that represents a permission grant\n * in the Vana protocol. The grant file contains all necessary information for\n * a grantee to perform operations on behalf of the grantor.\n *\n * @param params - The permission parameters to create the grant file from\n * @returns The constructed grant file object\n * @example\n * ```typescript\n * const grantFile = createGrantFile({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * operation: 'llm_inference',\n * parameters: {\n * model: 'gpt-4',\n * maxTokens: 1000\n * },\n * expiresAt: Date.now() + 86400000 // 24 hours\n * });\n *\n * console.log(grantFile);\n * // {\n * // grantee: '0x742d...',\n * // operation: 'llm_inference',\n * // parameters: { model: 'gpt-4', maxTokens: 1000 },\n * // expires: 1234567890\n * // }\n * ```\n */\nexport function createGrantFile(params: GrantPermissionParams): GrantFile {\n const grantFile: GrantFile = {\n grantee: params.grantee,\n operation: params.operation,\n parameters: params.parameters,\n };\n\n // Add expiration if provided\n if (params.expiresAt) {\n grantFile.expires = params.expiresAt;\n }\n\n return grantFile;\n}\n\n/**\n * Stores a grant file in IPFS via the relayer service.\n *\n * @remarks\n * This function uploads the grant file to IPFS through the relayer's upload endpoint.\n * The returned URL can be stored on-chain as part of the permission grant, allowing\n * anyone to retrieve the detailed permission parameters later.\n *\n * @param grantFile - The grant file to store\n * @param relayerUrl - URL of the relayer service\n * @returns Promise resolving to the IPFS URL\n * @throws {NetworkError} When the upload fails or relayer is unavailable\n * @example\n * ```typescript\n * const grantFile = createGrantFile(params);\n *\n * try {\n * const ipfsUrl = await storeGrantFile(grantFile, 'https://relayer.vana.com');\n * console.log(`Grant file stored at: ${ipfsUrl}`);\n * // ipfsUrl: \"ipfs://QmHash123...\"\n * } catch (error) {\n * console.error('Failed to store grant file:', error);\n * }\n * ```\n */\nexport async function storeGrantFile(\n grantFile: GrantFile,\n relayerUrl: string,\n): Promise<string> {\n try {\n // Convert grant file to blob and use IPFS upload endpoint\n const grantFileBlob = new Blob([JSON.stringify(grantFile, null, 2)], {\n type: \"application/json\",\n });\n\n const formData = new FormData();\n formData.append(\"file\", grantFileBlob, \"grant-file.json\");\n\n const response = await fetch(`${relayerUrl}/api/ipfs/upload`, {\n method: \"POST\",\n body: formData,\n });\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to store grant file: ${response.statusText}`,\n new Error(`HTTP ${response.status}`),\n );\n }\n\n const responseData: unknown = await response.json();\n const data = responseData as GrantFileStorageResponse;\n\n if (!data.success) {\n throw new NetworkError(data.error ?? \"Failed to store grant file\");\n }\n\n if (!data.url) {\n throw new NetworkError(\"Upload succeeded but no URL was returned\");\n }\n return data.url; // The IPFS URL from the upload response\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Network error while storing grant file: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error as Error,\n );\n }\n}\n\n/**\n * Retrieves detailed grant file data from IPFS or HTTP storage.\n *\n * @remarks\n * **This is Step 2 of the performant two-step permission API.**\n *\n * Use this method to resolve detailed permission data (operation, parameters, etc.)\n * for specific grants after first getting the fast on-chain data using\n * `getUserPermissionGrantsOnChain()`. This design eliminates N+1 query problems\n * by allowing selective lazy-loading of expensive off-chain data.\n *\n * **Performance**: Single network request per grant file (typically 100-500ms).\n * **Reliability**: Tries multiple IPFS gateways as fallbacks if primary URL fails.\n *\n * @param grantUrl - The grant file URL from OnChainPermissionGrant.grantUrl\n * @param _relayerUrl - URL of the relayer service (optional, unused)\n * @param downloadRelayer - Optional download relayer for proxying CORS-restricted downloads\n * @param downloadRelayer.proxyDownload - Function to proxy download requests through application server\n * @returns Promise resolving to the complete grant file with operation details\n * @throws {NetworkError} When all retrieval attempts fail\n * @throws {SerializationError} When grant file format is invalid\n * @example\n * ```typescript\n * // Step 1: Fast on-chain data (no N+1 queries)\n * const grants = await vana.permissions.getUserPermissionGrantsOnChain();\n *\n * // Step 2: Lazy-load details for specific grant when needed\n * const grantFile = await retrieveGrantFile(grants[0].grantUrl);\n *\n * console.log(`Operation: ${grantFile.operation}`);\n * console.log(`Grantee: ${grantFile.grantee}`);\n * console.log(`Parameters:`, grantFile.parameters);\n *\n * // Only fetch details for grants user actually wants to see\n * for (const grant of selectedGrants) {\n * const details = await retrieveGrantFile(grant.grantUrl);\n * displayGrantDetails(details);\n * }\n * ```\n */\nexport async function retrieveGrantFile(\n grantUrl: string,\n _relayerUrl?: string,\n downloadRelayer?: { proxyDownload: (url: string) => Promise<Blob> },\n): Promise<GrantFile> {\n try {\n // Check if the URL is a gateway URL instead of ipfs:// protocol\n if (grantUrl.startsWith(\"http\") && grantUrl.includes(\"/ipfs/\")) {\n console.warn(\n `⚠️ Grant URL uses HTTP gateway format instead of ipfs:// protocol. ` +\n `Found: ${grantUrl}. ` +\n `Consider using ipfs:// format for better protocol-agnostic storage.`,\n );\n }\n\n // Use the unified download utility\n const { universalFetch } = await import(\"./download\");\n const response = await universalFetch(grantUrl, downloadRelayer);\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to retrieve grant file: HTTP ${response.status}`,\n );\n }\n\n const text = await response.text();\n const grantFile = JSON.parse(text);\n\n if (!validateGrantFile(grantFile)) {\n throw new NetworkError(`Invalid grant file format from ${grantUrl}`);\n }\n\n return grantFile;\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Error retrieving grant file: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error as Error,\n );\n }\n}\n\n/**\n * Generates a content hash for a grant file.\n * This can be used for integrity verification.\n *\n * @remarks\n * Creates a deterministic keccak256 hash of the grant file by first sorting\n * all object keys recursively to ensure consistent hashing regardless of\n * property order. This hash can be used to verify grant file integrity\n * or as a unique identifier.\n *\n * @param grantFile - The grant file to generate a hash for\n * @returns The keccak256 hash of the grant file as a hex string\n * @throws {SerializationError} When the grant file cannot be serialized\n * @example\n * ```typescript\n * const grantFile = {\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * operation: 'read',\n * parameters: { version: '1.0', mode: 'full' }\n * };\n *\n * const hash = getGrantFileHash(grantFile);\n * console.log(`Grant file hash: ${hash}`);\n * // \"0x1234567890abcdef...\"\n *\n * // Same grant file with different property order produces same hash\n * const grantFile2 = {\n * operation: 'read',\n * parameters: { mode: 'full', version: '1.0' },\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36'\n * };\n *\n * const hash2 = getGrantFileHash(grantFile2);\n * console.log(hash === hash2); // true\n * ```\n */\nexport function getGrantFileHash(grantFile: GrantFile): string {\n try {\n // Create a stable JSON representation\n const sortedFile: GrantFile = {\n grantee: grantFile.grantee,\n operation: grantFile.operation,\n parameters: sortObjectKeys(grantFile.parameters) as Record<\n string,\n unknown\n >,\n };\n\n // Add expires if present\n if (grantFile.expires !== undefined) {\n sortedFile.expires = grantFile.expires;\n }\n\n const jsonString = JSON.stringify(sortedFile);\n console.info(`Hash: ${keccak256(toHex(jsonString))}`);\n return keccak256(toHex(jsonString));\n } catch (error) {\n throw new SerializationError(\n `Failed to generate grant file hash: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Recursively sorts object keys for stable serialization.\n *\n * @param obj - The object to sort keys recursively\n * @returns The object with all keys sorted recursively\n */\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => sortObjectKeys(item));\n }\n\n const sortedObj: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach((key) => {\n sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n });\n\n return sortedObj;\n}\n\n/**\n * Validates that a grant file has the required structure.\n *\n * @remarks\n * Performs runtime validation to ensure data conforms to the GrantFile interface.\n * Checks for required fields (grantee, operation, parameters) and validates their\n * types and formats. This is a type guard function that enables TypeScript to\n * narrow the type when it returns true.\n *\n * @param data - The data to validate as a grant file\n * @returns True if the data is a valid grant file, false otherwise\n * @example\n * ```typescript\n * const unknownData = await fetch(url).then(r => r.json());\n *\n * if (validateGrantFile(unknownData)) {\n * // TypeScript now knows unknownData is a GrantFile\n * console.log(`Grant for operation: ${unknownData.operation}`);\n * console.log(`Grantee: ${unknownData.grantee}`);\n * } else {\n * throw new Error('Invalid grant file format');\n * }\n *\n * // Validation examples:\n * validateGrantFile({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * operation: 'read',\n * parameters: {}\n * }); // true\n *\n * validateGrantFile({\n * grantee: 'invalid-address',\n * operation: 'read',\n * parameters: {}\n * }); // false (invalid address format)\n *\n * validateGrantFile({\n * operation: 'read',\n * parameters: {}\n * }); // false (missing grantee)\n * ```\n */\nexport function validateGrantFile(data: unknown): data is GrantFile {\n if (!data || typeof data !== \"object\") {\n return false;\n }\n\n const obj = data as Record<string, unknown>;\n\n // Validate required fields\n // Validate grantee address\n if (\n typeof obj.grantee !== \"string\" ||\n !obj.grantee.match(/^0x[a-fA-F0-9]{40}$/)\n ) {\n return false;\n }\n\n if (typeof obj.operation !== \"string\" || obj.operation.length === 0) {\n return false;\n }\n\n // Files are no longer stored in grant files - they're tracked in the contract\n\n if (!obj.parameters || typeof obj.parameters !== \"object\") {\n return false;\n }\n\n // Validate optional expires field\n if (obj.expires !== undefined) {\n if (\n typeof obj.expires !== \"number\" ||\n obj.expires < 0 ||\n !Number.isInteger(obj.expires)\n ) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,kBAAiC;AAEjC,oBAAiD;AAuC1C,SAAS,gBAAgB,QAA0C;AACxE,QAAM,YAAuB;AAAA,IAC3B,SAAS,OAAO;AAAA,IAChB,WAAW,OAAO;AAAA,IAClB,YAAY,OAAO;AAAA,EACrB;AAGA,MAAI,OAAO,WAAW;AACpB,cAAU,UAAU,OAAO;AAAA,EAC7B;AAEA,SAAO;AACT;AA2BA,eAAsB,eACpB,WACA,YACiB;AACjB,MAAI;AAEF,UAAM,gBAAgB,IAAI,KAAK,CAAC,KAAK,UAAU,WAAW,MAAM,CAAC,CAAC,GAAG;AAAA,MACnE,MAAM;AAAA,IACR,CAAC;AAED,UAAM,WAAW,IAAI,SAAS;AAC9B,aAAS,OAAO,QAAQ,eAAe,iBAAiB;AAExD,UAAM,WAAW,MAAM,MAAM,GAAG,UAAU,oBAAoB;AAAA,M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U,WAAW,GAAG;AACnE,WAAO;AAAA,EACT;AAIA,MAAI,CAAC,IAAI,cAAc,OAAO,IAAI,eAAe,UAAU;AACzD,WAAO;AAAA,EACT;AAGA,MAAI,IAAI,YAAY,QAAW;AAC7B,QACE,OAAO,IAAI,YAAY,YACvB,IAAI,UAAU,KACd,CAAC,OAAO,UAAU,IAAI,OAAO,GAC7B;AACA,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
1
+ {"version":3,"sources":["../../src/utils/grantFiles.ts"],"sourcesContent":["import { keccak256, toHex } from \"viem\";\nimport type { GrantFile, GrantPermissionParams } from \"../types/permissions\";\nimport { SerializationError, NetworkError } from \"../errors\";\n\ninterface GrantFileStorageResponse {\n success: boolean;\n error?: string;\n url?: string;\n}\n\n/**\n * Creates grant file structure for permission storage.\n *\n * @remarks\n * Constructs JSON structure that represents a permission grant\n * in the Vana protocol. The grant file contains all necessary information\n * for a grantee to perform operations on behalf of the grantor.\n *\n * @param params - Permission parameters to create the grant file from\n * @returns Grant file object for IPFS storage\n *\n * @example\n * ```typescript\n * const grant = createGrantFile({\n * grantee: '0x742d35Cc...',\n * operation: 'llm_inference',\n * parameters: { model: 'gpt-4' },\n * expiresAt: Date.now() + 86400000 // 24 hours\n * });\n * ```\n */\nexport function createGrantFile(params: GrantPermissionParams): GrantFile {\n const grantFile: GrantFile = {\n grantee: params.grantee,\n operation: params.operation,\n parameters: { ...params.parameters },\n };\n\n // Add filters to parameters if provided\n if (params.filters) {\n grantFile.parameters.filters = params.filters;\n }\n\n // Add expiration if provided\n if (params.expiresAt) {\n grantFile.expires = params.expiresAt;\n }\n\n return grantFile;\n}\n\n/**\n * Stores a grant file in IPFS via the relayer service.\n *\n * @remarks\n * This function uploads the grant file to IPFS through the relayer's upload endpoint.\n * The returned URL can be stored on-chain as part of the permission grant, allowing\n * anyone to retrieve the detailed permission parameters later.\n *\n * @param grantFile - The grant file to store\n * @param relayerUrl - URL of the relayer service\n * @returns Promise resolving to the IPFS URL\n * @throws {NetworkError} When the upload fails or relayer is unavailable\n * @example\n * ```typescript\n * const grantFile = createGrantFile(params);\n *\n * try {\n * const ipfsUrl = await storeGrantFile(grantFile, 'https://relayer.vana.com');\n * console.log(`Grant file stored at: ${ipfsUrl}`);\n * // ipfsUrl: \"ipfs://QmHash123...\"\n * } catch (error) {\n * console.error('Failed to store grant file:', error);\n * }\n * ```\n */\nexport async function storeGrantFile(\n grantFile: GrantFile,\n relayerUrl: string,\n): Promise<string> {\n try {\n // Convert grant file to blob and use IPFS upload endpoint\n const grantFileBlob = new Blob([JSON.stringify(grantFile, null, 2)], {\n type: \"application/json\",\n });\n\n const formData = new FormData();\n formData.append(\"file\", grantFileBlob, \"grant-file.json\");\n\n const response = await fetch(`${relayerUrl}/api/ipfs/upload`, {\n method: \"POST\",\n body: formData,\n });\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to store grant file: ${response.statusText}`,\n new Error(`HTTP ${response.status}`),\n );\n }\n\n const responseData: unknown = await response.json();\n const data = responseData as GrantFileStorageResponse;\n\n if (!data.success) {\n throw new NetworkError(data.error ?? \"Failed to store grant file\");\n }\n\n if (!data.url) {\n throw new NetworkError(\"Upload succeeded but no URL was returned\");\n }\n return data.url; // The IPFS URL from the upload response\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Network error while storing grant file: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error as Error,\n );\n }\n}\n\n/**\n * Retrieves detailed grant file data from IPFS or HTTP storage.\n *\n * @remarks\n * **This is Step 2 of the performant two-step permission API.**\n *\n * Use this method to resolve detailed permission data (operation, parameters, etc.)\n * for specific grants after first getting the fast on-chain data using\n * `getUserPermissionGrantsOnChain()`. This design eliminates N+1 query problems\n * by allowing selective lazy-loading of expensive off-chain data.\n *\n * **Performance**: Single network request per grant file (typically 100-500ms).\n * **Reliability**: Tries multiple IPFS gateways as fallbacks if primary URL fails.\n *\n * @param grantUrl - The grant file URL from OnChainPermissionGrant.grantUrl\n * @param _relayerUrl - URL of the relayer service (optional, unused)\n * @param downloadRelayer - Optional download relayer for proxying CORS-restricted downloads\n * @param downloadRelayer.proxyDownload - Function to proxy download requests through application server\n * @returns Promise resolving to the complete grant file with operation details\n * @throws {NetworkError} When all retrieval attempts fail\n * @throws {SerializationError} When grant file format is invalid\n * @example\n * ```typescript\n * // Step 1: Fast on-chain data (no N+1 queries)\n * const grants = await vana.permissions.getUserPermissionGrantsOnChain();\n *\n * // Step 2: Lazy-load details for specific grant when needed\n * const grantFile = await retrieveGrantFile(grants[0].grantUrl);\n *\n * console.log(`Operation: ${grantFile.operation}`);\n * console.log(`Grantee: ${grantFile.grantee}`);\n * console.log(`Parameters:`, grantFile.parameters);\n *\n * // Only fetch details for grants user actually wants to see\n * for (const grant of selectedGrants) {\n * const details = await retrieveGrantFile(grant.grantUrl);\n * displayGrantDetails(details);\n * }\n * ```\n */\nexport async function retrieveGrantFile(\n grantUrl: string,\n _relayerUrl?: string,\n downloadRelayer?: { proxyDownload: (url: string) => Promise<Blob> },\n): Promise<GrantFile> {\n try {\n // Check if the URL is a gateway URL instead of ipfs:// protocol\n if (grantUrl.startsWith(\"http\") && grantUrl.includes(\"/ipfs/\")) {\n console.warn(\n `⚠️ Grant URL uses HTTP gateway format instead of ipfs:// protocol. ` +\n `Found: ${grantUrl}. ` +\n `Consider using ipfs:// format for better protocol-agnostic storage.`,\n );\n }\n\n // Use the unified download utility\n const { universalFetch } = await import(\"./download\");\n const response = await universalFetch(grantUrl, downloadRelayer);\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to retrieve grant file: HTTP ${response.status}`,\n );\n }\n\n const text = await response.text();\n const grantFile = JSON.parse(text);\n\n if (!validateGrantFile(grantFile)) {\n throw new NetworkError(`Invalid grant file format from ${grantUrl}`);\n }\n\n return grantFile;\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error;\n }\n throw new NetworkError(\n `Error retrieving grant file: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n error as Error,\n );\n }\n}\n\n/**\n * Generates a content hash for a grant file.\n * This can be used for integrity verification.\n *\n * @remarks\n * Creates a deterministic keccak256 hash of the grant file by first sorting\n * all object keys recursively to ensure consistent hashing regardless of\n * property order. This hash can be used to verify grant file integrity\n * or as a unique identifier.\n *\n * @param grantFile - The grant file to generate a hash for\n * @returns The keccak256 hash of the grant file as a hex string\n * @throws {SerializationError} When the grant file cannot be serialized\n * @example\n * ```typescript\n * const grantFile = {\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * operation: 'read',\n * parameters: { version: '1.0', mode: 'full' }\n * };\n *\n * const hash = getGrantFileHash(grantFile);\n * console.log(`Grant file hash: ${hash}`);\n * // \"0x1234567890abcdef...\"\n *\n * // Same grant file with different property order produces same hash\n * const grantFile2 = {\n * operation: 'read',\n * parameters: { mode: 'full', version: '1.0' },\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36'\n * };\n *\n * const hash2 = getGrantFileHash(grantFile2);\n * console.log(hash === hash2); // true\n * ```\n */\nexport function getGrantFileHash(grantFile: GrantFile): string {\n try {\n // Create a stable JSON representation\n const sortedFile: GrantFile = {\n grantee: grantFile.grantee,\n operation: grantFile.operation,\n parameters: sortObjectKeys(grantFile.parameters) as Record<\n string,\n unknown\n >,\n };\n\n // Add expires if present\n if (grantFile.expires !== undefined) {\n sortedFile.expires = grantFile.expires;\n }\n\n const jsonString = JSON.stringify(sortedFile);\n console.info(`Hash: ${keccak256(toHex(jsonString))}`);\n return keccak256(toHex(jsonString));\n } catch (error) {\n throw new SerializationError(\n `Failed to generate grant file hash: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n }\n}\n\n/**\n * Recursively sorts object keys for stable serialization.\n *\n * @param obj - The object to sort keys recursively\n * @returns The object with all keys sorted recursively\n */\nfunction sortObjectKeys(obj: unknown): unknown {\n if (obj === null || typeof obj !== \"object\") {\n return obj;\n }\n\n if (Array.isArray(obj)) {\n return obj.map((item) => sortObjectKeys(item));\n }\n\n const sortedObj: Record<string, unknown> = {};\n Object.keys(obj as Record<string, unknown>)\n .sort()\n .forEach((key) => {\n sortedObj[key] = sortObjectKeys((obj as Record<string, unknown>)[key]);\n });\n\n return sortedObj;\n}\n\n/**\n * Validates that a grant file has the required structure.\n *\n * @remarks\n * Performs runtime validation to ensure data conforms to the GrantFile interface.\n * Checks for required fields (grantee, operation, parameters) and validates their\n * types and formats. This is a type guard function that enables TypeScript to\n * narrow the type when it returns true.\n *\n * @param data - The data to validate as a grant file\n * @returns True if the data is a valid grant file, false otherwise\n * @example\n * ```typescript\n * const unknownData = await fetch(url).then(r => r.json());\n *\n * if (validateGrantFile(unknownData)) {\n * // TypeScript now knows unknownData is a GrantFile\n * console.log(`Grant for operation: ${unknownData.operation}`);\n * console.log(`Grantee: ${unknownData.grantee}`);\n * } else {\n * throw new Error('Invalid grant file format');\n * }\n *\n * // Validation examples:\n * validateGrantFile({\n * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',\n * operation: 'read',\n * parameters: {}\n * }); // true\n *\n * validateGrantFile({\n * grantee: 'invalid-address',\n * operation: 'read',\n * parameters: {}\n * }); // false (invalid address format)\n *\n * validateGrantFile({\n * operation: 'read',\n * parameters: {}\n * }); // false (missing grantee)\n * ```\n */\nexport function validateGrantFile(data: unknown): data is GrantFile {\n if (!data || typeof data !== \"object\") {\n return false;\n }\n\n const obj = data as Record<string, unknown>;\n\n // Validate required fields\n // Validate grantee address\n if (\n typeof obj.grantee !== \"string\" ||\n !obj.grantee.match(/^0x[a-fA-F0-9]{40}$/)\n ) {\n return false;\n }\n\n if (typeof obj.operation !== \"string\" || obj.operation.length === 0) {\n return false;\n }\n\n // Files are no longer stored in grant files - they're tracked in the contract\n\n if (!obj.parameters || typeof obj.parameters !== \"object\") {\n return false;\n }\n\n // Validate optional expires field\n if (obj.expires !== undefined) {\n if (\n typeof obj.expires !== \"number\" ||\n obj.expires < 0 ||\n !Number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AAC;AAAA,EACpC,SAAS,OAAO;AACd,UAAM,IAAI;AAAA,MACR,uCAAuC,iBAAiB,QAAQ,MAAM,UAAU,eAAe;AAAA,IACjG;AAAA,EACF;AACF;AAQA,SAAS,eAAe,KAAuB;AAC7C,MAAI,QAAQ,QAAQ,OAAO,QAAQ,UAAU;AAC3C,WAAO;AAAA,EACT;AAEA,MAAI,MAAM,QAAQ,GAAG,GAAG;AACtB,WAAO,IAAI,IAAI,CAAC,SAAS,eAAe,IAAI,CAAC;AAAA,EAC/C;AAEA,QAAM,YAAqC,CAAC;AAC5C,SAAO,KAAK,GAA8B,EACvC,KAAK,EACL,QAAQ,CAAC,QAAQ;AAChB,cAAU,GAAG,IAAI,eAAgB,IAAgC,GAAG,CAAC;AAAA,EACvE,CAAC;AAEH,SAAO;AACT;AA4CO,SAAS,kBAAkB,MAAkC;AAClE,MAAI,CAAC,QAAQ,OAAO,SAAS,UAAU;AACrC,WAAO;AAAA,EACT;AAEA,QAAM,MAAM;AAIZ,MACE,OAAO,IAAI,YAAY,YACvB,CAAC,IAAI,QAAQ,MAAM,qBAAqB,GACxC;AACA,WAAO;AAAA,EACT;AAEA,MAAI,OAAO,IAAI,cAAc,YAAY,IAAI,UAAU,WAAW,GAAG;AACnE,WAAO;AAAA,EACT;AAIA,MAAI,CAAC,IAAI,cAAc,OAAO,IAAI,eAAe,UAAU;AACzD,WAAO;AAAA,EACT;AAGA,MAAI,IAAI,YAAY,QAAW;AAC7B,QACE,OAAO,IAAI,YAAY,YACvB,IAAI,UAAU,KACd,CAAC,OAAO,UAAU,IAAI,OAAO,GAC7B;AACA,aAAO;AAAA,IACT;AAAA,EACF;AAEA,SAAO;AACT;","names":[]}
@@ -1,33 +1,23 @@
1
1
  import type { GrantFile, GrantPermissionParams } from "../types/permissions";
2
2
  /**
3
- * Creates a grant file structure from permission parameters.
3
+ * Creates grant file structure for permission storage.
4
4
  *
5
5
  * @remarks
6
- * This function constructs the JSON structure that represents a permission grant
7
- * in the Vana protocol. The grant file contains all necessary information for
8
- * a grantee to perform operations on behalf of the grantor.
6
+ * Constructs JSON structure that represents a permission grant
7
+ * in the Vana protocol. The grant file contains all necessary information
8
+ * for a grantee to perform operations on behalf of the grantor.
9
+ *
10
+ * @param params - Permission parameters to create the grant file from
11
+ * @returns Grant file object for IPFS storage
9
12
  *
10
- * @param params - The permission parameters to create the grant file from
11
- * @returns The constructed grant file object
12
13
  * @example
13
14
  * ```typescript
14
- * const grantFile = createGrantFile({
15
- * grantee: '0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36',
15
+ * const grant = createGrantFile({
16
+ * grantee: '0x742d35Cc...',
16
17
  * operation: 'llm_inference',
17
- * parameters: {
18
- * model: 'gpt-4',
19
- * maxTokens: 1000
20
- * },
18
+ * parameters: { model: 'gpt-4' },
21
19
  * expiresAt: Date.now() + 86400000 // 24 hours
22
20
  * });
23
- *
24
- * console.log(grantFile);
25
- * // {
26
- * // grantee: '0x742d...',
27
- * // operation: 'llm_inference',
28
- * // parameters: { model: 'gpt-4', maxTokens: 1000 },
29
- * // expires: 1234567890
30
- * // }
31
21
  * ```
32
22
  */
33
23
  export declare function createGrantFile(params: GrantPermissionParams): GrantFile;
@@ -4,8 +4,11 @@ function createGrantFile(params) {
4
4
  const grantFile = {
5
5
  grantee: params.grantee,
6
6
  operation: params.operation,
7
- parameters: params.parameters
7
+ parameters: { ...params.parameters }
8
8
  };
9
+ if (params.filters) {
10
+ grantFile.parameters.filters = params.filters;
11
+ }
9
12
  if (params.expiresAt) {
10
13
  grantFile.expires = params.expiresAt;
11
14
  }