@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,38 @@
1
+ import $lodash from "lodash";
2
+ const { get, set, unset } = $lodash;
3
+ /**
4
+ * A simple implementation of the `IStateManager` interface that relies on an in-memory
5
+ * state. Intended for tests.
6
+ */
7
+ export class InMemoryState {
8
+ #state;
9
+ constructor(initialState) {
10
+ this.#state = initialState;
11
+ }
12
+ async get() {
13
+ return this.#state;
14
+ }
15
+ async getKey(key) {
16
+ return get(this.#state, key);
17
+ }
18
+ async setKey(key, value) {
19
+ set(this.#state, key, value);
20
+ }
21
+ async setKeyWith(key, updater) {
22
+ const oldValue = get(this.#state, key);
23
+ set(this.#state, key, updater(oldValue));
24
+ }
25
+ async update(callback) {
26
+ this.#state = callback(this.#state);
27
+ return this.#state;
28
+ }
29
+ async deleteKey(key) {
30
+ unset(this.#state, key);
31
+ }
32
+ async deleteKeys(keys) {
33
+ keys.forEach((key) => {
34
+ unset(this.#state, key);
35
+ });
36
+ }
37
+ }
38
+ //# sourceMappingURL=InMemoryState.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"InMemoryState.mjs","sourceRoot":"","sources":["../../../src/utils/state/InMemoryState.ts"],"names":[],"mappings":";;AAKA;;;GAGG;AACH,MAAM,OAAO,aAAa;IAGxB,MAAM,CAAc;IAEpB,YAAY,YAAyB;QACnC,IAAI,CAAC,MAAM,GAAG,YAAY,CAAC;IAC7B,CAAC;IAED,KAAK,CAAC,GAAG;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,MAAM,CACV,GAAW;QAEX,OAAO,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAA0B,CAAC;IACxD,CAAC;IAED,KAAK,CAAC,MAAM,CAAC,GAAW,EAAE,KAAmB;QAC3C,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,KAAK,CAAC,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,UAAU,CACd,GAAW,EACX,OAAqD;QAErD,MAAM,QAAQ,GAAG,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAuB,CAAC;QAC7D,GAAG,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,EAAE,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,MAAM,CACV,QAA6C;QAE7C,IAAI,CAAC,MAAM,GAAG,QAAQ,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,GAAW;QACzB,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;IAC1B,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,IAAc;QAC7B,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;YACnB,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC1B,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import { get, set, unset } from 'lodash';\n\nimport type { Serializable } from '../serialization/types';\nimport type { IStateManager } from './IStateManager';\n\n/**\n * A simple implementation of the `IStateManager` interface that relies on an in-memory\n * state. Intended for tests.\n */\nexport class InMemoryState<\n TStateValue extends Record<string, Serializable>,\n> implements IStateManager<TStateValue> {\n #state: TStateValue;\n\n constructor(initialState: TStateValue) {\n this.#state = initialState;\n }\n\n async get(): Promise<TStateValue> {\n return this.#state;\n }\n\n async getKey<TResponse extends Serializable>(\n key: string,\n ): Promise<TResponse | undefined> {\n return get(this.#state, key) as TResponse | undefined;\n }\n\n async setKey(key: string, value: Serializable): Promise<void> {\n set(this.#state, key, value);\n }\n\n async setKeyWith<TValue extends Serializable>(\n key: string,\n updater: (currentValue: TValue | undefined) => TValue,\n ): Promise<void> {\n const oldValue = get(this.#state, key) as TValue | undefined;\n set(this.#state, key, updater(oldValue));\n }\n\n async update(\n callback: (state: TStateValue) => TStateValue,\n ): Promise<TStateValue> {\n this.#state = callback(this.#state);\n return this.#state;\n }\n\n async deleteKey(key: string): Promise<void> {\n unset(this.#state, key);\n }\n\n async deleteKeys(keys: string[]): Promise<void> {\n keys.forEach((key) => {\n unset(this.#state, key);\n });\n }\n}\n"]}
@@ -0,0 +1,159 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.State = void 0;
4
+ const async_mutex_1 = require("async-mutex");
5
+ const lodash_1 = require("lodash");
6
+ const safeMerge_1 = require("../safeMerge/safeMerge.cjs");
7
+ const serialization_1 = require("../serialization/serialization.cjs");
8
+ /**
9
+ * Resolves the Snap RPC client from the global `snap` object provided by the Snap runtime.
10
+ *
11
+ * @returns The Snap `request` function.
12
+ */
13
+ const getSnapRequest = () => globalThis.snap.request;
14
+ /**
15
+ * Because we use both snap_manageState and snap_setState, we must protect against them
16
+ * being used at the same time. We must also protect against multiple parallel requests
17
+ * to snap_manageState.
18
+ *
19
+ * Path writes (`setKey` / `setKeyWith`) are serialized with a dedicated write mutex so
20
+ * concurrent read-modify-write updates cannot interleave. Path reads may still run in
21
+ * parallel with each other. A blob (`snap_manageState`) operation waits for in-flight path
22
+ * operations to finish and blocks new ones from starting until it completes.
23
+ */
24
+ class StateLock {
25
+ // Gate every operation must pass through to start. Path operations hold it only while
26
+ // registering; a blob operation holds it for its whole duration, so no path operation
27
+ // can start after a blob operation begins waiting for in-flight ones to finish.
28
+ #operationAdmissionMutex = new async_mutex_1.Mutex();
29
+ // Held while at least one path operation is in flight.
30
+ #regularStateUpdateMutex = new async_mutex_1.Mutex();
31
+ #regularStateWriteMutex = new async_mutex_1.Mutex();
32
+ #pendingRegularStateUpdates = 0;
33
+ #releaseRegularStateUpdateMutex = null;
34
+ async #acquireRegularStateUpdateMutex() {
35
+ if (!this.#regularStateUpdateMutex.isLocked()) {
36
+ this.#releaseRegularStateUpdateMutex =
37
+ await this.#regularStateUpdateMutex.acquire();
38
+ }
39
+ }
40
+ async wrapRegularStateOperation(callback) {
41
+ await this.#operationAdmissionMutex.runExclusive(async () => {
42
+ await this.#acquireRegularStateUpdateMutex();
43
+ this.#pendingRegularStateUpdates += 1;
44
+ });
45
+ try {
46
+ return await callback();
47
+ }
48
+ finally {
49
+ this.#pendingRegularStateUpdates -= 1;
50
+ if (this.#pendingRegularStateUpdates === 0 &&
51
+ this.#releaseRegularStateUpdateMutex) {
52
+ this.#releaseRegularStateUpdateMutex();
53
+ this.#releaseRegularStateUpdateMutex = null;
54
+ }
55
+ }
56
+ }
57
+ async wrapRegularStateWriteOperation(callback) {
58
+ return await this.#regularStateWriteMutex.runExclusive(async () => this.wrapRegularStateOperation(callback));
59
+ }
60
+ async wrapManageStateOperation(callback) {
61
+ return await this.#operationAdmissionMutex.runExclusive(async () => {
62
+ await this.#regularStateUpdateMutex.waitForUnlock();
63
+ return await callback();
64
+ });
65
+ }
66
+ }
67
+ /**
68
+ * Layer on top of `snap_manageState` / `snap_getState` / `snap_setState`:
69
+ *
70
+ * - Serializes values before storing them and deserializes after reading.
71
+ * - Merges `defaultState` on full-blob reads via `safeMerge`.
72
+ * - Serializes path writes and full-blob updates (lock strategy B).
73
+ */
74
+ class State {
75
+ #lock = new StateLock();
76
+ #config;
77
+ constructor(config) {
78
+ this.#config = config;
79
+ }
80
+ /**
81
+ * Reads and deserializes the value at `key`, or the whole state blob when `key` is omitted.
82
+ *
83
+ * @param key - The JSON-path key to read. Omit to read the whole blob.
84
+ * @returns The deserialized value, or `undefined` when the key is absent.
85
+ */
86
+ async #read(key) {
87
+ const value = await getSnapRequest()({
88
+ method: 'snap_getState',
89
+ params: {
90
+ ...(key === undefined ? {} : { key }),
91
+ encrypted: this.#config.encrypted,
92
+ },
93
+ });
94
+ return value === null || value === undefined
95
+ ? undefined
96
+ : (0, serialization_1.deserialize)(value);
97
+ }
98
+ /**
99
+ * Serializes `value` and writes it to `key`.
100
+ *
101
+ * @param key - The JSON-path key to write.
102
+ * @param value - The value to store.
103
+ */
104
+ async #write(key, value) {
105
+ await getSnapRequest()({
106
+ method: 'snap_setState',
107
+ params: {
108
+ key,
109
+ value: (0, serialization_1.serialize)(value),
110
+ encrypted: this.#config.encrypted,
111
+ },
112
+ });
113
+ }
114
+ async #unsafeGet() {
115
+ const state = (await this.#read()) ?? {};
116
+ // Clone the defaults so updaters that mutate the returned state (e.g. `deleteKey`
117
+ // via lodash `unset`) never leak into the shared `defaultState` object.
118
+ return (0, safeMerge_1.safeMerge)((0, lodash_1.cloneDeep)(this.#config.defaultState), state);
119
+ }
120
+ async get() {
121
+ return this.#lock.wrapRegularStateOperation(async () => this.#unsafeGet());
122
+ }
123
+ async getKey(key) {
124
+ return this.#lock.wrapRegularStateOperation(async () => this.#read(key));
125
+ }
126
+ async setKey(key, value) {
127
+ await this.#lock.wrapRegularStateWriteOperation(async () => this.#write(key, value));
128
+ }
129
+ async setKeyWith(key, updater) {
130
+ await this.#lock.wrapRegularStateWriteOperation(async () => this.#write(key, updater(await this.#read(key))));
131
+ }
132
+ async update(updaterFunction) {
133
+ return await this.#lock.wrapManageStateOperation(async () => {
134
+ const newState = updaterFunction(await this.#unsafeGet());
135
+ await getSnapRequest()({
136
+ method: 'snap_manageState',
137
+ params: {
138
+ operation: 'update',
139
+ newState: (0, serialization_1.serialize)(newState),
140
+ encrypted: this.#config.encrypted,
141
+ },
142
+ });
143
+ return newState;
144
+ });
145
+ }
146
+ async deleteKey(key) {
147
+ await this.deleteKeys([key]);
148
+ }
149
+ async deleteKeys(keys) {
150
+ await this.update((state) => {
151
+ keys.forEach((key) => {
152
+ (0, lodash_1.unset)(state, key);
153
+ });
154
+ return state;
155
+ });
156
+ }
157
+ }
158
+ exports.State = State;
159
+ //# sourceMappingURL=State.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"State.cjs","sourceRoot":"","sources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C,wBAAwB,CAAC,KAAK,IAAI,EAAE;YAC1D,MAAM,QAAQ,GAAG,eAAe,CAAC,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;YAE1D,MAAM,cAAc,EAAE,CAAC;gBACrB,MAAM,EAAE,kBAAkB;gBAC1B,MAAM,EAAE;oBACN,SAAS,EAAE,QAAQ;oBACnB,QAAQ,EAAE,IAAA,yBAAS,EAAC,QAAQ,CAAyB;oBACrD,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS;iBAClC;aACF,CAAC,CAAC;YAEH,OAAO,QAAQ,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,GAAW;QACzB,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,IAAc;QAC7B,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YAC1B,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;gBACnB,IAAA,cAAK,EAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YACpB,CAAC,CAAC,CAAC;YACH,OAAO,KAAK,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AApHD,sBAoHC","sourcesContent":["import type { Json, SnapsProvider } from '@metamask/snaps-sdk';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\nimport { cloneDeep, unset } from 'lodash';\n\nimport { safeMerge } from '../safeMerge/safeMerge';\nimport { deserialize, serialize } from '../serialization/serialization';\nimport type { Serializable } from '../serialization/types';\nimport type { IStateManager } from './IStateManager';\n\nexport type StateConfig<TValue extends Record<string, Serializable>> = {\n encrypted: boolean;\n defaultState: TValue;\n};\n\n/**\n * Resolves the Snap RPC client from the global `snap` object provided by the Snap runtime.\n *\n * @returns The Snap `request` function.\n */\nconst getSnapRequest = (): SnapsProvider['request'] =>\n (globalThis as typeof globalThis & { snap: SnapsProvider }).snap.request;\n\n/**\n * Because we use both snap_manageState and snap_setState, we must protect against them\n * being used at the same time. We must also protect against multiple parallel requests\n * to snap_manageState.\n *\n * Path writes (`setKey` / `setKeyWith`) are serialized with a dedicated write mutex so\n * concurrent read-modify-write updates cannot interleave. Path reads may still run in\n * parallel with each other. A blob (`snap_manageState`) operation waits for in-flight path\n * operations to finish and blocks new ones from starting until it completes.\n */\nclass StateLock {\n // Gate every operation must pass through to start. Path operations hold it only while\n // registering; a blob operation holds it for its whole duration, so no path operation\n // can start after a blob operation begins waiting for in-flight ones to finish.\n readonly #operationAdmissionMutex = new Mutex();\n\n // Held while at least one path operation is in flight.\n readonly #regularStateUpdateMutex = new Mutex();\n\n readonly #regularStateWriteMutex = new Mutex();\n\n #pendingRegularStateUpdates = 0;\n\n #releaseRegularStateUpdateMutex: MutexInterface.Releaser | null = null;\n\n async #acquireRegularStateUpdateMutex(): Promise<void> {\n if (!this.#regularStateUpdateMutex.isLocked()) {\n this.#releaseRegularStateUpdateMutex =\n await this.#regularStateUpdateMutex.acquire();\n }\n }\n\n async wrapRegularStateOperation<ReturnType>(\n callback: MutexInterface.Worker<ReturnType>,\n ): Promise<ReturnType> {\n await this.#operationAdmissionMutex.runExclusive(async () => {\n await this.#acquireRegularStateUpdateMutex();\n this.#pendingRegularStateUpdates += 1;\n });\n\n try {\n return await callback();\n } finally {\n this.#pendingRegularStateUpdates -= 1;\n\n if (\n this.#pendingRegularStateUpdates === 0 &&\n this.#releaseRegularStateUpdateMutex\n ) {\n this.#releaseRegularStateUpdateMutex();\n this.#releaseRegularStateUpdateMutex = null;\n }\n }\n }\n\n async wrapRegularStateWriteOperation<ReturnType>(\n callback: MutexInterface.Worker<ReturnType>,\n ): Promise<ReturnType> {\n return await this.#regularStateWriteMutex.runExclusive(async () =>\n this.wrapRegularStateOperation(callback),\n );\n }\n\n async wrapManageStateOperation<ReturnType>(\n callback: MutexInterface.Worker<ReturnType>,\n ): Promise<ReturnType> {\n return await this.#operationAdmissionMutex.runExclusive(async () => {\n await this.#regularStateUpdateMutex.waitForUnlock();\n\n return await callback();\n });\n }\n}\n\n/**\n * Layer on top of `snap_manageState` / `snap_getState` / `snap_setState`:\n *\n * - Serializes values before storing them and deserializes after reading.\n * - Merges `defaultState` on full-blob reads via `safeMerge`.\n * - Serializes path writes and full-blob updates (lock strategy B).\n */\nexport class State<\n TStateValue extends Record<string, Serializable>,\n> implements IStateManager<TStateValue> {\n readonly #lock = new StateLock();\n\n readonly #config: StateConfig<TStateValue>;\n\n constructor(config: StateConfig<TStateValue>) {\n this.#config = config;\n }\n\n /**\n * Reads and deserializes the value at `key`, or the whole state blob when `key` is omitted.\n *\n * @param key - The JSON-path key to read. Omit to read the whole blob.\n * @returns The deserialized value, or `undefined` when the key is absent.\n */\n async #read<TValue extends Serializable>(\n key?: string,\n ): Promise<TValue | undefined> {\n const value = await getSnapRequest()({\n method: 'snap_getState',\n params: {\n ...(key === undefined ? {} : { key }),\n encrypted: this.#config.encrypted,\n },\n });\n\n return value === null || value === undefined\n ? undefined\n : (deserialize(value) as TValue);\n }\n\n /**\n * Serializes `value` and writes it to `key`.\n *\n * @param key - The JSON-path key to write.\n * @param value - The value to store.\n */\n async #write(key: string, value: Serializable): Promise<void> {\n await getSnapRequest()({\n method: 'snap_setState',\n params: {\n key,\n value: serialize(value),\n encrypted: this.#config.encrypted,\n },\n });\n }\n\n async #unsafeGet(): Promise<TStateValue> {\n const state = (await this.#read<TStateValue>()) ?? ({} as TStateValue);\n\n // Clone the defaults so updaters that mutate the returned state (e.g. `deleteKey`\n // via lodash `unset`) never leak into the shared `defaultState` object.\n return safeMerge(cloneDeep(this.#config.defaultState), state);\n }\n\n async get(): Promise<TStateValue> {\n return this.#lock.wrapRegularStateOperation(async () => this.#unsafeGet());\n }\n\n async getKey<TResponse extends Serializable>(\n key: string,\n ): Promise<TResponse | undefined> {\n return this.#lock.wrapRegularStateOperation(async () =>\n this.#read<TResponse>(key),\n );\n }\n\n async setKey(key: string, value: Serializable): Promise<void> {\n await this.#lock.wrapRegularStateWriteOperation(async () =>\n this.#write(key, value),\n );\n }\n\n async setKeyWith<TValue extends Serializable>(\n key: string,\n updater: (currentValue: TValue | undefined) => TValue,\n ): Promise<void> {\n await this.#lock.wrapRegularStateWriteOperation(async () =>\n this.#write(key, updater(await this.#read<TValue>(key))),\n );\n }\n\n async update(\n updaterFunction: (state: TStateValue) => TStateValue,\n ): Promise<TStateValue> {\n return await this.#lock.wrapManageStateOperation(async () => {\n const newState = updaterFunction(await this.#unsafeGet());\n\n await getSnapRequest()({\n method: 'snap_manageState',\n params: {\n operation: 'update',\n newState: serialize(newState) as Record<string, Json>,\n encrypted: this.#config.encrypted,\n },\n });\n\n return newState;\n });\n }\n\n async deleteKey(key: string): Promise<void> {\n await this.deleteKeys([key]);\n }\n\n async deleteKeys(keys: string[]): Promise<void> {\n await this.update((state) => {\n keys.forEach((key) => {\n unset(state, key);\n });\n return state;\n });\n }\n}\n"]}
@@ -0,0 +1,25 @@
1
+ import type { Serializable } from "../serialization/types.cjs";
2
+ import type { IStateManager } from "./IStateManager.cjs";
3
+ export type StateConfig<TValue extends Record<string, Serializable>> = {
4
+ encrypted: boolean;
5
+ defaultState: TValue;
6
+ };
7
+ /**
8
+ * Layer on top of `snap_manageState` / `snap_getState` / `snap_setState`:
9
+ *
10
+ * - Serializes values before storing them and deserializes after reading.
11
+ * - Merges `defaultState` on full-blob reads via `safeMerge`.
12
+ * - Serializes path writes and full-blob updates (lock strategy B).
13
+ */
14
+ export declare class State<TStateValue extends Record<string, Serializable>> implements IStateManager<TStateValue> {
15
+ #private;
16
+ constructor(config: StateConfig<TStateValue>);
17
+ get(): Promise<TStateValue>;
18
+ getKey<TResponse extends Serializable>(key: string): Promise<TResponse | undefined>;
19
+ setKey(key: string, value: Serializable): Promise<void>;
20
+ setKeyWith<TValue extends Serializable>(key: string, updater: (currentValue: TValue | undefined) => TValue): Promise<void>;
21
+ update(updaterFunction: (state: TStateValue) => TStateValue): Promise<TStateValue>;
22
+ deleteKey(key: string): Promise<void>;
23
+ deleteKeys(keys: string[]): Promise<void>;
24
+ }
25
+ //# sourceMappingURL=State.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"State.d.cts","sourceRoot":"","sources":["../../../src/utils/state/State.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,YAAY,EAAE,mCAA+B;AAC3D,OAAO,KAAK,EAAE,aAAa,EAAE,4BAAwB;AAErD,MAAM,MAAM,WAAW,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,IAAI;IACrE,SAAS,EAAE,OAAO,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC;AAoFF;;;;;;GAMG;AACH,qBAAa,KAAK,CAChB,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAChD,YAAW,aAAa,CAAC,WAAW,CAAC;;gBAKzB,MAAM,EAAE,WAAW,CAAC,WAAW,CAAC;IAmDtC,GAAG,IAAI,OAAO,CAAC,WAAW,CAAC;IAI3B,MAAM,CAAC,SAAS,SAAS,YAAY,EACzC,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;IAM3B,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAMvD,UAAU,CAAC,MAAM,SAAS,YAAY,EAC1C,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,KAAK,MAAM,GACpD,OAAO,CAAC,IAAI,CAAC;IAMV,MAAM,CACV,eAAe,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,WAAW,GACnD,OAAO,CAAC,WAAW,CAAC;IAiBjB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIrC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAQhD"}
@@ -0,0 +1,25 @@
1
+ import type { Serializable } from "../serialization/types.mjs";
2
+ import type { IStateManager } from "./IStateManager.mjs";
3
+ export type StateConfig<TValue extends Record<string, Serializable>> = {
4
+ encrypted: boolean;
5
+ defaultState: TValue;
6
+ };
7
+ /**
8
+ * Layer on top of `snap_manageState` / `snap_getState` / `snap_setState`:
9
+ *
10
+ * - Serializes values before storing them and deserializes after reading.
11
+ * - Merges `defaultState` on full-blob reads via `safeMerge`.
12
+ * - Serializes path writes and full-blob updates (lock strategy B).
13
+ */
14
+ export declare class State<TStateValue extends Record<string, Serializable>> implements IStateManager<TStateValue> {
15
+ #private;
16
+ constructor(config: StateConfig<TStateValue>);
17
+ get(): Promise<TStateValue>;
18
+ getKey<TResponse extends Serializable>(key: string): Promise<TResponse | undefined>;
19
+ setKey(key: string, value: Serializable): Promise<void>;
20
+ setKeyWith<TValue extends Serializable>(key: string, updater: (currentValue: TValue | undefined) => TValue): Promise<void>;
21
+ update(updaterFunction: (state: TStateValue) => TStateValue): Promise<TStateValue>;
22
+ deleteKey(key: string): Promise<void>;
23
+ deleteKeys(keys: string[]): Promise<void>;
24
+ }
25
+ //# sourceMappingURL=State.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"State.d.mts","sourceRoot":"","sources":["../../../src/utils/state/State.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,YAAY,EAAE,mCAA+B;AAC3D,OAAO,KAAK,EAAE,aAAa,EAAE,4BAAwB;AAErD,MAAM,MAAM,WAAW,CAAC,MAAM,SAAS,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,IAAI;IACrE,SAAS,EAAE,OAAO,CAAC;IACnB,YAAY,EAAE,MAAM,CAAC;CACtB,CAAC;AAoFF;;;;;;GAMG;AACH,qBAAa,KAAK,CAChB,WAAW,SAAS,MAAM,CAAC,MAAM,EAAE,YAAY,CAAC,CAChD,YAAW,aAAa,CAAC,WAAW,CAAC;;gBAKzB,MAAM,EAAE,WAAW,CAAC,WAAW,CAAC;IAmDtC,GAAG,IAAI,OAAO,CAAC,WAAW,CAAC;IAI3B,MAAM,CAAC,SAAS,SAAS,YAAY,EACzC,GAAG,EAAE,MAAM,GACV,OAAO,CAAC,SAAS,GAAG,SAAS,CAAC;IAM3B,MAAM,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC;IAMvD,UAAU,CAAC,MAAM,SAAS,YAAY,EAC1C,GAAG,EAAE,MAAM,EACX,OAAO,EAAE,CAAC,YAAY,EAAE,MAAM,GAAG,SAAS,KAAK,MAAM,GACpD,OAAO,CAAC,IAAI,CAAC;IAMV,MAAM,CACV,eAAe,EAAE,CAAC,KAAK,EAAE,WAAW,KAAK,WAAW,GACnD,OAAO,CAAC,WAAW,CAAC;IAiBjB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAIrC,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAQhD"}
@@ -0,0 +1,156 @@
1
+ import { Mutex } from "async-mutex";
2
+ import $lodash from "lodash";
3
+ const { cloneDeep, unset } = $lodash;
4
+ import { safeMerge } from "../safeMerge/safeMerge.mjs";
5
+ import { deserialize, serialize } from "../serialization/serialization.mjs";
6
+ /**
7
+ * Resolves the Snap RPC client from the global `snap` object provided by the Snap runtime.
8
+ *
9
+ * @returns The Snap `request` function.
10
+ */
11
+ const getSnapRequest = () => globalThis.snap.request;
12
+ /**
13
+ * Because we use both snap_manageState and snap_setState, we must protect against them
14
+ * being used at the same time. We must also protect against multiple parallel requests
15
+ * to snap_manageState.
16
+ *
17
+ * Path writes (`setKey` / `setKeyWith`) are serialized with a dedicated write mutex so
18
+ * concurrent read-modify-write updates cannot interleave. Path reads may still run in
19
+ * parallel with each other. A blob (`snap_manageState`) operation waits for in-flight path
20
+ * operations to finish and blocks new ones from starting until it completes.
21
+ */
22
+ class StateLock {
23
+ // Gate every operation must pass through to start. Path operations hold it only while
24
+ // registering; a blob operation holds it for its whole duration, so no path operation
25
+ // can start after a blob operation begins waiting for in-flight ones to finish.
26
+ #operationAdmissionMutex = new Mutex();
27
+ // Held while at least one path operation is in flight.
28
+ #regularStateUpdateMutex = new Mutex();
29
+ #regularStateWriteMutex = new Mutex();
30
+ #pendingRegularStateUpdates = 0;
31
+ #releaseRegularStateUpdateMutex = null;
32
+ async #acquireRegularStateUpdateMutex() {
33
+ if (!this.#regularStateUpdateMutex.isLocked()) {
34
+ this.#releaseRegularStateUpdateMutex =
35
+ await this.#regularStateUpdateMutex.acquire();
36
+ }
37
+ }
38
+ async wrapRegularStateOperation(callback) {
39
+ await this.#operationAdmissionMutex.runExclusive(async () => {
40
+ await this.#acquireRegularStateUpdateMutex();
41
+ this.#pendingRegularStateUpdates += 1;
42
+ });
43
+ try {
44
+ return await callback();
45
+ }
46
+ finally {
47
+ this.#pendingRegularStateUpdates -= 1;
48
+ if (this.#pendingRegularStateUpdates === 0 &&
49
+ this.#releaseRegularStateUpdateMutex) {
50
+ this.#releaseRegularStateUpdateMutex();
51
+ this.#releaseRegularStateUpdateMutex = null;
52
+ }
53
+ }
54
+ }
55
+ async wrapRegularStateWriteOperation(callback) {
56
+ return await this.#regularStateWriteMutex.runExclusive(async () => this.wrapRegularStateOperation(callback));
57
+ }
58
+ async wrapManageStateOperation(callback) {
59
+ return await this.#operationAdmissionMutex.runExclusive(async () => {
60
+ await this.#regularStateUpdateMutex.waitForUnlock();
61
+ return await callback();
62
+ });
63
+ }
64
+ }
65
+ /**
66
+ * Layer on top of `snap_manageState` / `snap_getState` / `snap_setState`:
67
+ *
68
+ * - Serializes values before storing them and deserializes after reading.
69
+ * - Merges `defaultState` on full-blob reads via `safeMerge`.
70
+ * - Serializes path writes and full-blob updates (lock strategy B).
71
+ */
72
+ export class State {
73
+ #lock = new StateLock();
74
+ #config;
75
+ constructor(config) {
76
+ this.#config = config;
77
+ }
78
+ /**
79
+ * Reads and deserializes the value at `key`, or the whole state blob when `key` is omitted.
80
+ *
81
+ * @param key - The JSON-path key to read. Omit to read the whole blob.
82
+ * @returns The deserialized value, or `undefined` when the key is absent.
83
+ */
84
+ async #read(key) {
85
+ const value = await getSnapRequest()({
86
+ method: 'snap_getState',
87
+ params: {
88
+ ...(key === undefined ? {} : { key }),
89
+ encrypted: this.#config.encrypted,
90
+ },
91
+ });
92
+ return value === null || value === undefined
93
+ ? undefined
94
+ : deserialize(value);
95
+ }
96
+ /**
97
+ * Serializes `value` and writes it to `key`.
98
+ *
99
+ * @param key - The JSON-path key to write.
100
+ * @param value - The value to store.
101
+ */
102
+ async #write(key, value) {
103
+ await getSnapRequest()({
104
+ method: 'snap_setState',
105
+ params: {
106
+ key,
107
+ value: serialize(value),
108
+ encrypted: this.#config.encrypted,
109
+ },
110
+ });
111
+ }
112
+ async #unsafeGet() {
113
+ const state = (await this.#read()) ?? {};
114
+ // Clone the defaults so updaters that mutate the returned state (e.g. `deleteKey`
115
+ // via lodash `unset`) never leak into the shared `defaultState` object.
116
+ return safeMerge(cloneDeep(this.#config.defaultState), state);
117
+ }
118
+ async get() {
119
+ return this.#lock.wrapRegularStateOperation(async () => this.#unsafeGet());
120
+ }
121
+ async getKey(key) {
122
+ return this.#lock.wrapRegularStateOperation(async () => this.#read(key));
123
+ }
124
+ async setKey(key, value) {
125
+ await this.#lock.wrapRegularStateWriteOperation(async () => this.#write(key, value));
126
+ }
127
+ async setKeyWith(key, updater) {
128
+ await this.#lock.wrapRegularStateWriteOperation(async () => this.#write(key, updater(await this.#read(key))));
129
+ }
130
+ async update(updaterFunction) {
131
+ return await this.#lock.wrapManageStateOperation(async () => {
132
+ const newState = updaterFunction(await this.#unsafeGet());
133
+ await getSnapRequest()({
134
+ method: 'snap_manageState',
135
+ params: {
136
+ operation: 'update',
137
+ newState: serialize(newState),
138
+ encrypted: this.#config.encrypted,
139
+ },
140
+ });
141
+ return newState;
142
+ });
143
+ }
144
+ async deleteKey(key) {
145
+ await this.deleteKeys([key]);
146
+ }
147
+ async deleteKeys(keys) {
148
+ await this.update((state) => {
149
+ keys.forEach((key) => {
150
+ unset(state, key);
151
+ });
152
+ return state;
153
+ });
154
+ }
155
+ }
156
+ //# sourceMappingURL=State.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"State.mjs","sourceRoot":"","sources":["../../../src/utils/state/State.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,KAAK,EAAE,oBAAoB;;;AAGpC,OAAO,EAAE,SAAS,EAAE,mCAA+B;AACnD,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,2CAAuC;AASxE;;;;GAIG;AACH,MAAM,cAAc,GAAG,GAA6B,EAAE,CACnD,UAA0D,CAAC,IAAI,CAAC,OAAO,CAAC;AAE3E;;;;;;;;;GASG;AACH,MAAM,SAAS;IACb,sFAAsF;IACtF,sFAAsF;IACtF,gFAAgF;IACvE,wBAAwB,GAAG,IAAI,KAAK,EAAE,CAAC;IAEhD,uDAAuD;IAC9C,wBAAwB,GAAG,IAAI,KAAK,EAAE,CAAC;IAEvC,uBAAuB,GAAG,IAAI,KAAK,EAAE,CAAC;IAE/C,2BAA2B,GAAG,CAAC,CAAC;IAEhC,+BAA+B,GAAmC,IAAI,CAAC;IAEvE,KAAK,CAAC,+BAA+B;QACnC,IAAI,CAAC,IAAI,CAAC,wBAAwB,CAAC,QAAQ,EAAE,EAAE,CAAC;YAC9C,IAAI,CAAC,+BAA+B;gBAClC,MAAM,IAAI,CAAC,wBAAwB,CAAC,OAAO,EAAE,CAAC;QAClD,CAAC;IACH,CAAC;IAED,KAAK,CAAC,yBAAyB,CAC7B,QAA2C;QAE3C,MAAM,IAAI,CAAC,wBAAwB,CAAC,YAAY,CAAC,KAAK,IAAI,EAAE;YAC1D,MAAM,IAAI,CAAC,+BAA+B,EAAE,CAAC;YAC7C,IAAI,CAAC,2BAA2B,IAAI,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,KAAK,CAAC,UAAU,CACd,GAAW,EACX,OAAqD;QAErD,MAAM,IAAI,CAAC,KAAK,CAAC,8BAA8B,CAAC,KAAK,IAAI,EAAE,CACzD,IAAI,CAAC,MAAM,CAAC,GAAG,EAAE,OAAO,CAAC,MAAM,IAAI,CAAC,KAAK,CAAS,GAAG,CAAC,CAAC,CAAC,CACzD,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,MAAM,CACV,eAAoD;QAEpD,OAAO,MAAM,IAAI,CAAC,KAAK,CAAC,wBAAwB,CAAC,KAAK,IAAI,EAAE;YAC1D,MAAM,QAAQ,GAAG,eAAe,CAAC,MAAM,IAAI,CAAC,UAAU,EAAE,CAAC,CAAC;YAE1D,MAAM,cAAc,EAAE,CAAC;gBACrB,MAAM,EAAE,kBAAkB;gBAC1B,MAAM,EAAE;oBACN,SAAS,EAAE,QAAQ;oBACnB,QAAQ,EAAE,SAAS,CAAC,QAAQ,CAAyB;oBACrD,SAAS,EAAE,IAAI,CAAC,OAAO,CAAC,SAAS;iBAClC;aACF,CAAC,CAAC;YAEH,OAAO,QAAQ,CAAC;QAClB,CAAC,CAAC,CAAC;IACL,CAAC;IAED,KAAK,CAAC,SAAS,CAAC,GAAW;QACzB,MAAM,IAAI,CAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,UAAU,CAAC,IAAc;QAC7B,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE;YAC1B,IAAI,CAAC,OAAO,CAAC,CAAC,GAAG,EAAE,EAAE;gBACnB,KAAK,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;YACpB,CAAC,CAAC,CAAC;YACH,OAAO,KAAK,CAAC;QACf,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type { Json, SnapsProvider } from '@metamask/snaps-sdk';\nimport type { MutexInterface } from 'async-mutex';\nimport { Mutex } from 'async-mutex';\nimport { cloneDeep, unset } from 'lodash';\n\nimport { safeMerge } from '../safeMerge/safeMerge';\nimport { deserialize, serialize } from '../serialization/serialization';\nimport type { Serializable } from '../serialization/types';\nimport type { IStateManager } from './IStateManager';\n\nexport type StateConfig<TValue extends Record<string, Serializable>> = {\n encrypted: boolean;\n defaultState: TValue;\n};\n\n/**\n * Resolves the Snap RPC client from the global `snap` object provided by the Snap runtime.\n *\n * @returns The Snap `request` function.\n */\nconst getSnapRequest = (): SnapsProvider['request'] =>\n (globalThis as typeof globalThis & { snap: SnapsProvider }).snap.request;\n\n/**\n * Because we use both snap_manageState and snap_setState, we must protect against them\n * being used at the same time. We must also protect against multiple parallel requests\n * to snap_manageState.\n *\n * Path writes (`setKey` / `setKeyWith`) are serialized with a dedicated write mutex so\n * concurrent read-modify-write updates cannot interleave. Path reads may still run in\n * parallel with each other. A blob (`snap_manageState`) operation waits for in-flight path\n * operations to finish and blocks new ones from starting until it completes.\n */\nclass StateLock {\n // Gate every operation must pass through to start. Path operations hold it only while\n // registering; a blob operation holds it for its whole duration, so no path operation\n // can start after a blob operation begins waiting for in-flight ones to finish.\n readonly #operationAdmissionMutex = new Mutex();\n\n // Held while at least one path operation is in flight.\n readonly #regularStateUpdateMutex = new Mutex();\n\n readonly #regularStateWriteMutex = new Mutex();\n\n #pendingRegularStateUpdates = 0;\n\n #releaseRegularStateUpdateMutex: MutexInterface.Releaser | null = null;\n\n async #acquireRegularStateUpdateMutex(): Promise<void> {\n if (!this.#regularStateUpdateMutex.isLocked()) {\n this.#releaseRegularStateUpdateMutex =\n await this.#regularStateUpdateMutex.acquire();\n }\n }\n\n async wrapRegularStateOperation<ReturnType>(\n callback: MutexInterface.Worker<ReturnType>,\n ): Promise<ReturnType> {\n await this.#operationAdmissionMutex.runExclusive(async () => {\n await this.#acquireRegularStateUpdateMutex();\n this.#pendingRegularStateUpdates += 1;\n });\n\n try {\n return await callback();\n } finally {\n this.#pendingRegularStateUpdates -= 1;\n\n if (\n this.#pendingRegularStateUpdates === 0 &&\n this.#releaseRegularStateUpdateMutex\n ) {\n this.#releaseRegularStateUpdateMutex();\n this.#releaseRegularStateUpdateMutex = null;\n }\n }\n }\n\n async wrapRegularStateWriteOperation<ReturnType>(\n callback: MutexInterface.Worker<ReturnType>,\n ): Promise<ReturnType> {\n return await this.#regularStateWriteMutex.runExclusive(async () =>\n this.wrapRegularStateOperation(callback),\n );\n }\n\n async wrapManageStateOperation<ReturnType>(\n callback: MutexInterface.Worker<ReturnType>,\n ): Promise<ReturnType> {\n return await this.#operationAdmissionMutex.runExclusive(async () => {\n await this.#regularStateUpdateMutex.waitForUnlock();\n\n return await callback();\n });\n }\n}\n\n/**\n * Layer on top of `snap_manageState` / `snap_getState` / `snap_setState`:\n *\n * - Serializes values before storing them and deserializes after reading.\n * - Merges `defaultState` on full-blob reads via `safeMerge`.\n * - Serializes path writes and full-blob updates (lock strategy B).\n */\nexport class State<\n TStateValue extends Record<string, Serializable>,\n> implements IStateManager<TStateValue> {\n readonly #lock = new StateLock();\n\n readonly #config: StateConfig<TStateValue>;\n\n constructor(config: StateConfig<TStateValue>) {\n this.#config = config;\n }\n\n /**\n * Reads and deserializes the value at `key`, or the whole state blob when `key` is omitted.\n *\n * @param key - The JSON-path key to read. Omit to read the whole blob.\n * @returns The deserialized value, or `undefined` when the key is absent.\n */\n async #read<TValue extends Serializable>(\n key?: string,\n ): Promise<TValue | undefined> {\n const value = await getSnapRequest()({\n method: 'snap_getState',\n params: {\n ...(key === undefined ? {} : { key }),\n encrypted: this.#config.encrypted,\n },\n });\n\n return value === null || value === undefined\n ? undefined\n : (deserialize(value) as TValue);\n }\n\n /**\n * Serializes `value` and writes it to `key`.\n *\n * @param key - The JSON-path key to write.\n * @param value - The value to store.\n */\n async #write(key: string, value: Serializable): Promise<void> {\n await getSnapRequest()({\n method: 'snap_setState',\n params: {\n key,\n value: serialize(value),\n encrypted: this.#config.encrypted,\n },\n });\n }\n\n async #unsafeGet(): Promise<TStateValue> {\n const state = (await this.#read<TStateValue>()) ?? ({} as TStateValue);\n\n // Clone the defaults so updaters that mutate the returned state (e.g. `deleteKey`\n // via lodash `unset`) never leak into the shared `defaultState` object.\n return safeMerge(cloneDeep(this.#config.defaultState), state);\n }\n\n async get(): Promise<TStateValue> {\n return this.#lock.wrapRegularStateOperation(async () => this.#unsafeGet());\n }\n\n async getKey<TResponse extends Serializable>(\n key: string,\n ): Promise<TResponse | undefined> {\n return this.#lock.wrapRegularStateOperation(async () =>\n this.#read<TResponse>(key),\n );\n }\n\n async setKey(key: string, value: Serializable): Promise<void> {\n await this.#lock.wrapRegularStateWriteOperation(async () =>\n this.#write(key, value),\n );\n }\n\n async setKeyWith<TValue extends Serializable>(\n key: string,\n updater: (currentValue: TValue | undefined) => TValue,\n ): Promise<void> {\n await this.#lock.wrapRegularStateWriteOperation(async () =>\n this.#write(key, updater(await this.#read<TValue>(key))),\n );\n }\n\n async update(\n updaterFunction: (state: TStateValue) => TStateValue,\n ): Promise<TStateValue> {\n return await this.#lock.wrapManageStateOperation(async () => {\n const newState = updaterFunction(await this.#unsafeGet());\n\n await getSnapRequest()({\n method: 'snap_manageState',\n params: {\n operation: 'update',\n newState: serialize(newState) as Record<string, Json>,\n encrypted: this.#config.encrypted,\n },\n });\n\n return newState;\n });\n }\n\n async deleteKey(key: string): Promise<void> {\n await this.deleteKeys([key]);\n }\n\n async deleteKeys(keys: string[]): Promise<void> {\n await this.update((state) => {\n keys.forEach((key) => {\n unset(state, key);\n });\n return state;\n });\n }\n}\n"]}
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.resolveFlowTransactionType = void 0;
4
+ exports.resolveUnifiedSwapTransactionType = resolveUnifiedSwapTransactionType;
5
+ const keyring_api_1 = require("@metamask/keyring-api");
6
+ const utils_1 = require("@metamask/utils");
7
+ /**
8
+ * Resolves the transaction type for a unified swap or bridge flow.
9
+ *
10
+ * @param options - The source and destination asset ids.
11
+ * @param options.sourceAssetId - The source asset id.
12
+ * @param options.destAssetId - The destination asset id.
13
+ * @returns `swap` for assets on the same chain, `bridgeSend` for assets on
14
+ * different chains, or `undefined` when either asset id is missing or invalid.
15
+ */
16
+ function resolveUnifiedSwapTransactionType({ sourceAssetId, destAssetId, }) {
17
+ if (sourceAssetId === undefined || destAssetId === undefined) {
18
+ return undefined;
19
+ }
20
+ try {
21
+ const { chainId: sourceChainId } = (0, utils_1.parseCaipAssetType)(sourceAssetId);
22
+ const { chainId: destChainId } = (0, utils_1.parseCaipAssetType)(destAssetId);
23
+ return sourceChainId === destChainId
24
+ ? keyring_api_1.TransactionType.Swap
25
+ : keyring_api_1.TransactionType.BridgeSend;
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ }
31
+ exports.resolveFlowTransactionType = resolveUnifiedSwapTransactionType;
32
+ //# sourceMappingURL=transactionType.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transactionType.cjs","sourceRoot":"","sources":["../../../src/utils/transactionType/transactionType.ts"],"names":[],"mappings":";;;AAaA,8EAqBC;AAlCD,uDAAwD;AAExD,2CAAqD;AAErD;;;;;;;;GAQG;AACH,SAAgB,iCAAiC,CAAC,EAChD,aAAa,EACb,WAAW,GAIZ;IACC,IAAI,aAAa,KAAK,SAAS,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;QAC7D,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,CAAC;QACH,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,GAAG,IAAA,0BAAkB,EAAC,aAAa,CAAC,CAAC;QACrE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,IAAA,0BAAkB,EAAC,WAAW,CAAC,CAAC;QAEjE,OAAO,aAAa,KAAK,WAAW;YAClC,CAAC,CAAC,6BAAe,CAAC,IAAI;YACtB,CAAC,CAAC,6BAAe,CAAC,UAAU,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAEY,QAAA,0BAA0B,GAAG,iCAAiC,CAAC","sourcesContent":["import { TransactionType } from '@metamask/keyring-api';\nimport type { CaipAssetType } from '@metamask/utils';\nimport { parseCaipAssetType } from '@metamask/utils';\n\n/**\n * Resolves the transaction type for a unified swap or bridge flow.\n *\n * @param options - The source and destination asset ids.\n * @param options.sourceAssetId - The source asset id.\n * @param options.destAssetId - The destination asset id.\n * @returns `swap` for assets on the same chain, `bridgeSend` for assets on\n * different chains, or `undefined` when either asset id is missing or invalid.\n */\nexport function resolveUnifiedSwapTransactionType({\n sourceAssetId,\n destAssetId,\n}: {\n sourceAssetId?: CaipAssetType;\n destAssetId?: CaipAssetType;\n}): TransactionType | undefined {\n if (sourceAssetId === undefined || destAssetId === undefined) {\n return undefined;\n }\n\n try {\n const { chainId: sourceChainId } = parseCaipAssetType(sourceAssetId);\n const { chainId: destChainId } = parseCaipAssetType(destAssetId);\n\n return sourceChainId === destChainId\n ? TransactionType.Swap\n : TransactionType.BridgeSend;\n } catch {\n return undefined;\n }\n}\n\nexport const resolveFlowTransactionType = resolveUnifiedSwapTransactionType;\n"]}
@@ -0,0 +1,17 @@
1
+ import { TransactionType } from "@metamask/keyring-api";
2
+ import type { CaipAssetType } from "@metamask/utils";
3
+ /**
4
+ * Resolves the transaction type for a unified swap or bridge flow.
5
+ *
6
+ * @param options - The source and destination asset ids.
7
+ * @param options.sourceAssetId - The source asset id.
8
+ * @param options.destAssetId - The destination asset id.
9
+ * @returns `swap` for assets on the same chain, `bridgeSend` for assets on
10
+ * different chains, or `undefined` when either asset id is missing or invalid.
11
+ */
12
+ export declare function resolveUnifiedSwapTransactionType({ sourceAssetId, destAssetId, }: {
13
+ sourceAssetId?: CaipAssetType;
14
+ destAssetId?: CaipAssetType;
15
+ }): TransactionType | undefined;
16
+ export declare const resolveFlowTransactionType: typeof resolveUnifiedSwapTransactionType;
17
+ //# sourceMappingURL=transactionType.d.cts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transactionType.d.cts","sourceRoot":"","sources":["../../../src/utils/transactionType/transactionType.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,8BAA8B;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB;AAGrD;;;;;;;;GAQG;AACH,wBAAgB,iCAAiC,CAAC,EAChD,aAAa,EACb,WAAW,GACZ,EAAE;IACD,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,WAAW,CAAC,EAAE,aAAa,CAAC;CAC7B,GAAG,eAAe,GAAG,SAAS,CAe9B;AAED,eAAO,MAAM,0BAA0B,0CAAoC,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { TransactionType } from "@metamask/keyring-api";
2
+ import type { CaipAssetType } from "@metamask/utils";
3
+ /**
4
+ * Resolves the transaction type for a unified swap or bridge flow.
5
+ *
6
+ * @param options - The source and destination asset ids.
7
+ * @param options.sourceAssetId - The source asset id.
8
+ * @param options.destAssetId - The destination asset id.
9
+ * @returns `swap` for assets on the same chain, `bridgeSend` for assets on
10
+ * different chains, or `undefined` when either asset id is missing or invalid.
11
+ */
12
+ export declare function resolveUnifiedSwapTransactionType({ sourceAssetId, destAssetId, }: {
13
+ sourceAssetId?: CaipAssetType;
14
+ destAssetId?: CaipAssetType;
15
+ }): TransactionType | undefined;
16
+ export declare const resolveFlowTransactionType: typeof resolveUnifiedSwapTransactionType;
17
+ //# sourceMappingURL=transactionType.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transactionType.d.mts","sourceRoot":"","sources":["../../../src/utils/transactionType/transactionType.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,8BAA8B;AACxD,OAAO,KAAK,EAAE,aAAa,EAAE,wBAAwB;AAGrD;;;;;;;;GAQG;AACH,wBAAgB,iCAAiC,CAAC,EAChD,aAAa,EACb,WAAW,GACZ,EAAE;IACD,aAAa,CAAC,EAAE,aAAa,CAAC;IAC9B,WAAW,CAAC,EAAE,aAAa,CAAC;CAC7B,GAAG,eAAe,GAAG,SAAS,CAe9B;AAED,eAAO,MAAM,0BAA0B,0CAAoC,CAAC"}
@@ -0,0 +1,28 @@
1
+ import { TransactionType } from "@metamask/keyring-api";
2
+ import { parseCaipAssetType } from "@metamask/utils";
3
+ /**
4
+ * Resolves the transaction type for a unified swap or bridge flow.
5
+ *
6
+ * @param options - The source and destination asset ids.
7
+ * @param options.sourceAssetId - The source asset id.
8
+ * @param options.destAssetId - The destination asset id.
9
+ * @returns `swap` for assets on the same chain, `bridgeSend` for assets on
10
+ * different chains, or `undefined` when either asset id is missing or invalid.
11
+ */
12
+ export function resolveUnifiedSwapTransactionType({ sourceAssetId, destAssetId, }) {
13
+ if (sourceAssetId === undefined || destAssetId === undefined) {
14
+ return undefined;
15
+ }
16
+ try {
17
+ const { chainId: sourceChainId } = parseCaipAssetType(sourceAssetId);
18
+ const { chainId: destChainId } = parseCaipAssetType(destAssetId);
19
+ return sourceChainId === destChainId
20
+ ? TransactionType.Swap
21
+ : TransactionType.BridgeSend;
22
+ }
23
+ catch {
24
+ return undefined;
25
+ }
26
+ }
27
+ export const resolveFlowTransactionType = resolveUnifiedSwapTransactionType;
28
+ //# sourceMappingURL=transactionType.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transactionType.mjs","sourceRoot":"","sources":["../../../src/utils/transactionType/transactionType.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,8BAA8B;AAExD,OAAO,EAAE,kBAAkB,EAAE,wBAAwB;AAErD;;;;;;;;GAQG;AACH,MAAM,UAAU,iCAAiC,CAAC,EAChD,aAAa,EACb,WAAW,GAIZ;IACC,IAAI,aAAa,KAAK,SAAS,IAAI,WAAW,KAAK,SAAS,EAAE,CAAC;QAC7D,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,IAAI,CAAC;QACH,MAAM,EAAE,OAAO,EAAE,aAAa,EAAE,GAAG,kBAAkB,CAAC,aAAa,CAAC,CAAC;QACrE,MAAM,EAAE,OAAO,EAAE,WAAW,EAAE,GAAG,kBAAkB,CAAC,WAAW,CAAC,CAAC;QAEjE,OAAO,aAAa,KAAK,WAAW;YAClC,CAAC,CAAC,eAAe,CAAC,IAAI;YACtB,CAAC,CAAC,eAAe,CAAC,UAAU,CAAC;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAC;IACnB,CAAC;AACH,CAAC;AAED,MAAM,CAAC,MAAM,0BAA0B,GAAG,iCAAiC,CAAC","sourcesContent":["import { TransactionType } from '@metamask/keyring-api';\nimport type { CaipAssetType } from '@metamask/utils';\nimport { parseCaipAssetType } from '@metamask/utils';\n\n/**\n * Resolves the transaction type for a unified swap or bridge flow.\n *\n * @param options - The source and destination asset ids.\n * @param options.sourceAssetId - The source asset id.\n * @param options.destAssetId - The destination asset id.\n * @returns `swap` for assets on the same chain, `bridgeSend` for assets on\n * different chains, or `undefined` when either asset id is missing or invalid.\n */\nexport function resolveUnifiedSwapTransactionType({\n sourceAssetId,\n destAssetId,\n}: {\n sourceAssetId?: CaipAssetType;\n destAssetId?: CaipAssetType;\n}): TransactionType | undefined {\n if (sourceAssetId === undefined || destAssetId === undefined) {\n return undefined;\n }\n\n try {\n const { chainId: sourceChainId } = parseCaipAssetType(sourceAssetId);\n const { chainId: destChainId } = parseCaipAssetType(destAssetId);\n\n return sourceChainId === destChainId\n ? TransactionType.Swap\n : TransactionType.BridgeSend;\n } catch {\n return undefined;\n }\n}\n\nexport const resolveFlowTransactionType = resolveUnifiedSwapTransactionType;\n"]}