@augustdigital/sdk 4.0.6-alpha → 4.0.6-beta

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 (246) hide show
  1. package/README.md +169 -11
  2. package/lib/abis/AddressResolver.d.ts +28 -0
  3. package/lib/abis/AddressResolver.js +23 -0
  4. package/lib/abis/AddressResolver.js.map +1 -0
  5. package/lib/abis/ChainlinkV3.d.ts +87 -0
  6. package/lib/abis/ChainlinkV3.js +117 -0
  7. package/lib/abis/ChainlinkV3.js.map +1 -0
  8. package/lib/abis/ERC20.d.ts +168 -0
  9. package/lib/abis/ERC20.js +226 -0
  10. package/lib/abis/ERC20.js.map +1 -0
  11. package/lib/abis/ERC20_Bytes32.d.ts +135 -0
  12. package/lib/abis/ERC20_Bytes32.js +192 -0
  13. package/lib/abis/ERC20_Bytes32.js.map +1 -0
  14. package/lib/abis/ERC4626.d.ts +363 -0
  15. package/lib/abis/ERC4626.js +506 -0
  16. package/lib/abis/ERC4626.js.map +1 -0
  17. package/lib/abis/ERC721.d.ts +230 -0
  18. package/lib/abis/ERC721.js +320 -0
  19. package/lib/abis/ERC721.js.map +1 -0
  20. package/lib/abis/FeeOracle.d.ts +120 -0
  21. package/lib/abis/FeeOracle.js +161 -0
  22. package/lib/abis/FeeOracle.js.map +1 -0
  23. package/lib/abis/LendingPool.d.ts +1393 -0
  24. package/lib/abis/LendingPool.js +1806 -0
  25. package/lib/abis/LendingPool.js.map +1 -0
  26. package/lib/abis/LendingPoolV2.d.ts +55 -0
  27. package/lib/abis/LendingPoolV2.js +1832 -0
  28. package/lib/abis/LendingPoolV2.js.map +1 -0
  29. package/lib/abis/LendingPoolV3.d.ts +35 -0
  30. package/lib/abis/LendingPoolV3.js +1160 -0
  31. package/lib/abis/LendingPoolV3.js.map +1 -0
  32. package/lib/abis/Loan.d.ts +837 -0
  33. package/lib/abis/Loan.js +1080 -0
  34. package/lib/abis/Loan.js.map +1 -0
  35. package/lib/abis/Multicall3.d.ts +30 -0
  36. package/lib/abis/Multicall3.js +94 -0
  37. package/lib/abis/Multicall3.js.map +1 -0
  38. package/lib/abis/PoolAdapter.d.ts +76 -0
  39. package/lib/abis/PoolAdapter.js +412 -0
  40. package/lib/abis/PoolAdapter.js.map +1 -0
  41. package/lib/abis/RewardDistributor.d.ts +46 -0
  42. package/lib/abis/RewardDistributor.js +352 -0
  43. package/lib/abis/RewardDistributor.js.map +1 -0
  44. package/lib/abis/SmartAccount.d.ts +16 -0
  45. package/lib/abis/SmartAccount.js +16 -0
  46. package/lib/abis/SmartAccount.js.map +1 -0
  47. package/lib/abis/TextResolver.d.ts +16 -0
  48. package/lib/abis/TextResolver.js +16 -0
  49. package/lib/abis/TextResolver.js.map +1 -0
  50. package/lib/abis/TokenizedVaultV2.d.ts +1354 -0
  51. package/lib/abis/TokenizedVaultV2.js +1028 -0
  52. package/lib/abis/TokenizedVaultV2.js.map +1 -0
  53. package/lib/abis/TokenizedVaultV2Receipt.d.ts +1568 -0
  54. package/lib/abis/TokenizedVaultV2Receipt.js +1061 -0
  55. package/lib/abis/TokenizedVaultV2Receipt.js.map +1 -0
  56. package/lib/abis/TokenizedVaultV2WhitelistedAssets.d.ts +274 -0
  57. package/lib/abis/TokenizedVaultV2WhitelistedAssets.js +167 -0
  58. package/lib/abis/TokenizedVaultV2WhitelistedAssets.js.map +1 -0
  59. package/lib/abis/UniversalResolverResolve.d.ts +69 -0
  60. package/lib/abis/UniversalResolverResolve.js +35 -0
  61. package/lib/abis/UniversalResolverResolve.js.map +1 -0
  62. package/lib/abis/UniversalSignatureValidator.d.ts +17 -0
  63. package/lib/abis/UniversalSignatureValidator.js +27 -0
  64. package/lib/abis/UniversalSignatureValidator.js.map +1 -0
  65. package/lib/abis/WrapperAdapter.d.ts +60 -0
  66. package/lib/abis/WrapperAdapter.js +150 -0
  67. package/lib/abis/WrapperAdapter.js.map +1 -0
  68. package/lib/abis/index.d.ts +22 -0
  69. package/lib/abis/index.js +39 -0
  70. package/lib/abis/index.js.map +1 -0
  71. package/lib/adapters/evm/getters.d.ts +4 -0
  72. package/lib/adapters/evm/getters.js +152 -0
  73. package/lib/adapters/evm/getters.js.map +1 -0
  74. package/lib/adapters/evm/index.d.ts +19 -0
  75. package/lib/adapters/evm/index.js +54 -0
  76. package/lib/adapters/evm/index.js.map +1 -0
  77. package/lib/adapters/evm/utils.d.ts +2 -0
  78. package/lib/adapters/evm/utils.js +43 -0
  79. package/lib/adapters/evm/utils.js.map +1 -0
  80. package/lib/adapters/solana/constants.d.ts +25 -0
  81. package/lib/adapters/solana/constants.js +32 -0
  82. package/lib/adapters/solana/constants.js.map +1 -0
  83. package/lib/adapters/solana/getters.d.ts +3 -0
  84. package/lib/adapters/solana/getters.js +135 -0
  85. package/lib/adapters/solana/getters.js.map +1 -0
  86. package/lib/adapters/solana/idl/vault-idl.d.ts +338 -0
  87. package/lib/adapters/solana/idl/vault-idl.js +1075 -0
  88. package/lib/adapters/solana/idl/vault-idl.js.map +1 -0
  89. package/lib/adapters/solana/index.d.ts +136 -0
  90. package/lib/adapters/solana/index.js +174 -0
  91. package/lib/adapters/solana/index.js.map +1 -0
  92. package/lib/adapters/solana/types.d.ts +58 -0
  93. package/lib/adapters/solana/types.js +3 -0
  94. package/lib/adapters/solana/types.js.map +1 -0
  95. package/lib/adapters/solana/utils.d.ts +104 -0
  96. package/lib/adapters/solana/utils.js +380 -0
  97. package/lib/adapters/solana/utils.js.map +1 -0
  98. package/lib/adapters/solana/vault.actions.d.ts +18 -0
  99. package/lib/adapters/solana/vault.actions.js +235 -0
  100. package/lib/adapters/solana/vault.actions.js.map +1 -0
  101. package/lib/adapters/sui/index.d.ts +0 -0
  102. package/lib/adapters/sui/index.js +1 -0
  103. package/lib/adapters/sui/index.js.map +1 -0
  104. package/lib/core/auth/index.d.ts +1 -0
  105. package/lib/core/auth/index.js +18 -0
  106. package/lib/core/auth/index.js.map +1 -0
  107. package/lib/{verify.js → core/auth/verify.js} +3 -2
  108. package/lib/core/auth/verify.js.map +1 -0
  109. package/lib/core/base.class.d.ts +33 -0
  110. package/lib/core/base.class.js +66 -0
  111. package/lib/core/base.class.js.map +1 -0
  112. package/lib/core/constants.core.d.ts +59 -0
  113. package/lib/core/constants.core.js +63 -0
  114. package/lib/core/constants.core.js.map +1 -0
  115. package/lib/core/constants.d.ts +88 -0
  116. package/lib/core/constants.js +148 -0
  117. package/lib/core/constants.js.map +1 -0
  118. package/lib/core/constants.vaults.d.ts +19 -0
  119. package/lib/core/constants.vaults.js +130 -0
  120. package/lib/core/constants.vaults.js.map +1 -0
  121. package/lib/core/constants.web3.d.ts +30 -0
  122. package/lib/core/constants.web3.js +89 -0
  123. package/lib/core/constants.web3.js.map +1 -0
  124. package/lib/core/core.helpers.d.ts +23 -0
  125. package/lib/core/core.helpers.js +210 -0
  126. package/lib/core/core.helpers.js.map +1 -0
  127. package/lib/core/fetcher.d.ts +22 -0
  128. package/lib/core/fetcher.js +374 -0
  129. package/lib/core/fetcher.js.map +1 -0
  130. package/lib/core/helpers.core.d.ts +23 -0
  131. package/lib/core/helpers.core.js +210 -0
  132. package/lib/core/helpers.core.js.map +1 -0
  133. package/lib/core/helpers.vaults.d.ts +15 -0
  134. package/lib/core/helpers.vaults.js +118 -0
  135. package/lib/core/helpers.vaults.js.map +1 -0
  136. package/lib/core/helpers.web3.d.ts +29 -0
  137. package/lib/core/helpers.web3.js +365 -0
  138. package/lib/core/helpers.web3.js.map +1 -0
  139. package/lib/core/index.d.ts +10 -0
  140. package/lib/core/index.js +27 -0
  141. package/lib/core/index.js.map +1 -0
  142. package/lib/core/logger/index.d.ts +21 -0
  143. package/lib/core/logger/index.js +80 -0
  144. package/lib/core/logger/index.js.map +1 -0
  145. package/lib/core/logger/slack.d.ts +12 -0
  146. package/lib/core/logger/slack.js +49 -0
  147. package/lib/core/logger/slack.js.map +1 -0
  148. package/lib/core/read.actions.d.ts +3 -0
  149. package/lib/core/read.actions.js +39 -0
  150. package/lib/core/read.actions.js.map +1 -0
  151. package/lib/core/vault.utils.d.ts +4 -0
  152. package/lib/core/vault.utils.js +35 -0
  153. package/lib/core/vault.utils.js.map +1 -0
  154. package/lib/core/web3.helpers.d.ts +29 -0
  155. package/lib/core/web3.helpers.js +365 -0
  156. package/lib/core/web3.helpers.js.map +1 -0
  157. package/lib/core/write.actions.d.ts +9 -0
  158. package/lib/core/write.actions.js +51 -0
  159. package/lib/core/write.actions.js.map +1 -0
  160. package/lib/index.d.ts +5 -6
  161. package/lib/index.js +13 -7
  162. package/lib/index.js.map +1 -1
  163. package/lib/main.d.ts +88 -14
  164. package/lib/main.js +54 -17
  165. package/lib/main.js.map +1 -1
  166. package/lib/modules/vaults/constants.d.ts +63 -0
  167. package/lib/modules/vaults/constants.js +186 -0
  168. package/lib/modules/vaults/constants.js.map +1 -0
  169. package/lib/modules/vaults/fetcher.d.ts +101 -0
  170. package/lib/modules/vaults/fetcher.js +257 -0
  171. package/lib/modules/vaults/fetcher.js.map +1 -0
  172. package/lib/modules/vaults/getters.d.ts +67 -0
  173. package/lib/modules/vaults/getters.js +900 -0
  174. package/lib/modules/vaults/getters.js.map +1 -0
  175. package/lib/modules/vaults/index.d.ts +3 -0
  176. package/lib/modules/vaults/index.js +20 -0
  177. package/lib/modules/vaults/index.js.map +1 -0
  178. package/lib/modules/vaults/main.d.ts +98 -0
  179. package/lib/modules/vaults/main.js +519 -0
  180. package/lib/modules/vaults/main.js.map +1 -0
  181. package/lib/modules/vaults/read.actions.d.ts +3 -0
  182. package/lib/modules/vaults/read.actions.js +39 -0
  183. package/lib/modules/vaults/read.actions.js.map +1 -0
  184. package/lib/modules/vaults/utils.d.ts +12 -0
  185. package/lib/modules/vaults/utils.js +170 -0
  186. package/lib/modules/vaults/utils.js.map +1 -0
  187. package/lib/modules/vaults/vault.actions.d.ts +10 -0
  188. package/lib/modules/vaults/vault.actions.js +95 -0
  189. package/lib/modules/vaults/vault.actions.js.map +1 -0
  190. package/lib/modules/vaults/write.actions.d.ts +17 -0
  191. package/lib/modules/vaults/write.actions.js +143 -0
  192. package/lib/modules/vaults/write.actions.js.map +1 -0
  193. package/lib/services/coingecko/fetcher.d.ts +1 -0
  194. package/lib/services/coingecko/fetcher.js +36 -0
  195. package/lib/services/coingecko/fetcher.js.map +1 -0
  196. package/lib/services/coingecko/index.d.ts +2 -0
  197. package/lib/services/coingecko/index.js +19 -0
  198. package/lib/services/coingecko/index.js.map +1 -0
  199. package/lib/services/coingecko/utils.d.ts +1 -0
  200. package/lib/services/coingecko/utils.js +24 -0
  201. package/lib/services/coingecko/utils.js.map +1 -0
  202. package/lib/services/debank/fetcher.d.ts +2 -0
  203. package/lib/services/debank/fetcher.js +16 -0
  204. package/lib/services/debank/fetcher.js.map +1 -0
  205. package/lib/services/debank/index.d.ts +2 -0
  206. package/lib/services/debank/index.js +19 -0
  207. package/lib/services/debank/index.js.map +1 -0
  208. package/lib/services/debank/utils.d.ts +32 -0
  209. package/lib/services/debank/utils.js +229 -0
  210. package/lib/services/debank/utils.js.map +1 -0
  211. package/lib/services/subgraph/fetcher.d.ts +2 -0
  212. package/lib/services/subgraph/fetcher.js +59 -0
  213. package/lib/services/subgraph/fetcher.js.map +1 -0
  214. package/lib/services/subgraph/index.d.ts +2 -0
  215. package/lib/services/subgraph/index.js +19 -0
  216. package/lib/services/subgraph/index.js.map +1 -0
  217. package/lib/services/subgraph/vaults.d.ts +10 -0
  218. package/lib/services/subgraph/vaults.js +471 -0
  219. package/lib/services/subgraph/vaults.js.map +1 -0
  220. package/lib/types/index.d.ts +8 -0
  221. package/lib/types/index.js +24 -0
  222. package/lib/types/index.js.map +1 -0
  223. package/lib/types/pools.d.ts +141 -0
  224. package/lib/types/pools.js +3 -0
  225. package/lib/types/pools.js.map +1 -0
  226. package/lib/types/staking.d.ts +28 -0
  227. package/lib/types/staking.js +3 -0
  228. package/lib/types/staking.js.map +1 -0
  229. package/lib/types/subgraph.d.ts +45 -0
  230. package/lib/types/subgraph.js +3 -0
  231. package/lib/types/subgraph.js.map +1 -0
  232. package/lib/types/user.d.ts +1 -0
  233. package/lib/types/user.js +3 -0
  234. package/lib/types/user.js.map +1 -0
  235. package/lib/types/vaults.d.ts +170 -0
  236. package/lib/types/vaults.js +3 -0
  237. package/lib/types/vaults.js.map +1 -0
  238. package/lib/types/web3.d.ts +24 -0
  239. package/lib/types/web3.js +3 -0
  240. package/lib/types/web3.js.map +1 -0
  241. package/lib/types/webserver.d.ts +489 -0
  242. package/lib/types/webserver.js +3 -0
  243. package/lib/types/webserver.js.map +1 -0
  244. package/package.json +16 -10
  245. package/lib/verify.js.map +0 -1
  246. /package/lib/{verify.d.ts → core/auth/verify.d.ts} +0 -0
