@opendatalabs/vana-sdk 2.3.0 → 3.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 (618) hide show
  1. package/README.md +76 -92
  2. package/dist/auth/errors.cjs +54 -0
  3. package/dist/auth/errors.cjs.map +1 -0
  4. package/dist/auth/errors.d.ts +26 -0
  5. package/dist/auth/errors.js +28 -0
  6. package/dist/auth/errors.js.map +1 -0
  7. package/dist/auth/pkce.cjs +100 -0
  8. package/dist/auth/pkce.cjs.map +1 -0
  9. package/dist/auth/pkce.d.ts +55 -0
  10. package/dist/auth/pkce.js +71 -0
  11. package/dist/auth/pkce.js.map +1 -0
  12. package/dist/auth/token-store.cjs +59 -0
  13. package/dist/auth/token-store.cjs.map +1 -0
  14. package/dist/auth/token-store.d.ts +61 -0
  15. package/dist/auth/token-store.js +35 -0
  16. package/dist/auth/token-store.js.map +1 -0
  17. package/dist/auth/web3-signed-builder.cjs +70 -0
  18. package/dist/auth/web3-signed-builder.cjs.map +1 -0
  19. package/dist/auth/web3-signed-builder.d.ts +47 -0
  20. package/dist/auth/web3-signed-builder.js +45 -0
  21. package/dist/auth/web3-signed-builder.js.map +1 -0
  22. package/dist/auth/web3-signed.cjs +125 -0
  23. package/dist/auth/web3-signed.cjs.map +1 -0
  24. package/dist/auth/web3-signed.d.ts +59 -0
  25. package/dist/auth/web3-signed.js +104 -0
  26. package/dist/auth/web3-signed.js.map +1 -0
  27. package/dist/chains/definitions.cjs +2 -6
  28. package/dist/chains/definitions.cjs.map +1 -1
  29. package/dist/chains/definitions.d.ts +1 -7
  30. package/dist/chains/definitions.js +2 -6
  31. package/dist/chains/definitions.js.map +1 -1
  32. package/dist/config/chains.d.ts +18 -0
  33. package/dist/config/contracts.config.cjs +7 -95
  34. package/dist/config/contracts.config.cjs.map +1 -1
  35. package/dist/config/contracts.config.d.ts +0 -54
  36. package/dist/config/contracts.config.js +6 -93
  37. package/dist/config/contracts.config.js.map +1 -1
  38. package/dist/config/default-services.cjs +0 -10
  39. package/dist/config/default-services.cjs.map +1 -1
  40. package/dist/config/default-services.d.ts +1 -20
  41. package/dist/config/default-services.js +0 -9
  42. package/dist/config/default-services.js.map +1 -1
  43. package/dist/crypto/ecies/interface.cjs +2 -0
  44. package/dist/crypto/ecies/interface.cjs.map +1 -1
  45. package/dist/crypto/ecies/interface.js +2 -0
  46. package/dist/crypto/ecies/interface.js.map +1 -1
  47. package/dist/crypto/envelope/openpgp.cjs +59 -0
  48. package/dist/crypto/envelope/openpgp.cjs.map +1 -0
  49. package/dist/crypto/envelope/openpgp.d.ts +28 -0
  50. package/dist/crypto/envelope/openpgp.js +24 -0
  51. package/dist/crypto/envelope/openpgp.js.map +1 -0
  52. package/dist/crypto/keys/derive.cjs +65 -0
  53. package/dist/crypto/keys/derive.cjs.map +1 -0
  54. package/dist/crypto/keys/derive.d.ts +45 -0
  55. package/dist/crypto/keys/derive.js +38 -0
  56. package/dist/crypto/keys/derive.js.map +1 -0
  57. package/dist/errors.cjs +10 -0
  58. package/dist/errors.cjs.map +1 -1
  59. package/dist/errors.js +10 -0
  60. package/dist/errors.js.map +1 -1
  61. package/dist/generated/abi/index.cjs +2 -37
  62. package/dist/generated/abi/index.cjs.map +1 -1
  63. package/dist/generated/abi/index.d.ts +2683 -9296
  64. package/dist/generated/abi/index.js +2 -29
  65. package/dist/generated/abi/index.js.map +1 -1
  66. package/dist/generated/addresses.cjs +5 -107
  67. package/dist/generated/addresses.cjs.map +1 -1
  68. package/dist/generated/addresses.d.ts +5 -99
  69. package/dist/generated/addresses.js +5 -105
  70. package/dist/generated/addresses.js.map +1 -1
  71. package/dist/index.browser.d.ts +23 -140
  72. package/dist/index.browser.js +32090 -114
  73. package/dist/index.browser.js.map +7 -1
  74. package/dist/index.node.cjs +32809 -160
  75. package/dist/index.node.cjs.map +7 -1
  76. package/dist/index.node.d.ts +22 -210
  77. package/dist/index.node.js +32716 -133
  78. package/dist/index.node.js.map +7 -1
  79. package/dist/protocol/data-file.cjs +56 -0
  80. package/dist/protocol/data-file.cjs.map +1 -0
  81. package/dist/protocol/data-file.d.ts +20 -0
  82. package/dist/protocol/data-file.js +30 -0
  83. package/dist/protocol/data-file.js.map +1 -0
  84. package/dist/protocol/eip712.cjs +123 -0
  85. package/dist/protocol/eip712.cjs.map +1 -0
  86. package/dist/protocol/eip712.d.ts +117 -0
  87. package/dist/protocol/eip712.js +90 -0
  88. package/dist/protocol/eip712.js.map +1 -0
  89. package/dist/protocol/gateway.cjs +226 -0
  90. package/dist/protocol/gateway.cjs.map +1 -0
  91. package/dist/protocol/gateway.d.ts +120 -0
  92. package/dist/protocol/gateway.js +202 -0
  93. package/dist/protocol/gateway.js.map +1 -0
  94. package/dist/protocol/scopes.cjs +78 -0
  95. package/dist/protocol/scopes.cjs.map +1 -0
  96. package/dist/protocol/scopes.d.ts +13 -0
  97. package/dist/protocol/scopes.js +50 -0
  98. package/dist/protocol/scopes.js.map +1 -0
  99. package/dist/{types/atomicStore.cjs → storage/default.cjs} +9 -8
  100. package/dist/storage/default.cjs.map +1 -0
  101. package/dist/storage/default.d.ts +4 -0
  102. package/dist/storage/default.js +8 -0
  103. package/dist/storage/default.js.map +1 -0
  104. package/dist/storage/index.cjs +11 -2
  105. package/dist/storage/index.cjs.map +1 -1
  106. package/dist/storage/index.d.ts +9 -0
  107. package/dist/storage/index.js +7 -1
  108. package/dist/storage/index.js.map +1 -1
  109. package/dist/storage/providers/callback-storage.cjs +1 -0
  110. package/dist/storage/providers/callback-storage.cjs.map +1 -1
  111. package/dist/storage/providers/callback-storage.js +1 -0
  112. package/dist/storage/providers/callback-storage.js.map +1 -1
  113. package/dist/storage/providers/dropbox.cjs +1 -0
  114. package/dist/storage/providers/dropbox.cjs.map +1 -1
  115. package/dist/storage/providers/dropbox.js +1 -0
  116. package/dist/storage/providers/dropbox.js.map +1 -1
  117. package/dist/storage/providers/google-drive.cjs +1 -0
  118. package/dist/storage/providers/google-drive.cjs.map +1 -1
  119. package/dist/storage/providers/google-drive.js +1 -0
  120. package/dist/storage/providers/google-drive.js.map +1 -1
  121. package/dist/storage/providers/ipfs.cjs +1 -0
  122. package/dist/storage/providers/ipfs.cjs.map +1 -1
  123. package/dist/storage/providers/ipfs.js +1 -0
  124. package/dist/storage/providers/ipfs.js.map +1 -1
  125. package/dist/storage/providers/pinata.cjs +1 -0
  126. package/dist/storage/providers/pinata.cjs.map +1 -1
  127. package/dist/storage/providers/pinata.js +1 -0
  128. package/dist/storage/providers/pinata.js.map +1 -1
  129. package/dist/storage/providers/r2.cjs +376 -0
  130. package/dist/storage/providers/r2.cjs.map +1 -0
  131. package/dist/storage/providers/r2.d.ts +91 -0
  132. package/dist/storage/providers/r2.js +354 -0
  133. package/dist/storage/providers/r2.js.map +1 -0
  134. package/dist/storage/providers/vana-storage.cjs +251 -0
  135. package/dist/storage/providers/vana-storage.cjs.map +1 -0
  136. package/dist/storage/providers/vana-storage.d.ts +100 -0
  137. package/dist/storage/providers/vana-storage.js +231 -0
  138. package/dist/storage/providers/vana-storage.js.map +1 -0
  139. package/dist/types/config.cjs +0 -34
  140. package/dist/types/config.cjs.map +1 -1
  141. package/dist/types/config.d.ts +1 -607
  142. package/dist/types/config.js +0 -22
  143. package/dist/types/config.js.map +1 -1
  144. package/dist/types/contracts.cjs.map +1 -1
  145. package/dist/types/contracts.d.ts +1 -1
  146. package/dist/types/index.cjs +2 -33
  147. package/dist/types/index.cjs.map +1 -1
  148. package/dist/types/index.d.ts +2 -33
  149. package/dist/types/index.js +1 -35
  150. package/dist/types/index.js.map +1 -1
  151. package/dist/types/ps-errors.cjs +66 -0
  152. package/dist/types/ps-errors.cjs.map +1 -0
  153. package/dist/types/ps-errors.d.ts +25 -0
  154. package/dist/types/ps-errors.js +41 -0
  155. package/dist/types/ps-errors.js.map +1 -0
  156. package/dist/types.cjs.map +1 -1
  157. package/dist/types.d.ts +0 -29
  158. package/dist/types.js.map +1 -1
  159. package/package.json +7 -25
  160. package/dist/client/enhancedResponse.cjs +0 -164
  161. package/dist/client/enhancedResponse.cjs.map +0 -1
  162. package/dist/client/enhancedResponse.d.ts +0 -120
  163. package/dist/client/enhancedResponse.js +0 -138
  164. package/dist/client/enhancedResponse.js.map +0 -1
  165. package/dist/controllers/__tests__/data-consistency-integration.test.d.ts +0 -7
  166. package/dist/controllers/base.cjs +0 -116
  167. package/dist/controllers/base.cjs.map +0 -1
  168. package/dist/controllers/base.d.ts +0 -94
  169. package/dist/controllers/base.js +0 -92
  170. package/dist/controllers/base.js.map +0 -1
  171. package/dist/controllers/data.cjs +0 -2633
  172. package/dist/controllers/data.cjs.map +0 -1
  173. package/dist/controllers/data.d.ts +0 -1067
  174. package/dist/controllers/data.js +0 -2626
  175. package/dist/controllers/data.js.map +0 -1
  176. package/dist/controllers/operations.cjs +0 -430
  177. package/dist/controllers/operations.cjs.map +0 -1
  178. package/dist/controllers/operations.d.ts +0 -229
  179. package/dist/controllers/operations.js +0 -406
  180. package/dist/controllers/operations.js.map +0 -1
  181. package/dist/controllers/permissions.cjs +0 -4368
  182. package/dist/controllers/permissions.cjs.map +0 -1
  183. package/dist/controllers/permissions.d.ts +0 -1411
  184. package/dist/controllers/permissions.js +0 -4344
  185. package/dist/controllers/permissions.js.map +0 -1
  186. package/dist/controllers/protocol.cjs +0 -183
  187. package/dist/controllers/protocol.cjs.map +0 -1
  188. package/dist/controllers/protocol.d.ts +0 -138
  189. package/dist/controllers/protocol.js +0 -163
  190. package/dist/controllers/protocol.js.map +0 -1
  191. package/dist/controllers/schemas.cjs +0 -678
  192. package/dist/controllers/schemas.cjs.map +0 -1
  193. package/dist/controllers/schemas.d.ts +0 -293
  194. package/dist/controllers/schemas.js +0 -654
  195. package/dist/controllers/schemas.js.map +0 -1
  196. package/dist/controllers/server.cjs +0 -643
  197. package/dist/controllers/server.cjs.map +0 -1
  198. package/dist/controllers/server.d.ts +0 -322
  199. package/dist/controllers/server.js +0 -624
  200. package/dist/controllers/server.js.map +0 -1
  201. package/dist/controllers/staking.cjs +0 -626
  202. package/dist/controllers/staking.cjs.map +0 -1
  203. package/dist/controllers/staking.d.ts +0 -457
  204. package/dist/controllers/staking.js +0 -602
  205. package/dist/controllers/staking.js.map +0 -1
  206. package/dist/core/__tests__/pollingManager.test.d.ts +0 -4
  207. package/dist/core/apiClient.cjs +0 -378
  208. package/dist/core/apiClient.cjs.map +0 -1
  209. package/dist/core/apiClient.d.ts +0 -286
  210. package/dist/core/apiClient.js +0 -359
  211. package/dist/core/apiClient.js.map +0 -1
  212. package/dist/core/generics.cjs +0 -417
  213. package/dist/core/generics.cjs.map +0 -1
  214. package/dist/core/generics.d.ts +0 -205
  215. package/dist/core/generics.js +0 -386
  216. package/dist/core/generics.js.map +0 -1
  217. package/dist/core/health.cjs +0 -289
  218. package/dist/core/health.cjs.map +0 -1
  219. package/dist/core/health.d.ts +0 -143
  220. package/dist/core/health.js +0 -265
  221. package/dist/core/health.js.map +0 -1
  222. package/dist/core/inMemoryNonceManager.cjs +0 -138
  223. package/dist/core/inMemoryNonceManager.cjs.map +0 -1
  224. package/dist/core/inMemoryNonceManager.d.ts +0 -69
  225. package/dist/core/inMemoryNonceManager.js +0 -114
  226. package/dist/core/inMemoryNonceManager.js.map +0 -1
  227. package/dist/core/nonceManager.cjs +0 -304
  228. package/dist/core/nonceManager.cjs.map +0 -1
  229. package/dist/core/nonceManager.d.ts +0 -116
  230. package/dist/core/nonceManager.js +0 -280
  231. package/dist/core/nonceManager.js.map +0 -1
  232. package/dist/core/pollingManager.cjs +0 -292
  233. package/dist/core/pollingManager.cjs.map +0 -1
  234. package/dist/core/pollingManager.d.ts +0 -120
  235. package/dist/core/pollingManager.js +0 -268
  236. package/dist/core/pollingManager.js.map +0 -1
  237. package/dist/core.cjs +0 -781
  238. package/dist/core.cjs.map +0 -1
  239. package/dist/core.d.ts +0 -496
  240. package/dist/core.js +0 -756
  241. package/dist/core.js.map +0 -1
  242. package/dist/diagnostics.cjs +0 -37
  243. package/dist/diagnostics.cjs.map +0 -1
  244. package/dist/diagnostics.d.ts +0 -24
  245. package/dist/diagnostics.js +0 -13
  246. package/dist/diagnostics.js.map +0 -1
  247. package/dist/diagnostics.test.d.ts +0 -1
  248. package/dist/generated/abi/DLPPerformanceImplementation.cjs +0 -1202
  249. package/dist/generated/abi/DLPPerformanceImplementation.cjs.map +0 -1
  250. package/dist/generated/abi/DLPPerformanceImplementation.d.ts +0 -914
  251. package/dist/generated/abi/DLPPerformanceImplementation.js +0 -1178
  252. package/dist/generated/abi/DLPPerformanceImplementation.js.map +0 -1
  253. package/dist/generated/abi/DLPRewardDeployerImplementation.cjs +0 -1112
  254. package/dist/generated/abi/DLPRewardDeployerImplementation.cjs.map +0 -1
  255. package/dist/generated/abi/DLPRewardDeployerImplementation.d.ts +0 -840
  256. package/dist/generated/abi/DLPRewardDeployerImplementation.js +0 -1088
  257. package/dist/generated/abi/DLPRewardDeployerImplementation.js.map +0 -1
  258. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.cjs +0 -612
  259. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.cjs.map +0 -1
  260. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.d.ts +0 -451
  261. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.js +0 -588
  262. package/dist/generated/abi/DLPRewardDeployerTreasuryImplementation.js.map +0 -1
  263. package/dist/generated/abi/DLPRewardSwapImplementation.cjs +0 -939
  264. package/dist/generated/abi/DLPRewardSwapImplementation.cjs.map +0 -1
  265. package/dist/generated/abi/DLPRewardSwapImplementation.d.ts +0 -705
  266. package/dist/generated/abi/DLPRewardSwapImplementation.js +0 -915
  267. package/dist/generated/abi/DLPRewardSwapImplementation.js.map +0 -1
  268. package/dist/generated/abi/DLPRootImplementation.cjs +0 -1644
  269. package/dist/generated/abi/DLPRootImplementation.cjs.map +0 -1
  270. package/dist/generated/abi/DLPRootImplementation.d.ts +0 -1246
  271. package/dist/generated/abi/DLPRootImplementation.js +0 -1620
  272. package/dist/generated/abi/DLPRootImplementation.js.map +0 -1
  273. package/dist/generated/abi/DataLiquidityPoolImplementation.cjs +0 -985
  274. package/dist/generated/abi/DataLiquidityPoolImplementation.cjs.map +0 -1
  275. package/dist/generated/abi/DataLiquidityPoolImplementation.d.ts +0 -735
  276. package/dist/generated/abi/DataLiquidityPoolImplementation.js +0 -961
  277. package/dist/generated/abi/DataLiquidityPoolImplementation.js.map +0 -1
  278. package/dist/generated/abi/SwapHelperImplementation.cjs +0 -976
  279. package/dist/generated/abi/SwapHelperImplementation.cjs.map +0 -1
  280. package/dist/generated/abi/SwapHelperImplementation.d.ts +0 -728
  281. package/dist/generated/abi/SwapHelperImplementation.js +0 -952
  282. package/dist/generated/abi/SwapHelperImplementation.js.map +0 -1
  283. package/dist/generated/abi/TeePoolImplementation.cjs +0 -1313
  284. package/dist/generated/abi/TeePoolImplementation.cjs.map +0 -1
  285. package/dist/generated/abi/TeePoolImplementation.d.ts +0 -992
  286. package/dist/generated/abi/TeePoolImplementation.js +0 -1289
  287. package/dist/generated/abi/TeePoolImplementation.js.map +0 -1
  288. package/dist/generated/event-types.cjs +0 -17
  289. package/dist/generated/event-types.cjs.map +0 -1
  290. package/dist/generated/event-types.d.ts +0 -816
  291. package/dist/generated/event-types.js +0 -1
  292. package/dist/generated/event-types.js.map +0 -1
  293. package/dist/generated/eventRegistry.cjs +0 -4512
  294. package/dist/generated/eventRegistry.cjs.map +0 -1
  295. package/dist/generated/eventRegistry.d.ts +0 -14
  296. package/dist/generated/eventRegistry.js +0 -4487
  297. package/dist/generated/eventRegistry.js.map +0 -1
  298. package/dist/generated/server/server-exports.cjs +0 -45
  299. package/dist/generated/server/server-exports.cjs.map +0 -1
  300. package/dist/generated/server/server-exports.d.ts +0 -36
  301. package/dist/generated/server/server-exports.js +0 -19
  302. package/dist/generated/server/server-exports.js.map +0 -1
  303. package/dist/generated/server/server.cjs +0 -17
  304. package/dist/generated/server/server.cjs.map +0 -1
  305. package/dist/generated/server/server.d.ts +0 -907
  306. package/dist/generated/server/server.js +0 -1
  307. package/dist/generated/server/server.js.map +0 -1
  308. package/dist/generated/subgraph.cjs +0 -1440
  309. package/dist/generated/subgraph.cjs.map +0 -1
  310. package/dist/generated/subgraph.d.ts +0 -6113
  311. package/dist/generated/subgraph.js +0 -1404
  312. package/dist/generated/subgraph.js.map +0 -1
  313. package/dist/lib/__tests__/redisAtomicStore.test.d.ts +0 -1
  314. package/dist/lib/redisAtomicStore.cjs +0 -201
  315. package/dist/lib/redisAtomicStore.cjs.map +0 -1
  316. package/dist/lib/redisAtomicStore.d.ts +0 -120
  317. package/dist/lib/redisAtomicStore.js +0 -177
  318. package/dist/lib/redisAtomicStore.js.map +0 -1
  319. package/dist/server/relayerHandler.cjs +0 -452
  320. package/dist/server/relayerHandler.cjs.map +0 -1
  321. package/dist/server/relayerHandler.d.ts +0 -69
  322. package/dist/server/relayerHandler.js +0 -428
  323. package/dist/server/relayerHandler.js.map +0 -1
  324. package/dist/tests/abi.test.d.ts +0 -1
  325. package/dist/tests/chains-definitions.test.d.ts +0 -1
  326. package/dist/tests/core-encryption.test.d.ts +0 -1
  327. package/dist/tests/core-extended.test.d.ts +0 -1
  328. package/dist/tests/core-generics-coverage.test.d.ts +0 -1
  329. package/dist/tests/coverage-boost.test.d.ts +0 -1
  330. package/dist/tests/crypto-cross-platform-compatibility.test.d.ts +0 -1
  331. package/dist/tests/data-addfile-permissions-schema.test.d.ts +0 -1
  332. package/dist/tests/data-additional-methods.test.d.ts +0 -1
  333. package/dist/tests/data-controller-edge-cases.test.d.ts +0 -1
  334. package/dist/tests/data-ipfs-gateways.test.d.ts +0 -1
  335. package/dist/tests/data-relayer.test.d.ts +0 -1
  336. package/dist/tests/data-schema-validation.test.d.ts +0 -1
  337. package/dist/tests/data-simple-methods.test.d.ts +0 -1
  338. package/dist/tests/data-upload-owner-validation.test.d.ts +0 -1
  339. package/dist/tests/data.test.d.ts +0 -1
  340. package/dist/tests/demo-integration.test.d.ts +0 -1
  341. package/dist/tests/demo-trusted-server-integration.test.d.ts +0 -1
  342. package/dist/tests/download-relayer.test.d.ts +0 -1
  343. package/dist/tests/dual-mode-permissions.test.d.ts +0 -1
  344. package/dist/tests/dual-mode-trusted-servers.test.d.ts +0 -1
  345. package/dist/tests/encryption-correct-implementation.test.d.ts +0 -1
  346. package/dist/tests/encryption-coverage.test.d.ts +0 -1
  347. package/dist/tests/encryption-edge-cases.test.d.ts +0 -1
  348. package/dist/tests/encryption-utils-updated.test.d.ts +0 -1
  349. package/dist/tests/errors-coverage.test.d.ts +0 -1
  350. package/dist/tests/factories/mockFactory.d.ts +0 -316
  351. package/dist/tests/fakes/FakeStorageManager.d.ts +0 -200
  352. package/dist/tests/fakes/FakeStorageManager.test.d.ts +0 -1
  353. package/dist/tests/fakes/FakeWaitForTransactionEvents.d.ts +0 -170
  354. package/dist/tests/fakes/FakeWaitForTransactionEvents.test.d.ts +0 -1
  355. package/dist/tests/fakes/fake-pgp-port.d.ts +0 -13
  356. package/dist/tests/grantValidation-edge-cases.test.d.ts +0 -1
  357. package/dist/tests/grantValidation-unreachable-branch.test.d.ts +0 -1
  358. package/dist/tests/helper-methods.test.d.ts +0 -1
  359. package/dist/tests/helpers/typedMocks.d.ts +0 -64
  360. package/dist/tests/index-browser.test.d.ts +0 -1
  361. package/dist/tests/index-node.test.d.ts +0 -1
  362. package/dist/tests/index.test.d.ts +0 -1
  363. package/dist/tests/mocks/platformAdapter.d.ts +0 -12
  364. package/dist/tests/new-permissions-methods.test.d.ts +0 -1
  365. package/dist/tests/no-buffer-browser.test.d.ts +0 -1
  366. package/dist/tests/permissions-grantee.test.d.ts +0 -1
  367. package/dist/tests/permissions-revoke-relayer.test.d.ts +0 -1
  368. package/dist/tests/permissions-schema-validation.test.d.ts +0 -1
  369. package/dist/tests/permissions-server-files.test.d.ts +0 -1
  370. package/dist/tests/permissions-transaction-options.test.d.ts +0 -1
  371. package/dist/tests/permissions-trust-servers.test.d.ts +0 -1
  372. package/dist/tests/permissions.test.d.ts +0 -1
  373. package/dist/tests/personal.test.d.ts +0 -1
  374. package/dist/tests/platform-browser.test.d.ts +0 -1
  375. package/dist/tests/platform-crypto-expanded.test.d.ts +0 -1
  376. package/dist/tests/platform-crypto.test.d.ts +0 -1
  377. package/dist/tests/platform-index.test.d.ts +0 -1
  378. package/dist/tests/platform-node.test.d.ts +0 -1
  379. package/dist/tests/platform-shared-utils.test.d.ts +0 -1
  380. package/dist/tests/platform-updated.test.d.ts +0 -1
  381. package/dist/tests/protocol-additional-methods.test.d.ts +0 -1
  382. package/dist/tests/protocol.test.d.ts +0 -1
  383. package/dist/tests/read-only-mode.test.d.ts +0 -1
  384. package/dist/tests/relayer-integration.test.d.ts +0 -1
  385. package/dist/tests/relayer-unified.test.d.ts +0 -1
  386. package/dist/tests/schemas.test.d.ts +0 -1
  387. package/dist/tests/server-relayer-handler.test.d.ts +0 -1
  388. package/dist/tests/signatureFormatter.test.d.ts +0 -1
  389. package/dist/tests/staking.test.d.ts +0 -1
  390. package/dist/tests/trusted-server-queries.test.d.ts +0 -1
  391. package/dist/tests/typedDataConverter.test.d.ts +0 -1
  392. package/dist/tests/types-contracts.test.d.ts +0 -1
  393. package/dist/tests/types-data.test.d.ts +0 -1
  394. package/dist/tests/types-external-apis.test.d.ts +0 -1
  395. package/dist/tests/types-generics.test.d.ts +0 -1
  396. package/dist/tests/types-permissions.test.d.ts +0 -1
  397. package/dist/tests/types-upload-params.test.d.ts +0 -1
  398. package/dist/tests/types.test.d.ts +0 -1
  399. package/dist/tests/utils-formatters.test.d.ts +0 -1
  400. package/dist/tests/utils-grantFiles-edge-cases.test.d.ts +0 -1
  401. package/dist/tests/utils-grantFiles-validation.test.d.ts +0 -1
  402. package/dist/tests/utils-grantFiles.test.d.ts +0 -1
  403. package/dist/tests/utils-grantValidation-consolidated.test.d.ts +0 -1
  404. package/dist/tests/utils-grants.test.d.ts +0 -1
  405. package/dist/tests/utils-ipfs-additional.test.d.ts +0 -1
  406. package/dist/tests/utils-ipfs.test.d.ts +0 -4
  407. package/dist/tests/utils-schemaValidation.test.d.ts +0 -1
  408. package/dist/tests/vana.test.d.ts +0 -1
  409. package/dist/tests/wallet-crypto-compatibility.test.d.ts +0 -1
  410. package/dist/types/atomicStore.cjs.map +0 -1
  411. package/dist/types/atomicStore.d.ts +0 -236
  412. package/dist/types/atomicStore.js +0 -7
  413. package/dist/types/atomicStore.js.map +0 -1
  414. package/dist/types/blockchain.cjs +0 -17
  415. package/dist/types/blockchain.cjs.map +0 -1
  416. package/dist/types/blockchain.d.ts +0 -85
  417. package/dist/types/blockchain.js +0 -1
  418. package/dist/types/blockchain.js.map +0 -1
  419. package/dist/types/controller-context.cjs +0 -17
  420. package/dist/types/controller-context.cjs.map +0 -1
  421. package/dist/types/controller-context.d.ts +0 -68
  422. package/dist/types/controller-context.js +0 -1
  423. package/dist/types/controller-context.js.map +0 -1
  424. package/dist/types/data.cjs +0 -17
  425. package/dist/types/data.cjs.map +0 -1
  426. package/dist/types/data.d.ts +0 -763
  427. package/dist/types/data.js +0 -1
  428. package/dist/types/data.js.map +0 -1
  429. package/dist/types/external-apis.cjs +0 -61
  430. package/dist/types/external-apis.cjs.map +0 -1
  431. package/dist/types/external-apis.d.ts +0 -184
  432. package/dist/types/external-apis.js +0 -34
  433. package/dist/types/external-apis.js.map +0 -1
  434. package/dist/types/generics.cjs +0 -17
  435. package/dist/types/generics.cjs.map +0 -1
  436. package/dist/types/generics.d.ts +0 -518
  437. package/dist/types/generics.js +0 -1
  438. package/dist/types/generics.js.map +0 -1
  439. package/dist/types/operationStore.cjs +0 -17
  440. package/dist/types/operationStore.cjs.map +0 -1
  441. package/dist/types/operationStore.d.ts +0 -171
  442. package/dist/types/operationStore.js +0 -1
  443. package/dist/types/operationStore.js.map +0 -1
  444. package/dist/types/operations.cjs +0 -53
  445. package/dist/types/operations.cjs.map +0 -1
  446. package/dist/types/operations.d.ts +0 -204
  447. package/dist/types/operations.js +0 -26
  448. package/dist/types/operations.js.map +0 -1
  449. package/dist/types/options.cjs +0 -17
  450. package/dist/types/options.cjs.map +0 -1
  451. package/dist/types/options.d.ts +0 -308
  452. package/dist/types/options.js +0 -1
  453. package/dist/types/options.js.map +0 -1
  454. package/dist/types/permissions.cjs +0 -17
  455. package/dist/types/permissions.cjs.map +0 -1
  456. package/dist/types/permissions.d.ts +0 -955
  457. package/dist/types/permissions.js +0 -1
  458. package/dist/types/permissions.js.map +0 -1
  459. package/dist/types/personal.cjs +0 -17
  460. package/dist/types/personal.cjs.map +0 -1
  461. package/dist/types/personal.d.ts +0 -174
  462. package/dist/types/personal.js +0 -1
  463. package/dist/types/personal.js.map +0 -1
  464. package/dist/types/relayer.cjs +0 -17
  465. package/dist/types/relayer.cjs.map +0 -1
  466. package/dist/types/relayer.d.ts +0 -552
  467. package/dist/types/relayer.js +0 -1
  468. package/dist/types/relayer.js.map +0 -1
  469. package/dist/types/transactionResults.cjs +0 -17
  470. package/dist/types/transactionResults.cjs.map +0 -1
  471. package/dist/types/transactionResults.d.ts +0 -193
  472. package/dist/types/transactionResults.js +0 -1
  473. package/dist/types/transactionResults.js.map +0 -1
  474. package/dist/types/utils.cjs +0 -17
  475. package/dist/types/utils.cjs.map +0 -1
  476. package/dist/types/utils.d.ts +0 -771
  477. package/dist/types/utils.js +0 -1
  478. package/dist/types/utils.js.map +0 -1
  479. package/dist/utils/__tests__/chainQuery.test.d.ts +0 -1
  480. package/dist/utils/__tests__/parseTransaction.test.d.ts +0 -1
  481. package/dist/utils/__tests__/pojo-serialization.test.d.ts +0 -1
  482. package/dist/utils/__tests__/signatureCache.test.d.ts +0 -1
  483. package/dist/utils/__tests__/subgraphConsistency.test.d.ts +0 -4
  484. package/dist/utils/__tests__/subgraphPagination.test.d.ts +0 -4
  485. package/dist/utils/__tests__/transaction-edge-cases.test.d.ts +0 -1
  486. package/dist/utils/__tests__/transactionHelpers.test.d.ts +0 -1
  487. package/dist/utils/__tests__/urlResolver.test.d.ts +0 -4
  488. package/dist/utils/blockchain/registry.cjs +0 -81
  489. package/dist/utils/blockchain/registry.cjs.map +0 -1
  490. package/dist/utils/blockchain/registry.d.ts +0 -32
  491. package/dist/utils/blockchain/registry.js +0 -56
  492. package/dist/utils/blockchain/registry.js.map +0 -1
  493. package/dist/utils/blockchain/registry.test.d.ts +0 -1
  494. package/dist/utils/chainQuery.cjs +0 -107
  495. package/dist/utils/chainQuery.cjs.map +0 -1
  496. package/dist/utils/chainQuery.d.ts +0 -31
  497. package/dist/utils/chainQuery.js +0 -82
  498. package/dist/utils/chainQuery.js.map +0 -1
  499. package/dist/utils/download.cjs +0 -69
  500. package/dist/utils/download.cjs.map +0 -1
  501. package/dist/utils/download.d.ts +0 -40
  502. package/dist/utils/download.js +0 -45
  503. package/dist/utils/download.js.map +0 -1
  504. package/dist/utils/encryption.cjs +0 -176
  505. package/dist/utils/encryption.cjs.map +0 -1
  506. package/dist/utils/encryption.d.ts +0 -271
  507. package/dist/utils/encryption.js +0 -142
  508. package/dist/utils/encryption.js.map +0 -1
  509. package/dist/utils/formatters.cjs +0 -55
  510. package/dist/utils/formatters.cjs.map +0 -1
  511. package/dist/utils/formatters.d.ts +0 -118
  512. package/dist/utils/formatters.js +0 -28
  513. package/dist/utils/formatters.js.map +0 -1
  514. package/dist/utils/grantFiles.cjs +0 -181
  515. package/dist/utils/grantFiles.cjs.map +0 -1
  516. package/dist/utils/grantFiles.d.ts +0 -172
  517. package/dist/utils/grantFiles.js +0 -143
  518. package/dist/utils/grantFiles.js.map +0 -1
  519. package/dist/utils/grantValidation.cjs +0 -243
  520. package/dist/utils/grantValidation.cjs.map +0 -1
  521. package/dist/utils/grantValidation.d.ts +0 -226
  522. package/dist/utils/grantValidation.js +0 -201
  523. package/dist/utils/grantValidation.js.map +0 -1
  524. package/dist/utils/grants.cjs +0 -108
  525. package/dist/utils/grants.cjs.map +0 -1
  526. package/dist/utils/grants.d.ts +0 -148
  527. package/dist/utils/grants.js +0 -82
  528. package/dist/utils/grants.js.map +0 -1
  529. package/dist/utils/ipfs.cjs +0 -128
  530. package/dist/utils/ipfs.cjs.map +0 -1
  531. package/dist/utils/ipfs.d.ts +0 -88
  532. package/dist/utils/ipfs.js +0 -97
  533. package/dist/utils/ipfs.js.map +0 -1
  534. package/dist/utils/multicall.cjs +0 -233
  535. package/dist/utils/multicall.cjs.map +0 -1
  536. package/dist/utils/multicall.d.ts +0 -126
  537. package/dist/utils/multicall.js +0 -208
  538. package/dist/utils/multicall.js.map +0 -1
  539. package/dist/utils/parseTransactionPojo.cjs +0 -87
  540. package/dist/utils/parseTransactionPojo.cjs.map +0 -1
  541. package/dist/utils/parseTransactionPojo.d.ts +0 -31
  542. package/dist/utils/parseTransactionPojo.js +0 -63
  543. package/dist/utils/parseTransactionPojo.js.map +0 -1
  544. package/dist/utils/schemaValidation.cjs +0 -258
  545. package/dist/utils/schemaValidation.cjs.map +0 -1
  546. package/dist/utils/schemaValidation.d.ts +0 -168
  547. package/dist/utils/schemaValidation.js +0 -219
  548. package/dist/utils/schemaValidation.js.map +0 -1
  549. package/dist/utils/signatureCache.cjs +0 -192
  550. package/dist/utils/signatureCache.cjs.map +0 -1
  551. package/dist/utils/signatureCache.d.ts +0 -172
  552. package/dist/utils/signatureCache.js +0 -167
  553. package/dist/utils/signatureCache.js.map +0 -1
  554. package/dist/utils/signatureFormatter.cjs +0 -42
  555. package/dist/utils/signatureFormatter.cjs.map +0 -1
  556. package/dist/utils/signatureFormatter.d.ts +0 -36
  557. package/dist/utils/signatureFormatter.js +0 -18
  558. package/dist/utils/signatureFormatter.js.map +0 -1
  559. package/dist/utils/subgraphConsistency.cjs +0 -184
  560. package/dist/utils/subgraphConsistency.cjs.map +0 -1
  561. package/dist/utils/subgraphConsistency.d.ts +0 -65
  562. package/dist/utils/subgraphConsistency.js +0 -155
  563. package/dist/utils/subgraphConsistency.js.map +0 -1
  564. package/dist/utils/subgraphMetaCache.cjs +0 -101
  565. package/dist/utils/subgraphMetaCache.cjs.map +0 -1
  566. package/dist/utils/subgraphMetaCache.d.ts +0 -56
  567. package/dist/utils/subgraphMetaCache.js +0 -76
  568. package/dist/utils/subgraphMetaCache.js.map +0 -1
  569. package/dist/utils/subgraphPagination.cjs +0 -104
  570. package/dist/utils/subgraphPagination.cjs.map +0 -1
  571. package/dist/utils/subgraphPagination.d.ts +0 -78
  572. package/dist/utils/subgraphPagination.js +0 -78
  573. package/dist/utils/subgraphPagination.js.map +0 -1
  574. package/dist/utils/tests/multicall.test.d.ts +0 -1
  575. package/dist/utils/transactionHelpers.cjs +0 -54
  576. package/dist/utils/transactionHelpers.cjs.map +0 -1
  577. package/dist/utils/transactionHelpers.d.ts +0 -80
  578. package/dist/utils/transactionHelpers.js +0 -29
  579. package/dist/utils/transactionHelpers.js.map +0 -1
  580. package/dist/utils/typeGuards.cjs +0 -109
  581. package/dist/utils/typeGuards.cjs.map +0 -1
  582. package/dist/utils/typeGuards.d.ts +0 -138
  583. package/dist/utils/typeGuards.js +0 -74
  584. package/dist/utils/typeGuards.js.map +0 -1
  585. package/dist/utils/typedDataConverter.cjs +0 -43
  586. package/dist/utils/typedDataConverter.cjs.map +0 -1
  587. package/dist/utils/typedDataConverter.d.ts +0 -46
  588. package/dist/utils/typedDataConverter.js +0 -19
  589. package/dist/utils/typedDataConverter.js.map +0 -1
  590. package/dist/utils/urlResolver.cjs +0 -62
  591. package/dist/utils/urlResolver.cjs.map +0 -1
  592. package/dist/utils/urlResolver.d.ts +0 -56
  593. package/dist/utils/urlResolver.js +0 -37
  594. package/dist/utils/urlResolver.js.map +0 -1
  595. package/dist/utils/wallet.cjs +0 -63
  596. package/dist/utils/wallet.cjs.map +0 -1
  597. package/dist/utils/wallet.d.ts +0 -94
  598. package/dist/utils/wallet.js +0 -37
  599. package/dist/utils/wallet.js.map +0 -1
  600. package/dist/utils/withEvents.cjs +0 -44
  601. package/dist/utils/withEvents.cjs.map +0 -1
  602. package/dist/utils/withEvents.d.ts +0 -56
  603. package/dist/utils/withEvents.js +0 -18
  604. package/dist/utils/withEvents.js.map +0 -1
  605. /package/dist/{__tests__/waitForTransactionEvents.test.d.ts → auth/pkce.test.d.ts} +0 -0
  606. /package/dist/{client/__tests__/enhancedResponse.test.d.ts → auth/token-store.test.d.ts} +0 -0
  607. /package/dist/{controllers/__tests__/operations.processQueue.test.d.ts → auth/web3-signed.test.d.ts} +0 -0
  608. /package/dist/{controllers/__tests__/schemas-edge-cases.test.d.ts → crypto/envelope/openpgp.test.d.ts} +0 -0
  609. /package/dist/{controllers/data-error-handling.test.d.ts → crypto/keys/derive.test.d.ts} +0 -0
  610. /package/dist/{tests/errors.test.d.ts → errors.test.d.ts} +0 -0
  611. /package/dist/{controllers/server-additional.test.d.ts → protocol/data-file.test.d.ts} +0 -0
  612. /package/dist/{core/__tests__/health.test.d.ts → protocol/eip712.test.d.ts} +0 -0
  613. /package/dist/{core/__tests__/inMemoryNonceManager.test.d.ts → protocol/gateway.test.d.ts} +0 -0
  614. /package/dist/{core/__tests__/nonceManager.test.d.ts → protocol/scopes.test.d.ts} +0 -0
  615. /package/dist/{core/core.test.d.ts → storage/tests/defaultStorage.test.d.ts} +0 -0
  616. /package/dist/{core/tests/apiClient.test.d.ts → storage/tests/r2Storage.test.d.ts} +0 -0
  617. /package/dist/{core/tests/client.test.d.ts → storage/tests/vanaStorage.test.d.ts} +0 -0
  618. /package/dist/{core/tests/generics.test.d.ts → types/ps-errors.test.d.ts} +0 -0
