@metamask/snap-networks-utils 1.0.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (360) hide show
  1. package/CHANGELOG.md +63 -1
  2. package/README.md +4 -10
  3. package/dist/index.cjs +102 -5
  4. package/dist/index.cjs.map +1 -1
  5. package/dist/index.d.cts +51 -2
  6. package/dist/index.d.cts.map +1 -1
  7. package/dist/index.d.mts +51 -2
  8. package/dist/index.d.mts.map +1 -1
  9. package/dist/index.mjs +32 -1
  10. package/dist/index.mjs.map +1 -1
  11. package/dist/providers/assets/AssetsProvider.cjs +36 -18
  12. package/dist/providers/assets/AssetsProvider.cjs.map +1 -1
  13. package/dist/providers/assets/AssetsProvider.d.cts +30 -2
  14. package/dist/providers/assets/AssetsProvider.d.cts.map +1 -1
  15. package/dist/providers/assets/AssetsProvider.d.mts +30 -2
  16. package/dist/providers/assets/AssetsProvider.d.mts.map +1 -1
  17. package/dist/providers/assets/AssetsProvider.mjs +36 -18
  18. package/dist/providers/assets/AssetsProvider.mjs.map +1 -1
  19. package/dist/providers/remote-feature-flags/RemoteFeatureFlagsProvider.cjs +4 -17
  20. package/dist/providers/remote-feature-flags/RemoteFeatureFlagsProvider.cjs.map +1 -1
  21. package/dist/providers/remote-feature-flags/RemoteFeatureFlagsProvider.mjs +4 -17
  22. package/dist/providers/remote-feature-flags/RemoteFeatureFlagsProvider.mjs.map +1 -1
  23. package/dist/services/analytics/AnalyticsService.cjs +225 -0
  24. package/dist/services/analytics/AnalyticsService.cjs.map +1 -0
  25. package/dist/services/analytics/AnalyticsService.d.cts +175 -0
  26. package/dist/services/analytics/AnalyticsService.d.cts.map +1 -0
  27. package/dist/services/analytics/AnalyticsService.d.mts +175 -0
  28. package/dist/services/analytics/AnalyticsService.d.mts.map +1 -0
  29. package/dist/services/analytics/AnalyticsService.mjs +221 -0
  30. package/dist/services/analytics/AnalyticsService.mjs.map +1 -0
  31. package/dist/ui/ActionHeader/ActionHeader.cjs +23 -0
  32. package/dist/ui/ActionHeader/ActionHeader.cjs.map +1 -0
  33. package/dist/ui/ActionHeader/ActionHeader.d.cts +27 -0
  34. package/dist/ui/ActionHeader/ActionHeader.d.cts.map +1 -0
  35. package/dist/ui/ActionHeader/ActionHeader.d.mts +27 -0
  36. package/dist/ui/ActionHeader/ActionHeader.d.mts.map +1 -0
  37. package/dist/ui/ActionHeader/ActionHeader.mjs +19 -0
  38. package/dist/ui/ActionHeader/ActionHeader.mjs.map +1 -0
  39. package/dist/ui/Asset/Asset.cjs +68 -0
  40. package/dist/ui/Asset/Asset.cjs.map +1 -0
  41. package/dist/ui/Asset/Asset.d.cts +83 -0
  42. package/dist/ui/Asset/Asset.d.cts.map +1 -0
  43. package/dist/ui/Asset/Asset.d.mts +83 -0
  44. package/dist/ui/Asset/Asset.d.mts.map +1 -0
  45. package/dist/ui/Asset/Asset.mjs +60 -0
  46. package/dist/ui/Asset/Asset.mjs.map +1 -0
  47. package/dist/ui/Asset/question-mark.svg +3 -0
  48. package/dist/ui/EstimatedChanges/EstimatedChanges.cjs +57 -0
  49. package/dist/ui/EstimatedChanges/EstimatedChanges.cjs.map +1 -0
  50. package/dist/ui/EstimatedChanges/EstimatedChanges.d.cts +50 -0
  51. package/dist/ui/EstimatedChanges/EstimatedChanges.d.cts.map +1 -0
  52. package/dist/ui/EstimatedChanges/EstimatedChanges.d.mts +50 -0
  53. package/dist/ui/EstimatedChanges/EstimatedChanges.d.mts.map +1 -0
  54. package/dist/ui/EstimatedChanges/EstimatedChanges.mjs +53 -0
  55. package/dist/ui/EstimatedChanges/EstimatedChanges.mjs.map +1 -0
  56. package/dist/ui/TransactionAlert/TransactionAlert.cjs +72 -0
  57. package/dist/ui/TransactionAlert/TransactionAlert.cjs.map +1 -0
  58. package/dist/ui/TransactionAlert/TransactionAlert.d.cts +58 -0
  59. package/dist/ui/TransactionAlert/TransactionAlert.d.cts.map +1 -0
  60. package/dist/ui/TransactionAlert/TransactionAlert.d.mts +58 -0
  61. package/dist/ui/TransactionAlert/TransactionAlert.d.mts.map +1 -0
  62. package/dist/ui/TransactionAlert/TransactionAlert.mjs +68 -0
  63. package/dist/ui/TransactionAlert/TransactionAlert.mjs.map +1 -0
  64. package/dist/utils/async/async.cjs +95 -0
  65. package/dist/utils/async/async.cjs.map +1 -0
  66. package/dist/utils/async/async.d.cts +51 -0
  67. package/dist/utils/async/async.d.cts.map +1 -0
  68. package/dist/utils/async/async.d.mts +51 -0
  69. package/dist/utils/async/async.d.mts.map +1 -0
  70. package/dist/utils/async/async.mjs +88 -0
  71. package/dist/utils/async/async.mjs.map +1 -0
  72. package/dist/utils/buildUrl/buildUrl.cjs +54 -0
  73. package/dist/utils/buildUrl/buildUrl.cjs.map +1 -0
  74. package/dist/utils/buildUrl/buildUrl.d.cts +15 -0
  75. package/dist/utils/buildUrl/buildUrl.d.cts.map +1 -0
  76. package/dist/utils/buildUrl/buildUrl.d.mts +15 -0
  77. package/dist/utils/buildUrl/buildUrl.d.mts.map +1 -0
  78. package/dist/utils/buildUrl/buildUrl.mjs +51 -0
  79. package/dist/utils/buildUrl/buildUrl.mjs.map +1 -0
  80. package/dist/utils/cache/InMemoryCache.cjs +134 -0
  81. package/dist/utils/cache/InMemoryCache.cjs.map +1 -0
  82. package/dist/utils/cache/InMemoryCache.d.cts +29 -0
  83. package/dist/utils/cache/InMemoryCache.d.cts.map +1 -0
  84. package/dist/utils/cache/InMemoryCache.d.mts +29 -0
  85. package/dist/utils/cache/InMemoryCache.d.mts.map +1 -0
  86. package/dist/utils/cache/InMemoryCache.mjs +130 -0
  87. package/dist/utils/cache/InMemoryCache.mjs.map +1 -0
  88. package/dist/utils/cache/StateCache.cjs +193 -0
  89. package/dist/utils/cache/StateCache.cjs.map +1 -0
  90. package/dist/utils/cache/StateCache.d.cts +96 -0
  91. package/dist/utils/cache/StateCache.d.cts.map +1 -0
  92. package/dist/utils/cache/StateCache.d.mts +96 -0
  93. package/dist/utils/cache/StateCache.d.mts.map +1 -0
  94. package/dist/utils/cache/StateCache.mjs +189 -0
  95. package/dist/utils/cache/StateCache.mjs.map +1 -0
  96. package/dist/utils/cache/types.cjs +3 -0
  97. package/dist/utils/cache/types.cjs.map +1 -0
  98. package/dist/utils/cache/types.d.cts +99 -0
  99. package/dist/utils/cache/types.d.cts.map +1 -0
  100. package/dist/utils/cache/types.d.mts +99 -0
  101. package/dist/utils/cache/types.d.mts.map +1 -0
  102. package/dist/utils/cache/types.mjs +2 -0
  103. package/dist/utils/cache/types.mjs.map +1 -0
  104. package/dist/utils/cache/useCache.cjs +82 -0
  105. package/dist/utils/cache/useCache.cjs.map +1 -0
  106. package/dist/utils/cache/useCache.d.cts +57 -0
  107. package/dist/utils/cache/useCache.d.cts.map +1 -0
  108. package/dist/utils/cache/useCache.d.mts +57 -0
  109. package/dist/utils/cache/useCache.d.mts.map +1 -0
  110. package/dist/utils/cache/useCache.mjs +78 -0
  111. package/dist/utils/cache/useCache.mjs.map +1 -0
  112. package/dist/utils/cache/useCacheUntil.cjs +80 -0
  113. package/dist/utils/cache/useCacheUntil.cjs.map +1 -0
  114. package/dist/utils/cache/useCacheUntil.d.cts +54 -0
  115. package/dist/utils/cache/useCacheUntil.d.cts.map +1 -0
  116. package/dist/utils/cache/useCacheUntil.d.mts +54 -0
  117. package/dist/utils/cache/useCacheUntil.d.mts.map +1 -0
  118. package/dist/utils/cache/useCacheUntil.mjs +76 -0
  119. package/dist/utils/cache/useCacheUntil.mjs.map +1 -0
  120. package/dist/utils/config/BaseConfigProvider.cjs +62 -0
  121. package/dist/utils/config/BaseConfigProvider.cjs.map +1 -0
  122. package/dist/utils/config/BaseConfigProvider.d.cts +54 -0
  123. package/dist/utils/config/BaseConfigProvider.d.cts.map +1 -0
  124. package/dist/utils/config/BaseConfigProvider.d.mts +54 -0
  125. package/dist/utils/config/BaseConfigProvider.d.mts.map +1 -0
  126. package/dist/utils/config/BaseConfigProvider.mjs +58 -0
  127. package/dist/utils/config/BaseConfigProvider.mjs.map +1 -0
  128. package/dist/utils/config/envStructs.cjs +69 -0
  129. package/dist/utils/config/envStructs.cjs.map +1 -0
  130. package/dist/utils/config/envStructs.d.cts +57 -0
  131. package/dist/utils/config/envStructs.d.cts.map +1 -0
  132. package/dist/utils/config/envStructs.d.mts +57 -0
  133. package/dist/utils/config/envStructs.d.mts.map +1 -0
  134. package/dist/utils/config/envStructs.mjs +61 -0
  135. package/dist/utils/config/envStructs.mjs.map +1 -0
  136. package/dist/utils/config/environmentStruct.cjs +19 -0
  137. package/dist/utils/config/environmentStruct.cjs.map +1 -0
  138. package/dist/utils/config/environmentStruct.d.cts +20 -0
  139. package/dist/utils/config/environmentStruct.d.cts.map +1 -0
  140. package/dist/utils/config/environmentStruct.d.mts +20 -0
  141. package/dist/utils/config/environmentStruct.d.mts.map +1 -0
  142. package/dist/utils/config/environmentStruct.mjs +16 -0
  143. package/dist/utils/config/environmentStruct.mjs.map +1 -0
  144. package/dist/utils/config/logLevelStruct.cjs +14 -0
  145. package/dist/utils/config/logLevelStruct.cjs.map +1 -0
  146. package/dist/utils/config/logLevelStruct.d.cts +17 -0
  147. package/dist/utils/config/logLevelStruct.d.cts.map +1 -0
  148. package/dist/utils/config/logLevelStruct.d.mts +17 -0
  149. package/dist/utils/config/logLevelStruct.d.mts.map +1 -0
  150. package/dist/utils/config/logLevelStruct.mjs +11 -0
  151. package/dist/utils/config/logLevelStruct.mjs.map +1 -0
  152. package/dist/utils/config/parseEnv.cjs +30 -0
  153. package/dist/utils/config/parseEnv.cjs.map +1 -0
  154. package/dist/utils/config/parseEnv.d.cts +19 -0
  155. package/dist/utils/config/parseEnv.d.cts.map +1 -0
  156. package/dist/utils/config/parseEnv.d.mts +19 -0
  157. package/dist/utils/config/parseEnv.d.mts.map +1 -0
  158. package/dist/utils/config/parseEnv.mjs +26 -0
  159. package/dist/utils/config/parseEnv.mjs.map +1 -0
  160. package/dist/utils/dedupe/InFlightCoalescer.cjs +28 -0
  161. package/dist/utils/dedupe/InFlightCoalescer.cjs.map +1 -0
  162. package/dist/utils/dedupe/InFlightCoalescer.d.cts +12 -0
  163. package/dist/utils/dedupe/InFlightCoalescer.d.cts.map +1 -0
  164. package/dist/utils/dedupe/InFlightCoalescer.d.mts +12 -0
  165. package/dist/utils/dedupe/InFlightCoalescer.d.mts.map +1 -0
  166. package/dist/utils/dedupe/InFlightCoalescer.mjs +24 -0
  167. package/dist/utils/dedupe/InFlightCoalescer.mjs.map +1 -0
  168. package/dist/utils/errors/errors.cjs +44 -0
  169. package/dist/utils/errors/errors.cjs.map +1 -0
  170. package/dist/utils/errors/errors.d.cts +37 -0
  171. package/dist/utils/errors/errors.d.cts.map +1 -0
  172. package/dist/utils/errors/errors.d.mts +37 -0
  173. package/dist/utils/errors/errors.d.mts.map +1 -0
  174. package/dist/utils/errors/errors.mjs +40 -0
  175. package/dist/utils/errors/errors.mjs.map +1 -0
  176. package/dist/utils/errors/index.cjs +18 -0
  177. package/dist/utils/errors/index.cjs.map +1 -0
  178. package/dist/utils/errors/index.d.cts +10 -0
  179. package/dist/utils/errors/index.d.cts.map +1 -0
  180. package/dist/utils/errors/index.d.mts +10 -0
  181. package/dist/utils/errors/index.d.mts.map +1 -0
  182. package/dist/utils/errors/index.mjs +6 -0
  183. package/dist/utils/errors/index.mjs.map +1 -0
  184. package/dist/utils/errors/snapRpcError.cjs +33 -0
  185. package/dist/utils/errors/snapRpcError.cjs.map +1 -0
  186. package/dist/utils/errors/snapRpcError.d.cts +11 -0
  187. package/dist/utils/errors/snapRpcError.d.cts.map +1 -0
  188. package/dist/utils/errors/snapRpcError.d.mts +11 -0
  189. package/dist/utils/errors/snapRpcError.d.mts.map +1 -0
  190. package/dist/utils/errors/snapRpcError.mjs +30 -0
  191. package/dist/utils/errors/snapRpcError.mjs.map +1 -0
  192. package/dist/utils/errors/stringifyReason.cjs +36 -0
  193. package/dist/utils/errors/stringifyReason.cjs.map +1 -0
  194. package/dist/utils/errors/stringifyReason.d.cts +15 -0
  195. package/dist/utils/errors/stringifyReason.d.cts.map +1 -0
  196. package/dist/utils/errors/stringifyReason.d.mts +15 -0
  197. package/dist/utils/errors/stringifyReason.d.mts.map +1 -0
  198. package/dist/utils/errors/stringifyReason.mjs +33 -0
  199. package/dist/utils/errors/stringifyReason.mjs.map +1 -0
  200. package/dist/utils/errors/syncError.cjs +98 -0
  201. package/dist/utils/errors/syncError.cjs.map +1 -0
  202. package/dist/utils/errors/syncError.d.cts +60 -0
  203. package/dist/utils/errors/syncError.d.cts.map +1 -0
  204. package/dist/utils/errors/syncError.d.mts +60 -0
  205. package/dist/utils/errors/syncError.d.mts.map +1 -0
  206. package/dist/utils/errors/syncError.mjs +92 -0
  207. package/dist/utils/errors/syncError.mjs.map +1 -0
  208. package/dist/utils/errors/trackError.cjs +76 -0
  209. package/dist/utils/errors/trackError.cjs.map +1 -0
  210. package/dist/utils/errors/trackError.d.cts +64 -0
  211. package/dist/utils/errors/trackError.d.cts.map +1 -0
  212. package/dist/utils/errors/trackError.d.mts +64 -0
  213. package/dist/utils/errors/trackError.d.mts.map +1 -0
  214. package/dist/utils/errors/trackError.mjs +72 -0
  215. package/dist/utils/errors/trackError.mjs.map +1 -0
  216. package/dist/utils/handlers/wrapSnapHandlers.cjs +57 -0
  217. package/dist/utils/handlers/wrapSnapHandlers.cjs.map +1 -0
  218. package/dist/utils/handlers/wrapSnapHandlers.d.cts +74 -0
  219. package/dist/utils/handlers/wrapSnapHandlers.d.cts.map +1 -0
  220. package/dist/utils/handlers/wrapSnapHandlers.d.mts +74 -0
  221. package/dist/utils/handlers/wrapSnapHandlers.d.mts.map +1 -0
  222. package/dist/utils/handlers/wrapSnapHandlers.mjs +53 -0
  223. package/dist/utils/handlers/wrapSnapHandlers.mjs.map +1 -0
  224. package/dist/utils/keyringAccount/keyringAccount.cjs +25 -0
  225. package/dist/utils/keyringAccount/keyringAccount.cjs.map +1 -0
  226. package/dist/utils/keyringAccount/keyringAccount.d.cts +29 -0
  227. package/dist/utils/keyringAccount/keyringAccount.d.cts.map +1 -0
  228. package/dist/utils/keyringAccount/keyringAccount.d.mts +29 -0
  229. package/dist/utils/keyringAccount/keyringAccount.d.mts.map +1 -0
  230. package/dist/utils/keyringAccount/keyringAccount.mjs +22 -0
  231. package/dist/utils/keyringAccount/keyringAccount.mjs.map +1 -0
  232. package/dist/utils/logger/Logger.cjs +140 -0
  233. package/dist/utils/logger/Logger.cjs.map +1 -0
  234. package/dist/utils/logger/Logger.d.cts +118 -0
  235. package/dist/utils/logger/Logger.d.cts.map +1 -0
  236. package/dist/utils/logger/Logger.d.mts +118 -0
  237. package/dist/utils/logger/Logger.d.mts.map +1 -0
  238. package/dist/utils/logger/Logger.mjs +136 -0
  239. package/dist/utils/logger/Logger.mjs.map +1 -0
  240. package/dist/utils/logger/__mocks__/Logger.cjs +26 -0
  241. package/dist/utils/logger/__mocks__/Logger.cjs.map +1 -0
  242. package/dist/utils/logger/__mocks__/Logger.d.cts +3 -0
  243. package/dist/utils/logger/__mocks__/Logger.d.cts.map +1 -0
  244. package/dist/utils/logger/__mocks__/Logger.d.mts +3 -0
  245. package/dist/utils/logger/__mocks__/Logger.d.mts.map +1 -0
  246. package/dist/utils/logger/__mocks__/Logger.mjs +23 -0
  247. package/dist/utils/logger/__mocks__/Logger.mjs.map +1 -0
  248. package/dist/utils/originPermissions/createOriginPermissions.cjs +30 -0
  249. package/dist/utils/originPermissions/createOriginPermissions.cjs.map +1 -0
  250. package/dist/utils/originPermissions/createOriginPermissions.d.cts +24 -0
  251. package/dist/utils/originPermissions/createOriginPermissions.d.cts.map +1 -0
  252. package/dist/utils/originPermissions/createOriginPermissions.d.mts +24 -0
  253. package/dist/utils/originPermissions/createOriginPermissions.d.mts.map +1 -0
  254. package/dist/utils/originPermissions/createOriginPermissions.mjs +26 -0
  255. package/dist/utils/originPermissions/createOriginPermissions.mjs.map +1 -0
  256. package/dist/utils/originPermissions/validateOrigin.cjs +23 -0
  257. package/dist/utils/originPermissions/validateOrigin.cjs.map +1 -0
  258. package/dist/utils/originPermissions/validateOrigin.d.cts +10 -0
  259. package/dist/utils/originPermissions/validateOrigin.d.cts.map +1 -0
  260. package/dist/utils/originPermissions/validateOrigin.d.mts +10 -0
  261. package/dist/utils/originPermissions/validateOrigin.d.mts.map +1 -0
  262. package/dist/utils/originPermissions/validateOrigin.mjs +19 -0
  263. package/dist/utils/originPermissions/validateOrigin.mjs.map +1 -0
  264. package/dist/utils/proofOfOwnership/proofOfOwnership.cjs +89 -0
  265. package/dist/utils/proofOfOwnership/proofOfOwnership.cjs.map +1 -0
  266. package/dist/utils/proofOfOwnership/proofOfOwnership.d.cts +143 -0
  267. package/dist/utils/proofOfOwnership/proofOfOwnership.d.cts.map +1 -0
  268. package/dist/utils/proofOfOwnership/proofOfOwnership.d.mts +143 -0
  269. package/dist/utils/proofOfOwnership/proofOfOwnership.d.mts.map +1 -0
  270. package/dist/utils/proofOfOwnership/proofOfOwnership.mjs +85 -0
  271. package/dist/utils/proofOfOwnership/proofOfOwnership.mjs.map +1 -0
  272. package/dist/utils/safeMerge/safeMerge.cjs +26 -0
  273. package/dist/utils/safeMerge/safeMerge.cjs.map +1 -0
  274. package/dist/utils/safeMerge/safeMerge.d.cts +17 -0
  275. package/dist/utils/safeMerge/safeMerge.d.cts.map +1 -0
  276. package/dist/utils/safeMerge/safeMerge.d.mts +17 -0
  277. package/dist/utils/safeMerge/safeMerge.d.mts.map +1 -0
  278. package/dist/utils/safeMerge/safeMerge.mjs +22 -0
  279. package/dist/utils/safeMerge/safeMerge.mjs.map +1 -0
  280. package/dist/utils/sanitize/sanitize.cjs +42 -0
  281. package/dist/utils/sanitize/sanitize.cjs.map +1 -0
  282. package/dist/utils/sanitize/sanitize.d.cts +15 -0
  283. package/dist/utils/sanitize/sanitize.d.cts.map +1 -0
  284. package/dist/utils/sanitize/sanitize.d.mts +15 -0
  285. package/dist/utils/sanitize/sanitize.d.mts.map +1 -0
  286. package/dist/utils/sanitize/sanitize.mjs +38 -0
  287. package/dist/utils/sanitize/sanitize.mjs.map +1 -0
  288. package/dist/utils/serialization/serialization.cjs +73 -0
  289. package/dist/utils/serialization/serialization.cjs.map +1 -0
  290. package/dist/utils/serialization/serialization.d.cts +19 -0
  291. package/dist/utils/serialization/serialization.d.cts.map +1 -0
  292. package/dist/utils/serialization/serialization.d.mts +19 -0
  293. package/dist/utils/serialization/serialization.d.mts.map +1 -0
  294. package/dist/utils/serialization/serialization.mjs +69 -0
  295. package/dist/utils/serialization/serialization.mjs.map +1 -0
  296. package/dist/utils/serialization/types.cjs +3 -0
  297. package/dist/utils/serialization/types.cjs.map +1 -0
  298. package/dist/utils/serialization/types.d.cts +8 -0
  299. package/dist/utils/serialization/types.d.cts.map +1 -0
  300. package/dist/utils/serialization/types.d.mts +8 -0
  301. package/dist/utils/serialization/types.d.mts.map +1 -0
  302. package/dist/utils/serialization/types.mjs +2 -0
  303. package/dist/utils/serialization/types.mjs.map +1 -0
  304. package/dist/utils/state/IStateManager.cjs +3 -0
  305. package/dist/utils/state/IStateManager.cjs.map +1 -0
  306. package/dist/utils/state/IStateManager.d.cts +69 -0
  307. package/dist/utils/state/IStateManager.d.cts.map +1 -0
  308. package/dist/utils/state/IStateManager.d.mts +69 -0
  309. package/dist/utils/state/IStateManager.d.mts.map +1 -0
  310. package/dist/utils/state/IStateManager.mjs +2 -0
  311. package/dist/utils/state/IStateManager.mjs.map +1 -0
  312. package/dist/utils/state/InMemoryState.cjs +41 -0
  313. package/dist/utils/state/InMemoryState.cjs.map +1 -0
  314. package/dist/utils/state/InMemoryState.d.cts +18 -0
  315. package/dist/utils/state/InMemoryState.d.cts.map +1 -0
  316. package/dist/utils/state/InMemoryState.d.mts +18 -0
  317. package/dist/utils/state/InMemoryState.d.mts.map +1 -0
  318. package/dist/utils/state/InMemoryState.mjs +38 -0
  319. package/dist/utils/state/InMemoryState.mjs.map +1 -0
  320. package/dist/utils/state/State.cjs +159 -0
  321. package/dist/utils/state/State.cjs.map +1 -0
  322. package/dist/utils/state/State.d.cts +25 -0
  323. package/dist/utils/state/State.d.cts.map +1 -0
  324. package/dist/utils/state/State.d.mts +25 -0
  325. package/dist/utils/state/State.d.mts.map +1 -0
  326. package/dist/utils/state/State.mjs +156 -0
  327. package/dist/utils/state/State.mjs.map +1 -0
  328. package/dist/utils/transactionType/transactionType.cjs +32 -0
  329. package/dist/utils/transactionType/transactionType.cjs.map +1 -0
  330. package/dist/utils/transactionType/transactionType.d.cts +17 -0
  331. package/dist/utils/transactionType/transactionType.d.cts.map +1 -0
  332. package/dist/utils/transactionType/transactionType.d.mts +17 -0
  333. package/dist/utils/transactionType/transactionType.d.mts.map +1 -0
  334. package/dist/utils/transactionType/transactionType.mjs +28 -0
  335. package/dist/utils/transactionType/transactionType.mjs.map +1 -0
  336. package/dist/utils/urlStruct/urlStruct.cjs +96 -0
  337. package/dist/utils/urlStruct/urlStruct.cjs.map +1 -0
  338. package/dist/utils/urlStruct/urlStruct.d.cts +25 -0
  339. package/dist/utils/urlStruct/urlStruct.d.cts.map +1 -0
  340. package/dist/utils/urlStruct/urlStruct.d.mts +25 -0
  341. package/dist/utils/urlStruct/urlStruct.d.mts.map +1 -0
  342. package/dist/utils/urlStruct/urlStruct.mjs +93 -0
  343. package/dist/utils/urlStruct/urlStruct.mjs.map +1 -0
  344. package/dist/utils/uuidStruct/uuidStruct.cjs +12 -0
  345. package/dist/utils/uuidStruct/uuidStruct.cjs.map +1 -0
  346. package/dist/utils/uuidStruct/uuidStruct.d.cts +8 -0
  347. package/dist/utils/uuidStruct/uuidStruct.d.cts.map +1 -0
  348. package/dist/utils/uuidStruct/uuidStruct.d.mts +8 -0
  349. package/dist/utils/uuidStruct/uuidStruct.d.mts.map +1 -0
  350. package/dist/utils/uuidStruct/uuidStruct.mjs +9 -0
  351. package/dist/utils/uuidStruct/uuidStruct.mjs.map +1 -0
  352. package/package.json +33 -13
  353. package/dist/logger.cjs +0 -57
  354. package/dist/logger.cjs.map +0 -1
  355. package/dist/logger.d.cts +0 -30
  356. package/dist/logger.d.cts.map +0 -1
  357. package/dist/logger.d.mts +0 -30
  358. package/dist/logger.d.mts.map +0 -1
  359. package/dist/logger.mjs +0 -53
  360. package/dist/logger.mjs.map +0 -1
