@upshiftfinance/sdk 0.0.0-stage → 0.2.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 (344) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +408 -2
  3. package/lib/abis/AddressResolver.d.ts +28 -0
  4. package/lib/abis/AddressResolver.js +23 -0
  5. package/lib/abis/ChainlinkV3.d.ts +87 -0
  6. package/lib/abis/ChainlinkV3.js +117 -0
  7. package/lib/abis/ERC20.d.ts +168 -0
  8. package/lib/abis/ERC20.js +226 -0
  9. package/lib/abis/ERC20_Bytes32.d.ts +139 -0
  10. package/lib/abis/ERC20_Bytes32.js +196 -0
  11. package/lib/abis/ERC4626.d.ts +364 -0
  12. package/lib/abis/ERC4626.js +507 -0
  13. package/lib/abis/ERC721.d.ts +231 -0
  14. package/lib/abis/ERC721.js +321 -0
  15. package/lib/abis/FeeOracle.d.ts +120 -0
  16. package/lib/abis/FeeOracle.js +162 -0
  17. package/lib/abis/LendingPool.d.ts +1393 -0
  18. package/lib/abis/LendingPool.js +1807 -0
  19. package/lib/abis/LendingPoolV2.d.ts +1413 -0
  20. package/lib/abis/LendingPoolV2.js +1833 -0
  21. package/lib/abis/LendingPoolV3.d.ts +1677 -0
  22. package/lib/abis/LendingPoolV3.js +1160 -0
  23. package/lib/abis/Loan.d.ts +837 -0
  24. package/lib/abis/Loan.js +1080 -0
  25. package/lib/abis/MultiAssetNativeDepositWrapper.d.ts +137 -0
  26. package/lib/abis/MultiAssetNativeDepositWrapper.js +125 -0
  27. package/lib/abis/Multicall3.d.ts +30 -0
  28. package/lib/abis/Multicall3.js +97 -0
  29. package/lib/abis/OFT.d.ts +116 -0
  30. package/lib/abis/OFT.js +85 -0
  31. package/lib/abis/PoolAdapter.d.ts +36 -0
  32. package/lib/abis/PoolAdapter.js +51 -0
  33. package/lib/abis/RewardDistributor.d.ts +267 -0
  34. package/lib/abis/RewardDistributor.js +352 -0
  35. package/lib/abis/RwaRedeemSubaccount.d.ts +747 -0
  36. package/lib/abis/RwaRedeemSubaccount.js +548 -0
  37. package/lib/abis/SmartAccount.d.ts +17 -0
  38. package/lib/abis/SmartAccount.js +19 -0
  39. package/lib/abis/SwapRouter.d.ts +953 -0
  40. package/lib/abis/SwapRouter.js +1228 -0
  41. package/lib/abis/TextResolver.d.ts +16 -0
  42. package/lib/abis/TextResolver.js +16 -0
  43. package/lib/abis/TokenizedVaultV2.d.ts +1364 -0
  44. package/lib/abis/TokenizedVaultV2.js +1041 -0
  45. package/lib/abis/TokenizedVaultV2DepositWithPermit.d.ts +1456 -0
  46. package/lib/abis/TokenizedVaultV2DepositWithPermit.js +1878 -0
  47. package/lib/abis/TokenizedVaultV2Receipt.d.ts +1568 -0
  48. package/lib/abis/TokenizedVaultV2Receipt.js +1061 -0
  49. package/lib/abis/TokenizedVaultV2SenderAllocationWhitelist.d.ts +454 -0
  50. package/lib/abis/TokenizedVaultV2SenderAllocationWhitelist.js +327 -0
  51. package/lib/abis/TokenizedVaultV2WhitelistedAllocation.d.ts +1466 -0
  52. package/lib/abis/TokenizedVaultV2WhitelistedAllocation.js +1092 -0
  53. package/lib/abis/TokenizedVaultV2WhitelistedAssets.d.ts +274 -0
  54. package/lib/abis/TokenizedVaultV2WhitelistedAssets.js +167 -0
  55. package/lib/abis/UniversalResolverResolve.d.ts +69 -0
  56. package/lib/abis/UniversalResolverResolve.js +35 -0
  57. package/lib/abis/UniversalSignatureValidator.d.ts +17 -0
  58. package/lib/abis/UniversalSignatureValidator.js +30 -0
  59. package/lib/abis/WrapperAdapter.d.ts +71 -0
  60. package/lib/abis/WrapperAdapter.js +77 -0
  61. package/lib/abis/index.d.ts +34 -0
  62. package/lib/abis/index.js +51 -0
  63. package/lib/adapters/evm/getters.d.ts +19 -0
  64. package/lib/adapters/evm/getters.js +249 -0
  65. package/lib/adapters/evm/index.d.ts +539 -0
  66. package/lib/adapters/evm/index.js +656 -0
  67. package/lib/adapters/evm/utils.d.ts +8 -0
  68. package/lib/adapters/evm/utils.js +51 -0
  69. package/lib/adapters/solana/confirm.d.ts +88 -0
  70. package/lib/adapters/solana/confirm.js +291 -0
  71. package/lib/adapters/solana/constants.d.ts +42 -0
  72. package/lib/adapters/solana/constants.js +59 -0
  73. package/lib/adapters/solana/getters.d.ts +42 -0
  74. package/lib/adapters/solana/getters.js +275 -0
  75. package/lib/adapters/solana/idl/vault-idl.d.ts +700 -0
  76. package/lib/adapters/solana/idl/vault-idl.js +2101 -0
  77. package/lib/adapters/solana/idl/withdrawal-queue-idl.d.ts +795 -0
  78. package/lib/adapters/solana/idl/withdrawal-queue-idl.js +1864 -0
  79. package/lib/adapters/solana/index.d.ts +372 -0
  80. package/lib/adapters/solana/index.js +459 -0
  81. package/lib/adapters/solana/pricing.d.ts +184 -0
  82. package/lib/adapters/solana/pricing.js +239 -0
  83. package/lib/adapters/solana/queue-hints.d.ts +29 -0
  84. package/lib/adapters/solana/queue-hints.js +59 -0
  85. package/lib/adapters/solana/queue.actions.d.ts +97 -0
  86. package/lib/adapters/solana/queue.actions.js +468 -0
  87. package/lib/adapters/solana/token-reads.d.ts +108 -0
  88. package/lib/adapters/solana/token-reads.js +145 -0
  89. package/lib/adapters/solana/types.d.ts +325 -0
  90. package/lib/adapters/solana/types.js +3 -0
  91. package/lib/adapters/solana/utils.d.ts +229 -0
  92. package/lib/adapters/solana/utils.js +773 -0
  93. package/lib/adapters/solana/vault.actions.d.ts +140 -0
  94. package/lib/adapters/solana/vault.actions.js +657 -0
  95. package/lib/adapters/solana/withdrawal-queue.d.ts +125 -0
  96. package/lib/adapters/solana/withdrawal-queue.js +301 -0
  97. package/lib/adapters/stellar/actions.d.ts +41 -0
  98. package/lib/adapters/stellar/actions.js +126 -0
  99. package/lib/adapters/stellar/constants.d.ts +43 -0
  100. package/lib/adapters/stellar/constants.js +53 -0
  101. package/lib/adapters/stellar/getters.d.ts +68 -0
  102. package/lib/adapters/stellar/getters.js +290 -0
  103. package/lib/adapters/stellar/index.d.ts +126 -0
  104. package/lib/adapters/stellar/index.js +187 -0
  105. package/lib/adapters/stellar/invocation.d.ts +55 -0
  106. package/lib/adapters/stellar/invocation.js +92 -0
  107. package/lib/adapters/stellar/soroban.d.ts +131 -0
  108. package/lib/adapters/stellar/soroban.js +617 -0
  109. package/lib/adapters/stellar/submit.d.ts +42 -0
  110. package/lib/adapters/stellar/submit.js +195 -0
  111. package/lib/adapters/stellar/types.d.ts +57 -0
  112. package/lib/adapters/stellar/types.js +6 -0
  113. package/lib/adapters/stellar/utils.d.ts +24 -0
  114. package/lib/adapters/stellar/utils.js +34 -0
  115. package/lib/adapters/sui/client.d.ts +83 -0
  116. package/lib/adapters/sui/client.js +216 -0
  117. package/lib/adapters/sui/constants.d.ts +33 -0
  118. package/lib/adapters/sui/constants.js +31 -0
  119. package/lib/adapters/sui/index.d.ts +57 -0
  120. package/lib/adapters/sui/index.js +100 -0
  121. package/lib/adapters/sui/targets.d.ts +171 -0
  122. package/lib/adapters/sui/targets.js +225 -0
  123. package/lib/adapters/sui/utils.d.ts +8 -0
  124. package/lib/adapters/sui/utils.js +17 -0
  125. package/lib/core/analytics/app-name.d.ts +27 -0
  126. package/lib/core/analytics/app-name.js +48 -0
  127. package/lib/core/analytics/chain-name.d.ts +9 -0
  128. package/lib/core/analytics/chain-name.js +34 -0
  129. package/lib/core/analytics/constants.d.ts +15 -0
  130. package/lib/core/analytics/constants.js +28 -0
  131. package/lib/core/analytics/env.d.ts +46 -0
  132. package/lib/core/analytics/env.js +147 -0
  133. package/lib/core/analytics/index.d.ts +39 -0
  134. package/lib/core/analytics/index.js +83 -0
  135. package/lib/core/analytics/instrumentation.d.ts +29 -0
  136. package/lib/core/analytics/instrumentation.js +292 -0
  137. package/lib/core/analytics/method-taxonomy.d.ts +19 -0
  138. package/lib/core/analytics/method-taxonomy.js +156 -0
  139. package/lib/core/analytics/metrics.d.ts +48 -0
  140. package/lib/core/analytics/metrics.js +142 -0
  141. package/lib/core/analytics/sanitize.d.ts +57 -0
  142. package/lib/core/analytics/sanitize.js +272 -0
  143. package/lib/core/analytics/sentry-runtime.d.ts +15 -0
  144. package/lib/core/analytics/sentry-runtime.js +131 -0
  145. package/lib/core/analytics/sentry.d.ts +100 -0
  146. package/lib/core/analytics/sentry.js +696 -0
  147. package/lib/core/analytics/types.d.ts +55 -0
  148. package/lib/core/analytics/types.js +3 -0
  149. package/lib/core/analytics/user-identity.d.ts +55 -0
  150. package/lib/core/analytics/user-identity.js +218 -0
  151. package/lib/core/analytics/version.d.ts +6 -0
  152. package/lib/core/analytics/version.js +10 -0
  153. package/lib/core/attribution.d.ts +159 -0
  154. package/lib/core/attribution.js +194 -0
  155. package/lib/core/auth/index.d.ts +1 -0
  156. package/lib/core/auth/index.js +18 -0
  157. package/lib/core/auth/verify.d.ts +2 -0
  158. package/lib/core/auth/verify.js +35 -0
  159. package/lib/core/base.class.d.ts +193 -0
  160. package/lib/core/base.class.js +163 -0
  161. package/lib/core/cache.d.ts +9 -0
  162. package/lib/core/cache.js +31 -0
  163. package/lib/core/constants/adapters.d.ts +103 -0
  164. package/lib/core/constants/adapters.js +180 -0
  165. package/lib/core/constants/core.d.ts +162 -0
  166. package/lib/core/constants/core.js +281 -0
  167. package/lib/core/constants/swap-router.d.ts +180 -0
  168. package/lib/core/constants/swap-router.js +203 -0
  169. package/lib/core/constants/vaults.d.ts +93 -0
  170. package/lib/core/constants/vaults.js +277 -0
  171. package/lib/core/constants/web3.d.ts +106 -0
  172. package/lib/core/constants/web3.js +251 -0
  173. package/lib/core/errors/index.d.ts +177 -0
  174. package/lib/core/errors/index.js +257 -0
  175. package/lib/core/fetcher.d.ts +237 -0
  176. package/lib/core/fetcher.js +1103 -0
  177. package/lib/core/helpers/adapters.d.ts +13 -0
  178. package/lib/core/helpers/adapters.js +39 -0
  179. package/lib/core/helpers/chain-address.d.ts +13 -0
  180. package/lib/core/helpers/chain-address.js +47 -0
  181. package/lib/core/helpers/chain-error.d.ts +207 -0
  182. package/lib/core/helpers/chain-error.js +697 -0
  183. package/lib/core/helpers/chain-support.d.ts +98 -0
  184. package/lib/core/helpers/chain-support.js +139 -0
  185. package/lib/core/helpers/concurrency.d.ts +51 -0
  186. package/lib/core/helpers/concurrency.js +79 -0
  187. package/lib/core/helpers/core.d.ts +92 -0
  188. package/lib/core/helpers/core.js +368 -0
  189. package/lib/core/helpers/explorer-link.d.ts +16 -0
  190. package/lib/core/helpers/explorer-link.js +26 -0
  191. package/lib/core/helpers/multicall.d.ts +68 -0
  192. package/lib/core/helpers/multicall.js +103 -0
  193. package/lib/core/helpers/revert-decode.d.ts +248 -0
  194. package/lib/core/helpers/revert-decode.js +515 -0
  195. package/lib/core/helpers/signer.d.ts +61 -0
  196. package/lib/core/helpers/signer.js +184 -0
  197. package/lib/core/helpers/swap-router.d.ts +269 -0
  198. package/lib/core/helpers/swap-router.js +542 -0
  199. package/lib/core/helpers/vault-version.d.ts +24 -0
  200. package/lib/core/helpers/vault-version.js +83 -0
  201. package/lib/core/helpers/vaults.d.ts +89 -0
  202. package/lib/core/helpers/vaults.js +241 -0
  203. package/lib/core/helpers/web3.d.ts +366 -0
  204. package/lib/core/helpers/web3.js +1034 -0
  205. package/lib/core/index.d.ts +23 -0
  206. package/lib/core/index.js +40 -0
  207. package/lib/core/logger/curator-alert.d.ts +217 -0
  208. package/lib/core/logger/curator-alert.js +276 -0
  209. package/lib/core/logger/index.d.ts +99 -0
  210. package/lib/core/logger/index.js +163 -0
  211. package/lib/core/logger/slack.d.ts +49 -0
  212. package/lib/core/logger/slack.js +111 -0
  213. package/lib/core/vault-metadata.d.ts +12 -0
  214. package/lib/core/vault-metadata.js +42 -0
  215. package/lib/core/version-check.d.ts +58 -0
  216. package/lib/core/version-check.js +182 -0
  217. package/lib/evm/index.d.ts +2 -0
  218. package/lib/evm/index.js +19 -0
  219. package/lib/evm/methods/crossChainVault.d.ts +132 -0
  220. package/lib/evm/methods/crossChainVault.js +857 -0
  221. package/lib/evm/methods/crossChainVaultRegistry.d.ts +92 -0
  222. package/lib/evm/methods/crossChainVaultRegistry.js +239 -0
  223. package/lib/evm/methods/index.d.ts +2 -0
  224. package/lib/evm/methods/index.js +19 -0
  225. package/lib/evm/types/crossChain.d.ts +363 -0
  226. package/lib/evm/types/crossChain.js +20 -0
  227. package/lib/evm/types/index.d.ts +1 -0
  228. package/lib/evm/types/index.js +18 -0
  229. package/lib/index.d.ts +30 -0
  230. package/lib/index.js +52 -0
  231. package/lib/main.d.ts +596 -0
  232. package/lib/main.js +681 -0
  233. package/lib/modules/api/fetcher.d.ts +108 -0
  234. package/lib/modules/api/fetcher.js +187 -0
  235. package/lib/modules/api/index.d.ts +1 -0
  236. package/lib/modules/api/index.js +6 -0
  237. package/lib/modules/api/main.d.ts +587 -0
  238. package/lib/modules/api/main.js +911 -0
  239. package/lib/modules/sub-accounts/fetcher.d.ts +53 -0
  240. package/lib/modules/sub-accounts/fetcher.js +96 -0
  241. package/lib/modules/sub-accounts/index.d.ts +2 -0
  242. package/lib/modules/sub-accounts/index.js +19 -0
  243. package/lib/modules/sub-accounts/main.d.ts +249 -0
  244. package/lib/modules/sub-accounts/main.js +211 -0
  245. package/lib/modules/sub-accounts/utils.d.ts +106 -0
  246. package/lib/modules/sub-accounts/utils.js +112 -0
  247. package/lib/modules/vaults/adapter.helpers.d.ts +84 -0
  248. package/lib/modules/vaults/adapter.helpers.js +202 -0
  249. package/lib/modules/vaults/fetcher.d.ts +147 -0
  250. package/lib/modules/vaults/fetcher.js +357 -0
  251. package/lib/modules/vaults/getters.d.ts +1060 -0
  252. package/lib/modules/vaults/getters.js +4079 -0
  253. package/lib/modules/vaults/index.d.ts +20 -0
  254. package/lib/modules/vaults/index.js +44 -0
  255. package/lib/modules/vaults/main.d.ts +607 -0
  256. package/lib/modules/vaults/main.js +1687 -0
  257. package/lib/modules/vaults/prefetch.d.ts +65 -0
  258. package/lib/modules/vaults/prefetch.js +120 -0
  259. package/lib/modules/vaults/read.actions.d.ts +406 -0
  260. package/lib/modules/vaults/read.actions.js +891 -0
  261. package/lib/modules/vaults/types.d.ts +149 -0
  262. package/lib/modules/vaults/types.js +3 -0
  263. package/lib/modules/vaults/utils/call-data-decoder.d.ts +61 -0
  264. package/lib/modules/vaults/utils/call-data-decoder.js +194 -0
  265. package/lib/modules/vaults/utils/date-utils.d.ts +50 -0
  266. package/lib/modules/vaults/utils/date-utils.js +84 -0
  267. package/lib/modules/vaults/utils.d.ts +153 -0
  268. package/lib/modules/vaults/utils.js +818 -0
  269. package/lib/modules/vaults/write.actions.d.ts +812 -0
  270. package/lib/modules/vaults/write.actions.js +2377 -0
  271. package/lib/polyfills.d.ts +1 -0
  272. package/lib/polyfills.js +12 -0
  273. package/lib/sdk.d.ts +30173 -0
  274. package/lib/services/coingecko/fetcher.d.ts +15 -0
  275. package/lib/services/coingecko/fetcher.js +67 -0
  276. package/lib/services/coingecko/index.d.ts +2 -0
  277. package/lib/services/coingecko/index.js +19 -0
  278. package/lib/services/coingecko/utils.d.ts +1 -0
  279. package/lib/services/coingecko/utils.js +24 -0
  280. package/lib/services/debank/fetcher.d.ts +126 -0
  281. package/lib/services/debank/fetcher.js +47 -0
  282. package/lib/services/debank/index.d.ts +2 -0
  283. package/lib/services/debank/index.js +19 -0
  284. package/lib/services/debank/utils.d.ts +50 -0
  285. package/lib/services/debank/utils.js +325 -0
  286. package/lib/services/layerzero/deposits.d.ts +55 -0
  287. package/lib/services/layerzero/deposits.js +174 -0
  288. package/lib/services/layerzero/redeems.d.ts +20 -0
  289. package/lib/services/layerzero/redeems.js +92 -0
  290. package/lib/services/layerzero/utils.d.ts +9 -0
  291. package/lib/services/layerzero/utils.js +22 -0
  292. package/lib/services/octavfi/fetcher.d.ts +33 -0
  293. package/lib/services/octavfi/fetcher.js +39 -0
  294. package/lib/services/octavfi/index.d.ts +3 -0
  295. package/lib/services/octavfi/index.js +20 -0
  296. package/lib/services/octavfi/types.d.ts +34 -0
  297. package/lib/services/octavfi/types.js +3 -0
  298. package/lib/services/octavfi/utils.d.ts +16 -0
  299. package/lib/services/octavfi/utils.js +244 -0
  300. package/lib/services/subgraph/fetcher.d.ts +2 -0
  301. package/lib/services/subgraph/fetcher.js +66 -0
  302. package/lib/services/subgraph/index.d.ts +2 -0
  303. package/lib/services/subgraph/index.js +19 -0
  304. package/lib/services/subgraph/schema.d.ts +48 -0
  305. package/lib/services/subgraph/schema.js +87 -0
  306. package/lib/services/subgraph/vaults.d.ts +83 -0
  307. package/lib/services/subgraph/vaults.js +1282 -0
  308. package/lib/services/swap-quotes/index.d.ts +105 -0
  309. package/lib/services/swap-quotes/index.js +77 -0
  310. package/lib/services/swap-quotes/paraswap.d.ts +51 -0
  311. package/lib/services/swap-quotes/paraswap.js +138 -0
  312. package/lib/services/untangled/fetcher.d.ts +40 -0
  313. package/lib/services/untangled/fetcher.js +110 -0
  314. package/lib/services/untangled/index.d.ts +3 -0
  315. package/lib/services/untangled/index.js +20 -0
  316. package/lib/services/untangled/types.d.ts +83 -0
  317. package/lib/services/untangled/types.js +10 -0
  318. package/lib/services/untangled/utils.d.ts +91 -0
  319. package/lib/services/untangled/utils.js +339 -0
  320. package/lib/types/api.d.ts +498 -0
  321. package/lib/types/api.js +3 -0
  322. package/lib/types/index.d.ts +12 -0
  323. package/lib/types/index.js +28 -0
  324. package/lib/types/points.d.ts +28 -0
  325. package/lib/types/points.js +3 -0
  326. package/lib/types/pools.d.ts +144 -0
  327. package/lib/types/pools.js +3 -0
  328. package/lib/types/staking.d.ts +28 -0
  329. package/lib/types/staking.js +3 -0
  330. package/lib/types/sub-accounts.d.ts +150 -0
  331. package/lib/types/sub-accounts.js +3 -0
  332. package/lib/types/subgraph.d.ts +84 -0
  333. package/lib/types/subgraph.js +3 -0
  334. package/lib/types/typed-contract.d.ts +102 -0
  335. package/lib/types/typed-contract.js +3 -0
  336. package/lib/types/user.d.ts +1 -0
  337. package/lib/types/user.js +3 -0
  338. package/lib/types/vaults.d.ts +886 -0
  339. package/lib/types/vaults.js +30 -0
  340. package/lib/types/web3.d.ts +100 -0
  341. package/lib/types/web3.js +14 -0
  342. package/lib/types/webserver.d.ts +730 -0
  343. package/lib/types/webserver.js +3 -0
  344. package/package.json +79 -3