@@ -0,0 +1,900 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.getVault = getVault;
40
+ exports.getVaultLoans = getVaultLoans;
41
+ exports.getVaultAllocations = getVaultAllocations;
42
+ exports.getVaultAvailableRedemptions = getVaultAvailableRedemptions;
43
+ exports.getVaultRedemptionHistory = getVaultRedemptionHistory;
44
+ exports.getVaultPositions = getVaultPositions;
45
+ exports.getVaultApy = getVaultApy;
46
+ exports.getRewardsStakingPositions = getRewardsStakingPositions;
47
+ exports.getVaultTvl = getVaultTvl;
48
+ exports.getVaultBorrowerHealthFactor = getVaultBorrowerHealthFactor;
49
+ exports.getHealthFactorOfBorrowersByVault = getHealthFactorOfBorrowersByVault;
50
+ const abis_1 = require("../../abis");
51
+ const core_1 = require("../../core");
52
+ const ethers_1 = require("ethers");
53
+ const subgraph_1 = require("../../services/subgraph");
54
+ const debank_1 = require("../../services/debank");
55
+ const solana_1 = require("../../adapters/solana");
56
+ const EVM = __importStar(require("../../adapters/evm"));
57
+ const TokenizedVaultV2_1 = require("../../abis/TokenizedVaultV2");
58
+ const TokenizedVaultV2Receipt_1 = require("../../abis/TokenizedVaultV2Receipt");
59
+ const ethereum_block_by_date_1 = __importDefault(require("ethereum-block-by-date"));
60
+ async function getVault({ vault, loans = false, allocations = false, options, }) {
61
+ let returnedVault;
62
+ const vaultVersion = (0, core_1.getVaultVersion)(vault);
63
+ try {
64
+ const tokenizedVault = (await (0, core_1.fetchTokenizedVaults)(vault))?.[0];
65
+ switch (vaultVersion) {
66
+ case 'sol-0': {
67
+ return await solana_1.Solana.getters.getSolanaVault(tokenizedVault, options);
68
+ }
69
+ case 'evm-2': {
70
+ returnedVault = await EVM.getEvmVaultV2(tokenizedVault, options);
71
+ break;
72
+ }
73
+ default: {
74
+ returnedVault = await EVM.getEvmVaultV1(tokenizedVault, options);
75
+ break;
76
+ }
77
+ }
78
+ if (returnedVault === null) {
79
+ return null;
80
+ }
81
+ }
82
+ catch (err) {
83
+ core_1.Logger.log.error('getVault', err, { vault, vaultVersion });
84
+ throw new Error(`#getVault::${vault}::${vaultVersion}: ${err?.message}`);
85
+ }
86
+ if (!(0, core_1.isBadVault)(vault)) {
87
+ if (loans) {
88
+ try {
89
+ returnedVault = {
90
+ ...returnedVault,
91
+ loans: await getVaultLoans(returnedVault, options),
92
+ };
93
+ }
94
+ catch (e) {
95
+ core_1.Logger.log.error('getVault:loans', e, {
96
+ symbol: returnedVault.receipt.symbol,
97
+ });
98
+ }
99
+ }
100
+ if (allocations) {
101
+ try {
102
+ const vaultAllocations = await getVaultAllocations(vault, options);
103
+ returnedVault = {
104
+ ...returnedVault,
105
+ allocations: vaultAllocations,
106
+ };
107
+ }
108
+ catch (e) {
109
+ core_1.Logger.log.error('getVault:allocations', e, {
110
+ symbol: returnedVault.receipt.symbol,
111
+ });
112
+ throw new Error('Failure fetching debank res');
113
+ }
114
+ }
115
+ }
116
+ return returnedVault;
117
+ }
118
+ async function getVaultLoans(vault, options) {
119
+ const vaultAddress = typeof vault === 'string' ? vault : vault.address;
120
+ const vaultVersion = (0, core_1.getVaultVersion)(vaultAddress);
121
+ if (vaultVersion !== 'evm-0')
122
+ return [];
123
+ try {
124
+ let poolTotalSupply;
125
+ let poolDecimals;
126
+ const tokenizedVault = (await (0, core_1.fetchTokenizedVaults)(vaultAddress, options?.headers))?.[0];
127
+ const chainId = options?.chainId || tokenizedVault?.chain;
128
+ const provider = (0, core_1.createProvider)(options.rpcUrl);
129
+ const tokenizedVaultLoans = await (0, core_1.fetchTokenizedVaultLoans)(vaultAddress, chainId);
130
+ if (typeof vault === 'string') {
131
+ const poolContract = (0, core_1.createContract)({
132
+ provider,
133
+ address: vaultAddress,
134
+ abi: abis_1.ABI_LENDING_POOL_V2,
135
+ });
136
+ [poolTotalSupply, poolDecimals] = await Promise.all([
137
+ poolContract.totalSupply(),
138
+ (0, core_1.getDecimals)(provider, vaultAddress),
139
+ ]);
140
+ poolTotalSupply = BigInt(poolTotalSupply).toString();
141
+ poolDecimals = Number(poolDecimals);
142
+ }
143
+ else {
144
+ poolTotalSupply = vault.totalSupply.raw;
145
+ poolDecimals = vault.decimals;
146
+ }
147
+ const newLoans = (await Promise.all((Array.isArray(tokenizedVaultLoans) ? tokenizedVaultLoans : [])?.map(async (l) => {
148
+ const borrower = l.borrower;
149
+ const allocation = l.principal_amount /
150
+ Number((0, ethers_1.formatUnits)(poolTotalSupply, poolDecimals));
151
+ const loanFeeRate = await (0, core_1.getLoanOracleFeeRate)(provider, 'LOAN.REPAY.INTERESTS', l.address, chainId);
152
+ const loanApr = Number(l.apr || 0) / 100;
153
+ const loanAprAfterFees = loanApr * (1 - loanFeeRate / 100);
154
+ const isIdleCapital = core_1.IDLE_CAPITAL_BORROWER_ADDRESS.includes(borrower);
155
+ const newLoanObj = {
156
+ vault: vaultAddress,
157
+ address: l.address,
158
+ lender: l.lender,
159
+ borrower: l.borrower,
160
+ state: l.state,
161
+ totalRepaid: l.total_repaid,
162
+ principalToken: l.principal_token,
163
+ principalAmount: l.principal_amount,
164
+ interestAmount: l.interest_amount,
165
+ upcomingPayment: {
166
+ amount: l.upcoming_payment.amount,
167
+ dueDate: l.upcoming_payment.due_date,
168
+ },
169
+ apr: loanAprAfterFees,
170
+ initialPrincipalAmount: l.initial_principal_amount,
171
+ deployedDate: l.deployed_date,
172
+ isIdleCapital,
173
+ paymentInterval: l.payment_interval,
174
+ allocation,
175
+ };
176
+ return newLoanObj;
177
+ }))).filter((l) => l !== undefined);
178
+ return newLoans;
179
+ }
180
+ catch (e) {
181
+ core_1.Logger.log.error('getVaultLoans', e, { vault });
182
+ throw new Error(`#getVaultLoans::${vault}:${e?.message}`);
183
+ }
184
+ }
185
+ async function getVaultAllocations(vault, options) {
186
+ let protocolExposure = [];
187
+ let tokenExposure = [];
188
+ let cefiExposure = [];
189
+ let cefiBorrowerResponses = {};
190
+ let otcPositions = {};
191
+ let defiPerBorrower = {};
192
+ let exposurePerCategory = {
193
+ supplying: [],
194
+ borrowing: [],
195
+ wallet: [],
196
+ walletBalance: 0,
197
+ cefiBalance: 0,
198
+ defiBalance: 0,
199
+ lending: [],
200
+ loanBalance: 0,
201
+ };
202
+ let netValue = { value: 0 };
203
+ let debankErr = false;
204
+ let unfilteredTokens = [];
205
+ let uniqueBorrowers;
206
+ const tokenizedVault = (await (0, core_1.fetchTokenizedVaults)(vault, options?.headers))?.[0];
207
+ try {
208
+ const vaultVersion = (0, core_1.getVaultVersion)(vault);
209
+ if (vaultVersion === 'evm-0') {
210
+ const loans = await getVaultLoans(vault, options);
211
+ uniqueBorrowers = [...new Set(loans.map((l) => l.borrower))];
212
+ }
213
+ else {
214
+ uniqueBorrowers = tokenizedVault.subaccounts.map((s) => s.address);
215
+ }
216
+ }
217
+ catch (e) {
218
+ core_1.Logger.log.error('getVaultAllocations:borrowers', e);
219
+ }
220
+ if (vault.toLowerCase() === core_1.VAULT_AgoraAUSD.toLowerCase()) {
221
+ const debankRes = await (0, debank_1.fetchDebankResponse)(core_1.SUBACCOUNT_CALEB);
222
+ if (debankRes === false) {
223
+ debankErr = true;
224
+ }
225
+ (0, debank_1.parseVaultLevelDebank)(debankRes, protocolExposure, tokenExposure, core_1.SUBACCOUNT_CALEB, exposurePerCategory, netValue);
226
+ unfilteredTokens = debankRes?.subaccount?.tokens;
227
+ const debankPerLoan = (0, debank_1.parseLoanLevelDebank)(debankRes);
228
+ defiPerBorrower[core_1.SUBACCOUNT_CALEB] = debankPerLoan;
229
+ }
230
+ else {
231
+ for (const borrower of uniqueBorrowers) {
232
+ try {
233
+ const debankRes = await (0, debank_1.fetchDebankResponse)(borrower);
234
+ if (debankRes === false) {
235
+ debankErr = true;
236
+ }
237
+ (0, debank_1.parseVaultLevelDebank)(debankRes, protocolExposure, tokenExposure, borrower, exposurePerCategory, netValue);
238
+ unfilteredTokens = debankRes?.subaccount?.tokens;
239
+ const debankPerLoan = (0, debank_1.parseLoanLevelDebank)(debankRes);
240
+ defiPerBorrower[borrower] = debankPerLoan;
241
+ }
242
+ catch (e) {
243
+ core_1.Logger.log.error('getVaultAllocations:debank', e, { borrower });
244
+ }
245
+ try {
246
+ const cefiResponse = await (0, core_1.fetchAugustWithKey)(options.augustKey, core_1.WEBSERVER_ENDPOINTS.subaccount.cefi(borrower), { headers: options?.headers });
247
+ if (cefiResponse.status !== 200) {
248
+ console.error('#getVaultAllocations::cefi:', cefiResponse.status, cefiResponse.statusText);
249
+ }
250
+ if (cefiResponse.status === 200) {
251
+ const cefiRes = (await cefiResponse.json());
252
+ cefiBorrowerResponses[borrower] = cefiRes;
253
+ cefiExposure = cefiRes;
254
+ }
255
+ }
256
+ catch (e) {
257
+ console.error('#getVaultAllocations::cefi:', e);
258
+ }
259
+ try {
260
+ const otcResponse = await (0, core_1.fetchAugustWithKey)(options.augustKey, core_1.WEBSERVER_ENDPOINTS.subaccount.otc_positions(borrower), { headers: options?.headers });
261
+ if (otcResponse.status !== 200) {
262
+ console.error('#getVaultAllocations::otc:', otcResponse.status, otcResponse.statusText);
263
+ }
264
+ if (otcResponse.status === 200) {
265
+ const otcRes = (await otcResponse.json());
266
+ otcPositions[borrower] = otcRes;
267
+ }
268
+ }
269
+ catch (e) {
270
+ console.error('#getVaultAllocations::otc:', e);
271
+ }
272
+ }
273
+ }
274
+ const walletBalance = exposurePerCategory.wallet.reduce((sum, item) => sum + item.amount, 0);
275
+ const defiBalance = protocolExposure.reduce((sum, item) => sum + item.netUsdValue, 0);
276
+ const cefiBalance = cefiExposure.reduce((sum, item) => sum + item.value, 0);
277
+ exposurePerCategory.walletBalance = walletBalance;
278
+ exposurePerCategory.defiBalance = defiBalance;
279
+ exposurePerCategory.cefiBalance = cefiBalance;
280
+ netValue.value += cefiBalance;
281
+ if (debankErr) {
282
+ throw Error('failure to fetch debank response');
283
+ }
284
+ return {
285
+ defi: protocolExposure,
286
+ cefi: cefiExposure,
287
+ otc: otcPositions,
288
+ tokens: tokenExposure,
289
+ defiPerBorrower,
290
+ exposurePerCategory,
291
+ netValue: netValue.value,
292
+ unfilteredTokens: unfilteredTokens,
293
+ };
294
+ }
295
+ async function getVaultAvailableRedemptions({ vault, wallet, options, }) {
296
+ try {
297
+ const provider = (0, core_1.createProvider)(options.rpcUrl);
298
+ const tokenizedVault = (await (0, core_1.fetchTokenizedVaults)(vault, options?.headers))?.[0];
299
+ if (!tokenizedVault) {
300
+ return { availableRedemptions: [], pendingRedemptions: [] };
301
+ }
302
+ const version = (0, core_1.getVaultVersion)(vault);
303
+ let abi;
304
+ let decimals;
305
+ switch (version) {
306
+ case 'evm-2': {
307
+ abi = TokenizedVaultV2_1.ABI_TOKENIZED_VAULT_V2;
308
+ decimals = await (0, core_1.getDecimals)(provider, await (0, core_1.getReceiptTokenAddress)(provider, vault));
309
+ break;
310
+ }
311
+ default: {
312
+ abi = abis_1.ABI_LENDING_POOL_V2;
313
+ decimals = await (0, core_1.getDecimals)(provider, vault);
314
+ break;
315
+ }
316
+ }
317
+ const vaultContract = (0, core_1.createContract)({
318
+ address: vault,
319
+ abi: abi,
320
+ provider,
321
+ });
322
+ const { withdrawalRequesteds, withdrawalProcesseds } = await (0, subgraph_1.getSubgraphAllWithdrawals)(vault, provider);
323
+ const availableRedemptions = [];
324
+ const pendingRedemptions = [];
325
+ for (const ev of withdrawalRequesteds) {
326
+ if (!ev || typeof ev !== 'object') {
327
+ core_1.Logger.log.warn('getVaultAvailableRedemptions', `Skipping invalid event: ${ev}`);
328
+ continue;
329
+ }
330
+ if (!ev.year || !ev.month || !ev.day || !ev.receiverAddr) {
331
+ core_1.Logger.log.warn('getVaultAvailableRedemptions', `Skipping event with missing required properties: ${ev}`);
332
+ continue;
333
+ }
334
+ const fullDate = new Date(Number(ev.year), Number(ev.month) - 1, Number(ev.day));
335
+ const foundRedemptionAgainstClaim = withdrawalProcesseds.find((h) => new Date(h.processedOn).toDateString() === fullDate.toDateString() &&
336
+ h.receiverAddr === ev.receiverAddr);
337
+ if (wallet && (0, ethers_1.isAddress)(wallet)) {
338
+ if (ev?.receiverAddr?.toLowerCase() === wallet.toLowerCase()) {
339
+ const alreadyRedeemed = availableRedemptions.find((red) => BigInt(red.day.raw) === BigInt(ev.day) &&
340
+ BigInt(red.month.raw) === BigInt(ev.month) &&
341
+ BigInt(red.year.raw) === BigInt(ev.year));
342
+ if (!(foundRedemptionAgainstClaim && alreadyRedeemed)) {
343
+ try {
344
+ switch (version) {
345
+ case 'evm-2': {
346
+ availableRedemptions.push({
347
+ id: ev.transactionHash_ || ev.id,
348
+ hash: ev.transactionHash_ || ev.id,
349
+ timestamp: Number(ev.timestamp_),
350
+ receiver: ev.receiverAddr,
351
+ day: (0, core_1.toNormalizedBn)(ev.day, 0),
352
+ month: (0, core_1.toNormalizedBn)(ev.month, 0),
353
+ year: (0, core_1.toNormalizedBn)(ev.year, 0),
354
+ amount: (0, core_1.toNormalizedBn)(ev.shares, decimals),
355
+ date: fullDate,
356
+ vault,
357
+ });
358
+ pendingRedemptions.push({
359
+ id: ev.transactionHash_ || ev.id,
360
+ hash: ev.transactionHash_ || ev.id,
361
+ timestamp: Number(ev.timestamp_),
362
+ receiver: ev.receiverAddr,
363
+ day: (0, core_1.toNormalizedBn)(ev.day, 0),
364
+ month: (0, core_1.toNormalizedBn)(ev.month, 0),
365
+ year: (0, core_1.toNormalizedBn)(ev.year, 0),
366
+ amount: (0, core_1.toNormalizedBn)(ev.shares || BigInt(0), decimals),
367
+ date: fullDate,
368
+ vault,
369
+ });
370
+ break;
371
+ }
372
+ default: {
373
+ const trueClaimableAmount = await vaultContract?.getClaimableAmountByReceiver?.(BigInt(ev.year), BigInt(ev.month), BigInt(ev.day), (0, ethers_1.getAddress)(wallet));
374
+ if (trueClaimableAmount > BigInt(0)) {
375
+ availableRedemptions.push({
376
+ id: ev.transactionHash_ || ev.id,
377
+ hash: ev.transactionHash_ || ev.id,
378
+ timestamp: Number(ev.timestamp_),
379
+ receiver: ev.receiverAddr,
380
+ day: (0, core_1.toNormalizedBn)(ev.day, 0),
381
+ month: (0, core_1.toNormalizedBn)(ev.month, 0),
382
+ year: (0, core_1.toNormalizedBn)(ev.year, 0),
383
+ amount: (0, core_1.toNormalizedBn)(trueClaimableAmount, decimals),
384
+ date: fullDate,
385
+ vault,
386
+ });
387
+ }
388
+ pendingRedemptions.push({
389
+ id: ev.transactionHash_ || ev.id,
390
+ hash: ev.transactionHash_ || ev.id,
391
+ timestamp: Number(ev.timestamp_),
392
+ receiver: ev.receiverAddr,
393
+ day: (0, core_1.toNormalizedBn)(ev.day, 0),
394
+ month: (0, core_1.toNormalizedBn)(ev.month, 0),
395
+ year: (0, core_1.toNormalizedBn)(ev.year, 0),
396
+ amount: (0, core_1.toNormalizedBn)(trueClaimableAmount || BigInt(0), decimals),
397
+ date: fullDate,
398
+ vault,
399
+ });
400
+ break;
401
+ }
402
+ }
403
+ }
404
+ catch (contractError) {
405
+ core_1.Logger.log.error('getVaultAvailableRedemptions', `Contract call failed: ${contractError}`);
406
+ pendingRedemptions.push({
407
+ id: ev.transactionHash_ || ev.id,
408
+ hash: ev.transactionHash_ || ev.id,
409
+ timestamp: Number(ev.timestamp_),
410
+ receiver: ev.receiverAddr,
411
+ day: (0, core_1.toNormalizedBn)(ev.day, 0),
412
+ month: (0, core_1.toNormalizedBn)(ev.month, 0),
413
+ year: (0, core_1.toNormalizedBn)(ev.year, 0),
414
+ amount: (0, core_1.toNormalizedBn)(BigInt(0), decimals),
415
+ date: fullDate,
416
+ vault,
417
+ });
418
+ }
419
+ }
420
+ }
421
+ }
422
+ else {
423
+ if (!!foundRedemptionAgainstClaim) {
424
+ availableRedemptions.push({
425
+ id: ev.transactionHash_ || ev.id,
426
+ hash: ev.transactionHash_ || ev.id,
427
+ timestamp: Number(ev.timestamp_),
428
+ receiver: ev.receiverAddr,
429
+ day: (0, core_1.toNormalizedBn)(ev.day, 0),
430
+ month: (0, core_1.toNormalizedBn)(ev.month, 0),
431
+ year: (0, core_1.toNormalizedBn)(ev.year, 0),
432
+ amount: (0, core_1.toNormalizedBn)(ev.assets || BigInt(0), decimals),
433
+ date: fullDate,
434
+ vault,
435
+ });
436
+ }
437
+ }
438
+ }
439
+ return { availableRedemptions, pendingRedemptions };
440
+ }
441
+ catch (e) {
442
+ core_1.Logger.log.error('getVaultAvailableRedemptions', e, { vault, wallet });
443
+ return { availableRedemptions: [], pendingRedemptions: [] };
444
+ }
445
+ }
446
+ async function getVaultRedemptionHistory({ vault, wallet, options, }) {
447
+ try {
448
+ const provider = (0, core_1.createProvider)(options.rpcUrl);
449
+ const tokenizedVault = (await (0, core_1.fetchTokenizedVaults)(vault, options?.headers))?.[0];
450
+ if (!tokenizedVault) {
451
+ return [];
452
+ }
453
+ const chainId = tokenizedVault.chain;
454
+ const poolContract = (0, core_1.createContract)({
455
+ address: vault,
456
+ abi: abis_1.ABI_LENDING_POOL_V2,
457
+ provider,
458
+ });
459
+ let logPromises = [];
460
+ const currentBlock = await provider.getBlockNumber();
461
+ let startingBlock = currentBlock - (0, core_1.determineBlockSkipInternal)(chainId);
462
+ let endBlock = currentBlock;
463
+ const cutoffBlock = currentBlock - (0, core_1.determineBlockCutoff)(chainId);
464
+ while (endBlock >= cutoffBlock) {
465
+ const logBloomsPromises = poolContract.queryFilter('WithdrawalProcessed', BigInt(startingBlock), BigInt(endBlock));
466
+ logPromises.push(logBloomsPromises);
467
+ startingBlock -= (0, core_1.determineBlockSkipInternal)(chainId);
468
+ endBlock -= (0, core_1.determineBlockSkipInternal)(chainId);
469
+ }
470
+ const logs = (await Promise.all(logPromises.flat())).flat();
471
+ const iface = new ethers_1.ethers.Interface([
472
+ 'event WithdrawalProcessed (uint256 assetsAmount, uint256 processedOn, address receiverAddr, uint256 requestedOn)',
473
+ ]);
474
+ const events = logs.map((log) => iface.parseLog(log));
475
+ const decimals = await (0, core_1.getDecimals)(provider, vault);
476
+ const redemptions = [];
477
+ events?.forEach((ev) => {
478
+ if (!ev?.args)
479
+ return;
480
+ const [assetsAmount, processedOn, receiverAddr, requestedOn] = ev.args;
481
+ if (wallet) {
482
+ if (String(receiverAddr)?.toLowerCase() === wallet.toLowerCase()) {
483
+ redemptions.push({
484
+ receiver: receiverAddr,
485
+ amount: (0, core_1.toNormalizedBn)(assetsAmount, decimals),
486
+ processed: new Date(Number(processedOn) * 1000),
487
+ requested: new Date(Number(requestedOn) * 1000),
488
+ vault,
489
+ });
490
+ }
491
+ }
492
+ else {
493
+ redemptions.push({
494
+ receiver: receiverAddr,
495
+ amount: (0, core_1.toNormalizedBn)(assetsAmount, decimals),
496
+ processed: new Date(Number(processedOn) * 1000),
497
+ requested: new Date(Number(requestedOn) * 1000),
498
+ vault,
499
+ });
500
+ }
501
+ });
502
+ core_1.Logger.log.info('getVaultRedemptionHistory', redemptions.slice(0, 1));
503
+ return redemptions;
504
+ }
505
+ catch (e) {
506
+ core_1.Logger.log.error('getVaultRedemptionHistory', e, { vault, wallet });
507
+ return [];
508
+ }
509
+ }
510
+ async function getVaultPositions({ vault, wallet, solanaWallet, options, }) {
511
+ try {
512
+ const tokenizedVaults = await (0, core_1.fetchTokenizedVaults)(vault ? vault : undefined, options?.headers);
513
+ if (!tokenizedVaults || tokenizedVaults.length === 0) {
514
+ return [];
515
+ }
516
+ function renderStatus(_redemptions, _balance) {
517
+ if (_redemptions?.length)
518
+ return 'REDEEM';
519
+ if (BigInt(_balance.raw) > BigInt(0))
520
+ return 'STAKED';
521
+ return 'PENDING';
522
+ }
523
+ const promises = await Promise.all(tokenizedVaults.map(async (v) => {
524
+ try {
525
+ if (solana_1.Solana.utils.isSolanaAddress(v.address)) {
526
+ let balance = (0, core_1.toNormalizedBn)(0);
527
+ if (solana_1.Solana.utils.isSolanaAddress(solanaWallet)) {
528
+ const vaultStateRes = await options.solanaService.getVaultState(String(v.address), solana_1.Solana.constants.vaultIdl);
529
+ if (vaultStateRes &&
530
+ vaultStateRes?.vaultState?.shareMint) {
531
+ balance = (0, core_1.toNormalizedBn)(await options.solanaService.fetchUserShareBalance(solanaWallet, vaultStateRes?.vaultState?.shareMint));
532
+ }
533
+ }
534
+ return {
535
+ vault,
536
+ status: renderStatus([], balance),
537
+ availableRedemptions: [],
538
+ pendingRedemptions: [],
539
+ redeemable: balance,
540
+ walletBalance: balance,
541
+ };
542
+ }
543
+ const provider = (0, core_1.createProvider)(options.rpcUrl);
544
+ let decimals;
545
+ let abi;
546
+ const version = (0, core_1.getVaultVersion)(vault);
547
+ switch (version) {
548
+ case 'evm-2': {
549
+ decimals = await (0, core_1.getDecimals)(provider, await (0, core_1.getReceiptTokenAddress)(provider, vault));
550
+ abi = TokenizedVaultV2_1.ABI_TOKENIZED_VAULT_V2;
551
+ break;
552
+ }
553
+ default: {
554
+ decimals = await (0, core_1.getDecimals)(provider, vault);
555
+ abi = abis_1.ABI_LENDING_POOL_V2;
556
+ break;
557
+ }
558
+ }
559
+ const vaultContract = (0, core_1.createContract)({
560
+ provider,
561
+ abi: abi,
562
+ address: v.address,
563
+ });
564
+ let bal = BigInt(0);
565
+ if (wallet && (0, ethers_1.isAddress)(wallet)) {
566
+ switch (version) {
567
+ case 'evm-2': {
568
+ const receiptContract = (0, core_1.createContract)({
569
+ provider,
570
+ abi: TokenizedVaultV2Receipt_1.ABI_TOKENIZED_VAULT_V2_RECEIPT,
571
+ address: await (0, core_1.getReceiptTokenAddress)(provider, vault),
572
+ });
573
+ bal = await receiptContract.balanceOf(wallet);
574
+ break;
575
+ }
576
+ default: {
577
+ bal = await vaultContract.balanceOf(wallet);
578
+ break;
579
+ }
580
+ }
581
+ }
582
+ const balance = (0, core_1.toNormalizedBn)(bal, decimals);
583
+ const { availableRedemptions, pendingRedemptions } = await getVaultAvailableRedemptions({
584
+ vault: v.address,
585
+ wallet,
586
+ options,
587
+ });
588
+ const aggregateAvailableRedemptions = availableRedemptions?.reduce((acc, curr) => acc + BigInt(curr.amount.raw), BigInt(0));
589
+ return {
590
+ vault,
591
+ status: renderStatus(availableRedemptions, balance),
592
+ availableRedemptions,
593
+ pendingRedemptions,
594
+ redeemable: (0, core_1.toNormalizedBn)(aggregateAvailableRedemptions, decimals),
595
+ walletBalance: balance,
596
+ };
597
+ }
598
+ catch (vaultError) {
599
+ console.error(`#getVaultPositions: Error processing vault ${v.address}:`, vaultError);
600
+ return {
601
+ vault,
602
+ status: 'PENDING',
603
+ availableRedemptions: [],
604
+ pendingRedemptions: [],
605
+ redeemable: (0, core_1.toNormalizedBn)(0),
606
+ walletBalance: (0, core_1.toNormalizedBn)(0),
607
+ };
608
+ }
609
+ }));
610
+ return promises.flat();
611
+ }
612
+ catch (e) {
613
+ core_1.Logger.log.error('getVaultPositions', e, { vault, wallet, solanaWallet });
614
+ throw new Error(`#getVaultPositions::${vault}:${e?.message}`);
615
+ }
616
+ }
617
+ async function getVaultApy({ vault, options, historical, }) {
618
+ try {
619
+ if (!vault)
620
+ throw new Error('Vault input parameter is undefined.');
621
+ if (!historical) {
622
+ const tokenizedVault = (await (0, core_1.fetchTokenizedVaults)(vault, options?.headers))?.[0];
623
+ return [
624
+ {
625
+ value: tokenizedVault?.reported_apy?.apy || 0,
626
+ timestamp: new Date().toISOString(),
627
+ },
628
+ ];
629
+ }
630
+ else {
631
+ function paramBuilder(params) {
632
+ const urlParams = new URLSearchParams();
633
+ if (!params)
634
+ return '';
635
+ if (params.daysAgo)
636
+ urlParams.append('days_ago', params.daysAgo.toString());
637
+ return urlParams.toString();
638
+ }
639
+ const historicalApy = await (0, core_1.fetchAugustPublic)(`${core_1.WEBSERVER_ENDPOINTS.public.tokenizedVault.historicalApy(vault)}${paramBuilder(historical)}`, {
640
+ headers: !!options?.headers
641
+ ? options?.headers
642
+ : undefined,
643
+ });
644
+ if (!historicalApy.ok)
645
+ throw new Error('Failed to fetch historical apy.');
646
+ const historicalApyData = (await historicalApy.json());
647
+ return historicalApyData.data.values.map((val, index) => {
648
+ const respectiveDate = historicalApyData.data.labels[index];
649
+ return {
650
+ timestamp: new Date(respectiveDate).toISOString(),
651
+ value: val,
652
+ };
653
+ });
654
+ }
655
+ }
656
+ catch (e) {
657
+ core_1.Logger.log.error('getVaultApy', e, { vault });
658
+ throw new Error(`#getVaultApy::${vault}:${e?.message}`);
659
+ }
660
+ }
661
+ async function getRewardsStakingPositions({ rpcUrl, wallet, coinGeckoKey, }) {
662
+ const REWARDS_CHAIN = 43114;
663
+ const REWARDS_SYMBOL = 'AVAX';
664
+ const REWARDS_DECIMALS = 18;
665
+ const REWARDS_NAME = 'Avalanche';
666
+ const APR_MULTIPLIER = 31536000;
667
+ const UP_AUSD_SYMBOL = 'upAUSD';
668
+ try {
669
+ const provider = (0, core_1.createProvider)(rpcUrl);
670
+ const chainId = await (0, core_1.getChainId)(provider);
671
+ if (chainId !== REWARDS_CHAIN) {
672
+ core_1.Logger.log.warn('getStakingPositions:unsupported_chain', chainId);
673
+ return [];
674
+ }
675
+ if (wallet && !(0, ethers_1.isAddress)(wallet)) {
676
+ core_1.Logger.log.warn('getStakingPositions:invalid_wallet', wallet);
677
+ return [];
678
+ }
679
+ const rewardDistributorAddresses = (0, core_1.REWARD_DISTRIBUTOR_ADDRESS)(chainId);
680
+ const positions = await Promise.all(rewardDistributorAddresses.map(async (contract, i) => {
681
+ const rewardContract = (0, core_1.createContract)({
682
+ address: contract,
683
+ provider: provider,
684
+ abi: abis_1.ABI_REWARD_DISTRIBUTOR,
685
+ });
686
+ const totalStaked = await rewardContract.totalStaked();
687
+ const rewardsPerSecond = await rewardContract.rewardsPerSecond();
688
+ const stakingTokenCalls = ['decimals', 'symbol', 'name', 'totalSupply'];
689
+ const stakingTokenAddress = (await rewardContract.stakingToken());
690
+ const stakingTokenContract = (0, core_1.createContract)({
691
+ address: stakingTokenAddress,
692
+ provider: provider,
693
+ abi: abis_1.ABI_ERC20,
694
+ });
695
+ const [decimals, symbol, name] = await Promise.all(stakingTokenCalls.map((staking) => stakingTokenContract[staking]()));
696
+ let balance;
697
+ let earned;
698
+ if (wallet) {
699
+ const formattedWallet = (0, ethers_1.getAddress)(wallet);
700
+ balance = await rewardContract.balanceOf(formattedWallet);
701
+ earned = await rewardContract.earned(formattedWallet);
702
+ }
703
+ const rewardTokenPriceInUsd = await (0, core_1.fetchTokenPrice)(REWARDS_SYMBOL, null, coinGeckoKey);
704
+ const normalizedRewardTokenPrice = (0, core_1.toNormalizedBn)(rewardTokenPriceInUsd);
705
+ const normalizedTotalStakedInPool = (0, core_1.toNormalizedBn)(totalStaked, decimals);
706
+ const normalizedRedeemable = (0, core_1.toNormalizedBn)(earned, REWARDS_DECIMALS);
707
+ const normalizedRewardsPerSecond = (0, core_1.toNormalizedBn)(rewardsPerSecond, REWARDS_DECIMALS);
708
+ const normalizedTotalStakedBalance = (0, core_1.toNormalizedBn)(balance, decimals);
709
+ const rewardTokenPriceToMultiply = symbol === UP_AUSD_SYMBOL
710
+ ? Number(normalizedRewardTokenPrice?.normalized)
711
+ : 1;
712
+ const STAKED_APR = ((Number(normalizedRewardsPerSecond?.normalized) *
713
+ APR_MULTIPLIER *
714
+ rewardTokenPriceToMultiply) /
715
+ (Number(normalizedTotalStakedInPool?.normalized) * Number(1))) *
716
+ 100;
717
+ const MAX_APR = ((Number(normalizedRewardsPerSecond?.normalized) *
718
+ APR_MULTIPLIER *
719
+ rewardTokenPriceToMultiply) /
720
+ (Number(normalizedTotalStakedInPool?.normalized) * Number(1))) *
721
+ 100;
722
+ const activePosition = {
723
+ id: String(i),
724
+ rewardToken: {
725
+ decimals: REWARDS_DECIMALS,
726
+ symbol: REWARDS_SYMBOL,
727
+ address: ethers_1.ZeroAddress,
728
+ chain: REWARDS_CHAIN,
729
+ redeemable: normalizedRedeemable,
730
+ usd: normalizedRewardTokenPrice,
731
+ name: REWARDS_NAME,
732
+ },
733
+ stakingToken: {
734
+ decimals: Number(decimals),
735
+ symbol: symbol,
736
+ address: stakingTokenAddress,
737
+ chain: REWARDS_CHAIN,
738
+ totalStaked: normalizedTotalStakedBalance,
739
+ usd: normalizedRewardTokenPrice,
740
+ totalSupply: normalizedTotalStakedInPool,
741
+ name: name,
742
+ },
743
+ rewardDistributor: contract,
744
+ rewardPerSecond: (0, core_1.toNormalizedBn)(rewardsPerSecond),
745
+ apy: STAKED_APR,
746
+ maxApy: MAX_APR,
747
+ chainId: REWARDS_CHAIN,
748
+ };
749
+ return activePosition;
750
+ }));
751
+ return positions;
752
+ }
753
+ catch (e) {
754
+ core_1.Logger.log.error('getStakingPositions', e, { wallet });
755
+ return [];
756
+ }
757
+ }
758
+ async function getVaultTvl({ vault, options, historical, }) {
759
+ try {
760
+ if (!vault)
761
+ throw new Error('Vault input parameter is undefined.');
762
+ const _vaultExists = (await (0, core_1.fetchTokenizedVaults)(vault))?.[0];
763
+ if (!_vaultExists) {
764
+ throw new Error(`Vault ${vault} not found in backend`);
765
+ }
766
+ if (!historical) {
767
+ const vaultRes = await getVault({
768
+ vault,
769
+ options,
770
+ loans: false,
771
+ allocations: false,
772
+ });
773
+ const returnObj = [
774
+ { value: vaultRes.totalSupply, timestamp: new Date().toISOString() },
775
+ ];
776
+ core_1.Logger.log.info('getVaultTvl:current', returnObj);
777
+ return returnObj;
778
+ }
779
+ else {
780
+ if (typeof historical !== 'undefined' && !historical.order)
781
+ historical.order = 'desc';
782
+ if (typeof historical !== 'undefined' && !historical.interval)
783
+ historical.interval = 'days';
784
+ const provider = (0, core_1.createProvider)(options.rpcUrl);
785
+ const version = (0, core_1.getVaultVersion)(vault);
786
+ const vaultContract = (0, core_1.createContract)({
787
+ address: vault,
788
+ abi: version === 'evm-2' ? TokenizedVaultV2_1.ABI_TOKENIZED_VAULT_V2 : abis_1.ABI_LENDING_POOL_V2,
789
+ provider,
790
+ });
791
+ let minAbi = [];
792
+ let functionName = '';
793
+ let vaultDecimals = 0;
794
+ switch (version) {
795
+ case 'evm-2': {
796
+ minAbi = ['function getTotalAssets() view returns (uint256)'];
797
+ functionName = 'getTotalAssets';
798
+ const receiptTokenAddress = await (0, core_1.getReceiptTokenAddress)(provider, vault);
799
+ vaultDecimals = await (0, core_1.getDecimals)(provider, receiptTokenAddress);
800
+ break;
801
+ }
802
+ default: {
803
+ minAbi = ['function totalAssets() view returns (uint256)'];
804
+ functionName = 'totalAssets';
805
+ vaultDecimals = await (0, core_1.getDecimals)(provider, vault);
806
+ break;
807
+ }
808
+ }
809
+ const finalizedBlock = await provider.getBlock('finalized');
810
+ const finalizedTimestamp = finalizedBlock
811
+ ? finalizedBlock.timestamp * 1000
812
+ : Date.now() * 60 * 1000;
813
+ const daysAgo = historical.daysAgo * 24 * 60 * 60 * 1000;
814
+ const dater = new ethereum_block_by_date_1.default(provider);
815
+ const startDate = historical.daysAgo
816
+ ? new Date(finalizedTimestamp - daysAgo)
817
+ : new Date(finalizedTimestamp);
818
+ const blocks = await dater.getEvery(historical.interval, startDate.toUTCString(), new Date(finalizedTimestamp).toUTCString());
819
+ const orderedBlocks = historical.order === 'desc' ? (0, core_1.orderObjArrByDate)(blocks) : blocks;
820
+ const totalAssetsHistorical = await (0, core_1.promiseSettle)(orderedBlocks?.map(async ({ block, date }) => {
821
+ const totalAssetsAtBlock = await provider.call({
822
+ to: vaultContract,
823
+ data: new ethers_1.Interface(minAbi).encodeFunctionData(functionName, []),
824
+ blockTag: block,
825
+ });
826
+ if (totalAssetsAtBlock === '0x')
827
+ return {
828
+ timestamp: (0, core_1.dateToUnix)(new Date(date)),
829
+ value: (0, core_1.toNormalizedBn)(0, 0),
830
+ };
831
+ const readableTotalAssetsAtBlock = new ethers_1.Interface(minAbi).decodeFunctionResult(functionName, totalAssetsAtBlock);
832
+ return {
833
+ timestamp: (0, core_1.dateToUnix)(new Date(date)),
834
+ value: (0, core_1.toNormalizedBn)(readableTotalAssetsAtBlock?.[0], vaultDecimals),
835
+ };
836
+ }));
837
+ core_1.Logger.log.info('getVaultTvl:historical', totalAssetsHistorical.length);
838
+ return totalAssetsHistorical;
839
+ }
840
+ }
841
+ catch (e) {
842
+ core_1.Logger.log.error('getVaultTvl', e, { vault });
843
+ throw new Error(`Failed to fetch TVL for ${vault}: ${e instanceof Error ? e.message : 'Unknown error'}`);
844
+ }
845
+ }
846
+ async function getVaultBorrowerHealthFactor({ vault, options, }) {
847
+ const provider = (0, core_1.createProvider)(options.rpcUrl);
848
+ const loans = await getVaultLoans(vault, options);
849
+ const activeLoans = (await Promise.all(loans.map(async (l) => {
850
+ const loanContract = (0, core_1.createContract)({
851
+ provider,
852
+ address: l.address,
853
+ abi: abis_1.ABI_LOAN,
854
+ });
855
+ const loanState = await loanContract.loanState();
856
+ if ((0, core_1.loanStateToReadable)(loanState) !== 'ACTIVE')
857
+ return;
858
+ return l.address;
859
+ }))).filter((l) => l !== undefined);
860
+ const formattedLoansArray = await Promise.all(activeLoans.map(async (l) => {
861
+ const loanContract = (0, core_1.createContract)({
862
+ provider,
863
+ address: l,
864
+ abi: abis_1.ABI_LOAN,
865
+ });
866
+ return {
867
+ borrower: await loanContract.borrower(),
868
+ loan: l,
869
+ };
870
+ }));
871
+ const uniqueBorrowers = [
872
+ ...new Set(formattedLoansArray.map((l) => l.borrower)),
873
+ ];
874
+ let borrowerResponses = {};
875
+ for (const b of uniqueBorrowers) {
876
+ const response = await (0, core_1.fetchAugustWithKey)(options.augustKey, core_1.WEBSERVER_ENDPOINTS.subaccount.health_factor(b));
877
+ if (response.status === 200) {
878
+ borrowerResponses[b] = await response.json();
879
+ }
880
+ }
881
+ formattedLoansArray?.map((loan) => {
882
+ loan.health_factor = borrowerResponses[loan.borrower];
883
+ });
884
+ return formattedLoansArray;
885
+ }
886
+ async function getHealthFactorOfBorrowersByVault({ options, }) {
887
+ const vaults = await (0, core_1.fetchTokenizedVaults)();
888
+ const healthFactors = await Promise.all(vaults.map(async (v) => {
889
+ return getVaultBorrowerHealthFactor({
890
+ vault: v.address,
891
+ options,
892
+ });
893
+ }));
894
+ const healthFactorsByPool = {};
895
+ vaults.map((pool, index) => {
896
+ healthFactorsByPool[pool.address] = healthFactors[index];
897
+ });
898
+ return healthFactorsByPool;
899
+ }
900
+ //# sourceMappingURL=getters.js.map