@@ -1,4368 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
- var permissions_exports = {};
30
- __export(permissions_exports, {
31
- PermissionsController: () => PermissionsController
32
- });
33
- module.exports = __toCommonJS(permissions_exports);
34
- var import_viem = require("viem");
35
- var import_multicall = require("../utils/multicall");
36
- var import_pollingManager = require("../core/pollingManager");
37
- var import_errors = require("../errors");
38
- var import_addresses = require("../generated/addresses");
39
- var import_abi = require("../generated/abi");
40
- var import_grantFiles = require("../utils/grantFiles");
41
- var import_grantValidation = require("../utils/grantValidation");
42
- var import_signatureCache = require("../utils/signatureCache");
43
- var import_signatureFormatter = require("../utils/signatureFormatter");
44
- var import_typedDataConverter = require("../utils/typedDataConverter");
45
- var import_base = require("./base");
46
- const MAX_UINT256 = 115792089237316195423570985008687907853269984665640564039457584007913129639935n;
47
- class PermissionsController extends import_base.BaseController {
48
- constructor(context) {
49
- super(context);
50
- }
51
- /**
52
- * Grants permission for an application to access user data with gasless transactions.
53
- *
54
- * This method provides a complete end-to-end permission grant flow that returns
55
- * the permission ID and other relevant data immediately after successful submission.
56
- * For advanced users who need more control over the transaction lifecycle, use
57
- * `submitPermissionGrant()` instead.
58
- *
59
- * @param params - The permission grant configuration object
60
- * @returns Promise resolving to permission data from the PermissionAdded event
61
- * @throws {RelayerError} When gasless transaction submission fails
62
- * @throws {SignatureError} When user rejects the signature request
63
- * @throws {SerializationError} When grant data cannot be serialized
64
- * @throws {BlockchainError} When permission grant fails or event parsing fails
65
- * @throws {NetworkError} When transaction confirmation times out
66
- * @example
67
- * ```typescript
68
- * const result = await vana.permissions.grant({
69
- * grantee: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
70
- * operation: "llm_inference",
71
- * parameters: {
72
- * model: "gpt-4",
73
- * maxTokens: 1000,
74
- * temperature: 0.7,
75
- * },
76
- * });
77
- *
78
- * console.log(`Permission ${result.permissionId} granted to ${result.user}`);
79
- * console.log(`Transaction: ${result.transactionHash}`);
80
- *
81
- * // Can immediately use the permission ID for other operations
82
- * await vana.permissions.revoke({ permissionId: result.permissionId });
83
- * ```
84
- */
85
- async grant(params, options) {
86
- this.assertWallet();
87
- const { typedData, signature } = await this.createAndSign(params);
88
- const result = await this.submitSignedGrantWithEvents(
89
- typedData,
90
- signature,
91
- options
92
- );
93
- return result;
94
- }
95
- /**
96
- * Submits a permission grant transaction and returns a handle for flexible result access.
97
- *
98
- * @remarks
99
- * This lower-level method provides maximum control over transaction timing.
100
- * Returns a TransactionResult that can be serialized and passed across API boundaries.
101
- * Use this when handling multiple transactions or when you need granular control.
102
- *
103
- * @param params - The permission grant configuration object
104
- * @returns Promise resolving to TransactionResult with hash and event parsing capabilities
105
- * @throws {RelayerError} When gasless transaction submission fails
106
- * @throws {SignatureError} When user rejects the signature request
107
- * @throws {SerializationError} When grant data cannot be serialized
108
- * @throws {BlockchainError} When permission grant preparation fails
109
- * @example
110
- * ```typescript
111
- * // Submit transaction and get immediate hash access
112
- * const tx = await vana.permissions.submitPermissionGrant(params);
113
- * console.log(`Transaction submitted: ${tx.hash}`);
114
- *
115
- * // To wait for events, use SDK's waitForTransactionEvents
116
- * const eventData = await vana.waitForTransactionEvents(tx.hash);
117
- * console.log(`Permission ID: ${eventData.permissionId}`);
118
- * ```
119
- */
120
- async submitPermissionGrant(params, options) {
121
- this.assertWallet();
122
- const { typedData, signature } = await this.createAndSign(params);
123
- return await this.submitSignedGrant(typedData, signature, options);
124
- }
125
- /**
126
- * Prepares a permission grant with preview before signing.
127
- *
128
- * @remarks
129
- * This method implements a two-phase commit workflow that allows applications
130
- * to show users a preview of what they're authorizing before requesting a signature.
131
- * Unlike `createAndSign()`, this method does NOT upload to IPFS or prompt for signatures
132
- * until the returned `confirm()` function is called.
133
- * @param params - The permission grant parameters
134
- * @returns A promise resolving to a preview object and confirm function
135
- * @throws {SerializationError} When grant parameters are invalid or cannot be serialized
136
- * @throws {BlockchainError} When grant validation fails or preparation encounters an error
137
- * @example
138
- * ```typescript
139
- * const { preview, confirm } = await vana.permissions.prepareGrant({
140
- * grantee: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
141
- * operation: "llm_inference",
142
- * files: [1, 2, 3],
143
- * parameters: { model: "gpt-4", prompt: "Analyze my social media data" }
144
- * });
145
- *
146
- * console.log(`Granting ${preview.operation} access to ${preview.files?.length} files`);
147
- * const transactionHash = await confirm();
148
- * ```
149
- */
150
- async prepareGrant(params, options) {
151
- this.assertWallet();
152
- try {
153
- const grantFile = (0, import_grantFiles.createGrantFile)(params);
154
- (0, import_grantValidation.validateGrant)(grantFile);
155
- return {
156
- preview: grantFile,
157
- confirm: async () => {
158
- return await this.confirmGrantInternalWithEvents(
159
- params,
160
- grantFile,
161
- options
162
- );
163
- }
164
- };
165
- } catch (error) {
166
- if (error instanceof Error) {
167
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
168
- throw error;
169
- }
170
- throw new import_errors.BlockchainError(
171
- `Permission grant preparation failed: ${error.message}`,
172
- error
173
- );
174
- }
175
- throw new import_errors.BlockchainError(
176
- "Permission grant preparation failed with unknown error"
177
- );
178
- }
179
- }
180
- /**
181
- * Completes the grant process after user confirmation.
182
- *
183
- * @remarks
184
- * This internal method is called by the confirm() function returned from prepareGrant().
185
- * It handles IPFS upload, signature creation, and transaction submission.
186
- *
187
- * @param params - The permission grant parameters containing user and operation details
188
- * @param grantFile - The prepared grant file with permissions and metadata
189
- * @returns Promise resolving to TransactionResult for flexible result access
190
- * @throws {BlockchainError} When permission grant confirmation fails
191
- * @throws {NetworkError} When IPFS upload fails
192
- * @throws {SignatureError} When user rejects the signature
193
- */
194
- async confirmGrantInternal(params, grantFile, options) {
195
- try {
196
- let { grantUrl } = params;
197
- console.debug("\u{1F50D} Debug - Grant URL from params:", grantUrl);
198
- if (!grantUrl) {
199
- const canStoreViaRelayer = this.context.relayer !== void 0;
200
- if (!canStoreViaRelayer && !this.context.storageManager) {
201
- if (this.context.validateStorageRequired) {
202
- this.context.validateStorageRequired();
203
- } else {
204
- throw new Error(
205
- "No storage available. Provide a grantUrl, configure relayer, or storageManager."
206
- );
207
- }
208
- }
209
- if (canStoreViaRelayer && this.context.relayer) {
210
- const request = {
211
- type: "direct",
212
- operation: "storeGrantFile",
213
- params: grantFile
214
- };
215
- const response = await this.context.relayer(request);
216
- if (response.type === "error") {
217
- throw new Error(response.error);
218
- }
219
- if (response.type === "direct" && typeof response.result === "object" && response.result !== null && "url" in response.result) {
220
- grantUrl = response.result.url;
221
- } else {
222
- throw new Error("Invalid response from relayer for grant storage");
223
- }
224
- } else if (this.context.storageManager) {
225
- const blob = new Blob([JSON.stringify(grantFile)], {
226
- type: "application/json"
227
- });
228
- const result = await this.context.storageManager.upload(
229
- blob,
230
- `grant-${Date.now()}.json`
231
- );
232
- grantUrl = result.url;
233
- }
234
- if (!grantUrl) {
235
- throw new Error("Failed to store grant file - no URL returned");
236
- }
237
- }
238
- const nonce = await this.getPermissionsUserNonce();
239
- console.debug(
240
- "\u{1F50D} Debug - Final grant URL being passed to compose:",
241
- grantUrl
242
- );
243
- const typedData = await this.composePermissionGrantMessage({
244
- grantee: params.grantee,
245
- operation: params.operation,
246
- // Placeholder - real data is in IPFS
247
- files: params.files,
248
- // Placeholder - real data is in IPFS
249
- grantUrl,
250
- serializedParameters: (0, import_grantFiles.getGrantFileHash)(grantFile),
251
- // Hash as placeholder
252
- nonce
253
- });
254
- const signature = await this.signTypedData(typedData);
255
- return await this.submitSignedGrant(typedData, signature, options);
256
- } catch (error) {
257
- if (error instanceof Error) {
258
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
259
- throw error;
260
- }
261
- throw new import_errors.BlockchainError(
262
- `Permission grant confirmation failed: ${error.message}`,
263
- error
264
- );
265
- }
266
- throw new import_errors.BlockchainError(
267
- "Permission grant confirmation failed with unknown error"
268
- );
269
- }
270
- }
271
- /**
272
- * Creates typed data and signature for a permission grant without submitting.
273
- *
274
- * @remarks
275
- * This method handles the first phase of permission granting: creating the grant file,
276
- * storing it on IPFS, and generating the user's EIP-712 signature. Use this when you
277
- * want to handle submission separately or batch multiple operations. The method validates
278
- * the grant file against the JSON schema before creating the signature.
279
- *
280
- * For interactive user flows, consider using `prepareGrant()` instead,
281
- * which allows showing a preview before signing.
282
- * @param params - The permission grant configuration object
283
- * @returns A promise resolving to the typed data structure and signature for gasless submission
284
- * @throws {SignatureError} When the user rejects the signature request
285
- * @throws {SerializationError} When grant data cannot be properly formatted
286
- * @throws {BlockchainError} When permission grant preparation fails
287
- * @throws {NetworkError} When storage operations fail
288
- * @example
289
- * ```typescript
290
- * const { typedData, signature } = await vana.permissions.createAndSign({
291
- * grantee: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
292
- * operation: "data_analysis",
293
- * parameters: { analysisType: "sentiment" },
294
- * });
295
- *
296
- * const transactionHash = await vana.permissions.submitSignedGrant(typedData, signature);
297
- * ```
298
- */
299
- async createAndSign(params) {
300
- this.assertWallet();
301
- try {
302
- const grantFile = (0, import_grantFiles.createGrantFile)(params);
303
- (0, import_grantValidation.validateGrant)(grantFile);
304
- let { grantUrl } = params;
305
- console.debug("\u{1F50D} Debug - Grant URL from params:", grantUrl);
306
- if (!grantUrl) {
307
- const canStoreViaRelayer = this.context.relayer !== void 0;
308
- if (!canStoreViaRelayer && !this.context.storageManager) {
309
- if (this.context.validateStorageRequired) {
310
- this.context.validateStorageRequired();
311
- } else {
312
- throw new Error(
313
- "No storage available. Provide a grantUrl, configure relayer, or storageManager."
314
- );
315
- }
316
- }
317
- if (canStoreViaRelayer && this.context.relayer) {
318
- const request = {
319
- type: "direct",
320
- operation: "storeGrantFile",
321
- params: grantFile
322
- };
323
- const response = await this.context.relayer(request);
324
- if (response.type === "error") {
325
- throw new Error(response.error);
326
- }
327
- if (response.type === "direct" && typeof response.result === "object" && response.result !== null && "url" in response.result) {
328
- grantUrl = response.result.url;
329
- } else {
330
- throw new Error("Invalid response from relayer for grant storage");
331
- }
332
- } else if (this.context.storageManager) {
333
- const blob = new Blob([JSON.stringify(grantFile)], {
334
- type: "application/json"
335
- });
336
- const result = await this.context.storageManager.upload(
337
- blob,
338
- `grant-${Date.now()}.json`
339
- );
340
- grantUrl = result.url;
341
- }
342
- if (!grantUrl) {
343
- throw new Error("Failed to store grant file - no URL returned");
344
- }
345
- }
346
- const nonce = await this.getPermissionsUserNonce();
347
- console.debug(
348
- "\u{1F50D} Debug - Final grant URL being passed to compose:",
349
- grantUrl
350
- );
351
- const typedData = await this.composePermissionGrantMessage({
352
- grantee: params.grantee,
353
- operation: params.operation,
354
- // Placeholder - real data is in IPFS
355
- files: params.files,
356
- // Placeholder - real data is in IPFS
357
- grantUrl,
358
- serializedParameters: (0, import_grantFiles.getGrantFileHash)(grantFile),
359
- // Hash as placeholder
360
- nonce
361
- });
362
- const signature = await this.signTypedData(typedData);
363
- return { typedData, signature };
364
- } catch (error) {
365
- if (error instanceof Error) {
366
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
367
- throw error;
368
- }
369
- throw new import_errors.BlockchainError(
370
- `Permission grant preparation failed: ${error.message}`,
371
- error
372
- );
373
- }
374
- throw new import_errors.BlockchainError(
375
- "Permission grant preparation failed with unknown error"
376
- );
377
- }
378
- }
379
- /**
380
- * Submits an already-signed permission grant to the blockchain.
381
- *
382
- * @remarks
383
- * This method supports both relayer-based gasless transactions and direct transactions.
384
- * It automatically converts `bigint` values to JSON-safe strings when using relayer
385
- * callbacks and handles transaction submission with proper error handling and retry logic.
386
- * @param typedData - The EIP-712 typed data structure for the permission grant
387
- * @param signature - The user's signature as a hex string
388
- * @returns A Promise that resolves to the transaction hash
389
- * @throws {RelayerError} When gasless transaction submission fails
390
- * @throws {BlockchainError} When permission submission fails
391
- * @throws {NetworkError} When network communication fails
392
- * @example
393
- * ```typescript
394
- * const txHash = await vana.permissions.submitSignedGrant(
395
- * typedData,
396
- * "0x1234..."
397
- * );
398
- * ```
399
- */
400
- async submitSignedGrant(typedData, signature, options) {
401
- try {
402
- console.debug(
403
- "\u{1F50D} Debug - submitSignedGrant called with typed data:",
404
- JSON.stringify(
405
- typedData,
406
- (_key, value) => typeof value === "bigint" ? value.toString() : value,
407
- 2
408
- )
409
- );
410
- if (this.context.relayer) {
411
- const response = await this.context.relayer({
412
- type: "signed",
413
- operation: "submitAddPermission",
414
- typedData,
415
- signature,
416
- expectedUserAddress: this.context.userAddress
417
- });
418
- if (response.type === "error") {
419
- throw new Error(`Relayer error: ${response.error}`);
420
- }
421
- let finalHash;
422
- if (response.type === "submitted") {
423
- finalHash = response.hash;
424
- } else if (response.type === "pending") {
425
- const pollResult = await this.pollRelayerForConfirmation(
426
- response.operationId,
427
- options
428
- );
429
- finalHash = pollResult.hash;
430
- } else if (response.type === "confirmed") {
431
- finalHash = response.hash;
432
- } else if (response.type === "signed") {
433
- finalHash = response.hash;
434
- } else {
435
- throw new Error(
436
- "Invalid response from relayer: unexpected response type"
437
- );
438
- }
439
- const account = this.context.walletClient?.account ?? this.context.userAddress;
440
- const { tx } = await import("../utils/transactionHelpers");
441
- return tx({
442
- hash: finalHash,
443
- from: typeof account === "string" ? account : account.address,
444
- contract: "DataPortabilityPermissions",
445
- fn: "addPermission"
446
- });
447
- } else {
448
- return await this.submitDirectTransaction(
449
- typedData,
450
- signature,
451
- options
452
- );
453
- }
454
- } catch (error) {
455
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.NetworkError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SignatureError || error instanceof import_errors.NonceError) {
456
- throw error;
457
- }
458
- throw new import_errors.BlockchainError(
459
- `Permission submission failed: ${error instanceof Error ? error.message : "Unknown error"}`,
460
- error
461
- );
462
- }
463
- }
464
- /**
465
- * Submits an already-signed trust server transaction to the blockchain.
466
- *
467
- * @remarks
468
- * This method extracts the trust server input from typed data and submits it directly.
469
- * Used internally by trust server methods after signature collection.
470
- *
471
- * @param typedData - The EIP-712 typed data for TrustServer
472
- * @param signature - The user's signature obtained via `signTypedData()`
473
- * @returns Promise resolving to TransactionResult for transaction tracking
474
- * @throws {BlockchainError} When contract submission fails
475
- * @throws {NetworkError} When blockchain communication fails
476
- * @example
477
- * ```typescript
478
- * const txHandle = await vana.permissions.submitSignedTrustServer(
479
- * typedData,
480
- * "0x1234..."
481
- * );
482
- * const result = await txHandle.waitForEvents();
483
- * ```
484
- */
485
- async submitSignedTrustServer(typedData, signature, options) {
486
- try {
487
- const trustServerInput = {
488
- nonce: BigInt(typedData.message.nonce),
489
- serverId: typedData.message.serverId
490
- };
491
- const hash = await this.submitTrustServerTransaction(
492
- trustServerInput,
493
- signature,
494
- options
495
- );
496
- const account = this.context.userAddress;
497
- const { tx } = await import("../utils/transactionHelpers");
498
- return tx({
499
- hash,
500
- from: account,
501
- contract: "DataPortabilityServers",
502
- fn: "trustServerWithSignature"
503
- });
504
- } catch (error) {
505
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.NetworkError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SignatureError || error instanceof import_errors.NonceError) {
506
- throw error;
507
- }
508
- if (error instanceof Error && error.message.includes("ServerUrlMismatch")) {
509
- const match = error.message.match(
510
- /ServerUrlMismatch\(string existingUrl, string providedUrl\)\s+\(([^,]+),\s*([^)]+)\)/
511
- );
512
- if (match) {
513
- const existingUrl = match[1].trim();
514
- const providedUrl = match[2].trim();
515
- throw new import_errors.ServerUrlMismatchError(
516
- existingUrl,
517
- providedUrl,
518
- typedData.message.serverId.toString()
519
- );
520
- }
521
- }
522
- throw new import_errors.BlockchainError(
523
- `Trust server submission failed: ${error instanceof Error ? error.message : "Unknown error"}`,
524
- error
525
- );
526
- }
527
- }
528
- /**
529
- * Submits an already-signed add and trust server transaction to the blockchain.
530
- *
531
- * @remarks
532
- * This method extracts the add and trust server input from typed data and submits it directly.
533
- * Combines server registration and trust operations in a single transaction.
534
- *
535
- * @param typedData - The EIP-712 typed data for AddAndTrustServer
536
- * @param signature - The user's signature obtained via `signTypedData()`
537
- * @returns Promise resolving to TransactionResult for transaction tracking
538
- * @throws {BlockchainError} When contract submission fails
539
- * @throws {NetworkError} When blockchain communication fails
540
- * @example
541
- * ```typescript
542
- * const txHandle = await vana.permissions.submitSignedAddAndTrustServer(
543
- * typedData,
544
- * "0x1234..."
545
- * );
546
- * const result = await txHandle.waitForEvents();
547
- * ```
548
- */
549
- async submitSignedAddAndTrustServer(typedData, signature, options) {
550
- try {
551
- const addAndTrustServerInput = {
552
- nonce: BigInt(typedData.message.nonce),
553
- serverAddress: typedData.message.serverAddress,
554
- serverUrl: typedData.message.serverUrl,
555
- publicKey: typedData.message.publicKey
556
- };
557
- const hash = await this.submitAddAndTrustServerTransaction(
558
- addAndTrustServerInput,
559
- signature,
560
- options
561
- );
562
- const account = this.context.walletClient?.account ?? this.context.userAddress;
563
- const { tx } = await import("../utils/transactionHelpers");
564
- return tx({
565
- hash,
566
- from: typeof account === "string" ? account : account.address,
567
- contract: "DataPortabilityServers",
568
- fn: "addAndTrustServerWithSignature"
569
- });
570
- } catch (error) {
571
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.NetworkError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SignatureError || error instanceof import_errors.NonceError) {
572
- throw error;
573
- }
574
- throw new import_errors.BlockchainError(
575
- `Add and trust server submission failed444444: ${error instanceof Error ? error.message : "Unknown error"}`,
576
- error
577
- );
578
- }
579
- }
580
- /**
581
- * Internal method to submit a signed grant and wait for events.
582
- *
583
- * @internal
584
- * @param typedData - The EIP-712 typed data for the permission grant
585
- * @param signature - The user's signature authorizing the transaction
586
- * @returns Promise resolving to PermissionGrantResult with parsed events
587
- */
588
- async submitSignedGrantWithEvents(typedData, signature, options) {
589
- const txResult = await this.submitSignedGrant(
590
- typedData,
591
- signature,
592
- options
593
- );
594
- if (!this.context.waitForTransactionEvents) {
595
- throw new import_errors.BlockchainError("waitForTransactionEvents not configured");
596
- }
597
- const result = await this.context.waitForTransactionEvents(txResult);
598
- const event = result.expectedEvents.PermissionAdded;
599
- if (!event) {
600
- throw new import_errors.BlockchainError(
601
- "PermissionAdded event not found in transaction"
602
- );
603
- }
604
- const receipt = await this.context.publicClient.getTransactionReceipt({
605
- hash: result.hash
606
- });
607
- return {
608
- transactionHash: result.hash,
609
- blockNumber: receipt.blockNumber,
610
- gasUsed: receipt.gasUsed,
611
- permissionId: event.permissionId,
612
- user: event.user,
613
- grant: event.grant,
614
- fileIds: event.fileIds
615
- };
616
- }
617
- /**
618
- * Internal method for confirm grant with events.
619
- *
620
- * @internal
621
- * @param params - The permission grant parameters
622
- * @param grantFile - The pre-created grant file object
623
- * @returns Promise resolving to PermissionGrantResult with parsed events
624
- */
625
- async confirmGrantInternalWithEvents(params, grantFile, options) {
626
- const txResult = await this.confirmGrantInternal(
627
- params,
628
- grantFile,
629
- options
630
- );
631
- if (!this.context.waitForTransactionEvents) {
632
- throw new import_errors.BlockchainError("waitForTransactionEvents not configured");
633
- }
634
- const result = await this.context.waitForTransactionEvents(txResult);
635
- const event = result.expectedEvents.PermissionAdded;
636
- if (!event) {
637
- throw new import_errors.BlockchainError(
638
- "PermissionAdded event not found in transaction"
639
- );
640
- }
641
- const receipt = await this.context.publicClient.getTransactionReceipt({
642
- hash: result.hash
643
- });
644
- return {
645
- transactionHash: result.hash,
646
- blockNumber: receipt.blockNumber,
647
- gasUsed: receipt.gasUsed,
648
- permissionId: event.permissionId,
649
- user: event.user,
650
- grant: event.grant,
651
- fileIds: event.fileIds
652
- };
653
- }
654
- /**
655
- * Polls the relayer for confirmation of a pending operation.
656
- *
657
- * @param operationId - The operation ID to poll
658
- * @param options - Polling configuration including status updates and cancellation
659
- * @returns Promise resolving to the confirmed hash and receipt
660
- * @throws {TransactionPendingError} When the operation times out
661
- * @throws {Error} When the operation fails or is cancelled
662
- * @internal
663
- */
664
- async pollRelayerForConfirmation(operationId, options) {
665
- if (!this.context.relayer) {
666
- throw new Error("Relayer not configured for polling");
667
- }
668
- const pollingManager = new import_pollingManager.PollingManager(this.context.relayer);
669
- return await pollingManager.startPolling(operationId, {
670
- signal: options?.signal,
671
- onStatusUpdate: options?.onStatusUpdate,
672
- ...options?.pollingOptions
673
- });
674
- }
675
- /**
676
- * Submits an already-signed permission revoke transaction to the blockchain.
677
- *
678
- * @remarks
679
- * This method handles the revocation of previously granted permissions.
680
- * Used internally by revocation methods after signature collection.
681
- *
682
- * @param typedData - The EIP-712 typed data for PermissionRevoke
683
- * @param signature - The user's signature obtained via `signTypedData()`
684
- * @returns Promise resolving to TransactionResult for transaction tracking
685
- * @throws {BlockchainError} When contract submission fails
686
- * @throws {NetworkError} When blockchain communication fails
687
- * @example
688
- * ```typescript
689
- * const txHandle = await vana.permissions.submitSignedRevoke(
690
- * typedData,
691
- * "0x1234..."
692
- * );
693
- * const result = await txHandle.waitForEvents();
694
- * ```
695
- */
696
- async submitSignedRevoke(typedData, signature, options) {
697
- try {
698
- let hash;
699
- if (this.context.relayer) {
700
- const response = await this.context.relayer({
701
- type: "signed",
702
- operation: "submitPermissionRevoke",
703
- typedData,
704
- signature,
705
- expectedUserAddress: this.context.userAddress
706
- });
707
- if (response.type === "error") {
708
- throw new Error(`Relayer error: ${response.error}`);
709
- }
710
- if (response.type === "submitted") {
711
- hash = response.hash;
712
- } else if (response.type === "pending") {
713
- const pollResult = await this.pollRelayerForConfirmation(
714
- response.operationId,
715
- options
716
- );
717
- hash = pollResult.hash;
718
- } else if (response.type === "confirmed") {
719
- hash = response.hash;
720
- } else if (response.type === "signed") {
721
- hash = response.hash;
722
- } else {
723
- throw new Error(
724
- "Invalid response from relayer: unexpected response type"
725
- );
726
- }
727
- } else {
728
- hash = await this.submitDirectRevokeTransaction(
729
- typedData,
730
- signature,
731
- options
732
- );
733
- }
734
- const account = this.context.walletClient?.account ?? this.context.userAddress;
735
- const { tx } = await import("../utils/transactionHelpers");
736
- return tx({
737
- hash,
738
- from: typeof account === "string" ? account : account.address,
739
- contract: "DataPortabilityPermissions",
740
- fn: "revokePermissionWithSignature"
741
- });
742
- } catch (error) {
743
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.NetworkError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SignatureError || error instanceof import_errors.NonceError) {
744
- throw error;
745
- }
746
- throw new import_errors.BlockchainError(
747
- `Permission revoke submission failed: ${error instanceof Error ? error.message : "Unknown error"}`,
748
- error
749
- );
750
- }
751
- }
752
- /**
753
- * Submits an already-signed untrust server transaction to the blockchain.
754
- *
755
- * @remarks
756
- * This method handles the removal of trusted servers.
757
- * Used internally by untrust server methods after signature collection.
758
- *
759
- * @param typedData - The EIP-712 typed data for UntrustServer
760
- * @param signature - The user's signature obtained via `signTypedData()`
761
- * @returns Promise resolving to TransactionResult for transaction tracking
762
- * @throws {BlockchainError} When contract submission fails
763
- * @throws {NetworkError} When blockchain communication fails
764
- * @example
765
- * ```typescript
766
- * const txHandle = await vana.permissions.submitSignedUntrustServer(
767
- * typedData,
768
- * "0x1234..."
769
- * );
770
- * const result = await txHandle.waitForEvents();
771
- * ```
772
- */
773
- async submitSignedUntrustServer(typedData, signature, options) {
774
- try {
775
- let hash;
776
- if (this.context.relayer) {
777
- const response = await this.context.relayer({
778
- type: "signed",
779
- operation: "submitUntrustServer",
780
- typedData,
781
- signature,
782
- expectedUserAddress: this.context.userAddress
783
- });
784
- if (response.type === "submitted") {
785
- hash = response.hash;
786
- } else if (response.type === "signed") {
787
- hash = response.hash;
788
- } else if (response.type === "error") {
789
- throw new Error(`Relayer error: ${response.error}`);
790
- } else {
791
- throw new Error(
792
- "Invalid response from relayer: expected signed transaction"
793
- );
794
- }
795
- } else {
796
- hash = await this.submitSignedUntrustTransaction(
797
- typedData,
798
- signature,
799
- options
800
- );
801
- }
802
- const account = this.context.walletClient?.account ?? this.context.userAddress;
803
- const { tx } = await import("../utils/transactionHelpers");
804
- return tx({
805
- hash,
806
- from: typeof account === "string" ? account : account.address,
807
- contract: "DataPortabilityServers",
808
- fn: "untrustServerWithSignature"
809
- });
810
- } catch (error) {
811
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.NetworkError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SignatureError || error instanceof import_errors.NonceError) {
812
- throw error;
813
- }
814
- throw new import_errors.BlockchainError(
815
- `Untrust server submission failed: ${error instanceof Error ? error.message : "Unknown error"}`,
816
- error
817
- );
818
- }
819
- }
820
- /**
821
- * Submits a signed transaction directly to the blockchain.
822
- *
823
- * @remarks
824
- * Internal method used when relayer callbacks are not available. Formats the signature
825
- * and submits the permission grant directly to the smart contract.
826
- *
827
- * @param typedData - The typed data structure for the permission grant
828
- * @param signature - The cryptographic signature authorizing the transaction
829
- * @returns Promise resolving to the transaction hash
830
- * @throws {BlockchainError} When contract submission fails
831
- */
832
- async submitDirectTransaction(typedData, signature, options) {
833
- this.assertWallet();
834
- const chainId = await this.context.publicClient.getChainId();
835
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
836
- chainId,
837
- "DataPortabilityPermissions"
838
- );
839
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)("DataPortabilityPermissions");
840
- const permissionInput = {
841
- nonce: typedData.message.nonce,
842
- granteeId: typedData.message.granteeId,
843
- grant: typedData.message.grant,
844
- fileIds: typedData.message.fileIds
845
- };
846
- console.debug("\u{1F50D} Debug - Permission input being sent to contract:", {
847
- nonce: permissionInput.nonce.toString(),
848
- grant: permissionInput.grant,
849
- fileIds: permissionInput.fileIds.map((id) => id.toString())
850
- });
851
- console.debug("\u{1F50D} Debug - Grant field value:", typedData.message.grant);
852
- console.debug(
853
- "\u{1F50D} Debug - Grant field length:",
854
- typedData.message.grant?.length ?? 0
855
- );
856
- const formattedSignature = (0, import_signatureFormatter.formatSignatureForContract)(signature);
857
- const account = this.context.walletClient?.account ?? this.context.userAddress;
858
- const txHash = await this.context.walletClient.writeContract({
859
- address: DataPortabilityPermissionsAddress,
860
- abi: DataPortabilityPermissionsAbi,
861
- functionName: "addPermission",
862
- args: [permissionInput, formattedSignature],
863
- account,
864
- chain: this.context.walletClient?.chain ?? null,
865
- ...this.spreadTransactionOptions(options)
866
- });
867
- const { tx } = await import("../utils/transactionHelpers");
868
- return tx({
869
- hash: txHash,
870
- from: typeof account === "string" ? account : account.address,
871
- contract: "DataPortabilityPermissions",
872
- fn: "addPermission"
873
- });
874
- }
875
- /**
876
- * Revokes a previously granted permission.
877
- *
878
- * This method provides complete revocation with automatic event parsing to confirm
879
- * the permission was successfully revoked. For advanced users who need more control,
880
- * use `submitPermissionRevoke()` instead.
881
- *
882
- * @param params - Parameters for revoking the permission
883
- * @param params.permissionId - Permission identifier (accepts bigint, number, or string).
884
- * Obtain from permission grants via `getUserPermissionGrantsOnChain()`.
885
- * @returns Promise resolving to revocation data from PermissionRevoked event
886
- * @throws {BlockchainError} When revocation fails or event parsing fails
887
- * @throws {UserRejectedRequestError} When user rejects the transaction
888
- * @throws {NetworkError} When transaction confirmation times out
889
- * @example
890
- * ```typescript
891
- * // Revoke a permission and get confirmation
892
- * const result = await vana.permissions.revoke({
893
- * permissionId: 123n
894
- * });
895
- * console.log(`Permission ${result.permissionId} revoked in transaction ${result.transactionHash}`);
896
- * console.log(`Revoked in block ${result.blockNumber}`);
897
- * ```
898
- */
899
- async revoke(params) {
900
- this.assertWallet();
901
- const txResult = await this.submitPermissionRevoke(params);
902
- if (!this.context.waitForTransactionEvents) {
903
- throw new import_errors.BlockchainError("waitForTransactionEvents not configured");
904
- }
905
- const result = await this.context.waitForTransactionEvents(txResult);
906
- const event = result.expectedEvents.PermissionRevoked;
907
- if (!event) {
908
- throw new import_errors.BlockchainError(
909
- "PermissionRevoked event not found in transaction"
910
- );
911
- }
912
- const receipt = await this.context.publicClient.getTransactionReceipt({
913
- hash: result.hash
914
- });
915
- return {
916
- transactionHash: result.hash,
917
- blockNumber: receipt.blockNumber,
918
- gasUsed: receipt.gasUsed,
919
- permissionId: event.permissionId
920
- };
921
- }
922
- /**
923
- * Submits a permission revocation transaction and returns the transaction hash immediately.
924
- *
925
- * This is the lower-level method that provides maximum control over transaction timing.
926
- * Use this when you want to handle transaction confirmation and event parsing separately.
927
- *
928
- * @param params - Parameters for revoking the permission
929
- * @param options - Optional transaction options for gas parameters and timeout
930
- * @returns Promise resolving to the transaction hash when successfully submitted
931
- * @throws {BlockchainError} When revocation transaction fails
932
- * @throws {UserRejectedRequestError} When user rejects the transaction
933
- * @example
934
- * ```typescript
935
- * // Submit revocation and handle confirmation later
936
- * const txHash = await vana.permissions.submitPermissionRevoke({
937
- * permissionId: 123n
938
- * });
939
- * console.log(`Revocation submitted: ${txHash}`);
940
- * ```
941
- */
942
- async submitPermissionRevoke(params, options) {
943
- this.assertWallet();
944
- try {
945
- if (!this.context.walletClient?.chain?.id) {
946
- throw new import_errors.BlockchainError("Chain ID not available");
947
- }
948
- const chainId = await this.context.publicClient.getChainId();
949
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
950
- chainId,
951
- "DataPortabilityPermissions"
952
- );
953
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
954
- "DataPortabilityPermissions"
955
- );
956
- const account = this.context.walletClient?.account ?? this.context.userAddress;
957
- const txHash = await this.context.walletClient.writeContract({
958
- address: DataPortabilityPermissionsAddress,
959
- abi: DataPortabilityPermissionsAbi,
960
- functionName: "revokePermission",
961
- args: [params.permissionId],
962
- account,
963
- chain: this.context.walletClient?.chain ?? null,
964
- ...options?.gas && { gas: options.gas },
965
- ...options?.nonce && { nonce: options.nonce },
966
- // Use EIP-1559 if available, otherwise fall back to legacy gasPrice
967
- ...options?.maxFeePerGas || options?.maxPriorityFeePerGas ? {
968
- ...options.maxFeePerGas && {
969
- maxFeePerGas: options.maxFeePerGas
970
- },
971
- ...options.maxPriorityFeePerGas && {
972
- maxPriorityFeePerGas: options.maxPriorityFeePerGas
973
- }
974
- } : options?.gasPrice && { gasPrice: options.gasPrice }
975
- });
976
- const { tx } = await import("../utils/transactionHelpers");
977
- return tx({
978
- hash: txHash,
979
- from: typeof account === "string" ? account : account.address,
980
- contract: "DataPortabilityPermissions",
981
- fn: "revokePermission"
982
- });
983
- } catch (error) {
984
- if (error instanceof Error) {
985
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
986
- throw error;
987
- }
988
- throw new import_errors.BlockchainError(
989
- `Permission revoke failed: ${error.message}`,
990
- error
991
- );
992
- }
993
- throw new import_errors.BlockchainError("Permission revoke failed with unknown error");
994
- }
995
- }
996
- /**
997
- * Revokes a permission with a signature for gasless transactions.
998
- *
999
- * @remarks
1000
- * This method creates an EIP-712 signature for permission revocation and submits
1001
- * it either through relayer callbacks or directly to the blockchain. Provides
1002
- * gasless revocation when relayer is configured.
1003
- *
1004
- * @param params - Parameters for revoking the permission
1005
- * @param params.permissionId - Permission identifier to revoke (accepts bigint, number, or string)
1006
- * @returns Promise resolving to TransactionResult for transaction tracking
1007
- * @throws {BlockchainError} When chain ID is not available
1008
- * @throws {NonceError} When retrieving user nonce fails
1009
- * @throws {SignatureError} When user rejects the signature request
1010
- * @throws {RelayerError} When gasless submission fails
1011
- * @throws {PermissionError} When revocation fails for any other reason
1012
- * @example
1013
- * ```typescript
1014
- * const txHandle = await vana.permissions.submitRevokeWithSignature({
1015
- * permissionId: 123n
1016
- * });
1017
- * const result = await txHandle.waitForEvents();
1018
- * console.log(`Permission ${result.permissionId} revoked`);
1019
- * ```
1020
- */
1021
- async submitRevokeWithSignature(params, options) {
1022
- this.assertWallet();
1023
- try {
1024
- if (!this.context.walletClient?.chain?.id) {
1025
- throw new import_errors.BlockchainError("Chain ID not available");
1026
- }
1027
- const nonce = await this.getPermissionsUserNonce();
1028
- const revokePermissionInput = {
1029
- nonce,
1030
- permissionId: params.permissionId
1031
- };
1032
- const typedData = {
1033
- domain: await this.getPermissionDomain(),
1034
- types: {
1035
- RevokePermission: [
1036
- { name: "nonce", type: "uint256" },
1037
- { name: "permissionId", type: "uint256" }
1038
- ]
1039
- },
1040
- primaryType: "RevokePermission",
1041
- message: revokePermissionInput
1042
- };
1043
- const signature = await this.signTypedData(typedData);
1044
- let hash;
1045
- if (this.context.relayer) {
1046
- const response = await this.context.relayer({
1047
- type: "signed",
1048
- operation: "submitPermissionRevoke",
1049
- typedData,
1050
- signature,
1051
- expectedUserAddress: this.context.userAddress
1052
- });
1053
- if (response.type === "submitted") {
1054
- hash = response.hash;
1055
- } else if (response.type === "signed") {
1056
- hash = response.hash;
1057
- } else if (response.type === "error") {
1058
- throw new Error(`Relayer error: ${response.error}`);
1059
- } else {
1060
- throw new Error(
1061
- "Invalid response from relayer: expected signed transaction"
1062
- );
1063
- }
1064
- } else {
1065
- hash = await this.submitDirectRevokeTransaction(
1066
- typedData,
1067
- signature,
1068
- options
1069
- );
1070
- }
1071
- const account = this.context.walletClient?.account ?? this.context.userAddress;
1072
- const { tx } = await import("../utils/transactionHelpers");
1073
- return tx({
1074
- hash,
1075
- from: typeof account === "string" ? account : account.address,
1076
- contract: "DataPortabilityPermissions",
1077
- fn: "revokePermissionWithSignature"
1078
- });
1079
- } catch (error) {
1080
- throw new import_errors.PermissionError(
1081
- `Failed to revoke permission with signature: ${error instanceof Error ? error.message : "Unknown error"}`,
1082
- error
1083
- );
1084
- }
1085
- }
1086
- /**
1087
- * Retrieves the user's current nonce from the DataPortabilityServers contract.
1088
- * This nonce is used for server-related operations (AddAndTrustServer, TrustServer, UntrustServer).
1089
- *
1090
- * @returns Promise resolving to the current servers nonce
1091
- * @throws {NonceError} When reading nonce from contract fails
1092
- * @private
1093
- *
1094
- * @example
1095
- * ```typescript
1096
- * const nonce = await this.getServersUserNonce();
1097
- * console.log(`Current servers nonce: ${nonce}`);
1098
- * ```
1099
- */
1100
- /**
1101
- * Retrieves the user's current nonce from the DataPortabilityServers contract.
1102
- *
1103
- * @remarks
1104
- * Used for server-related operations (trust/untrust) to prevent replay attacks.
1105
- * The nonce must be incremented with each server operation.
1106
- *
1107
- * @returns Promise resolving to the user's current nonce as a bigint
1108
- * @throws {NonceError} When retrieving the nonce fails
1109
- */
1110
- async getServersUserNonce() {
1111
- try {
1112
- const userAddress = this.context.userAddress;
1113
- const chainId = await this.context.publicClient.getChainId();
1114
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
1115
- chainId,
1116
- "DataPortabilityServers"
1117
- );
1118
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
1119
- const [nonce] = await this.context.publicClient.readContract({
1120
- address: DataPortabilityServersAddress,
1121
- abi: DataPortabilityServersAbi,
1122
- functionName: "users",
1123
- args: [userAddress]
1124
- });
1125
- return nonce;
1126
- } catch (error) {
1127
- throw new import_errors.NonceError(
1128
- `Failed to retrieve server nonce: ${error instanceof Error ? error.message : "Unknown error"}`
1129
- );
1130
- }
1131
- }
1132
- /**
1133
- * Retrieves the user's current nonce from the DataPortabilityPermissions contract.
1134
- * This nonce is used for permission-related operations (addPermission, addServerFilesAndPermissions).
1135
- *
1136
- * @returns Promise resolving to the current permissions nonce
1137
- * @throws {NonceError} When reading nonce from contract fails
1138
- * @private
1139
- *
1140
- * @example
1141
- * ```typescript
1142
- * const nonce = await this.getPermissionsUserNonce();
1143
- * console.log(`Current permissions nonce: ${nonce}`);
1144
- * ```
1145
- */
1146
- /**
1147
- * Retrieves the user's current nonce from the DataPortabilityPermissions contract.
1148
- *
1149
- * @remarks
1150
- * Used for permission-related operations (grant/revoke) to prevent replay attacks.
1151
- * The nonce must be incremented with each permission operation.
1152
- *
1153
- * @returns Promise resolving to the user's current nonce as a bigint
1154
- * @throws {NonceError} When retrieving the nonce fails
1155
- */
1156
- async getPermissionsUserNonce() {
1157
- try {
1158
- const userAddress = this.context.userAddress;
1159
- const chainId = await this.context.publicClient.getChainId();
1160
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
1161
- chainId,
1162
- "DataPortabilityPermissions"
1163
- );
1164
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
1165
- "DataPortabilityPermissions"
1166
- );
1167
- const nonce = await this.context.publicClient.readContract({
1168
- address: DataPortabilityPermissionsAddress,
1169
- abi: DataPortabilityPermissionsAbi,
1170
- functionName: "userNonce",
1171
- args: [userAddress]
1172
- });
1173
- return nonce;
1174
- } catch (error) {
1175
- throw new import_errors.NonceError(
1176
- `Failed to retrieve permissions nonce: ${error instanceof Error ? error.message : "Unknown error"}`
1177
- );
1178
- }
1179
- }
1180
- /**
1181
- * Composes the EIP-712 typed data for PermissionGrant (new simplified format).
1182
- *
1183
- * @param params - The parameters for composing the permission grant message
1184
- * @param params.grantee - The recipient address for the permission grant
1185
- * @param params.operation - The type of operation being granted permission for
1186
- * @param params.files - Array of file IDs that the permission applies to
1187
- * @param params.grantUrl - URL where the grant details are stored
1188
- * @param params.serializedParameters - Serialized parameters for the operation
1189
- * @param params.nonce - Unique number to prevent replay attacks
1190
- * @returns Promise resolving to the typed data structure
1191
- */
1192
- async composePermissionGrantMessage(params) {
1193
- const domain = await this.getPermissionDomain();
1194
- console.debug(
1195
- "\u{1F50D} Debug - Composing permission message with grantUrl:",
1196
- params.grantUrl
1197
- );
1198
- const chainId = await this.context.publicClient.getChainId();
1199
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
1200
- chainId,
1201
- "DataPortabilityGrantees"
1202
- );
1203
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
1204
- const granteeId = await this.context.publicClient.readContract({
1205
- address: DataPortabilityGranteesAddress,
1206
- abi: DataPortabilityGranteesAbi,
1207
- functionName: "granteeAddressToId",
1208
- args: [params.grantee]
1209
- });
1210
- if (!params.grantUrl.startsWith("ipfs://") && params.grantUrl.includes("/ipfs/")) {
1211
- const { extractIpfsHash } = await import("../utils/ipfs");
1212
- const hash = extractIpfsHash(params.grantUrl);
1213
- if (hash) {
1214
- console.warn(
1215
- `\u26A0\uFE0F Storing HTTP gateway URL on-chain instead of ipfs:// protocol. Found: ${params.grantUrl}. Consider using ipfs://${hash} for better protocol-agnostic on-chain storage.`
1216
- );
1217
- }
1218
- }
1219
- return {
1220
- domain,
1221
- types: {
1222
- Permission: [
1223
- { name: "nonce", type: "uint256" },
1224
- { name: "granteeId", type: "uint256" },
1225
- { name: "grant", type: "string" },
1226
- { name: "fileIds", type: "uint256[]" }
1227
- ]
1228
- },
1229
- primaryType: "Permission",
1230
- message: {
1231
- nonce: params.nonce,
1232
- granteeId,
1233
- grant: params.grantUrl,
1234
- fileIds: params.files.map((fileId) => BigInt(fileId))
1235
- }
1236
- };
1237
- }
1238
- /**
1239
- * Creates EIP-712 typed data structure for server files and permissions.
1240
- *
1241
- * @param params - Parameters for the server files and permissions message
1242
- * @param params.granteeId - Grantee ID
1243
- * @param params.grant - Grant URL or grant data
1244
- * @param params.fileUrls - Array of file URLs
1245
- * @param params.schemaIds - Schema IDs for each file
1246
- * @param params.serverAddress - Server address
1247
- * @param params.serverUrl - Server URL
1248
- * @param params.serverPublicKey - Server public key
1249
- * @param params.filePermissions - File permissions array
1250
- * @param params.nonce - Unique number to prevent replay attacks
1251
- * @returns Promise resolving to the typed data structure
1252
- */
1253
- async composeServerFilesAndPermissionMessage(params) {
1254
- const domain = await this.getPermissionDomain();
1255
- console.debug(
1256
- "\u{1F50D} Debug - Composing server files and permission message with grant:",
1257
- params.grant
1258
- );
1259
- if (!params.grant.startsWith("ipfs://") && params.grant.includes("/ipfs/")) {
1260
- const { extractIpfsHash } = await import("../utils/ipfs");
1261
- const hash = extractIpfsHash(params.grant);
1262
- if (hash) {
1263
- console.warn(
1264
- `\u26A0\uFE0F Storing HTTP gateway URL on-chain instead of ipfs:// protocol. Found: ${params.grant}. Consider using ipfs://${hash} for better protocol-agnostic on-chain storage.`
1265
- );
1266
- }
1267
- }
1268
- return {
1269
- domain,
1270
- types: {
1271
- Permission: [
1272
- { name: "account", type: "address" },
1273
- { name: "key", type: "string" }
1274
- ],
1275
- ServerFilesAndPermission: [
1276
- { name: "nonce", type: "uint256" },
1277
- { name: "granteeId", type: "uint256" },
1278
- { name: "grant", type: "string" },
1279
- { name: "fileUrls", type: "string[]" },
1280
- { name: "schemaIds", type: "uint256[]" },
1281
- { name: "serverAddress", type: "address" },
1282
- { name: "serverUrl", type: "string" },
1283
- { name: "serverPublicKey", type: "string" },
1284
- { name: "filePermissions", type: "Permission[][]" }
1285
- ]
1286
- },
1287
- primaryType: "ServerFilesAndPermission",
1288
- message: {
1289
- nonce: params.nonce,
1290
- granteeId: params.granteeId,
1291
- grant: params.grant,
1292
- fileUrls: params.fileUrls,
1293
- schemaIds: params.schemaIds.map((id) => BigInt(id)),
1294
- serverAddress: params.serverAddress,
1295
- serverUrl: params.serverUrl,
1296
- serverPublicKey: params.serverPublicKey,
1297
- filePermissions: params.filePermissions
1298
- }
1299
- };
1300
- }
1301
- /**
1302
- * Gets the EIP-712 domain for PermissionGrant signatures.
1303
- *
1304
- * @returns Promise resolving to the EIP-712 domain configuration
1305
- */
1306
- async getPermissionDomain() {
1307
- const chainId = await this.context.publicClient.getChainId();
1308
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
1309
- chainId,
1310
- "DataPortabilityPermissions"
1311
- );
1312
- return {
1313
- name: "VanaDataPortabilityPermissions",
1314
- version: "1",
1315
- chainId,
1316
- verifyingContract: DataPortabilityPermissionsAddress
1317
- };
1318
- }
1319
- /**
1320
- * Signs typed data using the wallet client with signature caching.
1321
- *
1322
- * @param typedData - The EIP-712 typed data structure to sign
1323
- * @returns Promise resolving to the cryptographic signature
1324
- */
1325
- async signTypedData(typedData) {
1326
- this.assertWallet();
1327
- try {
1328
- const walletAddress = this.context.walletClient.account?.address ?? this.context.userAddress;
1329
- return await (0, import_signatureCache.withSignatureCache)(
1330
- this.context.platform.cache,
1331
- walletAddress,
1332
- typedData,
1333
- async () => {
1334
- const viemCompatibleTypedData = (0, import_typedDataConverter.toViemTypedDataDefinition)(typedData);
1335
- return await this.context.walletClient.signTypedData({
1336
- ...viemCompatibleTypedData,
1337
- // Use the account if available, otherwise use the wallet address
1338
- // This follows the same pattern used throughout this file
1339
- account: this.context.walletClient.account ?? walletAddress
1340
- });
1341
- }
1342
- );
1343
- } catch (error) {
1344
- if (error instanceof Error && error.message.includes("rejected")) {
1345
- throw new import_errors.UserRejectedRequestError();
1346
- }
1347
- throw new import_errors.SignatureError(
1348
- `Failed to sign typed data: ${error instanceof Error ? error.message : "Unknown error"}`,
1349
- error
1350
- );
1351
- }
1352
- }
1353
- /**
1354
- * Gets the user's address from the context.
1355
- *
1356
- * @returns The user's address
1357
- */
1358
- /**
1359
- * Gets on-chain permission grant data without expensive off-chain resolution.
1360
- *
1361
- * @remarks
1362
- * This method provides a fast, performance-focused way to retrieve permission grants
1363
- * by querying only the subgraph without making expensive IPFS or individual contract calls.
1364
- * It eliminates the N+1 query problem of the legacy `getUserPermissions()` method.
1365
- *
1366
- * The returned data contains all on-chain information but does NOT include resolved
1367
- * operation details, parameters, or file IDs. Use `retrieveGrantFile()` separately
1368
- * for specific grants when detailed data is needed.
1369
- *
1370
- * **Performance**: Completes in ~100-500ms regardless of permission count.
1371
- * **Reliability**: Single point of failure (subgraph) with clear RPC fallback path.
1372
- *
1373
- * @param options - Options for retrieving permissions (limit, subgraph URL)
1374
- * @returns A Promise that resolves to an array of `OnChainPermissionGrant` objects
1375
- * @throws {BlockchainError} When subgraph query fails
1376
- * @throws {NetworkError} When network requests fail
1377
- * @example
1378
- * ```typescript
1379
- * // Fast: Get all on-chain permission data
1380
- * const grants = await vana.permissions.getUserPermissionGrantsOnChain({ limit: 20 });
1381
- *
1382
- * // Display in UI immediately
1383
- * grants.forEach(grant => {
1384
- * console.log(`Permission ${grant.id}: ${grant.grantUrl}`);
1385
- * });
1386
- *
1387
- * // Lazy load detailed data for specific permission when user clicks
1388
- * const grantFile = await retrieveGrantFile(grants[0].grantUrl);
1389
- * console.log(`Operation: ${grantFile.operation}`);
1390
- * console.log(`Parameters:`, grantFile.parameters);
1391
- * ```
1392
- */
1393
- async getUserPermissionGrantsOnChain(options = {}) {
1394
- const { limit = 50, fetchAll = false, subgraphUrl } = options;
1395
- const pageSize = fetchAll ? 100 : limit;
1396
- const maxResults = fetchAll ? 1e4 : limit;
1397
- try {
1398
- const userAddress = this.context.userAddress;
1399
- const graphqlEndpoint = subgraphUrl ?? this.context.subgraphUrl;
1400
- if (!graphqlEndpoint) {
1401
- throw new import_errors.BlockchainError(
1402
- "subgraphUrl is required. Please provide a valid subgraph endpoint or configure it in Vana constructor."
1403
- );
1404
- }
1405
- const query = `
1406
- query GetUserPermissions($userId: ID!, $first: Int!, $skip: Int!) {
1407
- user(id: $userId) {
1408
- id
1409
- permissions(first: $first, skip: $skip, orderBy: addedAtBlock, orderDirection: desc) {
1410
- id
1411
- grant
1412
- nonce
1413
- signature
1414
- startBlock
1415
- endBlock
1416
- addedAtBlock
1417
- addedAtTimestamp
1418
- transactionHash
1419
- grantee {
1420
- id
1421
- address
1422
- }
1423
- }
1424
- }
1425
- }
1426
- `;
1427
- const allPermissions = [];
1428
- let currentOffset = 0;
1429
- if (!fetchAll) {
1430
- const response = await fetch(graphqlEndpoint, {
1431
- method: "POST",
1432
- headers: {
1433
- "Content-Type": "application/json"
1434
- },
1435
- body: JSON.stringify({
1436
- query,
1437
- variables: {
1438
- userId: userAddress.toLowerCase(),
1439
- first: limit,
1440
- skip: 0
1441
- }
1442
- })
1443
- });
1444
- if (!response.ok) {
1445
- throw new import_errors.BlockchainError(
1446
- `Subgraph request failed: ${response.status} ${response.statusText}`
1447
- );
1448
- }
1449
- const result = await response.json();
1450
- if (result.errors) {
1451
- throw new import_errors.BlockchainError(
1452
- `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
1453
- );
1454
- }
1455
- const userData = result.data?.user;
1456
- if (!userData?.permissions?.length) {
1457
- return [];
1458
- }
1459
- allPermissions.push(...userData.permissions);
1460
- } else {
1461
- while (allPermissions.length < maxResults) {
1462
- const currentLimit = Math.min(
1463
- pageSize,
1464
- maxResults - allPermissions.length
1465
- );
1466
- const response = await fetch(graphqlEndpoint, {
1467
- method: "POST",
1468
- headers: {
1469
- "Content-Type": "application/json"
1470
- },
1471
- body: JSON.stringify({
1472
- query,
1473
- variables: {
1474
- userId: userAddress.toLowerCase(),
1475
- first: currentLimit,
1476
- skip: currentOffset
1477
- }
1478
- })
1479
- });
1480
- if (!response.ok) {
1481
- throw new import_errors.BlockchainError(
1482
- `Subgraph request failed: ${response.status} ${response.statusText}`
1483
- );
1484
- }
1485
- const result = await response.json();
1486
- if (result.errors) {
1487
- throw new import_errors.BlockchainError(
1488
- `Subgraph errors: ${result.errors.map((e) => e.message).join(", ")}`
1489
- );
1490
- }
1491
- const userData = result.data?.user;
1492
- if (!userData?.permissions?.length) {
1493
- break;
1494
- }
1495
- allPermissions.push(...userData.permissions);
1496
- if (userData.permissions.length < currentLimit) {
1497
- break;
1498
- }
1499
- currentOffset += userData.permissions.length;
1500
- }
1501
- }
1502
- const onChainGrants = allPermissions.map(
1503
- (permission) => {
1504
- const endBlock = permission.endBlock === void 0 || permission.endBlock === null ? 0n : BigInt(permission.endBlock);
1505
- const active = !permission.endBlock || endBlock === 0n || endBlock === MAX_UINT256;
1506
- return {
1507
- id: BigInt(permission.id),
1508
- grantUrl: permission.grant,
1509
- grantSignature: permission.signature,
1510
- nonce: BigInt(permission.nonce),
1511
- startBlock: BigInt(permission.startBlock),
1512
- endBlock,
1513
- addedAtBlock: BigInt(permission.addedAtBlock),
1514
- addedAtTimestamp: BigInt(permission.addedAtTimestamp ?? "0"),
1515
- transactionHash: permission.transactionHash ?? "",
1516
- grantor: userAddress,
1517
- grantee: permission.grantee,
1518
- active
1519
- };
1520
- }
1521
- );
1522
- return onChainGrants.sort((a, b) => {
1523
- if (a.id < b.id) return 1;
1524
- if (a.id > b.id) return -1;
1525
- return 0;
1526
- });
1527
- } catch (error) {
1528
- if (error instanceof import_errors.BlockchainError || error instanceof import_errors.NetworkError) {
1529
- throw error;
1530
- }
1531
- throw new import_errors.BlockchainError(
1532
- `Failed to fetch user permission grants: ${error instanceof Error ? error.message : "Unknown error"}`
1533
- );
1534
- }
1535
- }
1536
- /**
1537
- * Registers a new server and immediately trusts it in the DataPortabilityServers contract.
1538
- *
1539
- * This is a combined operation that both registers a new data portability server
1540
- * and adds it to the user's trusted servers list in a single transaction.
1541
- * Trusted servers can handle data export and portability requests from the user.
1542
- *
1543
- * @param params - Parameters for adding and trusting the server
1544
- * @param params.serverAddress - Ethereum address of the server
1545
- * @param params.serverUrl - HTTPS URL where the server can be reached
1546
- * @param params.publicKey - Server's public key for encryption (hex string)
1547
- * @returns Promise resolving to transaction hash
1548
- * @throws {UserRejectedRequestError} When user rejects the transaction
1549
- * @throws {BlockchainError} When chain ID is unavailable or transaction fails
1550
- * @throws {ServerAlreadyRegisteredError} When server address is already registered
1551
- * @throws {Error} When wallet account is not available
1552
- *
1553
- * @example
1554
- * ```typescript
1555
- * // Add and trust a server by providing all required details
1556
- * const txHash = await vana.permissions.addAndTrustServer({
1557
- * owner: '0x1234567890abcdef1234567890abcdef12345678',
1558
- * serverAddress: '0x742d35Cc6634C0532925a3b8D4C9db96C4b4d8b6',
1559
- * serverUrl: 'https://myserver.example.com',
1560
- * publicKey: '0x456789abcdef456789abcdef456789abcdef456789abcdef'
1561
- * });
1562
- * console.log('Server added and trusted in transaction:', txHash);
1563
- *
1564
- * // Verify the server is now trusted
1565
- * const trustedServers = await vana.permissions.getTrustedServers();
1566
- * console.log('Now trusting servers:', trustedServers);
1567
- * ```
1568
- */
1569
- async addAndTrustServer(params) {
1570
- this.assertWallet();
1571
- try {
1572
- const chainId = await this.context.walletClient.getChainId();
1573
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
1574
- chainId,
1575
- "DataPortabilityServers"
1576
- );
1577
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
1578
- const account = this.context.walletClient?.account ?? this.context.userAddress;
1579
- const userAddress = typeof account === "string" ? account : account.address;
1580
- const normalizedUserAddress = (0, import_viem.getAddress)(userAddress);
1581
- const normalizedServerAddress = (0, import_viem.getAddress)(params.serverAddress);
1582
- const txHash = await this.context.walletClient.writeContract({
1583
- address: DataPortabilityServersAddress,
1584
- abi: DataPortabilityServersAbi,
1585
- functionName: "addAndTrustServerByManager",
1586
- args: [
1587
- normalizedUserAddress,
1588
- {
1589
- serverAddress: normalizedServerAddress,
1590
- serverUrl: params.serverUrl,
1591
- publicKey: params.publicKey
1592
- }
1593
- ],
1594
- account,
1595
- chain: this.context.walletClient?.chain ?? null
1596
- });
1597
- const { tx } = await import("../utils/transactionHelpers");
1598
- const txResult = tx({
1599
- hash: txHash,
1600
- from: userAddress,
1601
- contract: "DataPortabilityServers",
1602
- fn: "addAndTrustServerByManager"
1603
- });
1604
- if (!this.context.waitForTransactionEvents) {
1605
- throw new import_errors.BlockchainError("waitForTransactionEvents not configured");
1606
- }
1607
- const result = await this.context.waitForTransactionEvents(txResult);
1608
- const event = result.expectedEvents.ServerTrusted;
1609
- if (!event) {
1610
- throw new import_errors.BlockchainError(
1611
- "ServerTrusted event not found in transaction"
1612
- );
1613
- }
1614
- const receipt = await this.context.publicClient.getTransactionReceipt({
1615
- hash: txHash
1616
- });
1617
- return {
1618
- transactionHash: txHash,
1619
- blockNumber: receipt.blockNumber,
1620
- gasUsed: receipt.gasUsed,
1621
- user: event.user,
1622
- serverId: event.serverId,
1623
- // bigint from event
1624
- serverAddress: normalizedServerAddress,
1625
- // derived from params
1626
- serverUrl: params.serverUrl
1627
- // provided in params
1628
- };
1629
- } catch (error) {
1630
- if (error instanceof Error && error.message.includes("rejected")) {
1631
- throw new import_errors.UserRejectedRequestError();
1632
- }
1633
- throw new import_errors.BlockchainError(
1634
- `Failed to add and trust server: ${error instanceof Error ? error.message : "Unknown error"}`,
1635
- error
1636
- );
1637
- }
1638
- }
1639
- /**
1640
- * Trusts a server for data processing (legacy method).
1641
- *
1642
- * @param params - Parameters for trusting the server
1643
- * @returns Promise resolving to transaction hash
1644
- * @deprecated Use addAndTrustServer instead
1645
- */
1646
- async submitTrustServer(params) {
1647
- this.assertWallet();
1648
- try {
1649
- const chainId = await this.context.walletClient.getChainId();
1650
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
1651
- chainId,
1652
- "DataPortabilityServers"
1653
- );
1654
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
1655
- const account = this.context.walletClient?.account ?? this.context.userAddress;
1656
- const txHash = await this.context.walletClient.writeContract({
1657
- address: DataPortabilityServersAddress,
1658
- abi: DataPortabilityServersAbi,
1659
- functionName: "trustServer",
1660
- args: [BigInt(params.serverId)],
1661
- account,
1662
- chain: this.context.walletClient?.chain ?? null
1663
- });
1664
- const { tx } = await import("../utils/transactionHelpers");
1665
- return tx({
1666
- hash: txHash,
1667
- from: typeof account === "string" ? account : account.address,
1668
- contract: "DataPortabilityServers",
1669
- fn: "trustServer"
1670
- });
1671
- } catch (error) {
1672
- if (error instanceof Error && error.message.includes("rejected")) {
1673
- throw new import_errors.UserRejectedRequestError();
1674
- }
1675
- throw new import_errors.BlockchainError(
1676
- `Failed to trust server: ${error instanceof Error ? error.message : "Unknown error"}`,
1677
- error
1678
- );
1679
- }
1680
- }
1681
- /**
1682
- * Adds and trusts a server using a signature (gasless transaction).
1683
- *
1684
- * @param params - Parameters for adding and trusting the server
1685
- * @returns Promise resolving to TransactionResult with ServerTrustResult event data
1686
- */
1687
- async submitAddAndTrustServerWithSignature(params, options) {
1688
- this.assertWallet();
1689
- try {
1690
- const nonce = await this.getServersUserNonce();
1691
- const serverAddress = (0, import_viem.getAddress)(params.serverAddress);
1692
- const addAndTrustServerInput = {
1693
- nonce,
1694
- serverAddress,
1695
- publicKey: params.publicKey,
1696
- serverUrl: params.serverUrl
1697
- };
1698
- const typedData = await this.composeAddAndTrustServerMessage(
1699
- addAndTrustServerInput
1700
- );
1701
- console.debug("\u{1F50D} AddAndTrustServer Debug Info:", {
1702
- nonce: nonce.toString(),
1703
- serverAddress: params.serverAddress,
1704
- publicKey: params.publicKey,
1705
- serverUrl: params.serverUrl,
1706
- domain: typedData.domain,
1707
- typedDataMessage: typedData.message
1708
- });
1709
- const signature = await this.signTypedData(typedData);
1710
- console.debug("\u{1F50D} Generated signature:", signature);
1711
- let hash;
1712
- if (this.context.relayer) {
1713
- const request = {
1714
- type: "signed",
1715
- operation: "submitAddAndTrustServer",
1716
- typedData,
1717
- signature
1718
- };
1719
- const response = await this.context.relayer(request);
1720
- if (response.type === "error") {
1721
- throw new import_errors.RelayerError(response.error);
1722
- }
1723
- if (response.type === "submitted") {
1724
- hash = response.hash;
1725
- } else if (response.type === "signed") {
1726
- hash = response.hash;
1727
- } else {
1728
- throw new Error("Unexpected response type from relayer");
1729
- }
1730
- } else {
1731
- hash = await this.submitAddAndTrustServerTransaction(
1732
- addAndTrustServerInput,
1733
- signature,
1734
- options
1735
- );
1736
- }
1737
- const account = this.context.walletClient?.account ?? this.context.userAddress;
1738
- const { tx } = await import("../utils/transactionHelpers");
1739
- return tx({
1740
- hash,
1741
- from: typeof account === "string" ? account : account.address,
1742
- contract: "DataPortabilityServers",
1743
- fn: "addAndTrustServerWithSignature"
1744
- });
1745
- } catch (error) {
1746
- if (error instanceof Error) {
1747
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
1748
- throw error;
1749
- }
1750
- throw new import_errors.BlockchainError(
1751
- `Add and trust server failed: ${error.message}`,
1752
- error
1753
- );
1754
- }
1755
- throw new import_errors.BlockchainError(
1756
- "Add and trust server failed with unknown error"
1757
- );
1758
- }
1759
- }
1760
- /**
1761
- * Trusts a server using a signature (gasless transaction - legacy method).
1762
- *
1763
- * @param params - Parameters for trusting the server
1764
- * @returns Promise resolving to transaction hash
1765
- * @deprecated Use addAndTrustServerWithSignature instead
1766
- * @throws {BlockchainError} When chain ID is not available
1767
- * @throws {NonceError} When retrieving user nonce fails
1768
- * @throws {SignatureError} When user rejects the signature request
1769
- * @throws {RelayerError} When gasless submission fails
1770
- * @throws {ServerUrlMismatchError} When server URL doesn't match existing registration
1771
- * @throws {BlockchainError} When trust operation fails for any other reason
1772
- */
1773
- async submitTrustServerWithSignature(params, options) {
1774
- this.assertWallet();
1775
- try {
1776
- const nonce = await this.getServersUserNonce();
1777
- const trustServerInput = {
1778
- nonce,
1779
- serverId: params.serverId
1780
- };
1781
- const typedData = await this.composeTrustServerMessage(trustServerInput);
1782
- const signature = await this.signTypedData(typedData);
1783
- let hash;
1784
- if (this.context.relayer) {
1785
- const request = {
1786
- type: "signed",
1787
- operation: "submitTrustServer",
1788
- typedData,
1789
- signature
1790
- };
1791
- const response = await this.context.relayer(request);
1792
- if (response.type === "error") {
1793
- throw new import_errors.RelayerError(response.error);
1794
- }
1795
- if (response.type === "submitted") {
1796
- hash = response.hash;
1797
- } else if (response.type === "signed") {
1798
- hash = response.hash;
1799
- } else {
1800
- throw new Error("Unexpected response type from relayer");
1801
- }
1802
- } else {
1803
- hash = await this.submitTrustServerTransaction(
1804
- trustServerInput,
1805
- signature,
1806
- options
1807
- );
1808
- }
1809
- const account = this.context.walletClient?.account ?? this.context.userAddress;
1810
- const { tx } = await import("../utils/transactionHelpers");
1811
- return tx({
1812
- hash,
1813
- from: typeof account === "string" ? account : account.address,
1814
- contract: "DataPortabilityServers",
1815
- fn: "trustServerWithSignature"
1816
- });
1817
- } catch (error) {
1818
- if (error instanceof Error) {
1819
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
1820
- throw error;
1821
- }
1822
- throw new import_errors.BlockchainError(
1823
- `Trust server failed: ${error.message}`,
1824
- error
1825
- );
1826
- }
1827
- throw new import_errors.BlockchainError("Trust server failed with unknown error");
1828
- }
1829
- }
1830
- /**
1831
- * Submits a direct untrust server transaction (without signature).
1832
- *
1833
- * @param params - The untrust server parameters containing server details
1834
- * @returns Promise resolving to the transaction hash
1835
- */
1836
- /**
1837
- * Submits an untrust server transaction directly to the blockchain.
1838
- *
1839
- * @remarks
1840
- * Internal method used for direct blockchain submission of untrust server operations
1841
- * when relayer callbacks are not available.
1842
- *
1843
- * @param params - The untrust server parameters
1844
- * @returns Promise resolving to TransactionResult for transaction tracking
1845
- * @throws {BlockchainError} When contract submission fails
1846
- */
1847
- async submitDirectUntrustTransaction(params, options) {
1848
- this.assertWallet();
1849
- try {
1850
- const chainId = await this.context.walletClient.getChainId();
1851
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
1852
- chainId,
1853
- "DataPortabilityServers"
1854
- );
1855
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
1856
- const account = this.context.walletClient?.account ?? this.context.userAddress;
1857
- const txHash = await this.context.walletClient.writeContract({
1858
- address: DataPortabilityServersAddress,
1859
- abi: DataPortabilityServersAbi,
1860
- functionName: "untrustServer",
1861
- args: [BigInt(params.serverId)],
1862
- account,
1863
- chain: this.context.walletClient?.chain ?? null,
1864
- ...options?.gas && { gas: options.gas },
1865
- ...options?.nonce && { nonce: options.nonce },
1866
- // Use EIP-1559 if available, otherwise fall back to legacy gasPrice
1867
- ...options?.maxFeePerGas || options?.maxPriorityFeePerGas ? {
1868
- ...options.maxFeePerGas && {
1869
- maxFeePerGas: options.maxFeePerGas
1870
- },
1871
- ...options.maxPriorityFeePerGas && {
1872
- maxPriorityFeePerGas: options.maxPriorityFeePerGas
1873
- }
1874
- } : options?.gasPrice && { gasPrice: options.gasPrice }
1875
- });
1876
- const { tx } = await import("../utils/transactionHelpers");
1877
- return tx({
1878
- hash: txHash,
1879
- from: typeof account === "string" ? account : account.address,
1880
- contract: "DataPortabilityServers",
1881
- fn: "untrustServer"
1882
- });
1883
- } catch (error) {
1884
- if (error instanceof Error && error.message.includes("rejected")) {
1885
- throw new import_errors.UserRejectedRequestError();
1886
- }
1887
- throw new import_errors.BlockchainError(
1888
- `Failed to untrust server: ${error instanceof Error ? error.message : "Unknown error"}`,
1889
- error
1890
- );
1891
- }
1892
- }
1893
- /**
1894
- * Removes a server from the user's trusted servers list in the DataPortabilityServers contract.
1895
- *
1896
- * This revokes the server's authorization to handle data portability requests for the user.
1897
- * The server remains registered in the system but will no longer be trusted by this user.
1898
- *
1899
- * @param params - Parameters for untrusting the server
1900
- * @param params.serverId - The numeric ID of the server to untrust
1901
- * @param options - Optional transaction options for gas parameters and timeout
1902
- * @returns Promise resolving to transaction hash
1903
- * @throws {Error} When wallet account is not available
1904
- * @throws {NonceError} When retrieving user nonce fails
1905
- * @throws {UserRejectedRequestError} When user rejects the transaction
1906
- * @throws {ServerNotTrustedError} When the server is not currently trusted
1907
- * @throws {BlockchainError} When untrust transaction fails
1908
- *
1909
- * @example
1910
- * ```typescript
1911
- * // Untrust a specific server
1912
- * const txHash = await vana.permissions.untrustServer({
1913
- * serverId: 1
1914
- * });
1915
- * console.log('Server untrusted in transaction:', txHash);
1916
- *
1917
- * // Verify the server is no longer trusted
1918
- * const trustedServers = await vana.permissions.getTrustedServers();
1919
- * console.log('Still trusting servers:', trustedServers);
1920
- * ```
1921
- */
1922
- async submitUntrustServer(params, options) {
1923
- this.assertWallet();
1924
- const nonce = await this.getServersUserNonce();
1925
- const untrustServerInput = {
1926
- nonce,
1927
- serverId: params.serverId
1928
- };
1929
- return await this.submitDirectUntrustTransaction(
1930
- untrustServerInput,
1931
- options
1932
- );
1933
- }
1934
- /**
1935
- * Untrusts a server using a signature (gasless transaction).
1936
- *
1937
- * @param params - Parameters for untrusting the server
1938
- * @param params.serverId - The server's Ethereum address to untrust
1939
- * @returns Promise resolving to transaction hash
1940
- * @throws {Error} When wallet account is not available
1941
- * @throws {NonceError} When retrieving user nonce fails
1942
- * @throws {SignatureError} When user rejects the signature request
1943
- * @throws {RelayerError} When gasless submission fails
1944
- * @throws {BlockchainError} When untrust transaction fails
1945
- */
1946
- async submitUntrustServerWithSignature(params) {
1947
- this.assertWallet();
1948
- try {
1949
- const nonce = await this.getServersUserNonce();
1950
- const untrustServerInput = {
1951
- nonce,
1952
- serverId: params.serverId
1953
- };
1954
- const typedData = await this.composeUntrustServerMessage(untrustServerInput);
1955
- const signature = await this.signTypedData(typedData);
1956
- let hash;
1957
- if (this.context.relayer) {
1958
- const request = {
1959
- type: "signed",
1960
- operation: "submitUntrustServer",
1961
- typedData,
1962
- signature
1963
- };
1964
- const response = await this.context.relayer(request);
1965
- if (response.type === "error") {
1966
- throw new import_errors.RelayerError(response.error);
1967
- }
1968
- if (response.type === "submitted") {
1969
- hash = response.hash;
1970
- } else if (response.type === "signed") {
1971
- hash = response.hash;
1972
- } else {
1973
- throw new Error("Unexpected response type from relayer");
1974
- }
1975
- } else {
1976
- hash = await this.submitSignedUntrustTransaction(typedData, signature);
1977
- }
1978
- const account = this.context.walletClient?.account ?? this.context.userAddress;
1979
- const { tx } = await import("../utils/transactionHelpers");
1980
- return tx({
1981
- hash,
1982
- from: typeof account === "string" ? account : account.address,
1983
- contract: "DataPortabilityServers",
1984
- fn: "untrustServerWithSignature"
1985
- });
1986
- } catch (error) {
1987
- if (error instanceof Error) {
1988
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
1989
- throw error;
1990
- }
1991
- throw new import_errors.BlockchainError(
1992
- `Untrust server failed: ${error.message}`,
1993
- error
1994
- );
1995
- }
1996
- throw new import_errors.BlockchainError("Untrust server failed with unknown error");
1997
- }
1998
- }
1999
- /**
2000
- * Retrieves all servers trusted by a user from the DataPortabilityServers contract.
2001
- *
2002
- * Returns an array of server IDs that the specified user has explicitly trusted.
2003
- * Trusted servers are those that users have authorized to handle their data portability requests.
2004
- *
2005
- * @param userAddress - Optional user address to query (defaults to current wallet user)
2006
- * @returns Promise resolving to array of trusted server IDs (numeric)
2007
- * @throws {BlockchainError} When reading from contract fails or chain is unavailable
2008
- * @throws {NetworkError} When unable to connect to the blockchain network
2009
- *
2010
- * @example
2011
- * ```typescript
2012
- * // Get trusted servers for current user
2013
- * const myServers = await vana.permissions.getTrustedServers();
2014
- * console.log(`I trust ${myServers.length} servers: ${myServers.join(', ')}`);
2015
- *
2016
- * // Get trusted servers for another user
2017
- * const userServers = await vana.permissions.getTrustedServers("0x1234...");
2018
- * console.log(`User trusts servers: ${userServers.join(', ')}`);
2019
- * ```
2020
- */
2021
- async getTrustedServers(userAddress) {
2022
- try {
2023
- const user = userAddress ?? this.context.userAddress;
2024
- const chainId = await this.context.publicClient.getChainId();
2025
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2026
- chainId,
2027
- "DataPortabilityServers"
2028
- );
2029
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2030
- const serverIds = await this.context.publicClient.readContract({
2031
- address: DataPortabilityServersAddress,
2032
- abi: DataPortabilityServersAbi,
2033
- functionName: "userServerIdsValues",
2034
- args: [user]
2035
- });
2036
- return serverIds.map((id) => Number(id));
2037
- } catch (error) {
2038
- throw new import_errors.BlockchainError(
2039
- `Failed to get trusted servers: ${error instanceof Error ? error.message : "Unknown error"}`,
2040
- error
2041
- );
2042
- }
2043
- }
2044
- /**
2045
- * Gets the total count of trusted servers for a user.
2046
- *
2047
- * @param userAddress - Optional user address (defaults to current user)
2048
- * @returns Promise resolving to the number of trusted servers
2049
- * @throws {BlockchainError} When reading from contract fails or chain is unavailable
2050
- */
2051
- async getTrustedServersCount(userAddress) {
2052
- try {
2053
- const user = userAddress ?? this.context.userAddress;
2054
- const chainId = await this.context.publicClient.getChainId();
2055
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2056
- chainId,
2057
- "DataPortabilityServers"
2058
- );
2059
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2060
- const count = await this.context.publicClient.readContract({
2061
- address: DataPortabilityServersAddress,
2062
- abi: DataPortabilityServersAbi,
2063
- functionName: "userServerIdsLength",
2064
- args: [user]
2065
- });
2066
- return Number(count);
2067
- } catch (error) {
2068
- throw new import_errors.BlockchainError(
2069
- `Failed to get trusted servers count: ${error instanceof Error ? error.message : "Unknown error"}`,
2070
- error
2071
- );
2072
- }
2073
- }
2074
- /**
2075
- * Gets trusted servers with pagination support.
2076
- *
2077
- * @param options - Query options including pagination parameters
2078
- * @returns Promise resolving to paginated trusted servers
2079
- * @throws {BlockchainError} When reading from contract fails or chain is unavailable
2080
- */
2081
- async getTrustedServersPaginated(options = {}) {
2082
- try {
2083
- const user = options.userAddress ?? this.context.userAddress;
2084
- const limit = options.limit ?? 50;
2085
- const offset = options.offset ?? 0;
2086
- const chainId = await this.context.publicClient.getChainId();
2087
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2088
- chainId,
2089
- "DataPortabilityServers"
2090
- );
2091
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2092
- const totalCount = await this.context.publicClient.readContract({
2093
- address: DataPortabilityServersAddress,
2094
- abi: DataPortabilityServersAbi,
2095
- functionName: "userServerIdsLength",
2096
- args: [user]
2097
- });
2098
- const total = Number(totalCount);
2099
- if (offset >= total) {
2100
- return {
2101
- servers: [],
2102
- total,
2103
- offset,
2104
- limit,
2105
- hasMore: false
2106
- };
2107
- }
2108
- const endIndex = Math.min(offset + limit, total);
2109
- const serverIdCalls = [];
2110
- for (let i = offset; i < endIndex; i++) {
2111
- serverIdCalls.push({
2112
- address: DataPortabilityServersAddress,
2113
- abi: DataPortabilityServersAbi,
2114
- functionName: "userServerIdsAt",
2115
- args: [user, BigInt(i)]
2116
- });
2117
- }
2118
- const serverIdResults = await (0, import_multicall.gasAwareMulticall)(this.context.publicClient, {
2119
- contracts: serverIdCalls
2120
- });
2121
- const servers = serverIdResults.map((result) => Number(result)).filter((id) => id > 0);
2122
- return {
2123
- servers,
2124
- total,
2125
- offset,
2126
- limit,
2127
- hasMore: offset + limit < total
2128
- };
2129
- } catch (error) {
2130
- throw new import_errors.BlockchainError(
2131
- `Failed to get paginated trusted servers: ${error instanceof Error ? error.message : "Unknown error"}`,
2132
- error
2133
- );
2134
- }
2135
- }
2136
- /**
2137
- * Gets trusted servers with their complete information.
2138
- *
2139
- * @param options - Query options
2140
- * @returns Promise resolving to array of trusted server info
2141
- * @throws {BlockchainError} When reading from contract fails or chain is unavailable
2142
- */
2143
- async getTrustedServersWithInfo(options = {}) {
2144
- try {
2145
- const paginatedResult = await this.getTrustedServersPaginated(options);
2146
- const chainId = await this.context.publicClient.getChainId();
2147
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2148
- chainId,
2149
- "DataPortabilityServers"
2150
- );
2151
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2152
- const serverInfoCalls = paginatedResult.servers.map(
2153
- (serverId) => ({
2154
- address: DataPortabilityServersAddress,
2155
- abi: DataPortabilityServersAbi,
2156
- functionName: "servers",
2157
- args: [BigInt(serverId)]
2158
- })
2159
- );
2160
- const serverInfoResults = await (0, import_multicall.gasAwareMulticall)(this.context.publicClient, {
2161
- contracts: serverInfoCalls,
2162
- allowFailure: true
2163
- });
2164
- return serverInfoResults.map((result, index) => {
2165
- const serverId = paginatedResult.servers[index];
2166
- if (result.status === "success" && result.result) {
2167
- const serverInfo = result.result;
2168
- return {
2169
- id: BigInt(serverId),
2170
- owner: serverInfo.owner,
2171
- serverAddress: serverInfo.serverAddress,
2172
- publicKey: serverInfo.publicKey,
2173
- url: serverInfo.url,
2174
- startBlock: 0n,
2175
- // We don't have this info from the old method structure
2176
- endBlock: 0n
2177
- // 0 means still active
2178
- };
2179
- } else {
2180
- return {
2181
- id: BigInt(serverId),
2182
- owner: "0x0000000000000000000000000000000000000000",
2183
- serverAddress: "0x0000000000000000000000000000000000000000",
2184
- publicKey: "",
2185
- url: "",
2186
- startBlock: 0n,
2187
- endBlock: 0n
2188
- };
2189
- }
2190
- });
2191
- } catch (error) {
2192
- throw new import_errors.BlockchainError(
2193
- `Failed to get trusted servers with info: ${error instanceof Error ? error.message : "Unknown error"}`,
2194
- error
2195
- );
2196
- }
2197
- }
2198
- /**
2199
- * Gets server information for multiple servers efficiently.
2200
- *
2201
- * @remarks
2202
- * This method uses multicall to fetch information for multiple servers in a single
2203
- * blockchain call, improving performance when querying many servers. Failed lookups
2204
- * are returned separately for error handling.
2205
- *
2206
- * @param serverIds - Array of numeric server IDs to query
2207
- * @returns Promise resolving to batch result containing successful lookups and failed IDs
2208
- * @throws {BlockchainError} When reading from contract fails or chain is unavailable
2209
- * @example
2210
- * ```typescript
2211
- * const result = await vana.permissions.getServerInfoBatch([1, 2, 3, 999]);
2212
- *
2213
- * // Process successful lookups
2214
- * result.servers.forEach((server, id) => {
2215
- * console.log(`Server ${id}: ${server.url}`);
2216
- * });
2217
- *
2218
- * // Handle failed lookups
2219
- * if (result.failed.length > 0) {
2220
- * console.log(`Failed to fetch: ${result.failed.join(', ')}`);
2221
- * }
2222
- * ```
2223
- */
2224
- async getServerInfoBatch(serverIds) {
2225
- if (serverIds.length === 0) {
2226
- return {
2227
- servers: /* @__PURE__ */ new Map(),
2228
- failed: []
2229
- };
2230
- }
2231
- try {
2232
- const chainId = await this.context.publicClient.getChainId();
2233
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2234
- chainId,
2235
- "DataPortabilityServers"
2236
- );
2237
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2238
- const serverInfoCalls = serverIds.map(
2239
- (serverId) => ({
2240
- address: DataPortabilityServersAddress,
2241
- abi: DataPortabilityServersAbi,
2242
- functionName: "servers",
2243
- args: [BigInt(serverId)]
2244
- })
2245
- );
2246
- const serverInfoResults = await (0, import_multicall.gasAwareMulticall)(this.context.publicClient, {
2247
- contracts: serverInfoCalls,
2248
- allowFailure: true
2249
- });
2250
- const results = serverInfoResults.map((result, index) => {
2251
- const serverId = serverIds[index];
2252
- if (result.status === "success" && result.result) {
2253
- const serverInfo = result.result;
2254
- const server = {
2255
- id: Number(serverInfo.id),
2256
- owner: serverInfo.owner,
2257
- url: serverInfo.url,
2258
- serverAddress: serverInfo.serverAddress,
2259
- publicKey: serverInfo.publicKey
2260
- };
2261
- return { serverId, server, success: true };
2262
- } else {
2263
- return { serverId, server: null, success: false };
2264
- }
2265
- });
2266
- const servers = /* @__PURE__ */ new Map();
2267
- const failed = [];
2268
- for (const result of results) {
2269
- if (result.success && result.server) {
2270
- servers.set(result.serverId, result.server);
2271
- } else {
2272
- failed.push(result.serverId);
2273
- }
2274
- }
2275
- return { servers, failed };
2276
- } catch (error) {
2277
- throw new import_errors.BlockchainError(
2278
- `Failed to batch get server info: ${error instanceof Error ? error.message : "Unknown error"}`,
2279
- error
2280
- );
2281
- }
2282
- }
2283
- /**
2284
- * Checks whether a specific server is trusted by a user.
2285
- *
2286
- * @remarks
2287
- * This method queries the user's trusted server list and checks if the specified
2288
- * server is present. Returns both the trust status and the index in the trust list
2289
- * if trusted.
2290
- *
2291
- * @param serverId - Numeric server ID to check
2292
- * @param userAddress - Optional user address (defaults to current user)
2293
- * @returns Promise resolving to server trust status with trust index if applicable
2294
- * @throws {BlockchainError} When reading from contract fails
2295
- * @example
2296
- * ```typescript
2297
- * const status = await vana.permissions.checkServerTrustStatus(1);
2298
- * if (status.isTrusted) {
2299
- * console.log(`Server is trusted at index ${status.trustIndex}`);
2300
- * } else {
2301
- * console.log('Server is not trusted');
2302
- * }
2303
- * ```
2304
- */
2305
- async checkServerTrustStatus(serverId, userAddress) {
2306
- try {
2307
- const user = userAddress ?? this.context.userAddress;
2308
- const trustedServers = await this.getTrustedServers(user);
2309
- const trustIndex = trustedServers.findIndex(
2310
- (server) => server === serverId
2311
- );
2312
- return {
2313
- serverId,
2314
- isTrusted: trustIndex !== -1,
2315
- trustIndex: trustIndex !== -1 ? trustIndex : void 0
2316
- };
2317
- } catch (error) {
2318
- throw new import_errors.BlockchainError(
2319
- `Failed to check server trust status: ${error instanceof Error ? error.message : "Unknown error"}`,
2320
- error
2321
- );
2322
- }
2323
- }
2324
- /**
2325
- * Composes EIP-712 typed data for AddAndTrustServer.
2326
- *
2327
- * @remarks
2328
- * Creates the complete typed data structure required for EIP-712 signature generation
2329
- * when adding and trusting a new server in a single transaction.
2330
- *
2331
- * @param input - The add and trust server input data containing server details
2332
- * @returns Promise resolving to the typed data structure for server add and trust
2333
- */
2334
- async composeAddAndTrustServerMessage(input) {
2335
- const domain = await this.getServersDomain();
2336
- console.debug(domain);
2337
- return {
2338
- domain,
2339
- types: {
2340
- AddServer: [
2341
- { name: "nonce", type: "uint256" },
2342
- { name: "serverAddress", type: "address" },
2343
- { name: "publicKey", type: "string" },
2344
- { name: "serverUrl", type: "string" }
2345
- ]
2346
- },
2347
- primaryType: "AddServer",
2348
- message: input
2349
- };
2350
- }
2351
- /**
2352
- * Composes EIP-712 typed data for TrustServer.
2353
- *
2354
- * @param input - The trust server input data containing server details
2355
- * @returns Promise resolving to the typed data structure for server trust
2356
- */
2357
- async composeTrustServerMessage(input) {
2358
- const domain = await this.getServersDomain();
2359
- return {
2360
- domain,
2361
- types: {
2362
- TrustServer: [
2363
- { name: "nonce", type: "uint256" },
2364
- { name: "serverId", type: "uint256" }
2365
- ]
2366
- },
2367
- primaryType: "TrustServer",
2368
- message: input
2369
- };
2370
- }
2371
- /**
2372
- * Composes EIP-712 typed data for UntrustServer.
2373
- *
2374
- * @param input - The untrust server input data containing server details
2375
- * @returns Promise resolving to the typed data structure for server untrust
2376
- */
2377
- async composeUntrustServerMessage(input) {
2378
- const domain = await this.getServersDomain();
2379
- return {
2380
- domain,
2381
- types: {
2382
- UntrustServer: [
2383
- { name: "nonce", type: "uint256" },
2384
- { name: "serverId", type: "uint256" }
2385
- ]
2386
- },
2387
- primaryType: "UntrustServer",
2388
- message: input
2389
- };
2390
- }
2391
- /**
2392
- * Gets the EIP-712 domain for DataPortabilityServers signatures.
2393
- *
2394
- * @returns Promise resolving to the EIP-712 domain configuration
2395
- */
2396
- async getServersDomain() {
2397
- const chainId = await this.context.publicClient.getChainId();
2398
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2399
- chainId,
2400
- "DataPortabilityServers"
2401
- );
2402
- return {
2403
- name: "VanaDataPortabilityServers",
2404
- version: "1",
2405
- chainId,
2406
- verifyingContract: DataPortabilityServersAddress
2407
- };
2408
- }
2409
- /**
2410
- * Submits an add and trust server transaction directly to the blockchain.
2411
- *
2412
- * @param addAndTrustServerInput - The add and trust server input data containing server details
2413
- * @param signature - The cryptographic signature for the transaction
2414
- * @returns Promise resolving to the transaction hash
2415
- */
2416
- async submitAddAndTrustServerTransaction(addAndTrustServerInput, signature, options) {
2417
- this.assertWallet();
2418
- const chainId = await this.context.walletClient.getChainId();
2419
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2420
- chainId,
2421
- "DataPortabilityServers"
2422
- );
2423
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2424
- console.debug("\u{1F50D} Transaction Debug Info:", {
2425
- chainId,
2426
- contractAddress: DataPortabilityServersAddress,
2427
- input: {
2428
- nonce: addAndTrustServerInput.nonce.toString(),
2429
- serverAddress: addAndTrustServerInput.serverAddress,
2430
- publicKey: addAndTrustServerInput.publicKey,
2431
- serverUrl: addAndTrustServerInput.serverUrl
2432
- },
2433
- signature
2434
- });
2435
- const formattedSignature = (0, import_signatureFormatter.formatSignatureForContract)(signature);
2436
- const txHash = await this.context.walletClient.writeContract({
2437
- address: DataPortabilityServersAddress,
2438
- abi: DataPortabilityServersAbi,
2439
- functionName: "addAndTrustServerWithSignature",
2440
- args: [
2441
- {
2442
- nonce: addAndTrustServerInput.nonce,
2443
- serverAddress: addAndTrustServerInput.serverAddress,
2444
- publicKey: addAndTrustServerInput.publicKey,
2445
- serverUrl: addAndTrustServerInput.serverUrl
2446
- },
2447
- formattedSignature
2448
- ],
2449
- account: this.context.walletClient?.account ?? this.context.userAddress,
2450
- chain: this.context.walletClient?.chain ?? null,
2451
- ...options && {
2452
- gas: options.gas,
2453
- nonce: options.nonce,
2454
- // Use EIP-1559 gas pricing if available, otherwise legacy
2455
- ...options.maxFeePerGas || options.maxPriorityFeePerGas ? {
2456
- maxFeePerGas: options.maxFeePerGas,
2457
- maxPriorityFeePerGas: options.maxPriorityFeePerGas
2458
- } : options.gasPrice ? { gasPrice: options.gasPrice } : {}
2459
- }
2460
- });
2461
- return txHash;
2462
- }
2463
- /**
2464
- * Submits a trust server transaction directly to the blockchain.
2465
- *
2466
- * @param trustServerInput - The trust server input data containing server details
2467
- * @param signature - The cryptographic signature for the transaction
2468
- * @returns Promise resolving to the transaction hash
2469
- */
2470
- async submitTrustServerTransaction(trustServerInput, signature, options) {
2471
- this.assertWallet();
2472
- const chainId = await this.context.walletClient.getChainId();
2473
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2474
- chainId,
2475
- "DataPortabilityServers"
2476
- );
2477
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2478
- const formattedSignature = (0, import_signatureFormatter.formatSignatureForContract)(signature);
2479
- const txHash = await this.context.walletClient.writeContract({
2480
- address: DataPortabilityServersAddress,
2481
- abi: DataPortabilityServersAbi,
2482
- functionName: "trustServerWithSignature",
2483
- args: [
2484
- {
2485
- nonce: trustServerInput.nonce,
2486
- serverId: BigInt(trustServerInput.serverId)
2487
- },
2488
- formattedSignature
2489
- ],
2490
- account: this.context.walletClient?.account ?? this.context.userAddress,
2491
- chain: this.context.walletClient?.chain ?? null,
2492
- ...this.spreadTransactionOptions(options)
2493
- });
2494
- return txHash;
2495
- }
2496
- /**
2497
- * Submits a revoke transaction directly to the blockchain with signature.
2498
- *
2499
- * @param typedData - The EIP-712 typed data structure for the revoke operation
2500
- * @param signature - The cryptographic signature authorizing the revoke
2501
- * @returns Promise resolving to the transaction hash
2502
- */
2503
- async submitDirectRevokeTransaction(typedData, signature, options) {
2504
- this.assertWallet();
2505
- const chainId = await this.context.walletClient.getChainId();
2506
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
2507
- chainId,
2508
- "DataPortabilityPermissions"
2509
- );
2510
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)("DataPortabilityPermissions");
2511
- const formattedSignature = (0, import_signatureFormatter.formatSignatureForContract)(signature);
2512
- const txHash = await this.context.walletClient.writeContract({
2513
- address: DataPortabilityPermissionsAddress,
2514
- abi: DataPortabilityPermissionsAbi,
2515
- functionName: "revokePermissionWithSignature",
2516
- args: [typedData.message, formattedSignature],
2517
- account: this.context.walletClient?.account ?? this.context.userAddress,
2518
- chain: this.context.walletClient?.chain ?? null,
2519
- ...options && {
2520
- gas: options.gas,
2521
- nonce: options.nonce,
2522
- // Use EIP-1559 gas pricing if available, otherwise legacy
2523
- ...options.maxFeePerGas || options.maxPriorityFeePerGas ? {
2524
- maxFeePerGas: options.maxFeePerGas,
2525
- maxPriorityFeePerGas: options.maxPriorityFeePerGas
2526
- } : options.gasPrice ? { gasPrice: options.gasPrice } : {}
2527
- }
2528
- });
2529
- return txHash;
2530
- }
2531
- /**
2532
- * Submits an untrust server transaction with signature.
2533
- *
2534
- * @param typedData - The EIP-712 typed data structure for the untrust operation
2535
- * @param signature - The cryptographic signature authorizing the untrust
2536
- * @returns Promise resolving to the transaction hash
2537
- */
2538
- async submitSignedUntrustTransaction(typedData, signature, options) {
2539
- this.assertWallet();
2540
- const chainId = await this.context.walletClient.getChainId();
2541
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2542
- chainId,
2543
- "DataPortabilityServers"
2544
- );
2545
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2546
- const formattedSignature = (0, import_signatureFormatter.formatSignatureForContract)(signature);
2547
- const contractMessage = {
2548
- nonce: typedData.message.nonce,
2549
- serverId: BigInt(typedData.message.serverId)
2550
- };
2551
- const txHash = await this.context.walletClient.writeContract({
2552
- address: DataPortabilityServersAddress,
2553
- abi: DataPortabilityServersAbi,
2554
- functionName: "untrustServerWithSignature",
2555
- args: [contractMessage, formattedSignature],
2556
- account: this.context.walletClient?.account ?? this.context.userAddress,
2557
- chain: this.context.walletClient?.chain ?? null,
2558
- ...options && {
2559
- gas: options.gas,
2560
- nonce: options.nonce,
2561
- // Use EIP-1559 gas pricing if available, otherwise legacy
2562
- ...options.maxFeePerGas || options.maxPriorityFeePerGas ? {
2563
- maxFeePerGas: options.maxFeePerGas,
2564
- maxPriorityFeePerGas: options.maxPriorityFeePerGas
2565
- } : options.gasPrice ? { gasPrice: options.gasPrice } : {}
2566
- }
2567
- });
2568
- return txHash;
2569
- }
2570
- // ===========================
2571
- // GRANTEE METHODS
2572
- // ===========================
2573
- /**
2574
- * Registers a new grantee in the DataPortabilityGrantees contract.
2575
- *
2576
- * A grantee is an entity (like an application) that can receive data permissions
2577
- * from users. Once registered, users can grant the grantee access to their data.
2578
- *
2579
- * This method supports gasless transactions via relayer when configured.
2580
- * If no relayer is available, it falls back to direct wallet transactions.
2581
- *
2582
- * @param params - Parameters for registering the grantee
2583
- * @param params.owner - The Ethereum address that will own this grantee registration
2584
- * @param params.granteeAddress - The Ethereum address of the grantee (application)
2585
- * @param params.publicKey - The public key used for data encryption/decryption (hex string)
2586
- * @param options - Optional transaction options for gas parameters and timeout
2587
- * @returns Promise resolving to the transaction hash
2588
- * @throws {BlockchainError} When the grantee registration transaction fails
2589
- * @throws {UserRejectedRequestError} When user rejects the transaction
2590
- * @throws {RelayerError} When gasless transaction submission fails
2591
- *
2592
- * @example
2593
- * ```typescript
2594
- * const txHash = await vana.permissions.registerGrantee({
2595
- * owner: "0x742d35Cc6558Fd4D9e9E0E888F0462ef6919Bd36",
2596
- * granteeAddress: "0xApp1234567890123456789012345678901234567890",
2597
- * publicKey: "0x1234567890abcdef..."
2598
- * });
2599
- * console.log(`Grantee registered in transaction: ${txHash}`);
2600
- * ```
2601
- */
2602
- async submitRegisterGrantee(params, options) {
2603
- try {
2604
- let hash;
2605
- if (this.context.relayer) {
2606
- const request = {
2607
- type: "direct",
2608
- operation: "submitRegisterGrantee",
2609
- params: {
2610
- owner: params.owner,
2611
- granteeAddress: params.granteeAddress,
2612
- publicKey: params.publicKey
2613
- }
2614
- };
2615
- const response = await this.context.relayer(request);
2616
- if (response.type === "error") {
2617
- throw new import_errors.RelayerError(response.error);
2618
- }
2619
- if (response.type === "submitted") {
2620
- hash = response.hash;
2621
- } else if (response.type === "direct") {
2622
- const result = response.result;
2623
- hash = result.transactionHash;
2624
- } else {
2625
- throw new Error("Unexpected response type from relayer");
2626
- }
2627
- } else {
2628
- this.assertWallet();
2629
- const chainId = await this.context.walletClient.getChainId();
2630
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
2631
- chainId,
2632
- "DataPortabilityGrantees"
2633
- );
2634
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
2635
- const ownerAddress = (0, import_viem.getAddress)(params.owner);
2636
- const granteeAddress = (0, import_viem.getAddress)(params.granteeAddress);
2637
- const account2 = this.context.walletClient?.account ?? this.context.userAddress;
2638
- hash = await this.context.walletClient.writeContract({
2639
- address: DataPortabilityGranteesAddress,
2640
- abi: DataPortabilityGranteesAbi,
2641
- functionName: "registerGrantee",
2642
- args: [ownerAddress, granteeAddress, params.publicKey],
2643
- account: account2,
2644
- chain: this.context.walletClient?.chain ?? null,
2645
- ...this.spreadTransactionOptions(options)
2646
- });
2647
- }
2648
- const account = this.context.walletClient?.account ?? this.context.userAddress;
2649
- const { tx } = await import("../utils/transactionHelpers");
2650
- return tx({
2651
- hash,
2652
- from: typeof account === "string" ? account : account.address,
2653
- contract: "DataPortabilityGrantees",
2654
- fn: "registerGrantee"
2655
- });
2656
- } catch (error) {
2657
- if (error instanceof Error) {
2658
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.BlockchainError) {
2659
- throw error;
2660
- }
2661
- if (error.name === "ContractFunctionExecutionError") {
2662
- throw new import_errors.BlockchainError(
2663
- `Grantee registration failed: ${error.message}`,
2664
- error
2665
- );
2666
- }
2667
- if (error.name === "UserRejectedRequestError") {
2668
- throw new import_errors.UserRejectedRequestError(
2669
- "User rejected the grantee registration transaction"
2670
- );
2671
- }
2672
- throw new import_errors.BlockchainError(
2673
- `Failed to register grantee: ${error.message}`,
2674
- error
2675
- );
2676
- }
2677
- throw new import_errors.BlockchainError(`Failed to register grantee: ${String(error)}`);
2678
- }
2679
- }
2680
- // TODO: When DataPortabilityGrantees contract adds registerGranteeWithSignature function,
2681
- // implement submitRegisterGranteeWithSignature and submitSignedRegisterGrantee methods
2682
- // to support EIP-712 signed gasless transactions via relayer.
2683
- // Current implementation above supports direct gasless transactions (relayer pays gas directly).
2684
- /**
2685
- * Retrieves all registered grantees from the DataPortabilityGrantees contract.
2686
- *
2687
- * Returns a paginated list of all grantees (applications) that have been registered
2688
- * in the system and can receive data permissions from users.
2689
- *
2690
- * @param options - Query options for pagination and filtering
2691
- * @param options.limit - Maximum number of grantees to return (default: 50)
2692
- * @param options.offset - Number of grantees to skip for pagination (default: 0)
2693
- * @returns Promise resolving to paginated grantees with metadata
2694
- * @throws {BlockchainError} When contract read operation fails
2695
- * @throws {NetworkError} When unable to connect to the blockchain network
2696
- *
2697
- * @example
2698
- * ```typescript
2699
- * // Get first 10 grantees
2700
- * const result = await vana.permissions.getGrantees({
2701
- * limit: 10,
2702
- * offset: 0
2703
- * });
2704
- *
2705
- * console.log(`Found ${result.total} total grantees`);
2706
- * result.grantees.forEach(grantee => {
2707
- * console.log(`Grantee ${grantee.id}: ${grantee.granteeAddress}`);
2708
- * });
2709
- *
2710
- * // Check if there are more results
2711
- * if (result.hasMore) {
2712
- * console.log('More grantees available');
2713
- * }
2714
- * ```
2715
- */
2716
- async getGrantees(options = {}) {
2717
- const chainId = await this.context.publicClient.getChainId();
2718
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
2719
- chainId,
2720
- "DataPortabilityGrantees"
2721
- );
2722
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
2723
- const totalCount = await this.context.publicClient.readContract({
2724
- address: DataPortabilityGranteesAddress,
2725
- abi: DataPortabilityGranteesAbi,
2726
- functionName: "granteesCount"
2727
- });
2728
- const total = Number(totalCount);
2729
- const limit = options.limit ?? 50;
2730
- const offset = options.offset ?? 0;
2731
- const includePermissions = options.includePermissions ?? true;
2732
- const startId = total - offset;
2733
- const endId = Math.max(startId - limit + 1, 1);
2734
- const granteeIds = Array.from(
2735
- { length: startId - endId + 1 },
2736
- (_, i) => startId - i
2737
- // Generate IDs in descending order
2738
- );
2739
- let grantees;
2740
- if (includePermissions) {
2741
- const granteePromises = granteeIds.map(
2742
- (granteeId) => this.getGranteeById(granteeId)
2743
- );
2744
- const granteeResults = await Promise.all(granteePromises);
2745
- grantees = granteeResults.filter(
2746
- (grantee) => grantee !== null
2747
- );
2748
- } else {
2749
- const granteeInfoPromises = granteeIds.map(
2750
- async (granteeId) => {
2751
- try {
2752
- const granteeInfo = await this.context.publicClient.readContract({
2753
- address: DataPortabilityGranteesAddress,
2754
- abi: DataPortabilityGranteesAbi,
2755
- functionName: "granteesV2",
2756
- args: [BigInt(granteeId)]
2757
- });
2758
- const grantee = {
2759
- id: granteeId,
2760
- owner: granteeInfo.owner,
2761
- address: granteeInfo.granteeAddress,
2762
- publicKey: granteeInfo.publicKey,
2763
- permissionIds: []
2764
- // TypeScript infers number[] from Grantee type
2765
- };
2766
- return grantee;
2767
- } catch (error) {
2768
- console.warn(`Failed to fetch grantee ${granteeId}:`, error);
2769
- return null;
2770
- }
2771
- }
2772
- );
2773
- const granteeInfoResults = await Promise.all(granteeInfoPromises);
2774
- grantees = granteeInfoResults.filter(
2775
- (grantee) => grantee !== null
2776
- );
2777
- }
2778
- return {
2779
- grantees,
2780
- total,
2781
- offset,
2782
- limit,
2783
- hasMore: offset + limit < total
2784
- };
2785
- }
2786
- /**
2787
- * Retrieves a specific grantee by their Ethereum wallet address.
2788
- *
2789
- * @remarks
2790
- * Looks up a registered grantee (application) using their Ethereum address
2791
- * and returns their complete registration information including all associated permissions.
2792
- *
2793
- * Returns `null` if the address is not registered as a grantee or if an error occurs.
2794
- *
2795
- * @param granteeAddress - Ethereum wallet address of the grantee to query
2796
- * @returns Grantee information including ID, addresses, public key, and permission IDs, or `null` if not found
2797
- *
2798
- * @example
2799
- * ```typescript
2800
- * const granteeAddress = "0xApp1234567890123456789012345678901234567890";
2801
- * const grantee = await vana.permissions.getGranteeByAddress(granteeAddress);
2802
- *
2803
- * if (grantee) {
2804
- * console.log(`Found grantee ${grantee.id}`);
2805
- * console.log(`Owner: ${grantee.owner}`);
2806
- * console.log(`Public Key: ${grantee.publicKey}`);
2807
- * console.log(`Permissions: ${grantee.permissionIds.join(', ')}`);
2808
- * } else {
2809
- * console.log('Grantee not found');
2810
- * }
2811
- * ```
2812
- */
2813
- async getGranteeByAddress(granteeAddress) {
2814
- const chainId = await this.context.publicClient.getChainId();
2815
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
2816
- chainId,
2817
- "DataPortabilityGrantees"
2818
- );
2819
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
2820
- try {
2821
- const granteeId = await this.context.publicClient.readContract({
2822
- address: DataPortabilityGranteesAddress,
2823
- abi: DataPortabilityGranteesAbi,
2824
- functionName: "granteeAddressToId",
2825
- args: [granteeAddress]
2826
- });
2827
- if (granteeId === 0n) {
2828
- return null;
2829
- }
2830
- return await this.getGranteeById(Number(granteeId));
2831
- } catch (error) {
2832
- console.warn(`Failed to fetch grantee ${granteeAddress}:`, error);
2833
- return null;
2834
- }
2835
- }
2836
- /**
2837
- * Retrieves a specific grantee by their unique ID.
2838
- *
2839
- * @remarks
2840
- * Looks up a registered grantee (application) using their numeric ID assigned during
2841
- * registration and returns their complete information including all associated permissions.
2842
- *
2843
- * Returns `null` if the grantee is not found or if an error occurs during fetching.
2844
- *
2845
- * @param granteeId - Unique numeric ID of the grantee (1-indexed)
2846
- * @returns Grantee information including ID, addresses, public key, and permission IDs, or `null` if not found
2847
- *
2848
- * @example
2849
- * ```typescript
2850
- * const grantee = await vana.permissions.getGranteeById(1);
2851
- *
2852
- * if (grantee) {
2853
- * console.log(`Grantee ID: ${grantee.id}`);
2854
- * console.log(`Address: ${grantee.address}`);
2855
- * console.log(`Owner: ${grantee.owner}`);
2856
- * console.log(`Total permissions: ${grantee.permissionIds.length}`);
2857
- * } else {
2858
- * console.log('Grantee with ID 1 not found');
2859
- * }
2860
- * ```
2861
- */
2862
- async getGranteeById(granteeId) {
2863
- const chainId = await this.context.publicClient.getChainId();
2864
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
2865
- chainId,
2866
- "DataPortabilityGrantees"
2867
- );
2868
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
2869
- try {
2870
- const granteeInfoResult = await this.context.publicClient.readContract({
2871
- address: DataPortabilityGranteesAddress,
2872
- abi: DataPortabilityGranteesAbi,
2873
- functionName: "granteesV2",
2874
- args: [BigInt(granteeId)]
2875
- });
2876
- const granteeInfo = granteeInfoResult;
2877
- const allPermissionIdsResult = await this.getGranteePermissionsPaginated(
2878
- BigInt(granteeId)
2879
- );
2880
- const allPermissionIds = allPermissionIdsResult;
2881
- return {
2882
- id: granteeId,
2883
- owner: granteeInfo.owner,
2884
- address: granteeInfo.granteeAddress,
2885
- publicKey: granteeInfo.publicKey,
2886
- permissionIds: allPermissionIds.map((id) => Number(id))
2887
- };
2888
- } catch (error) {
2889
- console.warn(`Failed to fetch grantee ${granteeId}:`, error);
2890
- return null;
2891
- }
2892
- }
2893
- // ===========================
2894
- // DATA PORTABILITY SERVERS HELPER METHODS
2895
- // ===========================
2896
- /**
2897
- * Get all trusted server IDs for a user
2898
- *
2899
- * @param userAddress - User address to query (defaults to current user)
2900
- * @returns Promise resolving to array of server IDs
2901
- */
2902
- async getUserServerIds(userAddress) {
2903
- try {
2904
- const targetAddress = userAddress ?? this.context.userAddress;
2905
- const chainId = await this.context.publicClient.getChainId();
2906
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2907
- chainId,
2908
- "DataPortabilityServers"
2909
- );
2910
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2911
- const serverIds = await this.context.publicClient.readContract({
2912
- address: DataPortabilityServersAddress,
2913
- abi: DataPortabilityServersAbi,
2914
- functionName: "userServerIdsValues",
2915
- args: [targetAddress]
2916
- });
2917
- return [...serverIds];
2918
- } catch (error) {
2919
- throw new import_errors.BlockchainError(
2920
- `Failed to get user server IDs: ${error instanceof Error ? error.message : "Unknown error"}`,
2921
- error
2922
- );
2923
- }
2924
- }
2925
- /**
2926
- * Get server ID at specific index for a user
2927
- *
2928
- * @param userAddress - User address to query
2929
- * @param serverIndex - Index in the user's server list
2930
- * @returns Promise resolving to server ID
2931
- */
2932
- async getUserServerIdAt(userAddress, serverIndex) {
2933
- try {
2934
- const chainId = await this.context.publicClient.getChainId();
2935
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2936
- chainId,
2937
- "DataPortabilityServers"
2938
- );
2939
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2940
- const serverId = await this.context.publicClient.readContract({
2941
- address: DataPortabilityServersAddress,
2942
- abi: DataPortabilityServersAbi,
2943
- functionName: "userServerIdsAt",
2944
- args: [userAddress, serverIndex]
2945
- });
2946
- return serverId;
2947
- } catch (error) {
2948
- throw new import_errors.BlockchainError(
2949
- `Failed to get user server ID at index: ${error instanceof Error ? error.message : "Unknown error"}`,
2950
- error
2951
- );
2952
- }
2953
- }
2954
- /**
2955
- * Get the number of trusted servers for a user
2956
- *
2957
- * @param userAddress - User address to query (defaults to current user)
2958
- * @returns Promise resolving to number of trusted servers
2959
- */
2960
- async getUserServerCount(userAddress) {
2961
- try {
2962
- const targetAddress = userAddress ?? this.context.userAddress;
2963
- const chainId = await this.context.publicClient.getChainId();
2964
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2965
- chainId,
2966
- "DataPortabilityServers"
2967
- );
2968
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2969
- const count = await this.context.publicClient.readContract({
2970
- address: DataPortabilityServersAddress,
2971
- abi: DataPortabilityServersAbi,
2972
- functionName: "userServerIdsLength",
2973
- args: [targetAddress]
2974
- });
2975
- return count;
2976
- } catch (error) {
2977
- throw new import_errors.BlockchainError(
2978
- `Failed to get user server count: ${error instanceof Error ? error.message : "Unknown error"}`,
2979
- error
2980
- );
2981
- }
2982
- }
2983
- /**
2984
- * Get detailed information about trusted servers for a user
2985
- *
2986
- * @param userAddress - User address to query (defaults to current user)
2987
- * @returns Promise resolving to array of trusted server info
2988
- */
2989
- async getUserTrustedServers(userAddress) {
2990
- try {
2991
- const targetAddress = userAddress ?? this.context.userAddress;
2992
- const chainId = await this.context.publicClient.getChainId();
2993
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
2994
- chainId,
2995
- "DataPortabilityServers"
2996
- );
2997
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
2998
- const servers = await this.context.publicClient.readContract({
2999
- address: DataPortabilityServersAddress,
3000
- abi: DataPortabilityServersAbi,
3001
- functionName: "userServerValues",
3002
- args: [targetAddress]
3003
- });
3004
- return [...servers];
3005
- } catch (error) {
3006
- throw new import_errors.BlockchainError(
3007
- `Failed to get user trusted servers: ${error instanceof Error ? error.message : "Unknown error"}`,
3008
- error
3009
- );
3010
- }
3011
- }
3012
- /**
3013
- * Get trusted server info for a specific server ID and user
3014
- *
3015
- * @param userAddress - User address to query
3016
- * @param serverId - Server ID to get info for
3017
- * @returns Promise resolving to trusted server info
3018
- */
3019
- async getUserTrustedServer(userAddress, serverId) {
3020
- try {
3021
- const chainId = await this.context.publicClient.getChainId();
3022
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3023
- chainId,
3024
- "DataPortabilityServers"
3025
- );
3026
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3027
- const serverInfo = await this.context.publicClient.readContract({
3028
- address: DataPortabilityServersAddress,
3029
- abi: DataPortabilityServersAbi,
3030
- functionName: "userServers",
3031
- args: [userAddress, serverId]
3032
- });
3033
- return serverInfo;
3034
- } catch (error) {
3035
- throw new import_errors.BlockchainError(
3036
- `Failed to get user trusted server: ${error instanceof Error ? error.message : "Unknown error"}`,
3037
- error
3038
- );
3039
- }
3040
- }
3041
- /**
3042
- * Get server information by server ID
3043
- *
3044
- * @param serverId - Server ID to get info for
3045
- * @returns Promise resolving to server info
3046
- */
3047
- async getServerInfo(serverId) {
3048
- try {
3049
- const chainId = await this.context.publicClient.getChainId();
3050
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3051
- chainId,
3052
- "DataPortabilityServers"
3053
- );
3054
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3055
- const serverInfo = await this.context.publicClient.readContract({
3056
- address: DataPortabilityServersAddress,
3057
- abi: DataPortabilityServersAbi,
3058
- functionName: "servers",
3059
- args: [serverId]
3060
- });
3061
- return serverInfo;
3062
- } catch (error) {
3063
- throw new import_errors.BlockchainError(
3064
- `Failed to get server info: ${error instanceof Error ? error.message : "Unknown error"}`,
3065
- error
3066
- );
3067
- }
3068
- }
3069
- /**
3070
- * Get server information by server address
3071
- *
3072
- * @param serverAddress - Server address to get info for
3073
- * @returns Promise resolving to server info
3074
- */
3075
- async getServerInfoByAddress(serverAddress) {
3076
- try {
3077
- const chainId = await this.context.publicClient.getChainId();
3078
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3079
- chainId,
3080
- "DataPortabilityServers"
3081
- );
3082
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3083
- const serverInfo = await this.context.publicClient.readContract({
3084
- address: DataPortabilityServersAddress,
3085
- abi: DataPortabilityServersAbi,
3086
- functionName: "serverByAddress",
3087
- args: [serverAddress]
3088
- });
3089
- return serverInfo;
3090
- } catch (error) {
3091
- throw new import_errors.BlockchainError(
3092
- `Failed to get server info by address: ${error instanceof Error ? error.message : "Unknown error"}`,
3093
- error
3094
- );
3095
- }
3096
- }
3097
- // ===========================
3098
- // DATA PORTABILITY PERMISSIONS HELPER METHODS
3099
- // ===========================
3100
- /**
3101
- * Get all permission IDs for a user
3102
- *
3103
- * @param userAddress - User address to query (defaults to current user)
3104
- * @returns Promise resolving to array of permission IDs
3105
- */
3106
- async getUserPermissionIds(userAddress) {
3107
- try {
3108
- const targetAddress = userAddress ?? this.context.userAddress;
3109
- const chainId = await this.context.publicClient.getChainId();
3110
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3111
- chainId,
3112
- "DataPortabilityPermissions"
3113
- );
3114
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3115
- "DataPortabilityPermissions"
3116
- );
3117
- const permissionIds = await this.context.publicClient.readContract({
3118
- address: DataPortabilityPermissionsAddress,
3119
- abi: DataPortabilityPermissionsAbi,
3120
- functionName: "userPermissionIdsValues",
3121
- args: [targetAddress]
3122
- });
3123
- return [...permissionIds];
3124
- } catch (error) {
3125
- throw new import_errors.BlockchainError(
3126
- `Failed to get user permission IDs: ${error instanceof Error ? error.message : "Unknown error"}`,
3127
- error
3128
- );
3129
- }
3130
- }
3131
- /**
3132
- * Get permission ID at specific index for a user
3133
- *
3134
- * @param userAddress - User address to query
3135
- * @param permissionIndex - Index in the user's permission list
3136
- * @returns Promise resolving to permission ID
3137
- */
3138
- async getUserPermissionIdAt(userAddress, permissionIndex) {
3139
- try {
3140
- const chainId = await this.context.publicClient.getChainId();
3141
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3142
- chainId,
3143
- "DataPortabilityPermissions"
3144
- );
3145
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3146
- "DataPortabilityPermissions"
3147
- );
3148
- const permissionId = await this.context.publicClient.readContract({
3149
- address: DataPortabilityPermissionsAddress,
3150
- abi: DataPortabilityPermissionsAbi,
3151
- functionName: "userPermissionIdsAt",
3152
- args: [userAddress, permissionIndex]
3153
- });
3154
- return permissionId;
3155
- } catch (error) {
3156
- throw new import_errors.BlockchainError(
3157
- `Failed to get user permission ID at index: ${error instanceof Error ? error.message : "Unknown error"}`,
3158
- error
3159
- );
3160
- }
3161
- }
3162
- /**
3163
- * Get the number of permissions for a user
3164
- *
3165
- * @param userAddress - User address to query (defaults to current user)
3166
- * @returns Promise resolving to number of permissions
3167
- */
3168
- async getUserPermissionCount(userAddress) {
3169
- try {
3170
- const targetAddress = userAddress ?? this.context.userAddress;
3171
- const chainId = await this.context.publicClient.getChainId();
3172
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3173
- chainId,
3174
- "DataPortabilityPermissions"
3175
- );
3176
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3177
- "DataPortabilityPermissions"
3178
- );
3179
- const count = await this.context.publicClient.readContract({
3180
- address: DataPortabilityPermissionsAddress,
3181
- abi: DataPortabilityPermissionsAbi,
3182
- functionName: "userPermissionIdsLength",
3183
- args: [targetAddress]
3184
- });
3185
- return count;
3186
- } catch (error) {
3187
- throw new import_errors.BlockchainError(
3188
- `Failed to get user permission count: ${error instanceof Error ? error.message : "Unknown error"}`,
3189
- error
3190
- );
3191
- }
3192
- }
3193
- /**
3194
- * Get detailed permission information by permission ID
3195
- *
3196
- * @param permissionId - Permission ID to get info for
3197
- * @returns Promise resolving to permission info
3198
- */
3199
- async getPermissionInfo(permissionId) {
3200
- try {
3201
- const chainId = await this.context.publicClient.getChainId();
3202
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3203
- chainId,
3204
- "DataPortabilityPermissions"
3205
- );
3206
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3207
- "DataPortabilityPermissions"
3208
- );
3209
- const permissionInfo = await this.context.publicClient.readContract({
3210
- address: DataPortabilityPermissionsAddress,
3211
- abi: DataPortabilityPermissionsAbi,
3212
- functionName: "permissions",
3213
- args: [permissionId]
3214
- });
3215
- return permissionInfo;
3216
- } catch (error) {
3217
- throw new import_errors.BlockchainError(
3218
- `Failed to get permission info: ${error instanceof Error ? error.message : "Unknown error"}`,
3219
- error
3220
- );
3221
- }
3222
- }
3223
- /**
3224
- * Get all permission IDs for a specific file
3225
- *
3226
- * @param fileId - File ID to get permissions for
3227
- * @returns Promise resolving to array of permission IDs
3228
- */
3229
- async getFilePermissionIds(fileId) {
3230
- try {
3231
- const chainId = await this.context.publicClient.getChainId();
3232
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3233
- chainId,
3234
- "DataPortabilityPermissions"
3235
- );
3236
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3237
- "DataPortabilityPermissions"
3238
- );
3239
- const permissionIds = await this.context.publicClient.readContract({
3240
- address: DataPortabilityPermissionsAddress,
3241
- abi: DataPortabilityPermissionsAbi,
3242
- functionName: "filePermissionIds",
3243
- args: [fileId]
3244
- });
3245
- return [...permissionIds];
3246
- } catch (error) {
3247
- throw new import_errors.BlockchainError(
3248
- `Failed to get file permission IDs: ${error instanceof Error ? error.message : "Unknown error"}`,
3249
- error
3250
- );
3251
- }
3252
- }
3253
- /**
3254
- * Get all file IDs for a specific permission
3255
- *
3256
- * @param permissionId - Permission ID to get files for
3257
- * @returns Promise resolving to array of file IDs
3258
- */
3259
- async getPermissionFileIds(permissionId) {
3260
- try {
3261
- const chainId = await this.context.publicClient.getChainId();
3262
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3263
- chainId,
3264
- "DataPortabilityPermissions"
3265
- );
3266
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3267
- "DataPortabilityPermissions"
3268
- );
3269
- const fileIds = await this.context.publicClient.readContract({
3270
- address: DataPortabilityPermissionsAddress,
3271
- abi: DataPortabilityPermissionsAbi,
3272
- functionName: "permissionFileIds",
3273
- args: [permissionId]
3274
- });
3275
- return [...fileIds];
3276
- } catch (error) {
3277
- throw new import_errors.BlockchainError(
3278
- `Failed to get permission file IDs: ${error instanceof Error ? error.message : "Unknown error"}`,
3279
- error
3280
- );
3281
- }
3282
- }
3283
- /**
3284
- * Retrieves detailed grant file data from IPFS or HTTP storage.
3285
- *
3286
- * @remarks
3287
- * This method automatically uses the SDK's configured downloadRelayer to bypass CORS restrictions.
3288
- * Use this instead of importing the standalone `retrieveGrantFile` utility.
3289
- *
3290
- * @param grantUrl - The grant file URL (from OnChainPermissionGrant.grantUrl)
3291
- * @returns Promise resolving to the complete grant file with operation details
3292
- * @throws {NetworkError} When all retrieval attempts fail
3293
- * @example
3294
- * ```typescript
3295
- * const grants = await vana.permissions.getUserPermissionGrantsOnChain();
3296
- * const grantFile = await vana.permissions.retrieveGrantFile(grants[0].grantUrl);
3297
- * console.log(`Operation: ${grantFile.operation}`);
3298
- * ```
3299
- */
3300
- async retrieveGrantFile(grantUrl) {
3301
- const { retrieveGrantFile: retrieveGrantFileUtil } = await import("../utils/grantFiles");
3302
- return retrieveGrantFileUtil(
3303
- grantUrl,
3304
- void 0,
3305
- this.context.downloadRelayer
3306
- );
3307
- }
3308
- /**
3309
- * Get all permissions for a specific file (alias for getFilePermissionIds)
3310
- *
3311
- * @param fileId - File ID to get permissions for
3312
- * @returns Promise resolving to array of permission IDs
3313
- */
3314
- async getFilePermissions(fileId) {
3315
- const chainId = await this.context.publicClient.getChainId();
3316
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3317
- chainId,
3318
- "DataPortabilityPermissions"
3319
- );
3320
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)("DataPortabilityPermissions");
3321
- const permissions = await this.context.publicClient.readContract({
3322
- address: DataPortabilityPermissionsAddress,
3323
- abi: DataPortabilityPermissionsAbi,
3324
- functionName: "filePermissions",
3325
- args: [fileId]
3326
- });
3327
- return [...permissions];
3328
- }
3329
- // ===========================
3330
- // DATA PORTABILITY GRANTEES HELPER METHODS
3331
- // ===========================
3332
- /**
3333
- * Retrieves detailed grantee information including all associated permissions.
3334
- *
3335
- * @remarks
3336
- * Returns grantee metadata and associated permission IDs. Uses the newer
3337
- * paginated contract method internally for efficient permission fetching.
3338
- *
3339
- * @param granteeId - Unique grantee identifier as bigint
3340
- * @returns Grantee information containing owner address, grantee address, public key, and permission IDs
3341
- * @throws {BlockchainError} When grantee ID is not found or contract read fails
3342
- *
3343
- * @example
3344
- * ```typescript
3345
- * const granteeInfo = await vana.permissions.getGranteeInfo(BigInt(1));
3346
- * console.log(`Grantee ${granteeInfo.granteeAddress} has ${granteeInfo.permissionIds.length} permissions`);
3347
- * ```
3348
- */
3349
- async getGranteeInfo(granteeId) {
3350
- try {
3351
- const grantee = await this.getGranteeById(Number(granteeId));
3352
- if (!grantee) {
3353
- throw new Error("Grantee not found");
3354
- }
3355
- return {
3356
- owner: grantee.owner,
3357
- granteeAddress: grantee.address,
3358
- publicKey: grantee.publicKey,
3359
- permissionIds: grantee.permissionIds.map((id) => BigInt(id))
3360
- };
3361
- } catch (error) {
3362
- throw new import_errors.BlockchainError(
3363
- `Failed to get grantee info: ${error instanceof Error ? error.message : "Unknown error"}`,
3364
- error
3365
- );
3366
- }
3367
- }
3368
- /**
3369
- * Retrieves detailed grantee information by wallet address.
3370
- *
3371
- * @remarks
3372
- * Looks up the grantee ID from the provided address, then fetches complete
3373
- * grantee information including all associated permissions.
3374
- *
3375
- * @param granteeAddress - Ethereum wallet address of the grantee to query
3376
- * @returns Grantee information containing owner address, grantee address, public key, and permission IDs
3377
- * @throws {BlockchainError} When grantee address is not registered or contract read fails
3378
- *
3379
- * @example
3380
- * ```typescript
3381
- * const granteeInfo = await vana.permissions.getGranteeInfoByAddress("0x742d35Cc6634c0532925a3b844Bc9e8e1ee3b2De");
3382
- * console.log(`Found grantee with ${granteeInfo.permissionIds.length} permissions`);
3383
- * ```
3384
- */
3385
- async getGranteeInfoByAddress(granteeAddress) {
3386
- try {
3387
- const chainId = await this.context.publicClient.getChainId();
3388
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
3389
- chainId,
3390
- "DataPortabilityGrantees"
3391
- );
3392
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
3393
- const granteeIdResult = await this.context.publicClient.readContract({
3394
- address: DataPortabilityGranteesAddress,
3395
- abi: DataPortabilityGranteesAbi,
3396
- functionName: "granteeAddressToId",
3397
- args: [granteeAddress]
3398
- });
3399
- const granteeId = granteeIdResult;
3400
- if (granteeId === 0n) {
3401
- throw new Error("Grantee not found");
3402
- }
3403
- const grantee = await this.getGranteeById(Number(granteeId));
3404
- if (!grantee) {
3405
- throw new Error("Grantee not found");
3406
- }
3407
- return {
3408
- owner: grantee.owner,
3409
- granteeAddress: grantee.address,
3410
- publicKey: grantee.publicKey,
3411
- permissionIds: grantee.permissionIds.map((id) => BigInt(id))
3412
- };
3413
- } catch (error) {
3414
- throw new import_errors.BlockchainError(
3415
- `Failed to get grantee info by address: ${error instanceof Error ? error.message : "Unknown error"}`,
3416
- error
3417
- );
3418
- }
3419
- }
3420
- /**
3421
- * Get all permission IDs for a specific grantee
3422
- *
3423
- * @param granteeId - Grantee ID to get permissions for
3424
- * @returns Promise resolving to array of permission IDs
3425
- */
3426
- async getGranteePermissionIds(granteeId) {
3427
- try {
3428
- const chainId = await this.context.publicClient.getChainId();
3429
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
3430
- chainId,
3431
- "DataPortabilityGrantees"
3432
- );
3433
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
3434
- const permissionIds = await this.context.publicClient.readContract({
3435
- address: DataPortabilityGranteesAddress,
3436
- abi: DataPortabilityGranteesAbi,
3437
- functionName: "granteePermissionIds",
3438
- args: [granteeId]
3439
- });
3440
- return [...permissionIds];
3441
- } catch (error) {
3442
- throw new import_errors.BlockchainError(
3443
- `Failed to get grantee permission IDs: ${error instanceof Error ? error.message : "Unknown error"}`,
3444
- error
3445
- );
3446
- }
3447
- }
3448
- /**
3449
- * Get all permissions for a specific grantee (alias for getGranteePermissionIds)
3450
- *
3451
- * @param granteeId - Grantee ID to get permissions for
3452
- * @returns Promise resolving to array of permission IDs
3453
- */
3454
- async getGranteePermissions(granteeId) {
3455
- try {
3456
- const chainId = await this.context.publicClient.getChainId();
3457
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
3458
- chainId,
3459
- "DataPortabilityGrantees"
3460
- );
3461
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
3462
- const permissions = await this.context.publicClient.readContract({
3463
- address: DataPortabilityGranteesAddress,
3464
- abi: DataPortabilityGranteesAbi,
3465
- functionName: "granteePermissions",
3466
- args: [granteeId]
3467
- });
3468
- return [...permissions];
3469
- } catch (error) {
3470
- throw new import_errors.BlockchainError(
3471
- `Failed to get grantee permissions: ${error instanceof Error ? error.message : "Unknown error"}`,
3472
- error
3473
- );
3474
- }
3475
- }
3476
- /**
3477
- * Retrieves permission IDs for a specific grantee with flexible pagination.
3478
- *
3479
- * @remarks
3480
- * **Pagination Behavior:**
3481
- * Returns different types based on parameters:
3482
- * - Without offset/limit: Returns `bigint[]` of all permissions using batched multicall
3483
- * - With offset/limit: Returns paginated object with `permissionIds`, `totalCount`, and `hasMore`
3484
- *
3485
- * Uses gas-aware multicall for efficient batch fetching when retrieving all permissions.
3486
- *
3487
- * @param granteeId - Grantee ID to get permissions for
3488
- * @param options - Optional pagination parameters
3489
- * @param options.offset - Zero-based starting index for pagination. Defaults to 0 when fetching all permissions. Required for single-page requests.
3490
- * @param options.limit - Maximum number of permission IDs to return per page. Defaults to 100 when fetching all permissions. Required for single-page requests.
3491
- * @returns When called without options: Array of all permission IDs as `bigint[]`.
3492
- * When called with offset and limit: Paginated result object containing `permissionIds` array,
3493
- * `totalCount`, and `hasMore` boolean.
3494
- * @throws {BlockchainError} When contract read operation fails
3495
- *
3496
- * @example
3497
- * ```typescript
3498
- * // Fetch all permissions (no pagination params)
3499
- * const allPermissions = await vana.permissions.getGranteePermissionsPaginated(BigInt(1));
3500
- * console.log(`Total permissions: ${allPermissions.length}`);
3501
- *
3502
- * // Fetch a specific page (with pagination params)
3503
- * const page = await vana.permissions.getGranteePermissionsPaginated(BigInt(1), {
3504
- * offset: BigInt(0),
3505
- * limit: BigInt(100)
3506
- * });
3507
- * console.log(`Fetched ${page.permissionIds.length} permissions`);
3508
- * console.log(`Total: ${page.totalCount}, Has more: ${page.hasMore}`);
3509
- *
3510
- * // Fetch next page
3511
- * if (page.hasMore) {
3512
- * const nextPage = await vana.permissions.getGranteePermissionsPaginated(BigInt(1), {
3513
- * offset: BigInt(100),
3514
- * limit: BigInt(100)
3515
- * });
3516
- * }
3517
- * ```
3518
- */
3519
- async getGranteePermissionsPaginated(granteeId, options) {
3520
- try {
3521
- const chainId = await this.context.publicClient.getChainId();
3522
- const DataPortabilityGranteesAddress = (0, import_addresses.getContractAddress)(
3523
- chainId,
3524
- "DataPortabilityGrantees"
3525
- );
3526
- const DataPortabilityGranteesAbi = (0, import_abi.getAbi)("DataPortabilityGrantees");
3527
- const fetchOnlyOnePage = options?.offset !== void 0 && options?.limit !== void 0;
3528
- if (fetchOnlyOnePage) {
3529
- const result = await this.context.publicClient.readContract({
3530
- address: DataPortabilityGranteesAddress,
3531
- abi: DataPortabilityGranteesAbi,
3532
- functionName: "granteePermissionsPaginated",
3533
- args: [granteeId, options.offset, options.limit]
3534
- });
3535
- const [permissionIds, totalCount2, hasMore] = result;
3536
- return {
3537
- permissionIds: [...permissionIds],
3538
- totalCount: totalCount2,
3539
- hasMore
3540
- };
3541
- }
3542
- const countResult = await this.context.publicClient.readContract({
3543
- address: DataPortabilityGranteesAddress,
3544
- abi: DataPortabilityGranteesAbi,
3545
- functionName: "granteePermissionsPaginated",
3546
- args: [granteeId, BigInt(0), BigInt(1)]
3547
- });
3548
- const [, totalCount] = countResult;
3549
- if (totalCount === BigInt(0)) {
3550
- return [];
3551
- }
3552
- const batchSize = options?.limit ?? BigInt(100);
3553
- const startOffset = options?.offset ?? BigInt(0);
3554
- const endOffset = totalCount;
3555
- const numBatches = Math.ceil(
3556
- Number(endOffset - startOffset) / Number(batchSize)
3557
- );
3558
- const paginationCalls = Array.from({ length: numBatches }, (_, i) => ({
3559
- address: DataPortabilityGranteesAddress,
3560
- abi: DataPortabilityGranteesAbi,
3561
- functionName: "granteePermissionsPaginated",
3562
- args: [
3563
- granteeId,
3564
- startOffset + BigInt(i) * batchSize,
3565
- batchSize
3566
- ]
3567
- }));
3568
- const results = await (0, import_multicall.gasAwareMulticall)(
3569
- this.context.publicClient,
3570
- {
3571
- contracts: paginationCalls
3572
- }
3573
- );
3574
- const allPermissionIds = [];
3575
- for (const result of results) {
3576
- const [permissionIds] = result;
3577
- allPermissionIds.push(...permissionIds);
3578
- }
3579
- return allPermissionIds;
3580
- } catch (error) {
3581
- throw new import_errors.BlockchainError(
3582
- `Failed to get grantee permissions: ${error instanceof Error ? error.message : "Unknown error"}`,
3583
- error
3584
- );
3585
- }
3586
- }
3587
- // ===== DataPortabilityServersImplementation Methods =====
3588
- /**
3589
- * Get all server IDs for a user
3590
- *
3591
- * @param userAddress - User address to get server IDs for
3592
- * @returns Promise resolving to array of server IDs
3593
- */
3594
- async getUserServerIdsValues(userAddress) {
3595
- try {
3596
- const chainId = await this.context.publicClient.getChainId();
3597
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3598
- chainId,
3599
- "DataPortabilityServers"
3600
- );
3601
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3602
- const serverIds = await this.context.publicClient.readContract({
3603
- address: DataPortabilityServersAddress,
3604
- abi: DataPortabilityServersAbi,
3605
- functionName: "userServerIdsValues",
3606
- args: [userAddress]
3607
- });
3608
- return [...serverIds];
3609
- } catch (error) {
3610
- throw new import_errors.BlockchainError(
3611
- `Failed to get user server IDs: ${error instanceof Error ? error.message : "Unknown error"}`,
3612
- error
3613
- );
3614
- }
3615
- }
3616
- /**
3617
- * Get server ID at specific index for a user
3618
- *
3619
- * @param userAddress - User address
3620
- * @param serverIndex - Index of the server ID
3621
- * @returns Promise resolving to server ID
3622
- */
3623
- async getUserServerIdsAt(userAddress, serverIndex) {
3624
- try {
3625
- const chainId = await this.context.publicClient.getChainId();
3626
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3627
- chainId,
3628
- "DataPortabilityServers"
3629
- );
3630
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3631
- const serverId = await this.context.publicClient.readContract({
3632
- address: DataPortabilityServersAddress,
3633
- abi: DataPortabilityServersAbi,
3634
- functionName: "userServerIdsAt",
3635
- args: [userAddress, serverIndex]
3636
- });
3637
- return serverId;
3638
- } catch (error) {
3639
- throw new import_errors.BlockchainError(
3640
- `Failed to get user server ID at index: ${error instanceof Error ? error.message : "Unknown error"}`,
3641
- error
3642
- );
3643
- }
3644
- }
3645
- /**
3646
- * Get the number of servers a user has
3647
- *
3648
- * @param userAddress - User address
3649
- * @returns Promise resolving to number of servers
3650
- */
3651
- async getUserServerIdsLength(userAddress) {
3652
- try {
3653
- const chainId = await this.context.publicClient.getChainId();
3654
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3655
- chainId,
3656
- "DataPortabilityServers"
3657
- );
3658
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3659
- const length = await this.context.publicClient.readContract({
3660
- address: DataPortabilityServersAddress,
3661
- abi: DataPortabilityServersAbi,
3662
- functionName: "userServerIdsLength",
3663
- args: [userAddress]
3664
- });
3665
- return length;
3666
- } catch (error) {
3667
- throw new import_errors.BlockchainError(
3668
- `Failed to get user server IDs length: ${error instanceof Error ? error.message : "Unknown error"}`,
3669
- error
3670
- );
3671
- }
3672
- }
3673
- /**
3674
- * Get trusted server info for a specific user and server ID
3675
- *
3676
- * @param userAddress - User address
3677
- * @param serverId - Server ID
3678
- * @returns Promise resolving to trusted server info
3679
- */
3680
- async getUserServers(userAddress, serverId) {
3681
- try {
3682
- const chainId = await this.context.publicClient.getChainId();
3683
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3684
- chainId,
3685
- "DataPortabilityServers"
3686
- );
3687
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3688
- const serverInfo = await this.context.publicClient.readContract({
3689
- address: DataPortabilityServersAddress,
3690
- abi: DataPortabilityServersAbi,
3691
- functionName: "userServers",
3692
- args: [userAddress, serverId]
3693
- });
3694
- return {
3695
- id: serverInfo.id,
3696
- owner: serverInfo.owner,
3697
- serverAddress: serverInfo.serverAddress,
3698
- publicKey: serverInfo.publicKey,
3699
- url: serverInfo.url,
3700
- startBlock: serverInfo.startBlock,
3701
- endBlock: serverInfo.endBlock
3702
- };
3703
- } catch (error) {
3704
- throw new import_errors.BlockchainError(
3705
- `Failed to get user server info: ${error instanceof Error ? error.message : "Unknown error"}`,
3706
- error
3707
- );
3708
- }
3709
- }
3710
- /**
3711
- * Get server info by server ID
3712
- *
3713
- * @param serverId - Server ID
3714
- * @returns Promise resolving to server info
3715
- */
3716
- async getServers(serverId) {
3717
- try {
3718
- const chainId = await this.context.publicClient.getChainId();
3719
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3720
- chainId,
3721
- "DataPortabilityServers"
3722
- );
3723
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3724
- const serverInfo = await this.context.publicClient.readContract({
3725
- address: DataPortabilityServersAddress,
3726
- abi: DataPortabilityServersAbi,
3727
- functionName: "servers",
3728
- args: [serverId]
3729
- });
3730
- return {
3731
- id: serverInfo.id,
3732
- owner: serverInfo.owner,
3733
- serverAddress: serverInfo.serverAddress,
3734
- publicKey: serverInfo.publicKey,
3735
- url: serverInfo.url
3736
- };
3737
- } catch (error) {
3738
- throw new import_errors.BlockchainError(
3739
- `Failed to get server info: ${error instanceof Error ? error.message : "Unknown error"}`,
3740
- error
3741
- );
3742
- }
3743
- }
3744
- /**
3745
- * Get user info including nonce and trusted server IDs
3746
- *
3747
- * @param userAddress - User address
3748
- * @returns Promise resolving to user info
3749
- */
3750
- async getUsers(userAddress) {
3751
- try {
3752
- const chainId = await this.context.publicClient.getChainId();
3753
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3754
- chainId,
3755
- "DataPortabilityServers"
3756
- );
3757
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3758
- const userInfo = await this.context.publicClient.readContract({
3759
- address: DataPortabilityServersAddress,
3760
- abi: DataPortabilityServersAbi,
3761
- functionName: "users",
3762
- args: [userAddress]
3763
- });
3764
- return {
3765
- nonce: userInfo[0],
3766
- trustedServerIds: [...userInfo[1]]
3767
- };
3768
- } catch (error) {
3769
- throw new import_errors.BlockchainError(
3770
- `Failed to get user info: ${error instanceof Error ? error.message : "Unknown error"}`,
3771
- error
3772
- );
3773
- }
3774
- }
3775
- /**
3776
- * Update server URL
3777
- *
3778
- * @param serverId - Server ID to update
3779
- * @param url - New URL for the server
3780
- * @param options - Optional transaction options for gas parameters and timeout
3781
- * @returns Promise resolving to transaction hash
3782
- */
3783
- async submitUpdateServer(serverId, url, options) {
3784
- this.assertWallet();
3785
- try {
3786
- const chainId = await this.context.walletClient.getChainId();
3787
- const DataPortabilityServersAddress = (0, import_addresses.getContractAddress)(
3788
- chainId,
3789
- "DataPortabilityServers"
3790
- );
3791
- const DataPortabilityServersAbi = (0, import_abi.getAbi)("DataPortabilityServers");
3792
- const account = this.context.walletClient?.account ?? this.context.userAddress;
3793
- const hash = await this.context.walletClient.writeContract({
3794
- address: DataPortabilityServersAddress,
3795
- abi: DataPortabilityServersAbi,
3796
- functionName: "updateServer",
3797
- args: [serverId, url],
3798
- chain: this.context.walletClient?.chain,
3799
- account,
3800
- ...options?.gas && { gas: options.gas },
3801
- ...options?.nonce && { nonce: options.nonce },
3802
- // Use EIP-1559 if available, otherwise fall back to legacy gasPrice
3803
- ...options?.maxFeePerGas || options?.maxPriorityFeePerGas ? {
3804
- ...options.maxFeePerGas && {
3805
- maxFeePerGas: options.maxFeePerGas
3806
- },
3807
- ...options.maxPriorityFeePerGas && {
3808
- maxPriorityFeePerGas: options.maxPriorityFeePerGas
3809
- }
3810
- } : options?.gasPrice && { gasPrice: options.gasPrice }
3811
- });
3812
- const { tx } = await import("../utils/transactionHelpers");
3813
- return tx({
3814
- hash,
3815
- from: typeof account === "string" ? account : account.address,
3816
- contract: "DataPortabilityServers",
3817
- fn: "updateServer"
3818
- });
3819
- } catch (error) {
3820
- throw new import_errors.BlockchainError(
3821
- `Failed to update server: ${error instanceof Error ? error.message : "Unknown error"}`,
3822
- error
3823
- );
3824
- }
3825
- }
3826
- // ===== DataPortabilityPermissionsImplementation Methods =====
3827
- /**
3828
- * Get all permission IDs for a user
3829
- *
3830
- * @param userAddress - User address to get permission IDs for
3831
- * @returns Promise resolving to array of permission IDs
3832
- */
3833
- async getUserPermissionIdsValues(userAddress) {
3834
- try {
3835
- const chainId = await this.context.publicClient.getChainId();
3836
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3837
- chainId,
3838
- "DataPortabilityPermissions"
3839
- );
3840
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3841
- "DataPortabilityPermissions"
3842
- );
3843
- const permissionIds = await this.context.publicClient.readContract({
3844
- address: DataPortabilityPermissionsAddress,
3845
- abi: DataPortabilityPermissionsAbi,
3846
- functionName: "userPermissionIdsValues",
3847
- args: [userAddress]
3848
- });
3849
- return [...permissionIds];
3850
- } catch (error) {
3851
- throw new import_errors.BlockchainError(
3852
- `Failed to get user permission IDs: ${error instanceof Error ? error.message : "Unknown error"}`,
3853
- error
3854
- );
3855
- }
3856
- }
3857
- /**
3858
- * Get permission ID at specific index for a user
3859
- *
3860
- * @param userAddress - User address
3861
- * @param permissionIndex - Index of the permission ID
3862
- * @returns Promise resolving to permission ID
3863
- */
3864
- async getUserPermissionIdsAt(userAddress, permissionIndex) {
3865
- try {
3866
- const chainId = await this.context.publicClient.getChainId();
3867
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3868
- chainId,
3869
- "DataPortabilityPermissions"
3870
- );
3871
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3872
- "DataPortabilityPermissions"
3873
- );
3874
- const permissionId = await this.context.publicClient.readContract({
3875
- address: DataPortabilityPermissionsAddress,
3876
- abi: DataPortabilityPermissionsAbi,
3877
- functionName: "userPermissionIdsAt",
3878
- args: [userAddress, permissionIndex]
3879
- });
3880
- return permissionId;
3881
- } catch (error) {
3882
- throw new import_errors.BlockchainError(
3883
- `Failed to get user permission ID at index: ${error instanceof Error ? error.message : "Unknown error"}`,
3884
- error
3885
- );
3886
- }
3887
- }
3888
- /**
3889
- * Get the number of permissions a user has
3890
- *
3891
- * @param userAddress - User address
3892
- * @returns Promise resolving to number of permissions
3893
- */
3894
- async getUserPermissionIdsLength(userAddress) {
3895
- try {
3896
- const chainId = await this.context.publicClient.getChainId();
3897
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3898
- chainId,
3899
- "DataPortabilityPermissions"
3900
- );
3901
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3902
- "DataPortabilityPermissions"
3903
- );
3904
- const length = await this.context.publicClient.readContract({
3905
- address: DataPortabilityPermissionsAddress,
3906
- abi: DataPortabilityPermissionsAbi,
3907
- functionName: "userPermissionIdsLength",
3908
- args: [userAddress]
3909
- });
3910
- return length;
3911
- } catch (error) {
3912
- throw new import_errors.BlockchainError(
3913
- `Failed to get user permission IDs length: ${error instanceof Error ? error.message : "Unknown error"}`,
3914
- error
3915
- );
3916
- }
3917
- }
3918
- /**
3919
- * Get permission info by permission ID
3920
- *
3921
- * @param permissionId - Permission ID
3922
- * @returns Promise resolving to permission info
3923
- */
3924
- async getPermissions(permissionId) {
3925
- try {
3926
- const chainId = await this.context.publicClient.getChainId();
3927
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
3928
- chainId,
3929
- "DataPortabilityPermissions"
3930
- );
3931
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
3932
- "DataPortabilityPermissions"
3933
- );
3934
- const permissionInfo = await this.context.publicClient.readContract({
3935
- address: DataPortabilityPermissionsAddress,
3936
- abi: DataPortabilityPermissionsAbi,
3937
- functionName: "permissions",
3938
- args: [permissionId]
3939
- });
3940
- return {
3941
- id: permissionInfo.id,
3942
- grantor: permissionInfo.grantor,
3943
- nonce: permissionInfo.nonce,
3944
- granteeId: permissionInfo.granteeId,
3945
- grant: permissionInfo.grant,
3946
- startBlock: permissionInfo.startBlock,
3947
- endBlock: permissionInfo.endBlock,
3948
- fileIds: [...permissionInfo.fileIds]
3949
- };
3950
- } catch (error) {
3951
- throw new import_errors.BlockchainError(
3952
- `Failed to get permission info: ${error instanceof Error ? error.message : "Unknown error"}`,
3953
- error
3954
- );
3955
- }
3956
- }
3957
- /**
3958
- * Submit permission with signature to the blockchain (supports gasless transactions)
3959
- *
3960
- * @param params - Parameters for adding permission
3961
- * @returns Promise resolving to transaction hash
3962
- * @throws {RelayerError} When gasless transaction submission fails
3963
- * @throws {SignatureError} When user rejects the signature request
3964
- * @throws {BlockchainError} When permission addition fails
3965
- * @throws {NetworkError} When network communication fails
3966
- */
3967
- async submitAddPermission(params) {
3968
- this.assertWallet();
3969
- try {
3970
- const nonce = await this.getPermissionsUserNonce();
3971
- const addPermissionInput = {
3972
- nonce,
3973
- granteeId: params.granteeId,
3974
- grant: params.grant,
3975
- fileUrls: params.fileUrls,
3976
- schemaIds: params.schemaIds,
3977
- serverAddress: params.serverAddress,
3978
- serverUrl: params.serverUrl,
3979
- serverPublicKey: params.serverPublicKey,
3980
- filePermissions: params.filePermissions
3981
- };
3982
- const typedData = await this.composeServerFilesAndPermissionMessage(addPermissionInput);
3983
- const signature = await this.signTypedData(typedData);
3984
- return await this.submitSignedAddPermission(typedData, signature);
3985
- } catch (error) {
3986
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
3987
- throw error;
3988
- }
3989
- throw new import_errors.BlockchainError(
3990
- `Failed to add permission: ${error instanceof Error ? error.message : "Unknown error"}`,
3991
- error
3992
- );
3993
- }
3994
- }
3995
- /**
3996
- * Submits an already-signed add permission transaction to the blockchain.
3997
- * This method supports both relayer-based gasless transactions and direct transactions.
3998
- *
3999
- * @param typedData - The EIP-712 typed data for AddPermission
4000
- * @param signature - The user's signature
4001
- * @returns Promise resolving to TransactionResult with PermissionGrantResult event data
4002
- * @throws {RelayerError} When gasless transaction submission fails
4003
- * @throws {BlockchainError} When permission addition fails
4004
- * @throws {NetworkError} When network communication fails
4005
- */
4006
- async submitSignedAddPermission(typedData, signature, options) {
4007
- this.assertWallet();
4008
- try {
4009
- let hash;
4010
- if (this.context.relayer) {
4011
- const request = {
4012
- type: "signed",
4013
- operation: "submitAddPermission",
4014
- typedData,
4015
- signature
4016
- };
4017
- const response = await this.context.relayer(request);
4018
- if (response.type === "error") {
4019
- throw new import_errors.RelayerError(response.error);
4020
- }
4021
- if (response.type === "submitted") {
4022
- hash = response.hash;
4023
- } else if (response.type === "signed") {
4024
- hash = response.hash;
4025
- } else {
4026
- throw new Error("Unexpected response type from relayer");
4027
- }
4028
- } else {
4029
- hash = await this.submitDirectAddPermissionTransaction(
4030
- typedData,
4031
- signature,
4032
- options
4033
- );
4034
- }
4035
- const account = this.context.walletClient?.account ?? this.context.userAddress;
4036
- const { tx } = await import("../utils/transactionHelpers");
4037
- return tx({
4038
- hash,
4039
- from: typeof account === "string" ? account : account.address,
4040
- contract: "DataPortabilityPermissions",
4041
- fn: "addPermission"
4042
- });
4043
- } catch (error) {
4044
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.NetworkError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SignatureError || error instanceof import_errors.NonceError) {
4045
- throw error;
4046
- }
4047
- throw new import_errors.BlockchainError(
4048
- `Add permission submission failed: ${error instanceof Error ? error.message : "Unknown error"}`,
4049
- error
4050
- );
4051
- }
4052
- }
4053
- /**
4054
- * Submits server files and permissions with signature to the blockchain, supporting schema validation and gasless transactions.
4055
- *
4056
- * @remarks
4057
- * This method validates files against their specified schemas before submission.
4058
- * Schema validation ensures data conforms to expected formats before on-chain registration.
4059
- * Files with schemaId = 0 bypass validation. The method supports atomic batch operations
4060
- * where all files and permissions are registered in a single transaction.
4061
- *
4062
- * @param params - Parameters for adding server files and permissions
4063
- * @param params.granteeId - The ID of the permission grantee
4064
- * @param params.grant - Grant URL containing permission parameters (typically IPFS)
4065
- * @param params.fileUrls - Array of file URLs to register
4066
- * @param params.schemaIds - Schema IDs for each file. Use 0 for files without schema validation.
4067
- * Array length must match fileUrls length.
4068
- * @param params.serverAddress - Server wallet address for decryption permissions
4069
- * @param params.serverUrl - Server endpoint URL
4070
- * @param params.serverPublicKey - Server's public key for encryption.
4071
- * Obtain via `vana.server.getIdentity(userAddress).publicKey`.
4072
- * @param params.filePermissions - Nested array of permissions for each file
4073
- * @param options - Optional transaction options for gas parameters and timeout.
4074
- * Note: These options are only applied for direct blockchain transactions.
4075
- * When using relayer callbacks (gasless transactions), these options are ignored.
4076
- * @returns TransactionResult with immediate hash access and optional event data
4077
- * @throws {Error} When schemaIds array length doesn't match fileUrls array length
4078
- * @throws {SchemaValidationError} When file data doesn't match the specified schema.
4079
- * Verify data structure matches schema definition from `vana.schemas.get(schemaId)`.
4080
- * @throws {RelayerError} When gasless transaction submission fails.
4081
- * Retry without relayer configuration to submit direct transaction.
4082
- * @throws {SignatureError} When user rejects the signature request
4083
- * @throws {BlockchainError} When server files and permissions addition fails
4084
- * @throws {NetworkError} When network communication fails.
4085
- * Check network connection or configure alternative gateways.
4086
- *
4087
- * @example
4088
- * ```typescript
4089
- * // Submit with custom gas parameters and timeout
4090
- * const result = await vana.permissions.submitAddServerFilesAndPermissions({
4091
- * granteeId: BigInt(1),
4092
- * grant: "ipfs://QmXxx...",
4093
- * fileUrls: ["https://storage.example.com/data.json"],
4094
- * schemaIds: [123], // LinkedIn profile schema ID
4095
- * serverAddress: "0x742d35Cc6634C0532925a3b844Bc9e7595f0b0Bb",
4096
- * serverUrl: "https://server.example.com",
4097
- * serverPublicKey: serverInfo.publicKey,
4098
- * filePermissions: [[{
4099
- * account: "0x742d35Cc6634C0532925a3b844Bc9e7595f0b0Bb",
4100
- * key: encryptedKey
4101
- * }]]
4102
- * }, {
4103
- * maxFeePerGas: 100n * 10n ** 9n, // 100 gwei
4104
- * maxPriorityFeePerGas: 2n * 10n ** 9n, // 2 gwei tip
4105
- * });
4106
- *
4107
- * // Wait for confirmation with custom timeout
4108
- * const receipt = await vana.waitForTransactionReceipt(result, {
4109
- * timeout: 180000 // 3 minutes
4110
- * });
4111
- * console.log(`Transaction confirmed: ${receipt.transactionHash}`);
4112
- * ```
4113
- */
4114
- async submitAddServerFilesAndPermissions(params, options) {
4115
- this.assertWallet();
4116
- try {
4117
- if (params.schemaIds.length !== params.fileUrls.length) {
4118
- throw new Error(
4119
- `schemaIds array length (${params.schemaIds.length}) must match fileUrls array length (${params.fileUrls.length})`
4120
- );
4121
- }
4122
- const nonce = await this.getPermissionsUserNonce();
4123
- const serverFilesAndPermissionInput = {
4124
- nonce,
4125
- granteeId: params.granteeId,
4126
- grant: params.grant,
4127
- fileUrls: params.fileUrls,
4128
- schemaIds: params.schemaIds,
4129
- serverAddress: params.serverAddress,
4130
- serverUrl: params.serverUrl,
4131
- serverPublicKey: params.serverPublicKey,
4132
- filePermissions: params.filePermissions
4133
- };
4134
- const typedData = await this.composeServerFilesAndPermissionMessage(
4135
- serverFilesAndPermissionInput
4136
- );
4137
- const signature = await this.signTypedData(typedData);
4138
- return await this.submitSignedAddServerFilesAndPermissions(
4139
- typedData,
4140
- signature,
4141
- options
4142
- );
4143
- } catch (error) {
4144
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SerializationError || error instanceof import_errors.SignatureError || error instanceof import_errors.NetworkError || error instanceof import_errors.NonceError) {
4145
- throw error;
4146
- }
4147
- throw new import_errors.BlockchainError(
4148
- `Failed to add server files and permissions: ${error instanceof Error ? error.message : "Unknown error"}`,
4149
- error
4150
- );
4151
- }
4152
- }
4153
- /**
4154
- * Submits an already-signed add server files and permissions transaction to the blockchain.
4155
- *
4156
- * @remarks
4157
- * This method returns a TransactionResult that provides immediate access to the transaction hash.
4158
- * The eventData field may contain parsed event details after transaction confirmation.
4159
- *
4160
- * @param typedData - The EIP-712 typed data for AddServerFilesAndPermissions
4161
- * @param signature - The user's signature
4162
- * @param options - Optional transaction options for gas parameters and timeout.
4163
- * Note: These options are only applied for direct blockchain transactions.
4164
- * When using relayer callbacks (gasless transactions), these options are ignored.
4165
- * @returns TransactionResult with immediate hash access and optional event data
4166
- * @throws {RelayerError} When gasless transaction submission fails
4167
- * @throws {BlockchainError} When server files and permissions addition fails
4168
- * @throws {NetworkError} When network communication fails
4169
- *
4170
- * @example
4171
- * ```typescript
4172
- * const tx = await vana.permissions.submitSignedAddServerFilesAndPermissions(
4173
- * typedData,
4174
- * signature
4175
- * );
4176
- * console.log(`Transaction submitted: ${tx.hash}`);
4177
- *
4178
- * // Wait for confirmation and get the permission ID
4179
- * const { permissionId } = await tx.waitForEvents();
4180
- * console.log(`Permission created with ID: ${permissionId}`);
4181
- * ```
4182
- */
4183
- async submitSignedAddServerFilesAndPermissions(typedData, signature, options) {
4184
- this.assertWallet();
4185
- try {
4186
- let hash;
4187
- if (this.context.relayer) {
4188
- console.debug(
4189
- "\u{1F680} Using relayer for submitAddServerFilesAndPermissions"
4190
- );
4191
- const request = {
4192
- type: "signed",
4193
- operation: "submitAddServerFilesAndPermissions",
4194
- typedData,
4195
- signature
4196
- };
4197
- const response = await this.context.relayer(request);
4198
- if (response.type === "error") {
4199
- throw new import_errors.RelayerError(response.error);
4200
- }
4201
- if (response.type === "submitted") {
4202
- hash = response.hash;
4203
- } else if (response.type === "signed") {
4204
- hash = response.hash;
4205
- } else {
4206
- throw new Error("Unexpected response type from relayer");
4207
- }
4208
- } else {
4209
- console.debug(
4210
- "\u{1F4DD} Using direct transaction for submitAddServerFilesAndPermissions"
4211
- );
4212
- hash = await this.submitDirectAddServerFilesAndPermissionsTransaction(
4213
- typedData,
4214
- signature,
4215
- options
4216
- );
4217
- }
4218
- const account = this.context.walletClient?.account ?? this.context.userAddress;
4219
- const { tx } = await import("../utils/transactionHelpers");
4220
- return tx({
4221
- hash,
4222
- from: typeof account === "string" ? account : account.address,
4223
- contract: "DataPortabilityPermissions",
4224
- fn: "addServerFilesAndPermissions"
4225
- });
4226
- } catch (error) {
4227
- if (error instanceof import_errors.RelayerError || error instanceof import_errors.NetworkError || error instanceof import_errors.UserRejectedRequestError || error instanceof import_errors.SignatureError || error instanceof import_errors.NonceError) {
4228
- throw error;
4229
- }
4230
- throw new import_errors.BlockchainError(
4231
- `Add server files and permissions submission failed: ${error instanceof Error ? error.message : "Unknown error"}`,
4232
- error
4233
- );
4234
- }
4235
- }
4236
- /**
4237
- * Submit permission revocation with signature to the blockchain
4238
- *
4239
- * @param permissionId - Permission ID to revoke
4240
- * @param options - Optional transaction options for gas parameters and timeout
4241
- * @returns Promise resolving to transaction hash
4242
- */
4243
- async submitRevokePermission(permissionId, options) {
4244
- this.assertWallet();
4245
- try {
4246
- const chainId = await this.context.walletClient.getChainId();
4247
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
4248
- chainId,
4249
- "DataPortabilityPermissions"
4250
- );
4251
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)(
4252
- "DataPortabilityPermissions"
4253
- );
4254
- const { account } = this.context.walletClient;
4255
- if (!account) {
4256
- throw new Error("No wallet account connected");
4257
- }
4258
- const hash = await this.context.walletClient.writeContract({
4259
- address: DataPortabilityPermissionsAddress,
4260
- abi: DataPortabilityPermissionsAbi,
4261
- functionName: "revokePermission",
4262
- args: [permissionId],
4263
- chain: this.context.walletClient?.chain,
4264
- account,
4265
- ...options?.gas && { gas: options.gas },
4266
- ...options?.nonce && { nonce: options.nonce },
4267
- // Use EIP-1559 if available, otherwise fall back to legacy gasPrice
4268
- ...options?.maxFeePerGas || options?.maxPriorityFeePerGas ? {
4269
- ...options.maxFeePerGas && {
4270
- maxFeePerGas: options.maxFeePerGas
4271
- },
4272
- ...options.maxPriorityFeePerGas && {
4273
- maxPriorityFeePerGas: options.maxPriorityFeePerGas
4274
- }
4275
- } : options?.gasPrice && { gasPrice: options.gasPrice }
4276
- });
4277
- const { tx } = await import("../utils/transactionHelpers");
4278
- return tx({
4279
- hash,
4280
- from: typeof account === "string" ? account : account.address,
4281
- contract: "DataPortabilityPermissions",
4282
- fn: "revokePermission"
4283
- });
4284
- } catch (error) {
4285
- throw new import_errors.BlockchainError(
4286
- `Failed to revoke permission: ${error instanceof Error ? error.message : "Unknown error"}`,
4287
- error
4288
- );
4289
- }
4290
- }
4291
- /**
4292
- * Submits a signed add permission transaction directly to the blockchain.
4293
- *
4294
- * @param typedData - The typed data structure for the permission addition
4295
- * @param signature - The cryptographic signature authorizing the transaction
4296
- * @returns Promise resolving to the transaction hash
4297
- */
4298
- async submitDirectAddPermissionTransaction(typedData, signature, options) {
4299
- this.assertWallet();
4300
- const chainId = await this.context.walletClient.getChainId();
4301
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
4302
- chainId,
4303
- "DataPortabilityPermissions"
4304
- );
4305
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)("DataPortabilityPermissions");
4306
- const permissionInput = {
4307
- nonce: typedData.message.nonce,
4308
- granteeId: typedData.message.granteeId,
4309
- grant: typedData.message.grant,
4310
- fileIds: typedData.message.fileIds ?? []
4311
- };
4312
- const formattedSignature = (0, import_signatureFormatter.formatSignatureForContract)(signature);
4313
- const hash = await this.context.walletClient.writeContract({
4314
- address: DataPortabilityPermissionsAddress,
4315
- abi: DataPortabilityPermissionsAbi,
4316
- functionName: "addPermission",
4317
- args: [permissionInput, formattedSignature],
4318
- account: this.context.walletClient?.account ?? this.context.userAddress,
4319
- chain: this.context.walletClient?.chain ?? null,
4320
- ...this.spreadTransactionOptions(options)
4321
- });
4322
- return hash;
4323
- }
4324
- /**
4325
- * Submits a signed add server files and permissions transaction directly to the blockchain.
4326
- *
4327
- * @param typedData - The typed data structure for the server files and permissions addition
4328
- * @param signature - The cryptographic signature authorizing the transaction
4329
- * @returns Promise resolving to the transaction hash
4330
- */
4331
- async submitDirectAddServerFilesAndPermissionsTransaction(typedData, signature, options) {
4332
- this.assertWallet();
4333
- const chainId = await this.context.publicClient.getChainId();
4334
- const DataPortabilityPermissionsAddress = (0, import_addresses.getContractAddress)(
4335
- chainId,
4336
- "DataPortabilityPermissions"
4337
- );
4338
- const DataPortabilityPermissionsAbi = (0, import_abi.getAbi)("DataPortabilityPermissions");
4339
- const serverFilesAndPermissionInput = {
4340
- nonce: typedData.message.nonce,
4341
- granteeId: typedData.message.granteeId,
4342
- grant: typedData.message.grant,
4343
- fileUrls: typedData.message.fileUrls,
4344
- schemaIds: typedData.message.schemaIds,
4345
- serverAddress: typedData.message.serverAddress,
4346
- serverUrl: typedData.message.serverUrl,
4347
- serverPublicKey: typedData.message.serverPublicKey,
4348
- filePermissions: typedData.message.filePermissions
4349
- };
4350
- const formattedSignature = (0, import_signatureFormatter.formatSignatureForContract)(signature);
4351
- const hash = await this.context.walletClient.writeContract({
4352
- address: DataPortabilityPermissionsAddress,
4353
- abi: DataPortabilityPermissionsAbi,
4354
- functionName: "addServerFilesAndPermissions",
4355
- args: [serverFilesAndPermissionInput, formattedSignature],
4356
- account: this.context.walletClient?.account ?? this.context.userAddress,
4357
- chain: this.context.walletClient?.chain ?? null,
4358
- ...options?.value && { value: options.value },
4359
- ...this.spreadTransactionOptions(options)
4360
- });
4361
- return hash;
4362
- }
4363
- }
4364
- // Annotate the CommonJS export names for ESM import in node:
4365
- 0 && (module.exports = {
4366
- PermissionsController
4367
- });
4368
- //# sourceMappingURL=permissions.cjs.map