@@ -0,0 +1,1687 @@
1
+ "use strict";
2
+ /**
3
+ * The Upshift Vaults Module.
4
+ *
5
+ * @module UpshiftVaults
6
+ */
7
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
8
+ if (k2 === undefined) k2 = k;
9
+ var desc = Object.getOwnPropertyDescriptor(m, k);
10
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
11
+ desc = { enumerable: true, get: function() { return m[k]; } };
12
+ }
13
+ Object.defineProperty(o, k2, desc);
14
+ }) : (function(o, m, k, k2) {
15
+ if (k2 === undefined) k2 = k;
16
+ o[k2] = m[k];
17
+ }));
18
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
19
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
20
+ }) : function(o, v) {
21
+ o["default"] = v;
22
+ });
23
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
24
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
25
+ };
26
+ var __importStar = (this && this.__importStar) || (function () {
27
+ var ownKeys = function(o) {
28
+ ownKeys = Object.getOwnPropertyNames || function (o) {
29
+ var ar = [];
30
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
31
+ return ar;
32
+ };
33
+ return ownKeys(o);
34
+ };
35
+ return function (mod) {
36
+ if (mod && mod.__esModule) return mod;
37
+ var result = {};
38
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
39
+ __setModuleDefault(result, mod);
40
+ return result;
41
+ };
42
+ })();
43
+ Object.defineProperty(exports, "__esModule", { value: true });
44
+ exports.UpshiftVaults = void 0;
45
+ /**
46
+ * Export getters
47
+ */
48
+ __exportStar(require("./getters"), exports);
49
+ /**
50
+ * UpshiftVaults class
51
+ */
52
+ const fetcher_1 = require("./fetcher");
53
+ const ethers_1 = require("ethers");
54
+ const getters_1 = require("./getters");
55
+ const vaults_1 = require("../../services/subgraph/vaults");
56
+ const deposits_1 = require("../../services/layerzero/deposits");
57
+ const redeems_1 = require("../../services/layerzero/redeems");
58
+ const core_1 = require("../../core");
59
+ const utils_1 = require("../../adapters/solana/utils");
60
+ const utils_2 = require("../../adapters/stellar/utils");
61
+ const chain_address_1 = require("../../core/helpers/chain-address");
62
+ const errors_1 = require("../../core/errors");
63
+ const vaults_2 = require("../../core/constants/vaults");
64
+ const write_actions_1 = require("./write.actions");
65
+ const read_actions_1 = require("./read.actions");
66
+ const prefetch_1 = require("./prefetch");
67
+ /**
68
+ * Vault operations class handling multi-chain vault queries and user positions.
69
+ * Supports both EVM and Solana vaults with unified interface.
70
+ */
71
+ class UpshiftVaults extends core_1.UpshiftBase {
72
+ solanaService;
73
+ headers = null;
74
+ /**
75
+ * Consumer-supplied Soroban RPC override for Stellar vault reads, with the
76
+ * network it was configured for so it's only applied to matching-network
77
+ * vaults (see `IVaultBaseOptions.stellarRpc`).
78
+ */
79
+ _stellarRpc;
80
+ constructor(baseConfig, solana) {
81
+ super(baseConfig);
82
+ this.solanaService = solana;
83
+ // Network defaults to mainnet, matching the StellarAdapter constructor.
84
+ this._stellarRpc = baseConfig.stellar?.rpcUrl
85
+ ? {
86
+ rpcUrl: baseConfig.stellar.rpcUrl,
87
+ network: baseConfig.stellar.network ?? 'mainnet',
88
+ }
89
+ : undefined;
90
+ this.headers = {
91
+ 'x-environment': this.monitoring?.['x-environment'],
92
+ 'x-user-id': this.monitoring?.['x-user-id'],
93
+ };
94
+ }
95
+ /**
96
+ * @description deposit underlying token into the specified pool with adapter support. This is for when we cannot pass in a signer in sdk and need to do so as an arg
97
+ * @param signer signer / wallet object
98
+ * @param options object including pool contract address, user wallet address, string amount, and optional depositAsset
99
+ * @returns deposit tx hash
100
+ */
101
+ async vaultDeposit(signer, options) {
102
+ return (0, write_actions_1.vaultDeposit)(signer, options);
103
+ }
104
+ /**
105
+ * @description deposit native token (ETH/AVAX/etc) into a vault using MultiAssetNativeDepositWrapper
106
+ * @param signer signer / wallet object
107
+ * @param options object including wrapper contract address, receiver address (optional), and amount
108
+ * @returns deposit tx hash
109
+ */
110
+ async depositNative(signer, options) {
111
+ return (0, write_actions_1.depositNative)(signer, options);
112
+ }
113
+ /**
114
+ * Fetch all vaults across configured networks with optional enrichment.
115
+ * Automatically filters by available providers and optionally by chain IDs.
116
+ * Includes closed vaults that are still visible (`status: 'closed'`,
117
+ * `is_visible: true`) so consumers can render positions held in closed
118
+ * vaults; closed vaults with `is_visible: false` are excluded.
119
+ *
120
+ * RPC volume (worst case, wallet enrichment path): the per-vault
121
+ * `balanceOf`/`lagDuration` reads are aggregated into chunked Multicall3
122
+ * `aggregate3` batches per chain (10 calls per chunk) on chains where the
123
+ * canonical Multicall3 deployment is verified; other chains (e.g. Citrea
124
+ * 4114) keep one `eth_call` per read. Measured on a
125
+ * cold cache for a wallet with 62
126
+ * vaults across Ethereum + Avalanche: 83 RPC HTTP requests before batching,
127
+ * 54 after (~35% fewer; 124 per-vault `eth_call`s collapse into ~13
128
+ * `aggregate3` calls — the remaining requests are the per-vault cached
129
+ * decimals/receipt-token reads on a cold cache).
130
+ * @param options Filtering and enrichment configuration
131
+ * @returns Array of vault objects with optional loans/allocations/positions
132
+ */
133
+ async getVaults(options) {
134
+ // if (!(this.authorized && this.upshiftKey)) // @todo: commented out for integrators
135
+ const allVaults = await (0, core_1.fetchTokenizedVaults)(undefined, this.headers, options?.loadSubaccounts, options?.loadSnapshots);
136
+ const vaultsPerAvailableProviders = allVaults.filter((v) =>
137
+ // Stellar vaults are backend-only (no RPC provider required)
138
+ v?.chain_type === 'stellar' ||
139
+ // Solana vaults use this.solanaService (not this.providers). Without
140
+ // an explicit pass-through here they get silently dropped on any
141
+ // instance whose ACTIVE_RPC_URLS() doesn't register chainId -1.
142
+ // Gate on solanaService presence so we don't let a vault through that
143
+ // we have no adapter to fetch — that would crash the inner getter and
144
+ // turn into a PENDING entry that the final filter drops anyway.
145
+ (v?.chain_type === 'solana' && !!this.solanaService) ||
146
+ (this.providers?.[v?.chain] ? true : false));
147
+ const vaultsPerChainId = options?.chainIds
148
+ ? vaultsPerAvailableProviders.filter((v) => options.chainIds.includes(v.chain))
149
+ : vaultsPerAvailableProviders;
150
+ // Skip vaults the post-enrichment filter (filterVaultsIntelligently +
151
+ // the includeClosed gate below) is guaranteed to drop, BEFORE paying
152
+ // their per-vault enrichment. `status` / `is_visible` land on the
153
+ // enriched vault verbatim from this backend row, so filtering on the row
154
+ // is exactly equivalent to filtering on the enriched result — it just
155
+ // saves the on-chain reads (and their retry backoff) for vaults that can
156
+ // never appear in the output. The post-filter below is kept unchanged as
157
+ // the authority on the final shape.
158
+ const enrichableVaults = vaultsPerChainId.filter((v) => {
159
+ const status = v?.status || 'unknown';
160
+ if (status === 'closed')
161
+ return !!options?.includeClosed;
162
+ if (status === 'active')
163
+ return true;
164
+ // Mirrors filterVaultsIntelligently: an unknown-status vault survives
165
+ // only through the invisible bucket; a visible one lands in `failed`.
166
+ return !(v?.is_visible ?? true);
167
+ });
168
+ // The backend row for each vault about to be enriched. getVault re-uses
169
+ // it instead of re-fetching `GET /tokenized_vault/{address}` per vault —
170
+ // the row came from the same list response (same load flags), so this is
171
+ // a pure de-duplication of backend traffic, not a freshness change.
172
+ const vaultRowsByAddress = new Map(enrichableVaults.map((row) => [String(row.address).toLowerCase(), row]));
173
+ const isWalletMode = (options?.wallet && (0, ethers_1.isAddress)(options.wallet)) ||
174
+ (options?.solanaWallet &&
175
+ utils_1.SolanaUtils.isSolanaAddress(options.solanaWallet));
176
+ // Use comprehensive vault fetching for maximum coverage
177
+ const vaultFetchResult = await (0, fetcher_1.fetchVaultsComprehensive)(enrichableVaults, async (vault) => {
178
+ // Handle fallback RPC if provided
179
+ const rpcUrl = vault.fallbackRpc || this.providers?.[vault.chain];
180
+ // Closed vaults have no live loans/allocations. In portfolio mode,
181
+ // skip that enrichment so a closed vault is never dropped just because
182
+ // getVaultAllocations re-throws (no debank data / no subaccounts).
183
+ const isClosedVault = vault.status === 'closed';
184
+ const skipClosedEnrichment = !!options?.includeClosed && isClosedVault;
185
+ // Handle minimal data fetching
186
+ const shouldFetchLoans = !skipClosedEnrichment &&
187
+ !vault.minimal &&
188
+ (typeof options?.loans !== 'undefined' ? options?.loans : true);
189
+ const shouldFetchAllocations = !skipClosedEnrichment &&
190
+ !vault.minimal &&
191
+ (typeof options?.allocations !== 'undefined'
192
+ ? options?.allocations
193
+ : true);
194
+ const v = await (0, getters_1.getVault)({
195
+ vault: vault.address,
196
+ loans: shouldFetchLoans,
197
+ allocations: shouldFetchAllocations,
198
+ // Re-use the backend row from the list response instead of letting
199
+ // getVault re-fetch it per vault (an N+1 against the backend).
200
+ tokenizedVault: vaultRowsByAddress.get(String(vault.address).toLowerCase()),
201
+ options: {
202
+ rpcUrl,
203
+ solanaService: this.solanaService,
204
+ stellarRpc: this._stellarRpc,
205
+ env: this.monitoring?.env,
206
+ upshiftKey: this.keys?.upshift,
207
+ subgraphKey: this.keys?.graph,
208
+ // Portfolio mode: let the EVM getter resolve closed + invisible
209
+ // vaults instead of null-ing them, so the closed vault survives.
210
+ includeClosed: options?.includeClosed,
211
+ },
212
+ loadSubaccounts: options?.loadSubaccounts,
213
+ loadSnapshots: options?.loadSnapshots,
214
+ });
215
+ return v;
216
+ }, {
217
+ maxRetries: options?.maxRetries ?? 5,
218
+ baseDelay: options?.baseDelay ?? 2000,
219
+ batchSize: 15,
220
+ parallelLimit: 8,
221
+ includeClosed: true,
222
+ includeInvisible: false,
223
+ timeout: 60000,
224
+ fallbackRpcUrls: {
225
+ // Use configured fallback RPC endpoints for each chain
226
+ 1: (0, core_1.getFallbackRpcUrls)(1),
227
+ 56: (0, core_1.getFallbackRpcUrls)(56),
228
+ 43114: (0, core_1.getFallbackRpcUrls)(43114),
229
+ 8453: (0, core_1.getFallbackRpcUrls)(8453),
230
+ 42161: (0, core_1.getFallbackRpcUrls)(42161),
231
+ 137: (0, core_1.getFallbackRpcUrls)(137),
232
+ // [SPECIAL_CHAINS.solana.chainId]: getFallbackRpcUrls(SPECIAL_CHAINS.solana.chainId),
233
+ },
234
+ });
235
+ // Log vault fetching results in DEV mode
236
+ core_1.Logger.log.info('getVaults', `Total: ${vaultFetchResult.coverageReport.totalVaults}, ` +
237
+ `Success: ${vaultFetchResult.coverageReport.successfulVaults}, ` +
238
+ `Failed: ${vaultFetchResult.coverageReport.failedVaults}, ` +
239
+ `Rate: ${vaultFetchResult.successRate.toFixed(2)}%`);
240
+ if (vaultFetchResult.coverageReport.failedVaults > 0) {
241
+ core_1.Logger.log.warn('getVaults:failed', vaultFetchResult.failed.map((f) => ({
242
+ address: f.address,
243
+ chain: f.chain,
244
+ error: f.error.message,
245
+ attempts: f.attempts,
246
+ })));
247
+ }
248
+ // Use intelligent filtering to preserve more vaults
249
+ const vaultResponses = vaultFetchResult.successful
250
+ .sort((a, b) => a.index - b.index)
251
+ .map((item) => item.data);
252
+ const filteredResults = (0, fetcher_1.filterVaultsIntelligently)(vaultResponses, {
253
+ includeClosed: true,
254
+ includeInvisible: true,
255
+ minStatus: ['active', 'closed'],
256
+ });
257
+ // Closed vaults are included in the result ONLY when the caller opts in via
258
+ // `includeClosed` (portfolio mode). By default they are dropped, so the
259
+ // marketplace / discovery callers never receive a closed vault and don't
260
+ // have to filter `status === 'closed'` themselves. The portfolio passes
261
+ // `includeClosed: true` so a user's position in a closed vault can be
262
+ // joined against this list. Note: closed + invisible vaults land in the
263
+ // `closed` bucket (the status check precedes the visibility check in
264
+ // filterVaultsIntelligently), so this single gate covers them too.
265
+ const filteredResponses = [
266
+ ...filteredResults.active,
267
+ ...(options?.includeClosed ? filteredResults.closed : []),
268
+ ...filteredResults.invisible,
269
+ ];
270
+ if (isWalletMode) {
271
+ // Positions are only ever joined onto `filteredResponses`, which is
272
+ // derived from `enrichableVaults` — so fan out over that same list.
273
+ // Reading positions for vaults the `chainIds` / closed / invisible
274
+ // pre-filter already dropped would be RPC spent on rows the join
275
+ // discards.
276
+ //
277
+ // Batch the per-vault balanceOf/lagDuration reads (Multicall3, grouped
278
+ // by chain) before fanning out — vaults the batch couldn't serve fall
279
+ // back to their own reads inside getVaultPositions.
280
+ const prefetchedReads = await (0, prefetch_1.prefetchVaultPositionReads)({
281
+ vaults: enrichableVaults,
282
+ wallet: options.wallet,
283
+ providers: this.providers,
284
+ });
285
+ // Fetch all positions for the user wallet. Each entry is a thunk so
286
+ // promiseSettle can genuinely re-run the read on a transient failure
287
+ // (a bare promise can only be re-awaited, never retried).
288
+ const vaultResponses = await (0, core_1.promiseSettle)(enrichableVaults.map((v) => () => (0, getters_1.getVaultPositions)({
289
+ vault: v.address,
290
+ wallet: options.wallet,
291
+ solanaWallet: options.solanaWallet,
292
+ stellarWallet: options.stellarWallet,
293
+ options: {
294
+ rpcUrl: this.providers?.[v.chain],
295
+ solanaService: this.solanaService,
296
+ stellarRpc: this._stellarRpc,
297
+ env: this.monitoring?.env,
298
+ upshiftKey: this.keys?.upshift,
299
+ subgraphKey: this.keys?.graph,
300
+ },
301
+ prefetchedReads: prefetchedReads.get(String(v.address).toLowerCase()),
302
+ })), 5, // 5 retries
303
+ 2000);
304
+ // promiseSettle yields `null` for a vault whose read failed after all
305
+ // retries. Drop those slots before touching `.status`, so one broken
306
+ // vault degrades to "no position" instead of rejecting the whole call.
307
+ const positions = vaultResponses
308
+ .filter((res) => Array.isArray(res))
309
+ .flat()
310
+ .filter((v) => v.status !== 'PENDING');
311
+ return filteredResponses.map((r) => ({
312
+ ...r,
313
+ position: positions?.find((pos) => pos.vault?.toLowerCase() === r.address?.toLowerCase()) || null,
314
+ }));
315
+ }
316
+ if (options?.wallet && !(0, ethers_1.isAddress)(options.wallet)) {
317
+ core_1.Logger.log.warn('getVaults:invalid_wallet', options.wallet);
318
+ }
319
+ // console.log(`#getVaults:`, filteredResponses);
320
+ return filteredResponses;
321
+ }
322
+ /**
323
+ * Calculate total deposited across all tokenized vaults by summing latest_reported_tvl.
324
+ * Uses the /tokenized_vault endpoint which returns latest_reported_tvl in USD.
325
+ * Wrapper vaults (non-null `underlying_vault_address`) are skipped: their
326
+ * deposits sit in the underlying vault as LP and are already counted there.
327
+ * @param options Optional configuration for loading vaults
328
+ * @returns Total deposited amount in USD (sum of all latest_reported_tvl values)
329
+ */
330
+ async getTotalDeposited(options) {
331
+ const allVaults = await (0, core_1.fetchTokenizedVaults)(undefined, this.headers, options?.loadSubaccounts, options?.loadSnapshots);
332
+ let total = 0;
333
+ allVaults.forEach((vault) => {
334
+ if (vaults_2.TVL_EXCLUDED_VAULTS.has(vault.address?.toLowerCase()))
335
+ return;
336
+ if (vault.underlying_vault_address)
337
+ return;
338
+ if (vault.latest_reported_tvl !== null &&
339
+ vault.latest_reported_tvl !== undefined) {
340
+ total += vault.latest_reported_tvl;
341
+ }
342
+ });
343
+ return total;
344
+ }
345
+ /**
346
+ * Fetch detailed data for a single vault with optional enrichment.
347
+ * Automatically includes loans and allocations unless explicitly disabled.
348
+ * @param vault Vault contract address
349
+ * @param chainId Optional chain ID (uses active network if not provided)
350
+ * @param options Enrichment and wallet options
351
+ * @returns Single vault object with optional position data
352
+ * @throws {@link UpshiftValidationError} (`INVALID_CHAIN`) when `chainId` is
353
+ * not a chain the SDK recognises, or is a supported EVM chain with no RPC
354
+ * URL configured on this SDK instance.
355
+ */
356
+ async getVault({ vault, chainId, options, loadSubaccounts, loadSnapshots, }) {
357
+ if (!vault)
358
+ throw new Error('Vault input parameter is undefined.');
359
+ // if (!isAddress(vault))
360
+ // throw new Error(
361
+ // `Vault input parameter is not an address: ${String(vault)}`,
362
+ // );
363
+ (0, core_1.assertKnownChainId)(chainId, this.providers, 'getVault');
364
+ (0, core_1.assertSuiReadsSupported)(chainId, vault, 'getVault');
365
+ (0, core_1.assertEvmProviderConfigured)(chainId, this.providers, 'getVault');
366
+ // get vault data
367
+ const vaultResponse = await (0, getters_1.getVault)({
368
+ vault: vault,
369
+ loans: typeof options?.loans !== 'undefined' ? options?.loans : true,
370
+ allocations: typeof options?.allocations !== 'undefined'
371
+ ? options?.allocations
372
+ : true,
373
+ options: {
374
+ rpcUrl: chainId
375
+ ? this.providers?.[chainId]
376
+ : this.activeNetwork?.rpcUrl,
377
+ solanaService: this.solanaService,
378
+ stellarRpc: this._stellarRpc,
379
+ env: this.monitoring?.env,
380
+ upshiftKey: this.keys?.upshift,
381
+ subgraphKey: this.keys?.graph,
382
+ headers: this.headers,
383
+ // Rebuilding these options previously dropped this, making the flag
384
+ // unreachable on the per-address path.
385
+ includeClosed: options?.includeClosed,
386
+ },
387
+ loadSubaccounts,
388
+ loadSnapshots,
389
+ });
390
+ if (((0, ethers_1.isAddress)(vault) || (0, utils_2.isStellarAddress)(vault)) &&
391
+ ((options?.wallet && (0, ethers_1.isAddress)(options?.wallet)) ||
392
+ (options?.solanaWallet &&
393
+ utils_1.SolanaUtils.isSolanaAddress(options?.solanaWallet)) ||
394
+ (options?.stellarWallet && (0, utils_2.isStellarAddress)(options?.stellarWallet)))) {
395
+ // fetch all positions for user wallet
396
+ const vaultResponses = await (0, getters_1.getVaultPositions)({
397
+ vault: vault,
398
+ solanaWallet: options?.solanaWallet,
399
+ stellarWallet: options?.stellarWallet,
400
+ wallet: options?.wallet,
401
+ options: {
402
+ rpcUrl: chainId
403
+ ? this.providers?.[chainId]
404
+ : this.activeNetwork?.rpcUrl,
405
+ solanaService: this.solanaService,
406
+ stellarRpc: this._stellarRpc,
407
+ env: this.monitoring?.env,
408
+ upshiftKey: this.keys?.upshift,
409
+ subgraphKey: this.keys?.graph,
410
+ headers: this.headers,
411
+ },
412
+ });
413
+ // return vault object with position property
414
+ const positions = vaultResponses.filter((v) => v.status !== 'PENDING');
415
+ return {
416
+ ...vaultResponse,
417
+ position: positions?.find((pos) => pos.vault?.toLowerCase() === vault?.toLowerCase()) || null,
418
+ };
419
+ }
420
+ if (options?.wallet && !(0, ethers_1.isAddress)(options?.wallet)) {
421
+ core_1.Logger.log.warn('getVault:invalid_wallet', options?.wallet);
422
+ }
423
+ // console.log(`#getVault::${vaultResponse.symbol}:`, vaultResponse);
424
+ return vaultResponse;
425
+ }
426
+ /**
427
+ * Fetch the active loans issued by a vault.
428
+ * @param vault Vault contract address
429
+ * @param chainId Optional chain ID (uses active network if not provided)
430
+ * @returns Loan data for the vault
431
+ * @throws {@link UpshiftValidationError} (`INVALID_CHAIN`) when `chainId` is
432
+ * not a chain the SDK recognises, or is a supported EVM chain with no RPC
433
+ * URL configured on this SDK instance.
434
+ */
435
+ async getVaultLoans({ vault, chainId, }) {
436
+ // Sanitize
437
+ // if (!this.authorized) throw new Error('Not authorized.');
438
+ if (!vault)
439
+ throw new Error('Vault input parameter is undefined.');
440
+ (0, core_1.assertSuiReadsSupported)(chainId, vault, 'getVaultLoans');
441
+ if (!(0, ethers_1.isAddress)(vault))
442
+ throw new Error(`Vault input parameter is not an address: ${String(vault)}`);
443
+ (0, core_1.assertKnownChainId)(chainId, this.providers, 'getVaultLoans');
444
+ (0, core_1.assertEvmProviderConfigured)(chainId, this.providers, 'getVaultLoans');
445
+ // get vault loans data
446
+ const vaultResponse = await (0, getters_1.getVaultLoans)(vault, {
447
+ rpcUrl: chainId
448
+ ? this.providers?.[chainId]
449
+ : this.requireActiveNetwork().rpcUrl,
450
+ env: this.monitoring?.env,
451
+ upshiftKey: this.keys?.upshift,
452
+ subgraphKey: this.keys?.graph,
453
+ chainId: chainId,
454
+ solanaService: this.solanaService,
455
+ stellarRpc: this._stellarRpc,
456
+ headers: this.headers,
457
+ });
458
+ return vaultResponse;
459
+ }
460
+ /**
461
+ * Fetch a vault's loans broken down by sub-account.
462
+ * @param vault Vault contract address
463
+ * @param chainId Optional chain ID (uses active network if not provided)
464
+ * @returns Sub-account loan data for the vault
465
+ * @throws {@link UpshiftValidationError} (`INVALID_CHAIN`) when `chainId` is
466
+ * not a chain the SDK recognises, or is a supported EVM chain with no RPC
467
+ * URL configured on this SDK instance.
468
+ */
469
+ async getVaultSubaccountLoans({ vault, chainId, }) {
470
+ // Sanitize
471
+ if (!vault)
472
+ throw new Error('Vault input parameter is undefined.');
473
+ (0, core_1.assertSuiReadsSupported)(chainId, vault, 'getVaultSubaccountLoans');
474
+ if (!(0, ethers_1.isAddress)(vault))
475
+ throw new Error(`Vault input parameter is not an address: ${String(vault)}`);
476
+ (0, core_1.assertKnownChainId)(chainId, this.providers, 'getVaultSubaccountLoans');
477
+ (0, core_1.assertEvmProviderConfigured)(chainId, this.providers, 'getVaultSubaccountLoans');
478
+ // get vault subaccount loans data
479
+ const vaultResponse = await (0, getters_1.getVaultSubaccountLoans)(vault, {
480
+ rpcUrl: chainId
481
+ ? this.providers?.[chainId]
482
+ : this.requireActiveNetwork().rpcUrl,
483
+ env: this.monitoring?.env,
484
+ upshiftKey: this.keys?.upshift,
485
+ subgraphKey: this.keys?.graph,
486
+ chainId: chainId,
487
+ solanaService: this.solanaService,
488
+ stellarRpc: this._stellarRpc,
489
+ headers: this.headers,
490
+ });
491
+ return vaultResponse;
492
+ }
493
+ /**
494
+ * Fetch a vault's DeFi / CeFi / OTC allocation breakdown.
495
+ * @param vault Vault contract address
496
+ * @param chainId Optional chain ID (uses active network if not provided)
497
+ * @returns Allocation data for the vault
498
+ * @throws {@link UpshiftValidationError} (`INVALID_CHAIN`) when `chainId` is
499
+ * not a chain the SDK recognises, or is a supported EVM chain with no RPC
500
+ * URL configured on this SDK instance.
501
+ */
502
+ async getVaultAllocations({ vault, chainId, }) {
503
+ // Sanitize
504
+ // if (!this.authorized) throw new Error('Not authorized.');
505
+ if (!vault)
506
+ throw new Error('Vault input parameter is undefined.');
507
+ (0, core_1.assertSuiReadsSupported)(chainId, vault, 'getVaultAllocations');
508
+ if (!(0, ethers_1.isAddress)(vault) &&
509
+ !utils_1.SolanaUtils.isSolanaAddress(vault) &&
510
+ !(0, utils_2.isStellarAddress)(vault))
511
+ throw new Error(`Vault input parameter is not an address: ${String(vault)}`);
512
+ (0, core_1.assertKnownChainId)(chainId, this.providers, 'getVaultAllocations');
513
+ (0, core_1.assertEvmProviderConfigured)(chainId, this.providers, 'getVaultAllocations');
514
+ // get vault allocations data
515
+ try {
516
+ const vaultResponse = await (0, getters_1.getVaultAllocations)(vault, {
517
+ rpcUrl: chainId
518
+ ? this.providers?.[chainId]
519
+ : this.activeNetwork?.rpcUrl,
520
+ solanaService: this.solanaService,
521
+ stellarRpc: this._stellarRpc,
522
+ env: this.monitoring?.env,
523
+ upshiftKey: this.keys?.upshift,
524
+ subgraphKey: this.keys?.graph,
525
+ headers: this.headers,
526
+ });
527
+ return vaultResponse;
528
+ }
529
+ catch (e) {
530
+ const err = e;
531
+ if (err.message.includes('debank')) {
532
+ return {
533
+ status: 400,
534
+ message: 'There was an error fetching from debank',
535
+ };
536
+ }
537
+ return {
538
+ status: 400,
539
+ message: 'There was an error fetching vaults',
540
+ };
541
+ }
542
+ }
543
+ /**
544
+ * @deprecated use getVaultHistoricalTimeseries instead
545
+ * @function getVaultApy gets the vault/pool APR, both current and historical
546
+ * @param vault pool/vault contract address
547
+ * @param historical (optional) When passed, returns the historical records of the pool/vault APR
548
+ * @returns a value or array of objects containing the APR and timestamp
549
+ */
550
+ async getVaultApy({ vault, historical, }) {
551
+ // if (!this.authorized) throw new Error('Not authorized.');
552
+ if (!vault)
553
+ throw new Error('Vault input parameter is undefined.');
554
+ if (!(0, ethers_1.isAddress)(vault) && !(0, utils_2.isStellarAddress)(vault))
555
+ throw new Error(`Vault input parameter is not an address: ${String(vault)}`);
556
+ return await (0, getters_1.getVaultApy)({
557
+ vault,
558
+ historical,
559
+ options: {
560
+ rpcUrl: this.activeNetwork?.rpcUrl,
561
+ subgraphKey: this.keys?.graph,
562
+ headers: this.headers,
563
+ },
564
+ });
565
+ }
566
+ /**
567
+ * @function getVaultHistoricalTimeseries gets historical timeseries data for a vault
568
+ * @param vault Vault contract address
569
+ * @param nDays Number of days of historical data (default 30, min 1)
570
+ * @returns Historical timeseries data with TVL, APY, PnL, share price, and other metrics
571
+ */
572
+ async getVaultHistoricalTimeseries({ vault, nDays, }) {
573
+ if (!vault)
574
+ throw new Error('Vault input parameter is undefined.');
575
+ return await (0, getters_1.getVaultHistoricalTimeseries)({
576
+ vault,
577
+ nDays,
578
+ options: {
579
+ rpcUrl: this.activeNetwork?.rpcUrl,
580
+ headers: this.headers,
581
+ },
582
+ });
583
+ }
584
+ /**
585
+ * A wallet's redemption requests on one vault, split into
586
+ * `availableRedemptions` and `pendingRedemptions`. EVM, Stellar and Solana
587
+ * vault addresses are accepted; see `UpshiftSDK.getVaultAvailableRedemptions`
588
+ * for what each list holds on Solana.
589
+ *
590
+ * @param props - `vault`, the vault address; `chainId`, the EVM chain whose
591
+ * RPC to use (the active network when omitted); `wallet`, the holder,
592
+ * required for Solana, where it is base58; `verbose`, to also return the
593
+ * processed and requested withdrawal lists (always empty for Solana).
594
+ * @returns `{ availableRedemptions, pendingRedemptions }`, plus the verbose lists.
595
+ * @throws Error when unauthorized, or when `vault` is missing or not an address.
596
+ */
597
+ async getVaultAvailableRedemptions({ vault, chainId, wallet, verbose, }) {
598
+ if (!this.authorized)
599
+ throw new Error('Not authorized.');
600
+ if (!vault)
601
+ throw new Error('Vault input parameter is undefined.');
602
+ if (!(0, ethers_1.isAddress)(vault) &&
603
+ !(0, utils_2.isStellarAddress)(vault) &&
604
+ !utils_1.SolanaUtils.isSolanaAddress(vault))
605
+ throw new Error(`Vault input parameter is not an address: ${String(vault)}`);
606
+ return await (0, getters_1.getVaultAvailableRedemptions)({
607
+ vault,
608
+ wallet,
609
+ options: {
610
+ rpcUrl: chainId
611
+ ? this.providers?.[chainId]
612
+ : this.activeNetwork?.rpcUrl,
613
+ solanaService: this.solanaService,
614
+ stellarRpc: this._stellarRpc,
615
+ env: this.monitoring?.env,
616
+ upshiftKey: this.keys?.upshift,
617
+ subgraphKey: this.keys?.graph,
618
+ headers: this.headers,
619
+ verbose: verbose,
620
+ },
621
+ });
622
+ }
623
+ /**
624
+ * Historical redemption requests for a vault (settled, cancelled, and
625
+ * pending-but-out-of-window). Filterable by wallet.
626
+ *
627
+ * Stellar vaults return `[]` — on-chain redemption history is not yet
628
+ * indexed for that adapter.
629
+ *
630
+ * @param vault - Vault address (EVM or Stellar). Stellar input is
631
+ * accepted but always resolves to an empty array for now.
632
+ * @param chainId - Chain id to resolve the RPC URL against. Falls
633
+ * back to the active network.
634
+ * @param wallet - Optional EVM wallet filter; when omitted the
635
+ * response includes every wallet that has ever redeemed against
636
+ * the vault.
637
+ * @param lookbackBlocks - How far back to scan for redemption logs.
638
+ * Defaults to the SDK's internal lookback when omitted.
639
+ * @returns The same array shape `getVaultRedemptionHistory` returns
640
+ * at the module level — historical redemption records, newest
641
+ * first.
642
+ *
643
+ * @example
644
+ * ```ts
645
+ * const history = await sdk.vaultsModule.getVaultRedemptionHistory({
646
+ * vault: '0xVault',
647
+ * chainId: 8453,
648
+ * wallet: '0xWallet',
649
+ * });
650
+ * ```
651
+ */
652
+ async getVaultRedemptionHistory({ vault, chainId, wallet, lookbackBlocks, }) {
653
+ if (!this.authorized)
654
+ throw new Error('Not authorized.');
655
+ if (!vault)
656
+ throw new Error('Vault input parameter is undefined.');
657
+ if (!(0, ethers_1.isAddress)(vault) && !(0, utils_2.isStellarAddress)(vault)) {
658
+ throw new Error(`Vault input parameter is not an address: ${String(vault)}`);
659
+ }
660
+ return await (0, getters_1.getVaultRedemptionHistory)({
661
+ vault,
662
+ wallet,
663
+ lookbackBlocks,
664
+ options: {
665
+ rpcUrl: chainId
666
+ ? this.providers?.[chainId]
667
+ : this.activeNetwork?.rpcUrl,
668
+ env: this.monitoring?.env,
669
+ upshiftKey: this.keys?.upshift,
670
+ subgraphKey: this.keys?.graph,
671
+ headers: this.headers,
672
+ },
673
+ });
674
+ }
675
+ /**
676
+ * Fetch the wallet's positions across vaults — a single vault, one chain,
677
+ * or every chain with a configured provider.
678
+ *
679
+ * RPC volume (worst case, multi-vault paths): the two non-cacheable
680
+ * per-vault reads (`balanceOf`, `lagDuration`) are aggregated into chunked
681
+ * Multicall3 `aggregate3` batches per chain (10 calls per chunk) on chains
682
+ * where the canonical deployment is verified; unverified chains (e.g.
683
+ * Citrea 4114) and non-EVM vaults keep one `eth_call` per read. Measured
684
+ * on a cold cache for a wallet with 62
685
+ * vaults across Ethereum + Avalanche: 83 RPC HTTP requests before batching,
686
+ * 54 after (~35% fewer). A vault whose batched read fails (e.g. paused)
687
+ * falls back to its own per-vault reads — never to a zeroed balance.
688
+ */
689
+ async getVaultPositions({ vault, wallet, chainId, showAllVaults, solanaWallet, stellarWallet, suiWallet, options, }) {
690
+ // if (!this.authorized) throw new Error('Not authorized.');
691
+ // Validate that at least one wallet type is provided
692
+ if (solanaWallet && !utils_1.SolanaUtils.isSolanaAddress(solanaWallet)) {
693
+ throw new Error('Solana wallet parameter must be provided and be a valid Solana address');
694
+ }
695
+ if (suiWallet && !(0, chain_address_1.isSuiAddress)(suiWallet)) {
696
+ throw new errors_1.UpshiftValidationError('INVALID_ADDRESS', 'getVaultPositions: suiWallet must be a Sui address (0x + 64 hex chars).');
697
+ }
698
+ // Validate EVM wallet if provided
699
+ if (wallet && !(0, ethers_1.isAddress)(wallet)) {
700
+ throw new Error(`Wallet parameter is not a valid address: ${String(wallet)}`);
701
+ }
702
+ if (vault) {
703
+ const positions = await (0, getters_1.getVaultPositions)({
704
+ vault,
705
+ wallet,
706
+ solanaWallet,
707
+ stellarWallet,
708
+ options: {
709
+ rpcUrl: chainId
710
+ ? this.providers?.[chainId]
711
+ : this.activeNetwork?.rpcUrl,
712
+ solanaService: this.solanaService,
713
+ stellarRpc: this._stellarRpc,
714
+ env: this.monitoring?.env,
715
+ upshiftKey: this.keys?.upshift,
716
+ subgraphKey: this.keys?.graph,
717
+ headers: this.headers,
718
+ },
719
+ });
720
+ if (showAllVaults)
721
+ return positions;
722
+ return positions.filter((v) => v?.status !== 'PENDING');
723
+ }
724
+ const allVaults = await (0, core_1.fetchTokenizedVaults)(undefined, this.headers, false, false);
725
+ if (chainId) {
726
+ const vaultsPerChain = allVaults.filter((v) => v.chain === chainId);
727
+ // Batch balanceOf/lagDuration via Multicall3 before the per-vault
728
+ // fan-out; un-batched vaults fall back to their own reads.
729
+ const prefetchedReads = await (0, prefetch_1.prefetchVaultPositionReads)({
730
+ vaults: vaultsPerChain,
731
+ wallet,
732
+ providers: this.providers,
733
+ });
734
+ const vaultResponses = await Promise.all(vaultsPerChain.map((v) => (0, getters_1.getVaultPositions)({
735
+ vault: v.address,
736
+ solanaWallet,
737
+ stellarWallet,
738
+ wallet,
739
+ options: {
740
+ rpcUrl: this.providers?.[v.chain],
741
+ solanaService: this.solanaService,
742
+ stellarRpc: this._stellarRpc,
743
+ env: this.monitoring?.env,
744
+ upshiftKey: this.keys?.upshift,
745
+ subgraphKey: this.keys?.graph,
746
+ headers: this.headers,
747
+ },
748
+ prefetchedReads: prefetchedReads.get(String(v.address).toLowerCase()),
749
+ })));
750
+ const flattened = vaultResponses.flat();
751
+ let final;
752
+ if (showAllVaults)
753
+ final = flattened;
754
+ else
755
+ final = flattened.filter((v) => v?.status !== 'PENDING');
756
+ core_1.Logger.log.info(`getPositions::${chainId || 'all'}:`, final.map((v) => v.vault));
757
+ return final;
758
+ }
759
+ const vaultsPerAvailableProviders = allVaults.filter((v) =>
760
+ // Stellar vaults are backend-only (no RPC provider required)
761
+ v?.chain_type === 'stellar' ||
762
+ // Solana vaults use this.solanaService (not this.providers). Without
763
+ // this clause every Solana position is dropped on any instance where
764
+ // ACTIVE_RPC_URLS() doesn't register chainId -1 — which is exactly
765
+ // how the jitoSOL "missing position" regression manifested. Gate on
766
+ // solanaService presence so we don't pass Solana vaults through with
767
+ // no adapter to read them — the inner getter would crash, hit the
768
+ // outer catch, and silently return PENDING (then get filtered out).
769
+ (v?.chain_type === 'solana' && !!this.solanaService) ||
770
+ (this.providers?.[v?.chain] ? true : false));
771
+ // Batch balanceOf/lagDuration via Multicall3, grouped by chain, before
772
+ // the per-vault fan-out; un-batched vaults fall back to their own reads.
773
+ const prefetchedReads = await (0, prefetch_1.prefetchVaultPositionReads)({
774
+ vaults: vaultsPerAvailableProviders,
775
+ wallet,
776
+ providers: this.providers,
777
+ });
778
+ const vaultResponses = await Promise.all(vaultsPerAvailableProviders.map((v) => (0, getters_1.getVaultPositions)({
779
+ vault: v.address,
780
+ solanaWallet,
781
+ stellarWallet,
782
+ wallet,
783
+ options: {
784
+ rpcUrl: this.providers?.[v.chain],
785
+ solanaService: this.solanaService,
786
+ stellarRpc: this._stellarRpc,
787
+ env: this.monitoring?.env,
788
+ upshiftKey: this.keys?.upshift,
789
+ subgraphKey: this.keys?.graph,
790
+ headers: this.headers,
791
+ },
792
+ prefetchedReads: prefetchedReads.get(String(v.address).toLowerCase()),
793
+ })));
794
+ const flattened = vaultResponses.flat();
795
+ let final;
796
+ if (showAllVaults)
797
+ final = flattened;
798
+ else
799
+ final = flattened.filter((v) => v?.status !== 'PENDING');
800
+ // console.log(`#getPositions::${chainId || 'all'}:`, final);
801
+ return final;
802
+ }
803
+ /**
804
+ *
805
+ */
806
+ async getUserHistory({ wallet, chainId, vault, }) {
807
+ // Santize
808
+ // if (!this.authorized) throw new Error('Not authorized.');
809
+ if (!(0, ethers_1.isAddress)(wallet))
810
+ throw new Error(`Wallet parameter is not an address: ${String(wallet)}`);
811
+ // Get Chain ID — required for subgraph queries
812
+ const _chainId = chainId || this.activeNetwork?.chainId;
813
+ if (!_chainId) {
814
+ throw new Error('Chain ID is required for getUserHistory. Pass chainId explicitly or configure an active network.');
815
+ }
816
+ // Format history initialization
817
+ let finalArray = [];
818
+ function formatHistory(history) {
819
+ return history.map((h) => ({
820
+ timestamp: Number(h.timestamp_),
821
+ address: h.address,
822
+ amount: (0, core_1.toNormalizedBn)(BigInt(h.amount), h.decimals),
823
+ pool: h.contractId_,
824
+ chainId: _chainId,
825
+ type: h.type,
826
+ transactionHash: h.transactionHash_,
827
+ // Deposit rows on multi-asset (pre-deposit) vaults carry the actual
828
+ // deposited token address; propagate it so consumers render the right
829
+ // asset symbol instead of guessing the vault's first deposit asset.
830
+ assetIn: h.assetIn,
831
+ // withdraw-request rows carry the burned share amount. Normalize with
832
+ // the vault decimals (the share token's own decimals) so UIs can show
833
+ // the receipt-token quantity that was actually burned.
834
+ shares: h.shares
835
+ ? (0, core_1.toNormalizedBn)(BigInt(h.shares), h.decimals)
836
+ : undefined,
837
+ }));
838
+ }
839
+ // Helper function to fetch history for a vault
840
+ // For LayerZero-enabled vaults (coreUSDC, upUSDC), queries BOTH the standard
841
+ // subgraph and the LayerZero subgraph, since deposits can be either same-chain
842
+ // or cross-chain via LayerZero
843
+ const fetchVaultHistory = async (vaultAddress, vaultChainId) => {
844
+ // Always query the standard subgraph
845
+ const provider = (0, core_1.createProvider)(this.providers?.[vaultChainId]);
846
+ const standardHistory = await (0, vaults_1.getSubgraphUserHistory)(wallet, provider, vaultAddress);
847
+ const formattedStandard = formatHistory(standardHistory);
848
+ // If this vault also supports LayerZero cross-chain deposits,
849
+ // query the LayerZero subgraph and merge results
850
+ const layerZeroVaultKey = (0, deposits_1.isLayerZeroVault)(vaultAddress);
851
+ if (layerZeroVaultKey) {
852
+ try {
853
+ const layerZeroDeposits = await (0, deposits_1.queryLayerZeroDeposits)(layerZeroVaultKey, wallet);
854
+ const formattedLayerZero = layerZeroDeposits.map((deposit) => ({
855
+ timestamp: Number(deposit.timestamp_) || 0,
856
+ address: wallet,
857
+ amount: (0, core_1.toNormalizedBn)(BigInt(deposit.assetAmt), deposits_1.LAYERZERO_VAULTS[layerZeroVaultKey].decimals),
858
+ pool: deposits_1.LAYERZERO_VAULTS[layerZeroVaultKey].address,
859
+ chainId: vaultChainId || _chainId,
860
+ type: 'deposit',
861
+ transactionHash: deposit.transactionHash_,
862
+ }));
863
+ // For earnAUSD, also query LayerZero redeems
864
+ let formattedLayerZeroRedeems = [];
865
+ if (layerZeroVaultKey === 'earnAUSD') {
866
+ try {
867
+ const layerZeroRedeems = await (0, redeems_1.queryLayerZeroRedeems)(wallet);
868
+ formattedLayerZeroRedeems = layerZeroRedeems.map((redeem) => ({
869
+ timestamp: Number(redeem.timestamp_) || 0,
870
+ address: wallet,
871
+ amount: (0, core_1.toNormalizedBn)(BigInt(redeem.shareAmt), deposits_1.LAYERZERO_VAULTS[layerZeroVaultKey].decimals),
872
+ pool: deposits_1.LAYERZERO_VAULTS[layerZeroVaultKey].address,
873
+ chainId: vaultChainId || _chainId,
874
+ type: 'redeem',
875
+ transactionHash: redeem.transactionHash_,
876
+ }));
877
+ }
878
+ catch (redeemError) {
879
+ core_1.Logger.log.warn('getUserHistory:layerzero:redeems', `Failed to fetch LayerZero redeems for earnAUSD: ${redeemError.message}`);
880
+ }
881
+ }
882
+ // Deduplicate against standard subgraph history only — LZ deposits and
883
+ // LZ redeems are not deduped against each other because a single tx can
884
+ // legitimately emit both a Deposited and a Redeemed event.
885
+ const seenTxHashes = new Set(formattedStandard.map((h) => h.transactionHash?.toLowerCase()));
886
+ const uniqueLayerZero = formattedLayerZero.filter((h) => !seenTxHashes.has(h.transactionHash?.toLowerCase()));
887
+ const uniqueLayerZeroRedeems = formattedLayerZeroRedeems.filter((h) => !seenTxHashes.has(h.transactionHash?.toLowerCase()));
888
+ return [
889
+ ...formattedStandard,
890
+ ...uniqueLayerZero,
891
+ ...uniqueLayerZeroRedeems,
892
+ ];
893
+ }
894
+ catch (error) {
895
+ // If LayerZero query fails, still return standard history
896
+ core_1.Logger.log.warn('getUserHistory:layerzero', `Failed to fetch LayerZero deposits for ${layerZeroVaultKey}: ${error.message}`);
897
+ return formattedStandard;
898
+ }
899
+ }
900
+ return formattedStandard;
901
+ };
902
+ // If vault is provided, return history for that vault. This path is
903
+ // EVM-only (see fetchVaultHistory → getSubgraphUserHistory); a non-EVM
904
+ // vault address would drive eth_chainId against a Solana/Stellar RPC.
905
+ if (vault) {
906
+ // `_chainId` (explicit chainId, else the active network) — not the raw
907
+ // `chainId` arg, which is undefined for the common vault-only call and
908
+ // made the provider lookup fail with "no RPC URL provided".
909
+ finalArray = (0, ethers_1.isAddress)(vault)
910
+ ? await fetchVaultHistory(vault, _chainId)
911
+ : [];
912
+ }
913
+ else {
914
+ // Fetch all vaults
915
+ const allVaults = await (0, core_1.fetchTokenizedVaults)(undefined, this.headers, false, false);
916
+ // If chainId is provided, return history for all vaults on that chain.
917
+ // EVM-only: skip non-EVM (Solana/Stellar) vault addresses.
918
+ if (chainId) {
919
+ const vaultsPerChain = allVaults.filter((v) => v.chain === chainId && (0, ethers_1.isAddress)(v.address));
920
+ const vaultResponses = await Promise.all(vaultsPerChain.map((v) => fetchVaultHistory(v.address, v.chain)));
921
+ const flattened = vaultResponses.flat();
922
+ finalArray = flattened;
923
+ }
924
+ else {
925
+ // Else, fetch all history for all vaults across all initialized chains.
926
+ // Gate on isAddress(v.address): the Solana provider is registered under
927
+ // chainId -1, so without this a Solana vault passes `providers?.[v.chain]`
928
+ // and gets routed into the EVM subgraph path, throwing
929
+ // "eth_chainId is not available on SOLANA_MAINNET" on every fetch.
930
+ // LayerZero vaults query subgraphs directly and don't need a provider.
931
+ const vaultsPerAvailableProviders = allVaults.filter((v) => (0, ethers_1.isAddress)(v.address) &&
932
+ (this.providers?.[v?.chain] || (0, deposits_1.isLayerZeroVault)(v.address)));
933
+ const vaultResponses = await Promise.all(vaultsPerAvailableProviders.map((v) => fetchVaultHistory(v.address, v.chain)));
934
+ const flattened = vaultResponses.flat();
935
+ finalArray = flattened;
936
+ }
937
+ }
938
+ core_1.Logger.log.info('getUserHistory', `${wallet}::${finalArray.length}`);
939
+ return finalArray;
940
+ }
941
+ /**
942
+ * Get lifetime PnL for a user in a specific vault.
943
+ * @param props Vault address, wallet address, and optional chain ID
944
+ * @returns Lifetime PnL data including realized and unrealized PnL
945
+ * @throws {@link UpshiftHistoryUnavailableError} (`HISTORY_UNAVAILABLE`) when a
946
+ * live position has no indexed deposits, withdrawals or priceable share
947
+ * transfers.
948
+ * @throws {@link UpshiftPriceUnavailableError} (`PRICE_UNAVAILABLE`) when the
949
+ * vault's underlying asset has no USD price.
950
+ */
951
+ async getVaultUserLifetimePnl({ vault, wallet, chainId, }) {
952
+ if (!(0, ethers_1.isAddress)(wallet))
953
+ throw new Error(`Wallet parameter is not an address: ${String(wallet)}`);
954
+ if (!(0, ethers_1.isAddress)(vault) && !(0, utils_2.isStellarAddress)(vault))
955
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
956
+ const { getVaultUserLifetimePnl } = await Promise.resolve().then(() => __importStar(require('./getters')));
957
+ return await getVaultUserLifetimePnl({
958
+ vault,
959
+ wallet,
960
+ options: {
961
+ rpcUrl: chainId
962
+ ? this.providers?.[chainId]
963
+ : this.requireActiveNetwork().rpcUrl,
964
+ solanaService: this.solanaService,
965
+ stellarRpc: this._stellarRpc,
966
+ env: this.monitoring?.env,
967
+ upshiftKey: this.keys?.upshift,
968
+ subgraphKey: this.keys?.graph,
969
+ headers: this.headers,
970
+ },
971
+ coingeckoKey: this.keys?.coingecko,
972
+ });
973
+ }
974
+ /**
975
+ * Get PnL for a vault (vault-level, not user-specific).
976
+ * Returns the vault's overall profit and loss across all users.
977
+ * @param props Vault address and optional chain ID
978
+ * @returns Vault PnL in USD and notional value
979
+ */
980
+ async getVaultPnl({ vault, chainId, }) {
981
+ if (!(0, ethers_1.isAddress)(vault))
982
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
983
+ const { getVaultPnl } = await Promise.resolve().then(() => __importStar(require('./getters')));
984
+ return await getVaultPnl({
985
+ vault,
986
+ options: {
987
+ rpcUrl: chainId
988
+ ? this.providers?.[chainId]
989
+ : this.requireActiveNetwork().rpcUrl,
990
+ solanaService: this.solanaService,
991
+ stellarRpc: this._stellarRpc,
992
+ env: this.monitoring?.env,
993
+ upshiftKey: this.keys?.upshift,
994
+ subgraphKey: this.keys?.graph,
995
+ headers: this.headers,
996
+ },
997
+ });
998
+ }
999
+ /**
1000
+ *
1001
+ */
1002
+ async getUserTransfers({ wallet, chainId, vault, options, }) {
1003
+ // Santize
1004
+ // if (!this.authorized) throw new Error('Not authorized.');
1005
+ if (!(0, ethers_1.isAddress)(wallet))
1006
+ throw new Error(`Wallet parameter is not an address: ${String(wallet)}`);
1007
+ // Format history initialization
1008
+ let finalArray = [];
1009
+ function formatTransfers(transfers) {
1010
+ return transfers.map((t) => ({
1011
+ id: t.id,
1012
+ value: t.value,
1013
+ to: t.to,
1014
+ from: t.from,
1015
+ pool: t.contractId_,
1016
+ block: Number(t.block_number),
1017
+ timestamp: Number(t.timestamp_),
1018
+ transactionHash: t.transactionHash_,
1019
+ }));
1020
+ }
1021
+ // If vault is provided, return history for that vault. Resolve the chain
1022
+ // the same way getUserHistory does: explicit chainId, else the active
1023
+ // network — a bare `this.providers?.[chainId]` with chainId undefined
1024
+ // indexed nothing and threw "no RPC URL provided".
1025
+ if (vault) {
1026
+ const _chainId = chainId || this.activeNetwork?.chainId;
1027
+ const provider = (0, core_1.createProvider)(this.providers?.[_chainId]);
1028
+ const userHistory = await (0, vaults_1.getSubgraphUserTransfers)(wallet, provider, vault);
1029
+ finalArray = formatTransfers(userHistory);
1030
+ }
1031
+ else {
1032
+ // Fetch all vaults
1033
+ const allVaults = await (0, core_1.fetchTokenizedVaults)(undefined, this.headers, false, false);
1034
+ // If chainId is provided, return history for all vaults on that chain
1035
+ if (chainId) {
1036
+ const vaultsPerChain = allVaults.filter((v) => v.chain === chainId);
1037
+ const vaultResponses = await Promise.all(vaultsPerChain.map(async (v) => {
1038
+ const provider = (0, core_1.createProvider)(this.providers?.[v.chain]);
1039
+ const userHistory = await (0, vaults_1.getSubgraphUserTransfers)(wallet, provider, v.address);
1040
+ return userHistory;
1041
+ }));
1042
+ const flattened = vaultResponses.flat();
1043
+ finalArray = formatTransfers(flattened);
1044
+ }
1045
+ else {
1046
+ // Else, fetch all history for all vaults across all initialized chains
1047
+ const vaultsPerAvailableProviders = allVaults.filter((v) => this.providers?.[v?.chain] ? true : false);
1048
+ const vaultResponses = await Promise.all(vaultsPerAvailableProviders.map(async (v) => {
1049
+ const provider = (0, core_1.createProvider)(this.providers?.[v.chain]);
1050
+ const userHistory = await (0, vaults_1.getSubgraphUserTransfers)(wallet, provider, v.address);
1051
+ return userHistory;
1052
+ }));
1053
+ const flattened = vaultResponses.flat();
1054
+ finalArray = formatTransfers(flattened);
1055
+ }
1056
+ }
1057
+ core_1.Logger.log.info('getUserTransfers', `${wallet}::${finalArray.length}`);
1058
+ return finalArray;
1059
+ }
1060
+ /**
1061
+ * Fetch a vault's deposit/withdrawal activity across every participant.
1062
+ *
1063
+ * This is the vault-wide counterpart to {@link getUserHistory}: instead of
1064
+ * filtering the subgraph to one wallet, it returns every deposit,
1065
+ * withdrawal-request, and processed-withdrawal event for the pool. Use it to
1066
+ * answer flow questions ("how many deposits in the last 7 days", "net flow
1067
+ * this week") that point-in-time TVL cannot.
1068
+ *
1069
+ * Rows are read from the Goldsky subgraph, paginated internally so busy
1070
+ * vaults are not truncated at the 1000-row page cap. When `sinceTs` is
1071
+ * supplied the reader stops paging once it passes the window boundary, so a
1072
+ * short lookback stays cheap even on high-volume vaults.
1073
+ *
1074
+ * @param params - Query parameters.
1075
+ * @param params.vault - Vault (pool) address to read activity for.
1076
+ * @param params.chainId - Chain id of the vault; falls back to the active
1077
+ * network when omitted. Required for the subgraph lookup.
1078
+ * @param params.sinceTs - Lower bound (inclusive) as a Unix timestamp in
1079
+ * seconds. Events at or after this time are returned.
1080
+ * @param params.untilTs - Upper bound (inclusive) as a Unix timestamp in
1081
+ * seconds. Events at or before this time are returned.
1082
+ * @param params.types - Restrict to a subset of event types (e.g.
1083
+ * `['deposit']`). Returns all types when omitted.
1084
+ * @returns Activity items sorted oldest-first, each with a normalized
1085
+ * `amount`, actor `address`, `type`, and `transactionHash`.
1086
+ * @throws If `vault` is not a valid address, or no chain id can be resolved.
1087
+ * @example
1088
+ * ```ts
1089
+ * const weekAgo = Math.floor(Date.now() / 1000) - 7 * 86_400;
1090
+ * const deposits = await sdk.getVaultActivity({
1091
+ * vault: '0x36eDbF0C834591BFdfCaC0Ef9605528c75c406aA',
1092
+ * chainId: 143,
1093
+ * sinceTs: weekAgo,
1094
+ * types: ['deposit'],
1095
+ * });
1096
+ * console.log(`${deposits.length} deposits in the last 7 days`);
1097
+ * ```
1098
+ */
1099
+ async getVaultActivity({ vault, chainId, sinceTs, untilTs, types, }) {
1100
+ if (!(0, ethers_1.isAddress)(vault))
1101
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1102
+ const _chainId = chainId || this.activeNetwork?.chainId;
1103
+ if (!_chainId) {
1104
+ throw new Error('Chain ID is required for getVaultActivity. Pass chainId explicitly or configure an active network.');
1105
+ }
1106
+ const provider = (0, core_1.createProvider)(this.providers?.[_chainId]);
1107
+ const raw = await (0, vaults_1.getSubgraphVaultHistory)(provider, vault, undefined, {
1108
+ sinceTs,
1109
+ });
1110
+ const typeFilter = types?.length ? new Set(types) : undefined;
1111
+ return raw
1112
+ .map((h) => ({
1113
+ timestamp: Number(h.timestamp_),
1114
+ address: h.address,
1115
+ amount: (0, core_1.toNormalizedBn)(BigInt(h.amount), h.decimals),
1116
+ pool: h.contractId_,
1117
+ chainId: _chainId,
1118
+ type: h.type,
1119
+ transactionHash: h.transactionHash_,
1120
+ }))
1121
+ .filter((h) => {
1122
+ if (sinceTs !== undefined && h.timestamp < sinceTs)
1123
+ return false;
1124
+ if (untilTs !== undefined && h.timestamp > untilTs)
1125
+ return false;
1126
+ if (typeFilter && !typeFilter.has(h.type))
1127
+ return false;
1128
+ return true;
1129
+ });
1130
+ }
1131
+ /**
1132
+ * Resolve the ERC-20 tokens currently whitelisted for the `SwapRouter` on a
1133
+ * chain — the any-token set a deposit UI can offer as swap-and-deposit inputs,
1134
+ * each verified `true` against the router's on-chain allowlist.
1135
+ *
1136
+ * Reconstructs the set from the router's `TokenEnabled` event history and
1137
+ * re-checks `whitelistedTokens(token)` for each (the mapping is not
1138
+ * enumerable). See {@link getSwapRouterWhitelistedTokens} for the full
1139
+ * two-stage behavior and RPC cost. Uses this instance's configured provider
1140
+ * for `chainId`; returns `[]` (no RPC) when no router is deployed there or no
1141
+ * provider is configured.
1142
+ *
1143
+ * @param chainId - EVM chain ID to resolve the allowlist for.
1144
+ * @param options - Optional `fromBlock` to override the deploy-block scan floor.
1145
+ * @returns Checksummed whitelisted token addresses; `[]` when unavailable.
1146
+ * Callers still exclude a target vault's natively-accepted assets (those
1147
+ * deposit without a swap).
1148
+ * @throws UpshiftSDKError when an `eth_getLogs` scan chunk fails.
1149
+ * @example
1150
+ * ```ts
1151
+ * const tokens = await upshiftSdk.getSwapRouterWhitelistedTokens(1);
1152
+ * ```
1153
+ */
1154
+ async getSwapRouterWhitelistedTokens(chainId, options) {
1155
+ if (!(0, core_1.getSwapRouterAddress)(chainId))
1156
+ return [];
1157
+ const rpcUrl = this.providers?.[chainId];
1158
+ if (!rpcUrl) {
1159
+ core_1.Logger.log.warn('getSwapRouterWhitelistedTokens', `no provider configured for chain ${chainId}`);
1160
+ return [];
1161
+ }
1162
+ return (0, core_1.getSwapRouterWhitelistedTokens)(chainId, {
1163
+ rpcUrl,
1164
+ fromBlock: options?.fromBlock,
1165
+ });
1166
+ }
1167
+ /**
1168
+ * Resolve the vaults that offer the any-token `SwapRouter` deposit surface
1169
+ * (swap tokens) on a chain — every vault the Upshift API marks
1170
+ * `swaps_enabled`. See {@link getSwapRouterEligibleVaults}.
1171
+ *
1172
+ * Returns `[]` (no request) when no router is deployed on `chainId`. App-level
1173
+ * policy (e.g. excluding vaults with their own OVault deposit flow) remains
1174
+ * the caller's responsibility.
1175
+ *
1176
+ * @param chainId - EVM chain ID to resolve eligible vaults for.
1177
+ * @param options - Kept for compatibility; `fromBlock` is no longer read.
1178
+ * @returns Checksummed `swaps_enabled` vault addresses; `[]` when unavailable.
1179
+ * @throws When the Upshift API vault-list request fails.
1180
+ * @example
1181
+ * ```ts
1182
+ * const vaults = await upshiftSdk.getSwapRouterEligibleVaults(1);
1183
+ * ```
1184
+ */
1185
+ async getSwapRouterEligibleVaults(chainId, options) {
1186
+ return (0, core_1.getSwapRouterEligibleVaults)(chainId, options);
1187
+ }
1188
+ /**
1189
+ * Read a SwapRouter origin code's on-chain registration through this
1190
+ * instance's provider for `chainId`. See {@link getOriginInfo} for the
1191
+ * registration rule and caching.
1192
+ *
1193
+ * @param options - `chainId` and the `bytes32` `originCode` to look up.
1194
+ * @returns {@link IOriginInfo}.
1195
+ * @throws UpshiftValidationError (`INVALID_CHAIN`) when no provider is
1196
+ * configured for `chainId`; (`INVALID_INPUT`) for a malformed code.
1197
+ * @throws UpshiftSDKError when the `origins(bytes32)` read fails.
1198
+ * @worstCaseRpcCalls 1 — one `origins(bytes32)` read, cached for 5 minutes.
1199
+ * @example
1200
+ * ```ts
1201
+ * const info = await upshiftSdk.getOriginInfo({ chainId: 1, originCode });
1202
+ * ```
1203
+ */
1204
+ async getOriginInfo(options) {
1205
+ (0, core_1.assertEvmProviderConfigured)(options.chainId, this.providers, 'getOriginInfo');
1206
+ return (0, core_1.getOriginInfo)({
1207
+ ...options,
1208
+ rpcUrl: this.providers[options.chainId],
1209
+ });
1210
+ }
1211
+ /**
1212
+ * @function getStakingPositions gets all available reward staking positions
1213
+ * @param wallet optionally passed user wallet address
1214
+ * @param chainId optionally passed chainId
1215
+ * @returns all available staking positions for connected or passed network(s)
1216
+ */
1217
+ async getStakingPositions(wallet, chainId) {
1218
+ if (chainId) {
1219
+ const positions = await (0, getters_1.getRewardsStakingPositions)({
1220
+ rpcUrl: this.providers?.[chainId] || this.requireActiveNetwork().rpcUrl,
1221
+ wallet,
1222
+ });
1223
+ return positions;
1224
+ }
1225
+ const positions = await Promise.all(Object.values(this.providers).map((rpcUrl) => {
1226
+ return (0, getters_1.getRewardsStakingPositions)({
1227
+ rpcUrl: chainId
1228
+ ? this.providers?.[chainId]
1229
+ : rpcUrl || this.requireActiveNetwork().rpcUrl,
1230
+ wallet,
1231
+ });
1232
+ }));
1233
+ return positions.flat();
1234
+ }
1235
+ /**
1236
+ * @function getVaultTvl gets the vault/pool TVL, both current and historical
1237
+ * @param vault pool/vault contract address
1238
+ * @param historical (optional) When passed, returns the historical records of the pool/vault TVL
1239
+ * @returns an object or array of objects containing the TVL and timestamp
1240
+ */
1241
+ async getVaultTvl({ vault, chainId, historical, }) {
1242
+ if (!this.authorized)
1243
+ throw new Error('Not authorized.');
1244
+ if (!vault)
1245
+ throw new Error('Pool input parameter is undefined.');
1246
+ if (!(0, ethers_1.isAddress)(vault) && !(0, utils_2.isStellarAddress)(vault))
1247
+ throw new Error(`Pool input parameter is not an address: ${String(vault)}`);
1248
+ const resolvedChainId = chainId ?? this.activeNetwork?.chainId;
1249
+ const rpcUrl = chainId
1250
+ ? this.providers?.[chainId]
1251
+ : this.activeNetwork?.rpcUrl;
1252
+ return await (0, getters_1.getVaultTvl)({
1253
+ vault,
1254
+ options: {
1255
+ rpcUrl: rpcUrl,
1256
+ chainId: resolvedChainId,
1257
+ solanaService: this.solanaService,
1258
+ stellarRpc: this._stellarRpc,
1259
+ env: this.monitoring?.env,
1260
+ upshiftKey: this.keys?.upshift,
1261
+ subgraphKey: this.keys?.graph,
1262
+ headers: this.headers,
1263
+ },
1264
+ historical: historical,
1265
+ });
1266
+ }
1267
+ /**
1268
+ * @function getYieldLastRealizedOn gets the timestamp when yield was last realized for a vault
1269
+ * @param vault Vault contract address
1270
+ * @param chainId Optional chain ID (uses active network if not provided)
1271
+ * @returns Timestamp (Unix timestamp in seconds) when yield was last realized
1272
+ */
1273
+ async getYieldLastRealizedOn({ vault, chainId, }) {
1274
+ const rpcUrl = chainId
1275
+ ? this.providers?.[chainId]
1276
+ : this.activeNetwork?.rpcUrl;
1277
+ return await (0, getters_1.getYieldLastRealizedOn)({
1278
+ vault,
1279
+ options: {
1280
+ rpcUrl: rpcUrl,
1281
+ solanaService: this.solanaService,
1282
+ stellarRpc: this._stellarRpc,
1283
+ env: this.monitoring?.env,
1284
+ upshiftKey: this.keys?.upshift,
1285
+ subgraphKey: this.keys?.graph,
1286
+ headers: this.headers,
1287
+ },
1288
+ });
1289
+ }
1290
+ /**
1291
+ * Gets borrower health-factor data for vaults on a chain, optionally
1292
+ * scoped to a single vault.
1293
+ *
1294
+ * Pass `vault` whenever the caller knows which pool it cares about —
1295
+ * this skips the all-vaults cross-chain fanout and only reads the loans
1296
+ * for that one pool. The response map is keyed by **lowercased** vault
1297
+ * address; look entries up with `address.toLowerCase()`.
1298
+ *
1299
+ * Individual loan failures (bad/test loan contracts, unrecognized
1300
+ * borrowers) are isolated and logged rather than rejecting the batch.
1301
+ *
1302
+ * @param chainId Optional chain to scope the read to. When omitted,
1303
+ * iterates the SDK's configured providers and returns the flattened
1304
+ * list (legacy shape — prefer passing a chain).
1305
+ * @param vault Optional vault address. When provided alongside
1306
+ * `chainId`, only that vault's data is fetched.
1307
+ * @returns When `chainId` is set, an object map of lowercased vault
1308
+ * address → array of borrower-health-factor rows. When `chainId` is
1309
+ * omitted, a flat array (legacy behavior, kept for backward compat).
1310
+ */
1311
+ async getVaultBorrowerHealthFactor(chainId, vault) {
1312
+ if (chainId) {
1313
+ const health_factors = await (0, getters_1.getHealthFactorOfBorrowersByVault)({
1314
+ options: {
1315
+ rpcUrl: this.providers?.[chainId] || this.requireActiveNetwork().rpcUrl,
1316
+ env: this.monitoring?.env,
1317
+ upshiftKey: this.keys?.upshift,
1318
+ },
1319
+ vault,
1320
+ });
1321
+ return health_factors;
1322
+ }
1323
+ const health_factors = await Promise.all(Object.values(this.providers).map((rpcUrl) => {
1324
+ return (0, getters_1.getHealthFactorOfBorrowersByVault)({
1325
+ options: {
1326
+ rpcUrl: chainId
1327
+ ? this.providers?.[chainId]
1328
+ : rpcUrl || this.requireActiveNetwork().rpcUrl,
1329
+ solanaService: this.solanaService,
1330
+ stellarRpc: this._stellarRpc,
1331
+ env: this.monitoring?.env,
1332
+ upshiftKey: this.keys?.upshift,
1333
+ subgraphKey: this.keys?.graph,
1334
+ headers: this.headers,
1335
+ },
1336
+ vault,
1337
+ });
1338
+ }));
1339
+ return health_factors.flat();
1340
+ }
1341
+ /**
1342
+ * @function getUserPoints fetches user points from the backend API
1343
+ * @param userAddress User wallet address
1344
+ * @returns Points data from the backend API
1345
+ */
1346
+ async getUserPoints(userAddress) {
1347
+ const { getUserPoints } = await Promise.resolve().then(() => __importStar(require('./getters')));
1348
+ return await getUserPoints({
1349
+ userAddress,
1350
+ options: {
1351
+ rpcUrl: this.requireActiveNetwork().rpcUrl,
1352
+ env: this.monitoring?.env,
1353
+ upshiftKey: this.keys?.upshift,
1354
+ subgraphKey: this.keys?.graph,
1355
+ headers: this.headers,
1356
+ },
1357
+ });
1358
+ }
1359
+ /**
1360
+ * Register a user for the points program, authenticated by a wallet signature.
1361
+ *
1362
+ * The caller produces a personal_sign signature over a canonical message
1363
+ * built from these primitives — see `registerUserForPoints` in
1364
+ * `./getters` for the exact template and a worked example.
1365
+ *
1366
+ * @param userAddress EVM wallet address being registered.
1367
+ * @param referrerAddress Optional referrer EVM address.
1368
+ * @param chainId Chain on which the wallet signed; powers the EIP-1271
1369
+ * fallback for smart-contract wallets and pins the signature cross-chain.
1370
+ * @param signature 0x-prefixed hex personal_sign signature over the canonical message.
1371
+ * @param nonce Single-use random string (8–128 chars).
1372
+ * @param expiry Unix seconds; must be in the future, within the backend's TTL.
1373
+ * @returns Raw `Response` from the backend.
1374
+ */
1375
+ async registerUserForPoints(userAddress, referrerAddress, chainId, signature, nonce, expiry) {
1376
+ const { registerUserForPoints } = await Promise.resolve().then(() => __importStar(require('./getters')));
1377
+ return await registerUserForPoints({
1378
+ userAddress,
1379
+ referrerAddress,
1380
+ chainId,
1381
+ signature,
1382
+ nonce,
1383
+ expiry,
1384
+ options: {
1385
+ rpcUrl: this.requireActiveNetwork().rpcUrl,
1386
+ env: this.monitoring?.env,
1387
+ upshiftKey: this.keys?.upshift,
1388
+ subgraphKey: this.keys?.graph,
1389
+ headers: this.headers,
1390
+ },
1391
+ });
1392
+ }
1393
+ /**
1394
+ * @function fetchPointsLeaderboard fetches the points leaderboard data
1395
+ * @param params Optional parameters for pagination and sorting
1396
+ * @returns Leaderboard response data
1397
+ */
1398
+ async fetchPointsLeaderboard(params) {
1399
+ const { fetchPointsLeaderboard } = await Promise.resolve().then(() => __importStar(require('./getters')));
1400
+ return await fetchPointsLeaderboard({
1401
+ params,
1402
+ options: {
1403
+ rpcUrl: this.requireActiveNetwork().rpcUrl,
1404
+ env: this.monitoring?.env,
1405
+ upshiftKey: this.keys?.upshift,
1406
+ subgraphKey: this.keys?.graph,
1407
+ headers: this.headers,
1408
+ },
1409
+ });
1410
+ }
1411
+ /**
1412
+ * Get annualized APY metrics for a vault.
1413
+ *
1414
+ * Supported Vaults: cUSDO, tETH, wstETH, rsETH
1415
+ *
1416
+ * @deprecated The `hgETH30dLiquidAPY` and `hgETH7dLiquidAPY` response fields are deprecated.
1417
+ * These fields will be removed in the next major release.
1418
+ * Use `liquidAPY30Day` and `liquidAPY7Day` fields instead.
1419
+ *
1420
+ * @param vault Vault address
1421
+ * @returns Annualized APY data including liquidity APY
1422
+ */
1423
+ async getVaultAnnualizedApy(vault) {
1424
+ if (!vault)
1425
+ throw new Error('Vault address parameter is undefined.');
1426
+ if (!(0, ethers_1.isAddress)(vault)) {
1427
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1428
+ }
1429
+ const { getVaultAnnualizedApy } = await Promise.resolve().then(() => __importStar(require('./getters')));
1430
+ return await getVaultAnnualizedApy({
1431
+ vault,
1432
+ options: {
1433
+ rpcUrl: this.requireActiveNetwork().rpcUrl,
1434
+ env: this.monitoring?.env,
1435
+ upshiftKey: this.keys?.upshift,
1436
+ subgraphKey: this.keys?.graph,
1437
+ headers: this.headers,
1438
+ },
1439
+ });
1440
+ }
1441
+ /**
1442
+ * Get summary data for a vault (name, type, chain, recent returns).
1443
+ * @param vault Vault address
1444
+ * @returns Vault summary data
1445
+ */
1446
+ async getVaultSummary(vault) {
1447
+ if (!vault)
1448
+ throw new Error('Vault address parameter is undefined.');
1449
+ if (!(0, ethers_1.isAddress)(vault)) {
1450
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1451
+ }
1452
+ const { getVaultSummary } = await Promise.resolve().then(() => __importStar(require('./getters')));
1453
+ return await getVaultSummary({
1454
+ vault,
1455
+ options: {
1456
+ rpcUrl: this.requireActiveNetwork().rpcUrl,
1457
+ env: this.monitoring?.env,
1458
+ upshiftKey: this.keys?.upshift,
1459
+ subgraphKey: this.keys?.graph,
1460
+ headers: this.headers,
1461
+ },
1462
+ });
1463
+ }
1464
+ /**
1465
+ * Get withdrawal summary and pending queue for a vault.
1466
+ * @param vault Vault address
1467
+ * @param chainId Chain ID (will be converted to chain name)
1468
+ * @returns Withdrawal summary and pending queue
1469
+ */
1470
+ async getVaultWithdrawals(vault, chainId) {
1471
+ if (!vault)
1472
+ throw new Error('Vault address parameter is undefined.');
1473
+ if (!(0, ethers_1.isAddress)(vault)) {
1474
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1475
+ }
1476
+ const chain = chainId?.toString() || this.requireActiveNetwork().chainId.toString();
1477
+ const { getVaultWithdrawals } = await Promise.resolve().then(() => __importStar(require('./getters')));
1478
+ return await getVaultWithdrawals({
1479
+ vault,
1480
+ chain,
1481
+ options: {
1482
+ rpcUrl: this.requireActiveNetwork().rpcUrl,
1483
+ env: this.monitoring?.env,
1484
+ upshiftKey: this.keys?.upshift,
1485
+ subgraphKey: this.keys?.graph,
1486
+ headers: this.headers,
1487
+ },
1488
+ });
1489
+ }
1490
+ /**
1491
+ * Fetch pending redemptions for a vault with liquidity analysis.
1492
+ * @param vault - Vault contract address
1493
+ * @param pastDays - Number of past days to include (default 7, min 1, max 30)
1494
+ * @param futureDays - Number of future days to include (default 14, min 1, max 30)
1495
+ * @returns Pending redemptions grouped by date with liquidity summary
1496
+ */
1497
+ async getVaultPendingRedemptions({ vault, pastDays, futureDays, }) {
1498
+ if (!vault)
1499
+ throw new Error('Vault address parameter is undefined.');
1500
+ if (!(0, ethers_1.isAddress)(vault))
1501
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1502
+ const { getVaultPendingRedemptions } = await Promise.resolve().then(() => __importStar(require('./getters')));
1503
+ return await getVaultPendingRedemptions({
1504
+ vault,
1505
+ pastDays,
1506
+ futureDays,
1507
+ options: {
1508
+ rpcUrl: this.requireActiveNetwork().rpcUrl,
1509
+ env: this.monitoring?.env,
1510
+ upshiftKey: this.keys?.upshift,
1511
+ subgraphKey: this.keys?.graph,
1512
+ headers: this.headers,
1513
+ },
1514
+ });
1515
+ }
1516
+ /**
1517
+ * Preview the amount of assets that would be received for redeeming shares (queued redemption).
1518
+ * @param vault Vault contract address
1519
+ * @param sharesAmount Amount of shares to redeem (human-readable, raw bigint, or string)
1520
+ * @param chainId Optional chain ID (uses active network if not provided)
1521
+ * @returns The amount of assets as INormalizedNumber { normalized, raw }
1522
+ */
1523
+ async previewRedemption({ vault, sharesAmount, chainId, }) {
1524
+ const rpcUrl = chainId
1525
+ ? this.providers?.[chainId]
1526
+ : this.requireActiveNetwork().rpcUrl;
1527
+ return await (0, getters_1.getPreviewRedemption)({
1528
+ vault,
1529
+ sharesAmount,
1530
+ options: {
1531
+ rpcUrl,
1532
+ headers: this.headers,
1533
+ },
1534
+ });
1535
+ }
1536
+ /**
1537
+ * Get all withdrawal requests for a vault with deterministic status tracking.
1538
+ *
1539
+ * Matches requests to processed events by `(receiver, claimableDate)` tuple.
1540
+ *
1541
+ * **Status values:**
1542
+ * - `'processed'` — Matching `WithdrawalProcessed` event found on-chain.
1543
+ * - `'ready_to_claim'` — Claimable date has passed, no processed event found yet.
1544
+ * - `'pending'` — Claimable date is still in the future.
1545
+ *
1546
+ * **Lookback window:** Processed events are fetched from on-chain logs, which
1547
+ * only cover a finite block range. Requests whose claimable date is older than
1548
+ * this window with no matching processed event are excluded (assumed already
1549
+ * processed). Use `lookbackBlocks` to widen or narrow the scan range.
1550
+ *
1551
+ * @param vault - Vault contract address
1552
+ * @param receiver - Optional receiver address to filter by
1553
+ * @param lookbackBlocks - Optional on-chain log lookback window in blocks.
1554
+ * Defaults to chain-specific value (e.g. 150,000 for Ethereum, 3,456,000 for Monad).
1555
+ * @param chainId - Optional chain id for the vault address
1556
+ * @returns Array of withdrawal requests with status and claimable dates
1557
+ */
1558
+ async getWithdrawalRequestsWithStatus(vault, receiver, lookbackBlocks, chainId) {
1559
+ if (!vault)
1560
+ throw new Error('Vault address parameter is undefined.');
1561
+ if (!(0, ethers_1.isAddress)(vault)) {
1562
+ throw new Error(`Vault parameter is not an address: ${String(vault)}`);
1563
+ }
1564
+ const rpcUrl = (chainId && this.providers?.[chainId]) ||
1565
+ this.requireActiveNetwork().rpcUrl;
1566
+ const { getWithdrawalRequestsWithStatus } = await Promise.resolve().then(() => __importStar(require('./getters')));
1567
+ return await getWithdrawalRequestsWithStatus({
1568
+ vault,
1569
+ receiver,
1570
+ lookbackBlocks,
1571
+ options: {
1572
+ rpcUrl,
1573
+ env: this.monitoring?.env,
1574
+ upshiftKey: this.keys?.upshift,
1575
+ subgraphKey: this.keys?.graph,
1576
+ headers: this.headers,
1577
+ },
1578
+ });
1579
+ }
1580
+ /**
1581
+ * Redeem vault shares for an underlying asset via instant redemption (RWA subaccount).
1582
+ * Resolves the vault address to the RwaRedeemSubaccount internally.
1583
+ * Handles vault share approval automatically.
1584
+ * @param signer - Signer / wallet object
1585
+ * @param vault - Vault contract address
1586
+ * @param asset - Redeemable asset address (e.g. USDC, USDT)
1587
+ * @param amount - Amount of vault shares to redeem
1588
+ * @param minOut - Minimum output amount in output asset units (slippage protection)
1589
+ * @param chainId - Optional chain ID (uses active network if not provided)
1590
+ * @param wait - Wait for transaction confirmation
1591
+ * @returns transaction hash
1592
+ */
1593
+ async rwaRedeemAsset(signer, { vault, asset, amount, minOut, chainId, wait, }) {
1594
+ if (!vault)
1595
+ throw new Error('Vault address parameter is undefined.');
1596
+ // Fetch vault data to resolve subaccount address and decimals
1597
+ const vaultData = await (0, getters_1.getVault)({
1598
+ vault,
1599
+ loans: false,
1600
+ allocations: false,
1601
+ options: {
1602
+ rpcUrl: chainId ? this.providers?.[chainId] : this.activeNetwork.rpcUrl,
1603
+ solanaService: this.solanaService,
1604
+ stellarRpc: this._stellarRpc,
1605
+ env: this.monitoring?.env,
1606
+ upshiftKey: this.keys?.upshift,
1607
+ subgraphKey: this.keys?.graph,
1608
+ headers: this.headers,
1609
+ },
1610
+ loadSnapshots: false,
1611
+ loadSubaccounts: false,
1612
+ });
1613
+ if (!vaultData?.instant_redeem_config) {
1614
+ throw new Error(`Vault ${vault} does not support instant redemption.`);
1615
+ }
1616
+ const { subaccountAddress, redeemableAssets } = vaultData.instant_redeem_config;
1617
+ // Resolve output asset decimals from config
1618
+ const redeemableAsset = redeemableAssets.find((a) => a.address.toLowerCase() === asset.toLowerCase());
1619
+ if (!redeemableAsset) {
1620
+ throw new Error(`Asset ${asset} is not redeemable for vault ${vault}.`);
1621
+ }
1622
+ const walletAddress = (await signer.getAddress());
1623
+ return (0, write_actions_1.rwaRedeemAsset)(signer, {
1624
+ target: subaccountAddress,
1625
+ wallet: walletAddress,
1626
+ asset,
1627
+ amount,
1628
+ minOut,
1629
+ decimals: vaultData.decimals,
1630
+ outputDecimals: redeemableAsset.decimals,
1631
+ wait,
1632
+ });
1633
+ }
1634
+ /**
1635
+ * Preview the output amount for an RWA instant redemption.
1636
+ * Resolves the vault address to the RwaRedeemSubaccount internally.
1637
+ * @param vault - Vault contract address
1638
+ * @param asset - Redeemable asset address (e.g. USDC, USDT)
1639
+ * @param amount - Amount of vault shares to preview
1640
+ * @param chainId - Optional chain ID (uses active network if not provided)
1641
+ * @returns normalized number of the expected output amount (in output asset decimals)
1642
+ */
1643
+ async previewRwaRedemption({ vault, asset, amount, chainId, }) {
1644
+ if (!vault)
1645
+ throw new Error('Vault address parameter is undefined.');
1646
+ const rpcUrl = chainId
1647
+ ? this.providers?.[chainId]
1648
+ : this.activeNetwork.rpcUrl;
1649
+ // Fetch vault data to resolve subaccount address and decimals
1650
+ const vaultData = await (0, getters_1.getVault)({
1651
+ vault,
1652
+ loans: false,
1653
+ allocations: false,
1654
+ options: {
1655
+ rpcUrl,
1656
+ solanaService: this.solanaService,
1657
+ stellarRpc: this._stellarRpc,
1658
+ env: this.monitoring?.env,
1659
+ upshiftKey: this.keys?.upshift,
1660
+ subgraphKey: this.keys?.graph,
1661
+ headers: this.headers,
1662
+ },
1663
+ loadSnapshots: false,
1664
+ loadSubaccounts: false,
1665
+ });
1666
+ if (!vaultData?.instant_redeem_config) {
1667
+ throw new Error(`Vault ${vault} does not support instant redemption.`);
1668
+ }
1669
+ const { subaccountAddress, redeemableAssets } = vaultData.instant_redeem_config;
1670
+ // Resolve output asset decimals from config
1671
+ const redeemableAsset = redeemableAssets.find((a) => a.address.toLowerCase() === asset.toLowerCase());
1672
+ if (!redeemableAsset) {
1673
+ throw new Error(`Asset ${asset} is not redeemable for vault ${vault}.`);
1674
+ }
1675
+ const provider = (0, core_1.createProvider)(rpcUrl);
1676
+ return (0, read_actions_1.previewRwaRedemption)(provider, {
1677
+ target: subaccountAddress,
1678
+ asset,
1679
+ amount,
1680
+ decimals: vaultData.decimals,
1681
+ outputDecimals: redeemableAsset.decimals,
1682
+ });
1683
+ }
1684
+ }
1685
+ exports.UpshiftVaults = UpshiftVaults;
1686
+ exports.default = UpshiftVaults;
1687
+ //# sourceMappingURL=main.js.map