@@ -0,0 +1,99 @@
1
+ import type { Serializable } from "../serialization/types.cjs";
2
+ export type TimestampMilliseconds = number;
3
+ /**
4
+ * A single cache entry.
5
+ */
6
+ export type CacheEntry = {
7
+ value: Serializable;
8
+ expiresAt: TimestampMilliseconds;
9
+ };
10
+ /**
11
+ * Interface for a generic cache implementation.
12
+ *
13
+ * @template TValue - The type of values stored in the cache
14
+ */
15
+ export type ICache<TValue> = {
16
+ /**
17
+ * Retrieves a value from the cache by key.
18
+ *
19
+ * @param key - The key to retrieve
20
+ * @returns The value if found, undefined if not found
21
+ */
22
+ get(key: string): Promise<TValue | undefined>;
23
+ /**
24
+ * Stores a value in the cache with an optional TTL.
25
+ * - If a value is undefined, it will not be stored in the cache.
26
+ * - If a value is null, it will be stored in the cache.
27
+ *
28
+ * @param key - The key to store the value under
29
+ * @param value - The value to store
30
+ * @param ttlMilliseconds - Optional time-to-live in milliseconds. If not provided, the value will not expire.
31
+ * @throws Error if any entry's ttlMilliseconds is not a number, is negative, or is greater than 2^53 - 1
32
+ */
33
+ set(key: string, value: TValue, ttlMilliseconds?: number): Promise<void>;
34
+ /**
35
+ * Removes a value from the cache.
36
+ *
37
+ * @param key - The key to remove
38
+ * @returns true if the key was found and removed, false otherwise
39
+ */
40
+ delete(key: string): Promise<boolean>;
41
+ /**
42
+ * Removes all values from the cache.
43
+ */
44
+ clear(): Promise<void>;
45
+ /**
46
+ * Checks if a key exists in the cache.
47
+ *
48
+ * @param key - The key to check
49
+ * @returns true if the key exists, false otherwise
50
+ */
51
+ has(key: string): Promise<boolean>;
52
+ /**
53
+ * Returns all keys currently in the cache.
54
+ *
55
+ * @returns Array of keys
56
+ */
57
+ keys(): Promise<string[]>;
58
+ /**
59
+ * Returns the number of items in the cache.
60
+ *
61
+ * @returns The number of items
62
+ */
63
+ size(): Promise<number>;
64
+ /**
65
+ * Retrieves a value from the cache without affecting its TTL or last accessed time.
66
+ *
67
+ * @param key - The key to peek at
68
+ * @returns The value if found, undefined if not found
69
+ */
70
+ peek(key: string): Promise<TValue | undefined>;
71
+ /**
72
+ * Retrieves multiple values from the cache in a single operation.
73
+ *
74
+ * @param keys - Array of keys to retrieve
75
+ * @returns Object mapping keys to their values (or undefined if not found)
76
+ */
77
+ mget(keys: string[]): Promise<Record<string, TValue | undefined>>;
78
+ /**
79
+ * Stores multiple values in the cache in a single operation.
80
+ * - If a value is undefined, it will not be stored in the cache.
81
+ * - If a value is null, it will be stored in the cache.
82
+ *
83
+ * @param entries - Array of entries to store, each with key, value, and optional TTL (if not provided, the value will not expire)
84
+ * @throws Error if any entry's ttlMilliseconds is not a number, is negative, or is greater than 2^53 - 1
85
+ */
86
+ mset(entries: {
87
+ key: string;
88
+ value: TValue;
89
+ ttlMilliseconds?: number;
90
+ }[]): Promise<void>;
91
+ /**
92
+ * Removes multiple values from the cache.
93
+ *
94
+ * @param keys - Array of keys to remove
95
+ * @returns An object mapping each key to a boolean indicating whether it was found and removed
96
+ */
97
+ mdelete(keys: string[]): Promise<Record<string, boolean>>;
98
+ };
99
+ //# sourceMappingURL=types.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.cts","sourceRoot":"","sources":["../../../src/utils/cache/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,mCAA+B;AAE3D,MAAM,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAE3C;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,KAAK,EAAE,YAAY,CAAC;IACpB,SAAS,EAAE,qBAAqB,CAAC;CAClC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,MAAM,CAAC,MAAM,IAAI;IAC3B;;;;;OAKG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAE9C;;;;;;;;;OASG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzE;;;;;OAKG;IACH,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC;;OAEG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB;;;;;OAKG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAEnC;;;;OAIG;IACH,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAE1B;;;;OAIG;IACH,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAExB;;;;;OAKG;IACH,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAE/C;;;;;OAKG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;IAElE;;;;;;;OAOG;IACH,IAAI,CACF,OAAO,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,eAAe,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,GAClE,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB;;;;;OAKG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC3D,CAAC"}
@@ -0,0 +1,99 @@
1
+ import type { Serializable } from "../serialization/types.mjs";
2
+ export type TimestampMilliseconds = number;
3
+ /**
4
+ * A single cache entry.
5
+ */
6
+ export type CacheEntry = {
7
+ value: Serializable;
8
+ expiresAt: TimestampMilliseconds;
9
+ };
10
+ /**
11
+ * Interface for a generic cache implementation.
12
+ *
13
+ * @template TValue - The type of values stored in the cache
14
+ */
15
+ export type ICache<TValue> = {
16
+ /**
17
+ * Retrieves a value from the cache by key.
18
+ *
19
+ * @param key - The key to retrieve
20
+ * @returns The value if found, undefined if not found
21
+ */
22
+ get(key: string): Promise<TValue | undefined>;
23
+ /**
24
+ * Stores a value in the cache with an optional TTL.
25
+ * - If a value is undefined, it will not be stored in the cache.
26
+ * - If a value is null, it will be stored in the cache.
27
+ *
28
+ * @param key - The key to store the value under
29
+ * @param value - The value to store
30
+ * @param ttlMilliseconds - Optional time-to-live in milliseconds. If not provided, the value will not expire.
31
+ * @throws Error if any entry's ttlMilliseconds is not a number, is negative, or is greater than 2^53 - 1
32
+ */
33
+ set(key: string, value: TValue, ttlMilliseconds?: number): Promise<void>;
34
+ /**
35
+ * Removes a value from the cache.
36
+ *
37
+ * @param key - The key to remove
38
+ * @returns true if the key was found and removed, false otherwise
39
+ */
40
+ delete(key: string): Promise<boolean>;
41
+ /**
42
+ * Removes all values from the cache.
43
+ */
44
+ clear(): Promise<void>;
45
+ /**
46
+ * Checks if a key exists in the cache.
47
+ *
48
+ * @param key - The key to check
49
+ * @returns true if the key exists, false otherwise
50
+ */
51
+ has(key: string): Promise<boolean>;
52
+ /**
53
+ * Returns all keys currently in the cache.
54
+ *
55
+ * @returns Array of keys
56
+ */
57
+ keys(): Promise<string[]>;
58
+ /**
59
+ * Returns the number of items in the cache.
60
+ *
61
+ * @returns The number of items
62
+ */
63
+ size(): Promise<number>;
64
+ /**
65
+ * Retrieves a value from the cache without affecting its TTL or last accessed time.
66
+ *
67
+ * @param key - The key to peek at
68
+ * @returns The value if found, undefined if not found
69
+ */
70
+ peek(key: string): Promise<TValue | undefined>;
71
+ /**
72
+ * Retrieves multiple values from the cache in a single operation.
73
+ *
74
+ * @param keys - Array of keys to retrieve
75
+ * @returns Object mapping keys to their values (or undefined if not found)
76
+ */
77
+ mget(keys: string[]): Promise<Record<string, TValue | undefined>>;
78
+ /**
79
+ * Stores multiple values in the cache in a single operation.
80
+ * - If a value is undefined, it will not be stored in the cache.
81
+ * - If a value is null, it will be stored in the cache.
82
+ *
83
+ * @param entries - Array of entries to store, each with key, value, and optional TTL (if not provided, the value will not expire)
84
+ * @throws Error if any entry's ttlMilliseconds is not a number, is negative, or is greater than 2^53 - 1
85
+ */
86
+ mset(entries: {
87
+ key: string;
88
+ value: TValue;
89
+ ttlMilliseconds?: number;
90
+ }[]): Promise<void>;
91
+ /**
92
+ * Removes multiple values from the cache.
93
+ *
94
+ * @param keys - Array of keys to remove
95
+ * @returns An object mapping each key to a boolean indicating whether it was found and removed
96
+ */
97
+ mdelete(keys: string[]): Promise<Record<string, boolean>>;
98
+ };
99
+ //# sourceMappingURL=types.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.mts","sourceRoot":"","sources":["../../../src/utils/cache/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,mCAA+B;AAE3D,MAAM,MAAM,qBAAqB,GAAG,MAAM,CAAC;AAE3C;;GAEG;AACH,MAAM,MAAM,UAAU,GAAG;IACvB,KAAK,EAAE,YAAY,CAAC;IACpB,SAAS,EAAE,qBAAqB,CAAC;CAClC,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,MAAM,CAAC,MAAM,IAAI;IAC3B;;;;;OAKG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAE9C;;;;;;;;;OASG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,eAAe,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAEzE;;;;;OAKG;IACH,MAAM,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAEtC;;OAEG;IACH,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IAEvB;;;;;OAKG;IACH,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAEnC;;;;OAIG;IACH,IAAI,IAAI,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAE1B;;;;OAIG;IACH,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC,CAAC;IAExB;;;;;OAKG;IACH,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAE/C;;;;;OAKG;IACH,IAAI,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAC;IAElE;;;;;;;OAOG;IACH,IAAI,CACF,OAAO,EAAE;QAAE,GAAG,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAC;QAAC,eAAe,CAAC,EAAE,MAAM,CAAA;KAAE,EAAE,GAClE,OAAO,CAAC,IAAI,CAAC,CAAC;IAEjB;;;;;OAKG;IACH,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CAC3D,CAAC"}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.mjs","sourceRoot":"","sources":["../../../src/utils/cache/types.ts"],"names":[],"mappings":"","sourcesContent":["import type { Serializable } from '../serialization/types';\n\nexport type TimestampMilliseconds = number;\n\n/**\n * A single cache entry.\n */\nexport type CacheEntry = {\n value: Serializable;\n expiresAt: TimestampMilliseconds;\n};\n\n/**\n * Interface for a generic cache implementation.\n *\n * @template TValue - The type of values stored in the cache\n */\nexport type ICache<TValue> = {\n /**\n * Retrieves a value from the cache by key.\n *\n * @param key - The key to retrieve\n * @returns The value if found, undefined if not found\n */\n get(key: string): Promise<TValue | undefined>;\n\n /**\n * Stores a value in the cache with an optional TTL.\n * - If a value is undefined, it will not be stored in the cache.\n * - If a value is null, it will be stored in the cache.\n *\n * @param key - The key to store the value under\n * @param value - The value to store\n * @param ttlMilliseconds - Optional time-to-live in milliseconds. If not provided, the value will not expire.\n * @throws Error if any entry's ttlMilliseconds is not a number, is negative, or is greater than 2^53 - 1\n */\n set(key: string, value: TValue, ttlMilliseconds?: number): Promise<void>;\n\n /**\n * Removes a value from the cache.\n *\n * @param key - The key to remove\n * @returns true if the key was found and removed, false otherwise\n */\n delete(key: string): Promise<boolean>;\n\n /**\n * Removes all values from the cache.\n */\n clear(): Promise<void>;\n\n /**\n * Checks if a key exists in the cache.\n *\n * @param key - The key to check\n * @returns true if the key exists, false otherwise\n */\n has(key: string): Promise<boolean>;\n\n /**\n * Returns all keys currently in the cache.\n *\n * @returns Array of keys\n */\n keys(): Promise<string[]>;\n\n /**\n * Returns the number of items in the cache.\n *\n * @returns The number of items\n */\n size(): Promise<number>;\n\n /**\n * Retrieves a value from the cache without affecting its TTL or last accessed time.\n *\n * @param key - The key to peek at\n * @returns The value if found, undefined if not found\n */\n peek(key: string): Promise<TValue | undefined>;\n\n /**\n * Retrieves multiple values from the cache in a single operation.\n *\n * @param keys - Array of keys to retrieve\n * @returns Object mapping keys to their values (or undefined if not found)\n */\n mget(keys: string[]): Promise<Record<string, TValue | undefined>>;\n\n /**\n * Stores multiple values in the cache in a single operation.\n * - If a value is undefined, it will not be stored in the cache.\n * - If a value is null, it will be stored in the cache.\n *\n * @param entries - Array of entries to store, each with key, value, and optional TTL (if not provided, the value will not expire)\n * @throws Error if any entry's ttlMilliseconds is not a number, is negative, or is greater than 2^53 - 1\n */\n mset(\n entries: { key: string; value: TValue; ttlMilliseconds?: number }[],\n ): Promise<void>;\n\n /**\n * Removes multiple values from the cache.\n *\n * @param keys - Array of keys to remove\n * @returns An object mapping each key to a boolean indicating whether it was found and removed\n */\n mdelete(keys: string[]): Promise<Record<string, boolean>>;\n};\n"]}
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ /* eslint-disable no-void */
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ exports.useCache = void 0;
5
+ const Logger_1 = require("../logger/Logger.cjs");
6
+ const serialization_1 = require("../serialization/serialization.cjs");
7
+ /**
8
+ * A logger that discards all messages, used when no logger is provided.
9
+ */
10
+ const silentLogger = new Logger_1.Logger({ level: Logger_1.LogLevel.SILENT });
11
+ /**
12
+ * Default function to generate the cache key for a function call.
13
+ *
14
+ * @param functionName - The name of the function.
15
+ * @param args - The arguments of the function call.
16
+ * @returns The cache key.
17
+ */
18
+ const defaultGenerateCacheKey = (functionName, args) => `${functionName}:${args.map((arg) => JSON.stringify((0, serialization_1.serialize)(arg))).join(':')}`;
19
+ /**
20
+ * Wraps a function with caching behavior.
21
+ *
22
+ * WARNINGS:
23
+ * - The cache write is fire-and-forget (not awaited). This is only safe with
24
+ * caches whose writes are effectively instantaneous, such as
25
+ * `InMemoryCache`. Do not pair this wrapper with a mutex-guarded, persisted
26
+ * cache such as `StateCache`: unawaited state writes accumulate without
27
+ * backpressure, the state mutex queue grows without bound under sustained
28
+ * traffic, and foreground state operations eventually hit the snap's RPC
29
+ * timeout. Use `useCacheUntil` (which awaits its write) with a persisted
30
+ * cache instead.
31
+ *
32
+ * @template TArgs - Tuple type representing the arguments of the function.
33
+ * @template TResult - The return type of the function, must be Serializable.
34
+ * @param fn - The asynchronous function to wrap. Must return a Promise<Serializable>.
35
+ * @param cache - The cache instance to use.
36
+ * @param options - The caching options.
37
+ * @param options.ttlMilliseconds - The time to live for the cache in milliseconds.
38
+ * @param options.refreshCache - Whether to refresh the cache.
39
+ * @param options.functionName - The name of the function.
40
+ * @param options.generateCacheKey - Optional function to generate the cache key.
41
+ * @param options.logger - Optional logger for cache errors.
42
+ * @returns A new asynchronous function with caching behavior.
43
+ */
44
+ const useCache = (fn, cache, { ttlMilliseconds, functionName, generateCacheKey, refreshCache = false, logger = silentLogger, }) => {
45
+ // Use provided key generator or default, adapting the default to use the function's name
46
+ const _generateCacheKey = generateCacheKey ?? defaultGenerateCacheKey;
47
+ // Get the function name for the default key generator, handle anonymous functions
48
+ const _functionName = functionName ?? fn.name ?? 'anonymousFunction';
49
+ return async (...args) => {
50
+ const cacheKey = _generateCacheKey(_functionName, args);
51
+ // Check if the data is cached
52
+ if (!refreshCache) {
53
+ try {
54
+ const cached = await cache.get(cacheKey);
55
+ // Check explicitly for undefined, as null or other falsy values might be valid cache results
56
+ if (cached !== undefined) {
57
+ // Type assertion because cache stores Serializable, but we expect TResult
58
+ return cached;
59
+ }
60
+ }
61
+ catch (error) {
62
+ // Log cache get errors but proceed to execute the function
63
+ logger.error(`Cache get error for key "${cacheKey}":`, error);
64
+ }
65
+ }
66
+ // Execute the original function
67
+ const result = await fn(...args);
68
+ // Cache the result, handling potential errors silently.
69
+ // Fire-and-forget: we don't await this, allowing it to happen in the
70
+ // background. This is safe only because the snaps pair this wrapper with
71
+ // `InMemoryCache` (writes resolve in a microtask). With a mutex-guarded
72
+ // persisted cache such as `StateCache`, unawaited writes would accumulate
73
+ // without backpressure and starve foreground state operations — see the
74
+ // warnings in this function's documentation.
75
+ void cache.set(cacheKey, result, ttlMilliseconds).catch((error) => {
76
+ logger.error(`Cache set error for key "${cacheKey}":`, error);
77
+ });
78
+ return result;
79
+ };
80
+ };
81
+ exports.useCache = useCache;
82
+ //# sourceMappingURL=useCache.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCache.cjs","sourceRoot":"","sources":["../../../src/utils/cache/useCache.ts"],"names":[],"mappings":";AAAA,4BAA4B;;;AAE5B,iDAAoD;AACpD,sEAA2D;AAI3D;;GAEG;AACH,MAAM,YAAY,GAAG,IAAI,eAAM,CAAC,EAAE,KAAK,EAAE,iBAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;AA8B5D;;;;;;GAMG;AACH,MAAM,uBAAuB,GAAG,CAC9B,YAAoB,EACpB,IAAoB,EACZ,EAAE,CACV,GAAG,YAAY,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAA,yBAAS,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AAEnF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACI,MAAM,QAAQ,GAAG,CAItB,EAAwC,EACxC,KAA2B,EAC3B,EACE,eAAe,EACf,YAAY,EACZ,gBAAgB,EAChB,YAAY,GAAG,KAAK,EACpB,MAAM,GAAG,YAAY,GACR,EACyB,EAAE;IAC1C,yFAAyF;IACzF,MAAM,iBAAiB,GAAG,gBAAgB,IAAI,uBAAuB,CAAC;IAEtE,kFAAkF;IAClF,MAAM,aAAa,GAAG,YAAY,IAAI,EAAE,CAAC,IAAI,IAAI,mBAAmB,CAAC;IAErE,OAAO,KAAK,EAAE,GAAG,IAAW,EAAoB,EAAE;QAChD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QACxD,8BAA8B;QAC9B,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,IAAI,CAAC;gBACH,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACzC,6FAA6F;gBAC7F,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;oBACzB,0EAA0E;oBAC1E,OAAO,MAAiB,CAAC;gBAC3B,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,2DAA2D;gBAC3D,MAAM,CAAC,KAAK,CAAC,4BAA4B,QAAQ,IAAI,EAAE,KAAK,CAAC,CAAC;YAChE,CAAC;QACH,CAAC;QAED,gCAAgC;QAChC,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QAEjC,wDAAwD;QACxD,qEAAqE;QACrE,yEAAyE;QACzE,wEAAwE;QACxE,0EAA0E;QAC1E,wEAAwE;QACxE,6CAA6C;QAC7C,KAAK,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;YAChE,MAAM,CAAC,KAAK,CAAC,4BAA4B,QAAQ,IAAI,EAAE,KAAK,CAAC,CAAC;QAChE,CAAC,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC,CAAC;AArDW,QAAA,QAAQ,YAqDnB","sourcesContent":["/* eslint-disable no-void */\n\nimport { Logger, LogLevel } from '../logger/Logger';\nimport { serialize } from '../serialization/serialization';\nimport type { Serializable } from '../serialization/types';\nimport type { ICache } from './types';\n\n/**\n * A logger that discards all messages, used when no logger is provided.\n */\nconst silentLogger = new Logger({ level: LogLevel.SILENT });\n\n/**\n * Options for configuring the caching behavior of a function.\n */\nexport type CacheOptions = {\n /**\n * The time to live for the cache in milliseconds.\n */\n ttlMilliseconds: number;\n /**\n * Set this if you want to use a custom function name for the cache key.\n */\n functionName?: string;\n /**\n * Optional function to generate the cache key for the function call.\n * Defaults to a function that generates the key based on function name and JSON stringified args separated by colons.\n */\n generateCacheKey?: (functionName: string, args: Serializable[]) => string;\n /**\n * Whether to refresh the cache.\n * Defaults to false.\n */\n refreshCache?: boolean;\n /**\n * Optional logger for cache errors. Defaults to a silent logger.\n */\n logger?: Logger;\n};\n\n/**\n * Default function to generate the cache key for a function call.\n *\n * @param functionName - The name of the function.\n * @param args - The arguments of the function call.\n * @returns The cache key.\n */\nconst defaultGenerateCacheKey = (\n functionName: string,\n args: Serializable[],\n): string =>\n `${functionName}:${args.map((arg) => JSON.stringify(serialize(arg))).join(':')}`;\n\n/**\n * Wraps a function with caching behavior.\n *\n * WARNINGS:\n * - The cache write is fire-and-forget (not awaited). This is only safe with\n * caches whose writes are effectively instantaneous, such as\n * `InMemoryCache`. Do not pair this wrapper with a mutex-guarded, persisted\n * cache such as `StateCache`: unawaited state writes accumulate without\n * backpressure, the state mutex queue grows without bound under sustained\n * traffic, and foreground state operations eventually hit the snap's RPC\n * timeout. Use `useCacheUntil` (which awaits its write) with a persisted\n * cache instead.\n *\n * @template TArgs - Tuple type representing the arguments of the function.\n * @template TResult - The return type of the function, must be Serializable.\n * @param fn - The asynchronous function to wrap. Must return a Promise<Serializable>.\n * @param cache - The cache instance to use.\n * @param options - The caching options.\n * @param options.ttlMilliseconds - The time to live for the cache in milliseconds.\n * @param options.refreshCache - Whether to refresh the cache.\n * @param options.functionName - The name of the function.\n * @param options.generateCacheKey - Optional function to generate the cache key.\n * @param options.logger - Optional logger for cache errors.\n * @returns A new asynchronous function with caching behavior.\n */\nexport const useCache = <\n TArgs extends Serializable[],\n TResult extends Serializable,\n>(\n fn: (...args: TArgs) => Promise<TResult>,\n cache: ICache<Serializable>,\n {\n ttlMilliseconds,\n functionName,\n generateCacheKey,\n refreshCache = false,\n logger = silentLogger,\n }: CacheOptions,\n): ((...args: TArgs) => Promise<TResult>) => {\n // Use provided key generator or default, adapting the default to use the function's name\n const _generateCacheKey = generateCacheKey ?? defaultGenerateCacheKey;\n\n // Get the function name for the default key generator, handle anonymous functions\n const _functionName = functionName ?? fn.name ?? 'anonymousFunction';\n\n return async (...args: TArgs): Promise<TResult> => {\n const cacheKey = _generateCacheKey(_functionName, args);\n // Check if the data is cached\n if (!refreshCache) {\n try {\n const cached = await cache.get(cacheKey);\n // Check explicitly for undefined, as null or other falsy values might be valid cache results\n if (cached !== undefined) {\n // Type assertion because cache stores Serializable, but we expect TResult\n return cached as TResult;\n }\n } catch (error) {\n // Log cache get errors but proceed to execute the function\n logger.error(`Cache get error for key \"${cacheKey}\":`, error);\n }\n }\n\n // Execute the original function\n const result = await fn(...args);\n\n // Cache the result, handling potential errors silently.\n // Fire-and-forget: we don't await this, allowing it to happen in the\n // background. This is safe only because the snaps pair this wrapper with\n // `InMemoryCache` (writes resolve in a microtask). With a mutex-guarded\n // persisted cache such as `StateCache`, unawaited writes would accumulate\n // without backpressure and starve foreground state operations — see the\n // warnings in this function's documentation.\n void cache.set(cacheKey, result, ttlMilliseconds).catch((error) => {\n logger.error(`Cache set error for key \"${cacheKey}\":`, error);\n });\n\n return result;\n };\n};\n"]}
@@ -0,0 +1,57 @@
1
+ import { Logger } from "../logger/Logger.cjs";
2
+ import type { Serializable } from "../serialization/types.cjs";
3
+ import type { ICache } from "./types.cjs";
4
+ /**
5
+ * Options for configuring the caching behavior of a function.
6
+ */
7
+ export type CacheOptions = {
8
+ /**
9
+ * The time to live for the cache in milliseconds.
10
+ */
11
+ ttlMilliseconds: number;
12
+ /**
13
+ * Set this if you want to use a custom function name for the cache key.
14
+ */
15
+ functionName?: string;
16
+ /**
17
+ * Optional function to generate the cache key for the function call.
18
+ * Defaults to a function that generates the key based on function name and JSON stringified args separated by colons.
19
+ */
20
+ generateCacheKey?: (functionName: string, args: Serializable[]) => string;
21
+ /**
22
+ * Whether to refresh the cache.
23
+ * Defaults to false.
24
+ */
25
+ refreshCache?: boolean;
26
+ /**
27
+ * Optional logger for cache errors. Defaults to a silent logger.
28
+ */
29
+ logger?: Logger;
30
+ };
31
+ /**
32
+ * Wraps a function with caching behavior.
33
+ *
34
+ * WARNINGS:
35
+ * - The cache write is fire-and-forget (not awaited). This is only safe with
36
+ * caches whose writes are effectively instantaneous, such as
37
+ * `InMemoryCache`. Do not pair this wrapper with a mutex-guarded, persisted
38
+ * cache such as `StateCache`: unawaited state writes accumulate without
39
+ * backpressure, the state mutex queue grows without bound under sustained
40
+ * traffic, and foreground state operations eventually hit the snap's RPC
41
+ * timeout. Use `useCacheUntil` (which awaits its write) with a persisted
42
+ * cache instead.
43
+ *
44
+ * @template TArgs - Tuple type representing the arguments of the function.
45
+ * @template TResult - The return type of the function, must be Serializable.
46
+ * @param fn - The asynchronous function to wrap. Must return a Promise<Serializable>.
47
+ * @param cache - The cache instance to use.
48
+ * @param options - The caching options.
49
+ * @param options.ttlMilliseconds - The time to live for the cache in milliseconds.
50
+ * @param options.refreshCache - Whether to refresh the cache.
51
+ * @param options.functionName - The name of the function.
52
+ * @param options.generateCacheKey - Optional function to generate the cache key.
53
+ * @param options.logger - Optional logger for cache errors.
54
+ * @returns A new asynchronous function with caching behavior.
55
+ */
56
+ export declare const useCache: <TArgs extends Serializable[], TResult extends Serializable>(fn: (...args: TArgs) => Promise<TResult>, cache: ICache<Serializable>, { ttlMilliseconds, functionName, generateCacheKey, refreshCache, logger, }: CacheOptions) => ((...args: TArgs) => Promise<TResult>);
57
+ //# sourceMappingURL=useCache.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCache.d.cts","sourceRoot":"","sources":["../../../src/utils/cache/useCache.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAY,6BAAyB;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,mCAA+B;AAC3D,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAgB;AAOtC;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB;;OAEG;IACH,eAAe,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,KAAK,MAAM,CAAC;IAC1E;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAeF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,QAAQ,GACnB,KAAK,SAAS,YAAY,EAAE,EAC5B,OAAO,SAAS,YAAY,EAE5B,IAAI,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,EACxC,OAAO,MAAM,CAAC,YAAY,CAAC,EAC3B,4EAMG,YAAY,KACd,CAAC,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,CAwCvC,CAAC"}
@@ -0,0 +1,57 @@
1
+ import { Logger } from "../logger/Logger.mjs";
2
+ import type { Serializable } from "../serialization/types.mjs";
3
+ import type { ICache } from "./types.mjs";
4
+ /**
5
+ * Options for configuring the caching behavior of a function.
6
+ */
7
+ export type CacheOptions = {
8
+ /**
9
+ * The time to live for the cache in milliseconds.
10
+ */
11
+ ttlMilliseconds: number;
12
+ /**
13
+ * Set this if you want to use a custom function name for the cache key.
14
+ */
15
+ functionName?: string;
16
+ /**
17
+ * Optional function to generate the cache key for the function call.
18
+ * Defaults to a function that generates the key based on function name and JSON stringified args separated by colons.
19
+ */
20
+ generateCacheKey?: (functionName: string, args: Serializable[]) => string;
21
+ /**
22
+ * Whether to refresh the cache.
23
+ * Defaults to false.
24
+ */
25
+ refreshCache?: boolean;
26
+ /**
27
+ * Optional logger for cache errors. Defaults to a silent logger.
28
+ */
29
+ logger?: Logger;
30
+ };
31
+ /**
32
+ * Wraps a function with caching behavior.
33
+ *
34
+ * WARNINGS:
35
+ * - The cache write is fire-and-forget (not awaited). This is only safe with
36
+ * caches whose writes are effectively instantaneous, such as
37
+ * `InMemoryCache`. Do not pair this wrapper with a mutex-guarded, persisted
38
+ * cache such as `StateCache`: unawaited state writes accumulate without
39
+ * backpressure, the state mutex queue grows without bound under sustained
40
+ * traffic, and foreground state operations eventually hit the snap's RPC
41
+ * timeout. Use `useCacheUntil` (which awaits its write) with a persisted
42
+ * cache instead.
43
+ *
44
+ * @template TArgs - Tuple type representing the arguments of the function.
45
+ * @template TResult - The return type of the function, must be Serializable.
46
+ * @param fn - The asynchronous function to wrap. Must return a Promise<Serializable>.
47
+ * @param cache - The cache instance to use.
48
+ * @param options - The caching options.
49
+ * @param options.ttlMilliseconds - The time to live for the cache in milliseconds.
50
+ * @param options.refreshCache - Whether to refresh the cache.
51
+ * @param options.functionName - The name of the function.
52
+ * @param options.generateCacheKey - Optional function to generate the cache key.
53
+ * @param options.logger - Optional logger for cache errors.
54
+ * @returns A new asynchronous function with caching behavior.
55
+ */
56
+ export declare const useCache: <TArgs extends Serializable[], TResult extends Serializable>(fn: (...args: TArgs) => Promise<TResult>, cache: ICache<Serializable>, { ttlMilliseconds, functionName, generateCacheKey, refreshCache, logger, }: CacheOptions) => ((...args: TArgs) => Promise<TResult>);
57
+ //# sourceMappingURL=useCache.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCache.d.mts","sourceRoot":"","sources":["../../../src/utils/cache/useCache.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,MAAM,EAAY,6BAAyB;AAEpD,OAAO,KAAK,EAAE,YAAY,EAAE,mCAA+B;AAC3D,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAgB;AAOtC;;GAEG;AACH,MAAM,MAAM,YAAY,GAAG;IACzB;;OAEG;IACH,eAAe,EAAE,MAAM,CAAC;IACxB;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB;;;OAGG;IACH,gBAAgB,CAAC,EAAE,CAAC,YAAY,EAAE,MAAM,EAAE,IAAI,EAAE,YAAY,EAAE,KAAK,MAAM,CAAC;IAC1E;;;OAGG;IACH,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAeF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,eAAO,MAAM,QAAQ,GACnB,KAAK,SAAS,YAAY,EAAE,EAC5B,OAAO,SAAS,YAAY,EAE5B,IAAI,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,EACxC,OAAO,MAAM,CAAC,YAAY,CAAC,EAC3B,4EAMG,YAAY,KACd,CAAC,CAAC,GAAG,IAAI,EAAE,KAAK,KAAK,OAAO,CAAC,OAAO,CAAC,CAwCvC,CAAC"}
@@ -0,0 +1,78 @@
1
+ /* eslint-disable no-void */
2
+ import { Logger, LogLevel } from "../logger/Logger.mjs";
3
+ import { serialize } from "../serialization/serialization.mjs";
4
+ /**
5
+ * A logger that discards all messages, used when no logger is provided.
6
+ */
7
+ const silentLogger = new Logger({ level: LogLevel.SILENT });
8
+ /**
9
+ * Default function to generate the cache key for a function call.
10
+ *
11
+ * @param functionName - The name of the function.
12
+ * @param args - The arguments of the function call.
13
+ * @returns The cache key.
14
+ */
15
+ const defaultGenerateCacheKey = (functionName, args) => `${functionName}:${args.map((arg) => JSON.stringify(serialize(arg))).join(':')}`;
16
+ /**
17
+ * Wraps a function with caching behavior.
18
+ *
19
+ * WARNINGS:
20
+ * - The cache write is fire-and-forget (not awaited). This is only safe with
21
+ * caches whose writes are effectively instantaneous, such as
22
+ * `InMemoryCache`. Do not pair this wrapper with a mutex-guarded, persisted
23
+ * cache such as `StateCache`: unawaited state writes accumulate without
24
+ * backpressure, the state mutex queue grows without bound under sustained
25
+ * traffic, and foreground state operations eventually hit the snap's RPC
26
+ * timeout. Use `useCacheUntil` (which awaits its write) with a persisted
27
+ * cache instead.
28
+ *
29
+ * @template TArgs - Tuple type representing the arguments of the function.
30
+ * @template TResult - The return type of the function, must be Serializable.
31
+ * @param fn - The asynchronous function to wrap. Must return a Promise<Serializable>.
32
+ * @param cache - The cache instance to use.
33
+ * @param options - The caching options.
34
+ * @param options.ttlMilliseconds - The time to live for the cache in milliseconds.
35
+ * @param options.refreshCache - Whether to refresh the cache.
36
+ * @param options.functionName - The name of the function.
37
+ * @param options.generateCacheKey - Optional function to generate the cache key.
38
+ * @param options.logger - Optional logger for cache errors.
39
+ * @returns A new asynchronous function with caching behavior.
40
+ */
41
+ export const useCache = (fn, cache, { ttlMilliseconds, functionName, generateCacheKey, refreshCache = false, logger = silentLogger, }) => {
42
+ // Use provided key generator or default, adapting the default to use the function's name
43
+ const _generateCacheKey = generateCacheKey ?? defaultGenerateCacheKey;
44
+ // Get the function name for the default key generator, handle anonymous functions
45
+ const _functionName = functionName ?? fn.name ?? 'anonymousFunction';
46
+ return async (...args) => {
47
+ const cacheKey = _generateCacheKey(_functionName, args);
48
+ // Check if the data is cached
49
+ if (!refreshCache) {
50
+ try {
51
+ const cached = await cache.get(cacheKey);
52
+ // Check explicitly for undefined, as null or other falsy values might be valid cache results
53
+ if (cached !== undefined) {
54
+ // Type assertion because cache stores Serializable, but we expect TResult
55
+ return cached;
56
+ }
57
+ }
58
+ catch (error) {
59
+ // Log cache get errors but proceed to execute the function
60
+ logger.error(`Cache get error for key "${cacheKey}":`, error);
61
+ }
62
+ }
63
+ // Execute the original function
64
+ const result = await fn(...args);
65
+ // Cache the result, handling potential errors silently.
66
+ // Fire-and-forget: we don't await this, allowing it to happen in the
67
+ // background. This is safe only because the snaps pair this wrapper with
68
+ // `InMemoryCache` (writes resolve in a microtask). With a mutex-guarded
69
+ // persisted cache such as `StateCache`, unawaited writes would accumulate
70
+ // without backpressure and starve foreground state operations — see the
71
+ // warnings in this function's documentation.
72
+ void cache.set(cacheKey, result, ttlMilliseconds).catch((error) => {
73
+ logger.error(`Cache set error for key "${cacheKey}":`, error);
74
+ });
75
+ return result;
76
+ };
77
+ };
78
+ //# sourceMappingURL=useCache.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCache.mjs","sourceRoot":"","sources":["../../../src/utils/cache/useCache.ts"],"names":[],"mappings":"AAAA,4BAA4B;AAE5B,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,6BAAyB;AACpD,OAAO,EAAE,SAAS,EAAE,2CAAuC;AAI3D;;GAEG;AACH,MAAM,YAAY,GAAG,IAAI,MAAM,CAAC,EAAE,KAAK,EAAE,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;AA8B5D;;;;;;GAMG;AACH,MAAM,uBAAuB,GAAG,CAC9B,YAAoB,EACpB,IAAoB,EACZ,EAAE,CACV,GAAG,YAAY,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AAEnF;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CAItB,EAAwC,EACxC,KAA2B,EAC3B,EACE,eAAe,EACf,YAAY,EACZ,gBAAgB,EAChB,YAAY,GAAG,KAAK,EACpB,MAAM,GAAG,YAAY,GACR,EACyB,EAAE;IAC1C,yFAAyF;IACzF,MAAM,iBAAiB,GAAG,gBAAgB,IAAI,uBAAuB,CAAC;IAEtE,kFAAkF;IAClF,MAAM,aAAa,GAAG,YAAY,IAAI,EAAE,CAAC,IAAI,IAAI,mBAAmB,CAAC;IAErE,OAAO,KAAK,EAAE,GAAG,IAAW,EAAoB,EAAE;QAChD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QACxD,8BAA8B;QAC9B,IAAI,CAAC,YAAY,EAAE,CAAC;YAClB,IAAI,CAAC;gBACH,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACzC,6FAA6F;gBAC7F,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;oBACzB,0EAA0E;oBAC1E,OAAO,MAAiB,CAAC;gBAC3B,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,2DAA2D;gBAC3D,MAAM,CAAC,KAAK,CAAC,4BAA4B,QAAQ,IAAI,EAAE,KAAK,CAAC,CAAC;YAChE,CAAC;QACH,CAAC;QAED,gCAAgC;QAChC,MAAM,MAAM,GAAG,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QAEjC,wDAAwD;QACxD,qEAAqE;QACrE,yEAAyE;QACzE,wEAAwE;QACxE,0EAA0E;QAC1E,wEAAwE;QACxE,6CAA6C;QAC7C,KAAK,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;YAChE,MAAM,CAAC,KAAK,CAAC,4BAA4B,QAAQ,IAAI,EAAE,KAAK,CAAC,CAAC;QAChE,CAAC,CAAC,CAAC;QAEH,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC,CAAC","sourcesContent":["/* eslint-disable no-void */\n\nimport { Logger, LogLevel } from '../logger/Logger';\nimport { serialize } from '../serialization/serialization';\nimport type { Serializable } from '../serialization/types';\nimport type { ICache } from './types';\n\n/**\n * A logger that discards all messages, used when no logger is provided.\n */\nconst silentLogger = new Logger({ level: LogLevel.SILENT });\n\n/**\n * Options for configuring the caching behavior of a function.\n */\nexport type CacheOptions = {\n /**\n * The time to live for the cache in milliseconds.\n */\n ttlMilliseconds: number;\n /**\n * Set this if you want to use a custom function name for the cache key.\n */\n functionName?: string;\n /**\n * Optional function to generate the cache key for the function call.\n * Defaults to a function that generates the key based on function name and JSON stringified args separated by colons.\n */\n generateCacheKey?: (functionName: string, args: Serializable[]) => string;\n /**\n * Whether to refresh the cache.\n * Defaults to false.\n */\n refreshCache?: boolean;\n /**\n * Optional logger for cache errors. Defaults to a silent logger.\n */\n logger?: Logger;\n};\n\n/**\n * Default function to generate the cache key for a function call.\n *\n * @param functionName - The name of the function.\n * @param args - The arguments of the function call.\n * @returns The cache key.\n */\nconst defaultGenerateCacheKey = (\n functionName: string,\n args: Serializable[],\n): string =>\n `${functionName}:${args.map((arg) => JSON.stringify(serialize(arg))).join(':')}`;\n\n/**\n * Wraps a function with caching behavior.\n *\n * WARNINGS:\n * - The cache write is fire-and-forget (not awaited). This is only safe with\n * caches whose writes are effectively instantaneous, such as\n * `InMemoryCache`. Do not pair this wrapper with a mutex-guarded, persisted\n * cache such as `StateCache`: unawaited state writes accumulate without\n * backpressure, the state mutex queue grows without bound under sustained\n * traffic, and foreground state operations eventually hit the snap's RPC\n * timeout. Use `useCacheUntil` (which awaits its write) with a persisted\n * cache instead.\n *\n * @template TArgs - Tuple type representing the arguments of the function.\n * @template TResult - The return type of the function, must be Serializable.\n * @param fn - The asynchronous function to wrap. Must return a Promise<Serializable>.\n * @param cache - The cache instance to use.\n * @param options - The caching options.\n * @param options.ttlMilliseconds - The time to live for the cache in milliseconds.\n * @param options.refreshCache - Whether to refresh the cache.\n * @param options.functionName - The name of the function.\n * @param options.generateCacheKey - Optional function to generate the cache key.\n * @param options.logger - Optional logger for cache errors.\n * @returns A new asynchronous function with caching behavior.\n */\nexport const useCache = <\n TArgs extends Serializable[],\n TResult extends Serializable,\n>(\n fn: (...args: TArgs) => Promise<TResult>,\n cache: ICache<Serializable>,\n {\n ttlMilliseconds,\n functionName,\n generateCacheKey,\n refreshCache = false,\n logger = silentLogger,\n }: CacheOptions,\n): ((...args: TArgs) => Promise<TResult>) => {\n // Use provided key generator or default, adapting the default to use the function's name\n const _generateCacheKey = generateCacheKey ?? defaultGenerateCacheKey;\n\n // Get the function name for the default key generator, handle anonymous functions\n const _functionName = functionName ?? fn.name ?? 'anonymousFunction';\n\n return async (...args: TArgs): Promise<TResult> => {\n const cacheKey = _generateCacheKey(_functionName, args);\n // Check if the data is cached\n if (!refreshCache) {\n try {\n const cached = await cache.get(cacheKey);\n // Check explicitly for undefined, as null or other falsy values might be valid cache results\n if (cached !== undefined) {\n // Type assertion because cache stores Serializable, but we expect TResult\n return cached as TResult;\n }\n } catch (error) {\n // Log cache get errors but proceed to execute the function\n logger.error(`Cache get error for key \"${cacheKey}\":`, error);\n }\n }\n\n // Execute the original function\n const result = await fn(...args);\n\n // Cache the result, handling potential errors silently.\n // Fire-and-forget: we don't await this, allowing it to happen in the\n // background. This is safe only because the snaps pair this wrapper with\n // `InMemoryCache` (writes resolve in a microtask). With a mutex-guarded\n // persisted cache such as `StateCache`, unawaited writes would accumulate\n // without backpressure and starve foreground state operations — see the\n // warnings in this function's documentation.\n void cache.set(cacheKey, result, ttlMilliseconds).catch((error) => {\n logger.error(`Cache set error for key \"${cacheKey}\":`, error);\n });\n\n return result;\n };\n};\n"]}
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.useCacheUntil = void 0;
4
+ const Logger_1 = require("../logger/Logger.cjs");
5
+ const serialization_1 = require("../serialization/serialization.cjs");
6
+ /**
7
+ * A logger that discards all messages, used when no logger is provided.
8
+ */
9
+ const silentLogger = new Logger_1.Logger({ level: Logger_1.LogLevel.SILENT });
10
+ /**
11
+ * Default function to generate the cache key for a function call.
12
+ *
13
+ * @param functionName - The name of the function.
14
+ * @param args - The arguments of the function call.
15
+ * @returns The cache key.
16
+ */
17
+ const defaultGenerateCacheKey = (functionName, args) => `${functionName}:${args.map((arg) => JSON.stringify((0, serialization_1.serialize)(arg))).join(':')}`;
18
+ /**
19
+ * Wraps an async function with caching behavior where expiry is determined
20
+ * by the function result itself (dynamic TTL).
21
+ *
22
+ * Unlike `useCache` which uses a fixed TTL, this utility allows the wrapped
23
+ * function to specify when its result expires. This is useful for caching
24
+ * data that has known invalidation points (e.g., blockchain maintenance periods).
25
+ *
26
+ * @template TArgs - Tuple type representing the arguments of the function.
27
+ * @template TResult - The return type of the function, must be Serializable.
28
+ * @param fn - The asynchronous function to wrap. Must return a Promise<ResultWithExpiry<TResult>>.
29
+ * @param cache - The cache instance to use.
30
+ * @param options - The caching options.
31
+ * @param options.refreshCache - Whether to refresh the cache.
32
+ * @param options.functionName - The name of the function.
33
+ * @param options.generateCacheKey - Optional function to generate the cache key.
34
+ * @param options.logger - Optional logger for cache errors.
35
+ * @returns A new asynchronous function with caching behavior.
36
+ */
37
+ const useCacheUntil = (fn, cache, { functionName, generateCacheKey, refreshCache = false, logger = silentLogger, }) => {
38
+ // Use provided key generator or default, adapting the default to use the function's name
39
+ const _generateCacheKey = generateCacheKey ?? defaultGenerateCacheKey;
40
+ // Get the function name for the default key generator, handle anonymous functions
41
+ const _functionName = functionName ?? fn.name ?? 'anonymousFunction';
42
+ // Map to track expiry timestamps for each cache key
43
+ const expiryMap = new Map();
44
+ return async (...args) => {
45
+ const cacheKey = _generateCacheKey(_functionName, args);
46
+ const now = Date.now();
47
+ // Check if cached and not expired.
48
+ // The cache owns the persisted TTL. When this wrapper is recreated after a
49
+ // Snap restart, expiryMap is empty, so consult the cache to hydrate a still
50
+ // valid entry instead of fetching it again.
51
+ const expiresAt = expiryMap.get(cacheKey);
52
+ if (!refreshCache && (expiresAt === undefined || now < expiresAt)) {
53
+ try {
54
+ const cached = await cache.get(cacheKey);
55
+ // Check explicitly for undefined, as null or other falsy values might be valid cache results
56
+ if (cached !== undefined) {
57
+ // Type assertion because cache stores Serializable, but we expect TResult
58
+ return cached;
59
+ }
60
+ }
61
+ catch (error) {
62
+ // Log cache get errors but proceed to execute the function
63
+ logger.error(`Cache get error for key "${cacheKey}":`, error);
64
+ }
65
+ }
66
+ // Execute the original function to get result and new expiry
67
+ const { result, expiresAt: newExpiresAt } = await fn(...args);
68
+ // Calculate TTL from expiry timestamp
69
+ const ttlMilliseconds = Math.max(0, newExpiresAt - now);
70
+ // Store result in cache with calculated TTL
71
+ await cache.set(cacheKey, result, ttlMilliseconds).catch((error) => {
72
+ logger.error(`Cache set error for key "${cacheKey}":`, error);
73
+ });
74
+ // Store expiry timestamp
75
+ expiryMap.set(cacheKey, newExpiresAt);
76
+ return result;
77
+ };
78
+ };
79
+ exports.useCacheUntil = useCacheUntil;
80
+ //# sourceMappingURL=useCacheUntil.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"useCacheUntil.cjs","sourceRoot":"","sources":["../../../src/utils/cache/useCacheUntil.ts"],"names":[],"mappings":";;;AAAA,iDAAoD;AACpD,sEAA2D;AAI3D;;GAEG;AACH,MAAM,YAAY,GAAG,IAAI,eAAM,CAAC,EAAE,KAAK,EAAE,iBAAQ,CAAC,MAAM,EAAE,CAAC,CAAC;AAkC5D;;;;;;GAMG;AACH,MAAM,uBAAuB,GAAG,CAC9B,YAAoB,EACpB,IAAoB,EACZ,EAAE,CACV,GAAG,YAAY,IAAI,IAAI,CAAC,GAAG,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,IAAI,CAAC,SAAS,CAAC,IAAA,yBAAS,EAAC,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC;AAEnF;;;;;;;;;;;;;;;;;;GAkBG;AACI,MAAM,aAAa,GAAG,CAI3B,EAA0D,EAC1D,KAA2B,EAC3B,EACE,YAAY,EACZ,gBAAgB,EAChB,YAAY,GAAG,KAAK,EACpB,MAAM,GAAG,YAAY,GACH,EACoB,EAAE;IAC1C,yFAAyF;IACzF,MAAM,iBAAiB,GAAG,gBAAgB,IAAI,uBAAuB,CAAC;IAEtE,kFAAkF;IAClF,MAAM,aAAa,GAAG,YAAY,IAAI,EAAE,CAAC,IAAI,IAAI,mBAAmB,CAAC;IAErE,oDAAoD;IACpD,MAAM,SAAS,GAAG,IAAI,GAAG,EAAkB,CAAC;IAE5C,OAAO,KAAK,EAAE,GAAG,IAAW,EAAoB,EAAE;QAChD,MAAM,QAAQ,GAAG,iBAAiB,CAAC,aAAa,EAAE,IAAI,CAAC,CAAC;QACxD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QAEvB,mCAAmC;QACnC,2EAA2E;QAC3E,4EAA4E;QAC5E,4CAA4C;QAC5C,MAAM,SAAS,GAAG,SAAS,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC1C,IAAI,CAAC,YAAY,IAAI,CAAC,SAAS,KAAK,SAAS,IAAI,GAAG,GAAG,SAAS,CAAC,EAAE,CAAC;YAClE,IAAI,CAAC;gBACH,MAAM,MAAM,GAAG,MAAM,KAAK,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;gBACzC,6FAA6F;gBAC7F,IAAI,MAAM,KAAK,SAAS,EAAE,CAAC;oBACzB,0EAA0E;oBAC1E,OAAO,MAAiB,CAAC;gBAC3B,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,2DAA2D;gBAC3D,MAAM,CAAC,KAAK,CAAC,4BAA4B,QAAQ,IAAI,EAAE,KAAK,CAAC,CAAC;YAChE,CAAC;QACH,CAAC;QAED,6DAA6D;QAC7D,MAAM,EAAE,MAAM,EAAE,SAAS,EAAE,YAAY,EAAE,GAAG,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC;QAE9D,sCAAsC;QACtC,MAAM,eAAe,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,YAAY,GAAG,GAAG,CAAC,CAAC;QAExD,4CAA4C;QAC5C,MAAM,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,EAAE,eAAe,CAAC,CAAC,KAAK,CAAC,CAAC,KAAK,EAAE,EAAE;YACjE,MAAM,CAAC,KAAK,CAAC,4BAA4B,QAAQ,IAAI,EAAE,KAAK,CAAC,CAAC;QAChE,CAAC,CAAC,CAAC;QAEH,yBAAyB;QACzB,SAAS,CAAC,GAAG,CAAC,QAAQ,EAAE,YAAY,CAAC,CAAC;QAEtC,OAAO,MAAM,CAAC;IAChB,CAAC,CAAC;AACJ,CAAC,CAAC;AA7DW,QAAA,aAAa,iBA6DxB","sourcesContent":["import { Logger, LogLevel } from '../logger/Logger';\nimport { serialize } from '../serialization/serialization';\nimport type { Serializable } from '../serialization/types';\nimport type { ICache } from './types';\n\n/**\n * A logger that discards all messages, used when no logger is provided.\n */\nconst silentLogger = new Logger({ level: LogLevel.SILENT });\n\n/**\n * Result type for functions that provide their own expiry time.\n */\nexport type ResultWithExpiry<TResult> = {\n result: TResult;\n expiresAt: number; // Unix timestamp in milliseconds\n};\n\n/**\n * Options for configuring the caching behavior of a function with dynamic expiry.\n */\nexport type CacheUntilOptions = {\n /**\n * Set this if you want to use a custom function name for the cache key.\n */\n functionName?: string;\n /**\n * Optional function to generate the cache key for the function call.\n * Defaults to a function that generates the key based on function name and JSON stringified args separated by colons.\n */\n generateCacheKey?: (functionName: string, args: Serializable[]) => string;\n /**\n * Whether to refresh the cache.\n * Defaults to false.\n */\n refreshCache?: boolean;\n /**\n * Optional logger for cache errors. Defaults to a silent logger.\n */\n logger?: Logger;\n};\n\n/**\n * Default function to generate the cache key for a function call.\n *\n * @param functionName - The name of the function.\n * @param args - The arguments of the function call.\n * @returns The cache key.\n */\nconst defaultGenerateCacheKey = (\n functionName: string,\n args: Serializable[],\n): string =>\n `${functionName}:${args.map((arg) => JSON.stringify(serialize(arg))).join(':')}`;\n\n/**\n * Wraps an async function with caching behavior where expiry is determined\n * by the function result itself (dynamic TTL).\n *\n * Unlike `useCache` which uses a fixed TTL, this utility allows the wrapped\n * function to specify when its result expires. This is useful for caching\n * data that has known invalidation points (e.g., blockchain maintenance periods).\n *\n * @template TArgs - Tuple type representing the arguments of the function.\n * @template TResult - The return type of the function, must be Serializable.\n * @param fn - The asynchronous function to wrap. Must return a Promise<ResultWithExpiry<TResult>>.\n * @param cache - The cache instance to use.\n * @param options - The caching options.\n * @param options.refreshCache - Whether to refresh the cache.\n * @param options.functionName - The name of the function.\n * @param options.generateCacheKey - Optional function to generate the cache key.\n * @param options.logger - Optional logger for cache errors.\n * @returns A new asynchronous function with caching behavior.\n */\nexport const useCacheUntil = <\n TArgs extends Serializable[],\n TResult extends Serializable,\n>(\n fn: (...args: TArgs) => Promise<ResultWithExpiry<TResult>>,\n cache: ICache<Serializable>,\n {\n functionName,\n generateCacheKey,\n refreshCache = false,\n logger = silentLogger,\n }: CacheUntilOptions,\n): ((...args: TArgs) => Promise<TResult>) => {\n // Use provided key generator or default, adapting the default to use the function's name\n const _generateCacheKey = generateCacheKey ?? defaultGenerateCacheKey;\n\n // Get the function name for the default key generator, handle anonymous functions\n const _functionName = functionName ?? fn.name ?? 'anonymousFunction';\n\n // Map to track expiry timestamps for each cache key\n const expiryMap = new Map<string, number>();\n\n return async (...args: TArgs): Promise<TResult> => {\n const cacheKey = _generateCacheKey(_functionName, args);\n const now = Date.now();\n\n // Check if cached and not expired.\n // The cache owns the persisted TTL. When this wrapper is recreated after a\n // Snap restart, expiryMap is empty, so consult the cache to hydrate a still\n // valid entry instead of fetching it again.\n const expiresAt = expiryMap.get(cacheKey);\n if (!refreshCache && (expiresAt === undefined || now < expiresAt)) {\n try {\n const cached = await cache.get(cacheKey);\n // Check explicitly for undefined, as null or other falsy values might be valid cache results\n if (cached !== undefined) {\n // Type assertion because cache stores Serializable, but we expect TResult\n return cached as TResult;\n }\n } catch (error) {\n // Log cache get errors but proceed to execute the function\n logger.error(`Cache get error for key \"${cacheKey}\":`, error);\n }\n }\n\n // Execute the original function to get result and new expiry\n const { result, expiresAt: newExpiresAt } = await fn(...args);\n\n // Calculate TTL from expiry timestamp\n const ttlMilliseconds = Math.max(0, newExpiresAt - now);\n\n // Store result in cache with calculated TTL\n await cache.set(cacheKey, result, ttlMilliseconds).catch((error) => {\n logger.error(`Cache set error for key \"${cacheKey}\":`, error);\n });\n\n // Store expiry timestamp\n expiryMap.set(cacheKey, newExpiresAt);\n\n return result;\n };\n};\n"]}