@augustdigital/sdk 8.3.2 → 8.5.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 (204) hide show
  1. package/lib/abis/ERC20_Bytes32.d.ts +4 -0
  2. package/lib/abis/ERC20_Bytes32.js +4 -0
  3. package/lib/abis/ERC4626.d.ts +1 -0
  4. package/lib/abis/ERC4626.js +1 -0
  5. package/lib/abis/ERC721.d.ts +1 -0
  6. package/lib/abis/ERC721.js +1 -0
  7. package/lib/abis/FeeOracle.js +1 -0
  8. package/lib/abis/LendingPool.js +1 -0
  9. package/lib/abis/LendingPoolV2.js +1 -0
  10. package/lib/abis/Multicall3.js +3 -0
  11. package/lib/abis/OFT.d.ts +20 -0
  12. package/lib/abis/OFT.js +20 -0
  13. package/lib/abis/SmartAccount.d.ts +1 -0
  14. package/lib/abis/SmartAccount.js +3 -0
  15. package/lib/abis/SwapRouter.d.ts +1 -0
  16. package/lib/abis/SwapRouter.js +1 -0
  17. package/lib/abis/UniversalSignatureValidator.js +3 -0
  18. package/lib/abis/index.d.ts +5 -0
  19. package/lib/abis/index.js +5 -0
  20. package/lib/adapters/evm/getters.d.ts +17 -2
  21. package/lib/adapters/evm/getters.js +35 -3
  22. package/lib/adapters/evm/index.d.ts +262 -0
  23. package/lib/adapters/evm/index.js +268 -1
  24. package/lib/adapters/evm/utils.d.ts +6 -0
  25. package/lib/adapters/evm/utils.js +7 -0
  26. package/lib/adapters/solana/constants.js +4 -1
  27. package/lib/adapters/solana/getters.d.ts +8 -0
  28. package/lib/adapters/solana/getters.js +21 -0
  29. package/lib/adapters/solana/idl/vault-idl.js +9 -0
  30. package/lib/adapters/solana/index.d.ts +55 -0
  31. package/lib/adapters/solana/index.js +57 -0
  32. package/lib/adapters/solana/utils.d.ts +28 -0
  33. package/lib/adapters/solana/utils.js +79 -4
  34. package/lib/adapters/solana/vault.actions.d.ts +19 -0
  35. package/lib/adapters/solana/vault.actions.js +47 -3
  36. package/lib/adapters/stellar/actions.d.ts +25 -0
  37. package/lib/adapters/stellar/actions.js +33 -0
  38. package/lib/adapters/stellar/constants.d.ts +26 -0
  39. package/lib/adapters/stellar/constants.js +29 -0
  40. package/lib/adapters/stellar/getters.d.ts +56 -0
  41. package/lib/adapters/stellar/getters.js +81 -0
  42. package/lib/adapters/stellar/index.d.ts +48 -0
  43. package/lib/adapters/stellar/index.js +48 -0
  44. package/lib/adapters/stellar/soroban.d.ts +20 -0
  45. package/lib/adapters/stellar/soroban.js +46 -0
  46. package/lib/adapters/stellar/submit.d.ts +12 -0
  47. package/lib/adapters/stellar/submit.js +19 -0
  48. package/lib/adapters/stellar/types.d.ts +27 -0
  49. package/lib/adapters/stellar/types.js +3 -0
  50. package/lib/adapters/stellar/utils.d.ts +10 -0
  51. package/lib/adapters/stellar/utils.js +10 -0
  52. package/lib/adapters/sui/getters.d.ts +6 -0
  53. package/lib/adapters/sui/getters.js +6 -0
  54. package/lib/adapters/sui/index.d.ts +15 -0
  55. package/lib/adapters/sui/index.js +15 -0
  56. package/lib/adapters/sui/transformer.d.ts +6 -0
  57. package/lib/adapters/sui/transformer.js +6 -0
  58. package/lib/adapters/sui/utils.d.ts +6 -0
  59. package/lib/adapters/sui/utils.js +6 -0
  60. package/lib/core/analytics/chain-name.d.ts +8 -0
  61. package/lib/core/analytics/chain-name.js +8 -0
  62. package/lib/core/analytics/constants.d.ts +4 -0
  63. package/lib/core/analytics/constants.js +4 -0
  64. package/lib/core/analytics/env.d.ts +25 -0
  65. package/lib/core/analytics/env.js +26 -0
  66. package/lib/core/analytics/index.d.ts +26 -0
  67. package/lib/core/analytics/index.js +35 -0
  68. package/lib/core/analytics/instrumentation.d.ts +26 -0
  69. package/lib/core/analytics/instrumentation.js +66 -2
  70. package/lib/core/analytics/method-taxonomy.d.ts +16 -0
  71. package/lib/core/analytics/method-taxonomy.js +18 -0
  72. package/lib/core/analytics/metrics.d.ts +23 -0
  73. package/lib/core/analytics/metrics.js +40 -0
  74. package/lib/core/analytics/sanitize.d.ts +38 -0
  75. package/lib/core/analytics/sanitize.js +46 -0
  76. package/lib/core/analytics/sentry-runtime.d.ts +11 -0
  77. package/lib/core/analytics/sentry-runtime.js +19 -0
  78. package/lib/core/analytics/sentry.d.ts +45 -0
  79. package/lib/core/analytics/sentry.js +115 -2
  80. package/lib/core/analytics/types.d.ts +27 -0
  81. package/lib/core/analytics/user-identity.d.ts +34 -0
  82. package/lib/core/analytics/user-identity.js +42 -0
  83. package/lib/core/analytics/version.d.ts +6 -1
  84. package/lib/core/analytics/version.js +6 -1
  85. package/lib/core/auth/verify.js +5 -0
  86. package/lib/core/base.class.d.ts +75 -0
  87. package/lib/core/base.class.js +56 -0
  88. package/lib/core/cache.d.ts +5 -0
  89. package/lib/core/cache.js +6 -0
  90. package/lib/core/constants/adapters.d.ts +15 -0
  91. package/lib/core/constants/adapters.js +28 -8
  92. package/lib/core/constants/core.d.ts +12 -1
  93. package/lib/core/constants/core.js +12 -0
  94. package/lib/core/constants/swap-router.d.ts +46 -0
  95. package/lib/core/constants/swap-router.js +50 -0
  96. package/lib/core/constants/vaults.d.ts +56 -0
  97. package/lib/core/constants/vaults.js +66 -1
  98. package/lib/core/constants/web3.d.ts +3 -0
  99. package/lib/core/constants/web3.js +18 -5
  100. package/lib/core/errors/index.d.ts +36 -0
  101. package/lib/core/errors/index.js +29 -0
  102. package/lib/core/fetcher.d.ts +134 -0
  103. package/lib/core/fetcher.js +191 -5
  104. package/lib/core/helpers/adapters.d.ts +9 -0
  105. package/lib/core/helpers/adapters.js +11 -0
  106. package/lib/core/helpers/chain-address.d.ts +10 -0
  107. package/lib/core/helpers/chain-address.js +11 -0
  108. package/lib/core/helpers/core.d.ts +42 -0
  109. package/lib/core/helpers/core.js +66 -1
  110. package/lib/core/helpers/explorer-link.d.ts +14 -0
  111. package/lib/core/helpers/explorer-link.js +14 -0
  112. package/lib/core/helpers/signer.d.ts +26 -0
  113. package/lib/core/helpers/signer.js +39 -0
  114. package/lib/core/helpers/swap-router.d.ts +32 -0
  115. package/lib/core/helpers/swap-router.js +32 -0
  116. package/lib/core/helpers/vault-version.d.ts +1 -0
  117. package/lib/core/helpers/vault-version.js +2 -0
  118. package/lib/core/helpers/vaults.d.ts +8 -0
  119. package/lib/core/helpers/vaults.js +22 -8
  120. package/lib/core/helpers/web3.d.ts +152 -0
  121. package/lib/core/helpers/web3.js +183 -6
  122. package/lib/core/logger/index.d.ts +55 -0
  123. package/lib/core/logger/index.js +19 -0
  124. package/lib/core/logger/slack.d.ts +3 -0
  125. package/lib/core/logger/slack.js +3 -0
  126. package/lib/core/vault-metadata.d.ts +6 -0
  127. package/lib/core/vault-metadata.js +6 -0
  128. package/lib/core/version-check.d.ts +52 -0
  129. package/lib/core/version-check.js +81 -0
  130. package/lib/evm/methods/crossChainVault.d.ts +90 -0
  131. package/lib/evm/methods/crossChainVault.js +186 -1
  132. package/lib/evm/methods/crossChainVaultRegistry.d.ts +93 -0
  133. package/lib/evm/methods/crossChainVaultRegistry.js +240 -0
  134. package/lib/evm/methods/index.d.ts +1 -0
  135. package/lib/evm/methods/index.js +1 -0
  136. package/lib/evm/types/crossChain.d.ts +202 -0
  137. package/lib/evm/types/crossChain.js +11 -0
  138. package/lib/index.d.ts +16 -0
  139. package/lib/index.js +19 -0
  140. package/lib/main.d.ts +288 -5
  141. package/lib/main.js +305 -0
  142. package/lib/modules/api/index.d.ts +1 -0
  143. package/lib/modules/api/index.js +6 -0
  144. package/lib/modules/api/main.d.ts +52 -0
  145. package/lib/modules/api/main.js +130 -0
  146. package/lib/modules/sub-accounts/fetcher.d.ts +15 -0
  147. package/lib/modules/sub-accounts/fetcher.js +15 -0
  148. package/lib/modules/sub-accounts/main.d.ts +33 -0
  149. package/lib/modules/sub-accounts/main.js +38 -0
  150. package/lib/modules/sub-accounts/utils.d.ts +3 -0
  151. package/lib/modules/sub-accounts/utils.js +3 -0
  152. package/lib/modules/vaults/adapter.helpers.d.ts +18 -0
  153. package/lib/modules/vaults/adapter.helpers.js +34 -0
  154. package/lib/modules/vaults/fetcher.d.ts +20 -0
  155. package/lib/modules/vaults/fetcher.js +40 -3
  156. package/lib/modules/vaults/getters.d.ts +295 -0
  157. package/lib/modules/vaults/getters.js +552 -12
  158. package/lib/modules/vaults/index.d.ts +12 -0
  159. package/lib/modules/vaults/index.js +12 -0
  160. package/lib/modules/vaults/main.d.ts +292 -4
  161. package/lib/modules/vaults/main.js +379 -7
  162. package/lib/modules/vaults/read.actions.d.ts +168 -0
  163. package/lib/modules/vaults/read.actions.js +143 -0
  164. package/lib/modules/vaults/types.d.ts +34 -0
  165. package/lib/modules/vaults/utils/call-data-decoder.d.ts +47 -0
  166. package/lib/modules/vaults/utils/call-data-decoder.js +56 -0
  167. package/lib/modules/vaults/utils/date-utils.d.ts +39 -0
  168. package/lib/modules/vaults/utils/date-utils.js +47 -1
  169. package/lib/modules/vaults/utils.d.ts +69 -0
  170. package/lib/modules/vaults/utils.js +104 -5
  171. package/lib/modules/vaults/write.actions.d.ts +363 -3
  172. package/lib/modules/vaults/write.actions.js +364 -2
  173. package/lib/polyfills.js +2 -0
  174. package/lib/sdk.d.ts +23705 -0
  175. package/lib/services/coingecko/fetcher.d.ts +13 -0
  176. package/lib/services/coingecko/fetcher.js +17 -0
  177. package/lib/services/debank/fetcher.d.ts +14 -0
  178. package/lib/services/debank/fetcher.js +12 -0
  179. package/lib/services/debank/utils.js +17 -0
  180. package/lib/services/layerzero/deposits.d.ts +11 -0
  181. package/lib/services/layerzero/deposits.js +34 -11
  182. package/lib/services/layerzero/redeems.d.ts +10 -0
  183. package/lib/services/layerzero/redeems.js +13 -0
  184. package/lib/services/layerzero/utils.d.ts +8 -0
  185. package/lib/services/layerzero/utils.js +11 -0
  186. package/lib/services/octavfi/fetcher.d.ts +7 -0
  187. package/lib/services/octavfi/fetcher.js +25 -0
  188. package/lib/services/octavfi/utils.d.ts +12 -0
  189. package/lib/services/octavfi/utils.js +44 -10
  190. package/lib/services/subgraph/fetcher.js +4 -2
  191. package/lib/services/subgraph/vaults.d.ts +12 -0
  192. package/lib/services/subgraph/vaults.js +43 -2
  193. package/lib/services/swap-quotes/index.d.ts +71 -0
  194. package/lib/services/swap-quotes/index.js +25 -0
  195. package/lib/services/swap-quotes/paraswap.d.ts +17 -0
  196. package/lib/services/swap-quotes/paraswap.js +14 -0
  197. package/lib/types/pools.d.ts +3 -0
  198. package/lib/types/typed-contract.d.ts +64 -0
  199. package/lib/types/vaults.d.ts +137 -2
  200. package/lib/types/vaults.js +10 -0
  201. package/lib/types/web3.d.ts +8 -0
  202. package/lib/types/web3.js +1 -0
  203. package/lib/types/webserver.d.ts +45 -0
  204. package/package.json +6 -5
@@ -2,31 +2,183 @@ import { ethers, Interface, InterfaceAbi, JsonRpcProvider } from 'ethers';
2
2
  import type { Abi } from 'abitype';
3
3
  import type { TypedContract } from '../../types/typed-contract';
4
4
  import { IAddress, IContractRunner, IInfuraOptions } from '../../types';
5
+ /**
6
+ * Web3 Helper Utilities
7
+ *
8
+ * Core utilities for blockchain interaction:
9
+ * - Provider Management: createProvider, getInfuraProvider, getChainId
10
+ * - Contract Helpers: createContract, getDecimals, getSymbol, getTokenMetadata
11
+ * - Transaction Utilities: simulateTransaction, checkAddress
12
+ * - Historical Queries: getHistoricalContractData, getHistoricalContractDataByDate
13
+ * - Oracle Integration: getLoanOracleFeeRate
14
+ * - Block Utilities: determineBlockCutoff, determineBlockSkipInternal
15
+ */
16
+ /**
17
+ * Get maximum block range for historical queries per chain.
18
+ * Prevents RPC timeouts by limiting lookback window.
19
+ * @param chain Chain ID
20
+ * @returns Maximum number of blocks to query
21
+ */
5
22
  export declare const determineBlockCutoff: (chain: number) => 120000 | 3456000 | 150000;
23
+ /**
24
+ * Approximate block time in seconds per chain.
25
+ * Used to estimate time ranges from block counts.
26
+ * @param chain - Chain ID
27
+ * @returns Seconds per block
28
+ */
6
29
  export declare const determineSecondsPerBlock: (chain: number) => number;
30
+ /**
31
+ * Get block interval for paginated historical queries per chain.
32
+ * Respects RPC eth_getLogs range limits.
33
+ * @param chain Chain ID
34
+ * @returns Block interval for pagination
35
+ */
7
36
  export declare const determineBlockSkipInternal: (chain: number) => 1000 | 8000 | 50000;
37
+ /**
38
+ * Retrieve chain ID from web3 provider.
39
+ * Handles both initialized and uninitialized provider states.
40
+ * @param provider Web3 provider instance
41
+ * @returns Numeric chain ID
42
+ */
8
43
  export declare const getChainId: (provider: IContractRunner) => Promise<number>;
44
+ /**
45
+ * Create ethers contract instance with address validation.
46
+ * @param provider Web3 provider for contract calls
47
+ * @param address Contract address (must be checksummed)
48
+ * @param abi Contract ABI (must be declared with `as const`)
49
+ * @returns Strongly-typed contract instance or undefined if address invalid
50
+ */
9
51
  export declare function createContract<const TAbi extends Abi>({ provider, address, abi, }: {
10
52
  address: string;
11
53
  provider: IContractRunner;
12
54
  abi: TAbi;
13
55
  }): TypedContract<TAbi> | undefined;
56
+ /**
57
+ * Create or reuse a cached JSON-RPC provider.
58
+ * Passing `chainId` enables ethers' `staticNetwork` to skip the `eth_chainId`
59
+ * round-trip on first use.
60
+ *
61
+ * @param rpcUrl RPC endpoint URL — must be a non-empty string.
62
+ * @param chainId Optional chain ID — enables staticNetwork
63
+ * @throws Error with a clear, remediable message when `rpcUrl` is missing or
64
+ * empty. Without this guard, ethers v6 silently defaults to
65
+ * `http://localhost:8545` and surfaces a cryptic
66
+ * `network is not available yet (NETWORK_ERROR)` on the first RPC call.
67
+ */
14
68
  export declare const createProvider: (rpcUrl: string, chainId?: number) => JsonRpcProvider;
69
+ /**
70
+ * Create or reuse a cached Infura provider for the specified chain.
71
+ * @param infura Configuration with chain ID and API key
72
+ */
15
73
  export declare const getInfuraProvider: (infura: IInfuraOptions) => JsonRpcProvider;
16
74
  export { explorerLink } from './explorer-link';
75
+ /**
76
+ * Fetch token decimals from contract or Solana mint.
77
+ * Results are cached to minimize RPC calls.
78
+ * @param provider Web3 provider
79
+ * @param address Token contract address or Solana mint
80
+ * @returns Number of decimals for the token
81
+ */
17
82
  export declare const getDecimals: (provider: IContractRunner, address: IAddress, isVault?: boolean) => Promise<number>;
83
+ /**
84
+ * Fetch the whitelisted deposit-asset addresses from a vault's whitelist
85
+ * contract. Cached with a 5-minute TTL; a fresh fetch fans out into N
86
+ * decimals/symbol reads downstream.
87
+ * @internal
88
+ */
18
89
  export declare const getWhitelistedAssets: (provider: IContractRunner, whitelistAddress: IAddress) => Promise<IAddress[]>;
90
+ /**
91
+ * Fetch receipt token address from tokenized vault contract.
92
+ * Results are cached to minimize RPC calls.
93
+ * @param provider Web3 provider
94
+ * @param address Tokenized vault contract address
95
+ * @returns Receipt token address
96
+ */
19
97
  export declare const getReceiptTokenAddress: (provider: IContractRunner, address: IAddress) => Promise<`0x${string}`>;
98
+ /**
99
+ * Fetch token symbol from contract.
100
+ * Results are cached to minimize RPC calls.
101
+ * @param provider Web3 provider
102
+ * @param address Token contract address
103
+ * @returns Token symbol string
104
+ */
20
105
  export declare const getSymbol: (provider: IContractRunner, address: IAddress | undefined, isVault?: boolean) => Promise<string>;
106
+ /**
107
+ * Batch fetch multiple token metadata fields in a single call.
108
+ * Efficiently retrieves name, symbol, decimals, and totalSupply.
109
+ * @param provider Web3 provider
110
+ * @param asset Token contract address
111
+ * @param meta Array of metadata fields to fetch
112
+ * @returns Array of metadata values in same order as requested
113
+ */
21
114
  export declare function getTokenMetadata(provider: IContractRunner, asset: IAddress, meta: ('symbol' | 'decimals' | 'name' | 'totalSupply')[]): Promise<any[]>;
115
+ /**
116
+ * Fetch management fee percentage from vault contract.
117
+ * Performs static call first to check if method exists.
118
+ * @todo fix so that when lending pool does not have "managementFeePercent", to not break everything
119
+ * @param provider Web3 provider
120
+ * @param address Vault contract address
121
+ * @returns Management fee as percentage or undefined if not supported
122
+ */
22
123
  export declare const getManagementFeePercent: (provider: IContractRunner, address: IAddress) => Promise<number>;
124
+ /**
125
+ * Simulate contract transaction without executing on-chain.
126
+ * Useful for testing transaction viability before sending.
127
+ * @param provider Web3 provider
128
+ * @param abi Contract ABI
129
+ * @param functionName Function to simulate
130
+ * @param options Transaction parameters including args, from, to
131
+ * @returns Decoded function result or false if simulation fails
132
+ */
23
133
  export declare function simulateTransaction(provider: IContractRunner, abi: string[] | any, functionName: string, options?: {
24
134
  args?: (string | number | bigint)[][];
25
135
  from?: string;
26
136
  to?: string;
27
137
  }): Promise<boolean | ethers.Result>;
138
+ /**
139
+ * Validate Ethereum address format and checksum.
140
+ * @param address Address string to validate
141
+ * @param logger Optional logger for error messages
142
+ * @param type Context type for logging
143
+ * @returns True if address is valid and checksummed
144
+ */
28
145
  export declare function checkAddress(address: string, logger?: any, type?: 'wallet' | 'contract'): boolean;
29
146
  type ILoanOracleFeeCategories = 'LOAN.REPAY.INTERESTS';
147
+ /**
148
+ * Fetch dynamic fee rate from on-chain oracle contract.
149
+ * Used for calculating loan interest repayment fees.
150
+ * @param provider Web3 provider
151
+ * @param category_id Fee category identifier
152
+ * @param address Context address for fee calculation
153
+ * @param chainId Optional chain ID (auto-detected if not provided)
154
+ * @returns Fee rate as decimal number
155
+ */
30
156
  export declare function getLoanOracleFeeRate(provider: IContractRunner, category_id: ILoanOracleFeeCategories, address: IAddress, chainId?: number): Promise<number>;
157
+ /**
158
+ * Query historical contract state across a block range.
159
+ * Useful for reconstructing historical data like TVL over time.
160
+ * @param provider Web3 provider
161
+ * @param contractAddress Target contract address
162
+ * @param abi Contract ABI
163
+ * @param methodName View function to call
164
+ * @param args Function arguments
165
+ * @param startBlock Starting block number
166
+ * @param endBlock Ending block number (current block if not specified)
167
+ * @param blockInterval Blocks between each query
168
+ * @returns Array of results with block numbers and timestamps
169
+ */
31
170
  export declare function getHistoricalContractData(provider: IContractRunner, contractAddress: IAddress, abi: Interface | InterfaceAbi, methodName: string, args: (string | number | bigint | boolean)[], startBlock: number, endBlock: number, blockInterval?: number): Promise<any[]>;
171
+ /**
172
+ * Query historical contract state at regular time intervals.
173
+ * Uses binary search to find blocks closest to target timestamps.
174
+ * @param provider Web3 provider
175
+ * @param contractAddress Target contract address
176
+ * @param abi Contract ABI
177
+ * @param methodName View function to call
178
+ * @param args Function arguments
179
+ * @param startDate Start date (string or timestamp)
180
+ * @param endDate End date (string or timestamp)
181
+ * @param intervalHours Hours between each query
182
+ * @returns Array of results with dates, blocks, and values
183
+ */
32
184
  export declare function getHistoricalContractDataByDate(provider: IContractRunner, contractAddress: IAddress, abi: Interface | InterfaceAbi, methodName: string, args: (string | number | bigint | boolean)[], startDate: string | number, endDate: string | number, intervalHours?: number): Promise<any[]>;
@@ -19,7 +19,25 @@ const constants_1 = require("../../adapters/solana/constants");
19
19
  const abis_1 = require("../../abis");
20
20
  const TokenizedVaultV2_1 = require("../../abis/TokenizedVaultV2");
21
21
  const TokenizedVaultV2WhitelistedAssets_1 = require("../../abis/TokenizedVaultV2WhitelistedAssets");
22
+ //import { getVaultVersion } from './helpers.vaults';
22
23
  const vault_version_1 = require("./vault-version");
24
+ /**
25
+ * Web3 Helper Utilities
26
+ *
27
+ * Core utilities for blockchain interaction:
28
+ * - Provider Management: createProvider, getInfuraProvider, getChainId
29
+ * - Contract Helpers: createContract, getDecimals, getSymbol, getTokenMetadata
30
+ * - Transaction Utilities: simulateTransaction, checkAddress
31
+ * - Historical Queries: getHistoricalContractData, getHistoricalContractDataByDate
32
+ * - Oracle Integration: getLoanOracleFeeRate
33
+ * - Block Utilities: determineBlockCutoff, determineBlockSkipInternal
34
+ */
35
+ /**
36
+ * Get maximum block range for historical queries per chain.
37
+ * Prevents RPC timeouts by limiting lookback window.
38
+ * @param chain Chain ID
39
+ * @returns Maximum number of blocks to query
40
+ */
23
41
  const determineBlockCutoff = (chain) => {
24
42
  switch (chain) {
25
43
  case 56:
@@ -33,33 +51,51 @@ const determineBlockCutoff = (chain) => {
33
51
  }
34
52
  };
35
53
  exports.determineBlockCutoff = determineBlockCutoff;
54
+ /**
55
+ * Approximate block time in seconds per chain.
56
+ * Used to estimate time ranges from block counts.
57
+ * @param chain - Chain ID
58
+ * @returns Seconds per block
59
+ */
36
60
  const determineSecondsPerBlock = (chain) => {
37
61
  switch (chain) {
38
- case 143:
62
+ case 143: // Monad ~500ms
39
63
  return 0.5;
40
- case 56:
41
- case 43114:
64
+ case 56: // BSC ~2s
65
+ case 43114: // Avalanche ~2s
42
66
  return 2;
43
- default:
67
+ default: // Ethereum ~12s
44
68
  return 12;
45
69
  }
46
70
  };
47
71
  exports.determineSecondsPerBlock = determineSecondsPerBlock;
72
+ /**
73
+ * Get block interval for paginated historical queries per chain.
74
+ * Respects RPC eth_getLogs range limits.
75
+ * @param chain Chain ID
76
+ * @returns Block interval for pagination
77
+ */
48
78
  const determineBlockSkipInternal = (chain) => {
49
79
  switch (chain) {
50
80
  case 43114:
51
81
  return 8000;
52
82
  case 56:
53
83
  return 8000;
54
- case 143:
84
+ case 143: // Monad — Alchemy limits eth_getLogs to 1000 blocks
55
85
  return 1000;
56
- case 999:
86
+ case 999: // HyperEVM — rpc.hypurrscan.io limits eth_getLogs to 1000 blocks
57
87
  return 1000;
58
88
  default:
59
89
  return 50000;
60
90
  }
61
91
  };
62
92
  exports.determineBlockSkipInternal = determineBlockSkipInternal;
93
+ /**
94
+ * Retrieve chain ID from web3 provider.
95
+ * Handles both initialized and uninitialized provider states.
96
+ * @param provider Web3 provider instance
97
+ * @returns Numeric chain ID
98
+ */
63
99
  const getChainId = async (provider) => {
64
100
  try {
65
101
  if (!provider?._network) {
@@ -74,6 +110,13 @@ const getChainId = async (provider) => {
74
110
  }
75
111
  };
76
112
  exports.getChainId = getChainId;
113
+ /**
114
+ * Create ethers contract instance with address validation.
115
+ * @param provider Web3 provider for contract calls
116
+ * @param address Contract address (must be checksummed)
117
+ * @param abi Contract ABI (must be declared with `as const`)
118
+ * @returns Strongly-typed contract instance or undefined if address invalid
119
+ */
77
120
  function createContract({ provider, address, abi, }) {
78
121
  const goodAddress = checkAddress(address);
79
122
  if (!goodAddress)
@@ -85,6 +128,18 @@ function createContract({ provider, address, abi, }) {
85
128
  }
86
129
  return contract;
87
130
  }
131
+ /**
132
+ * Create or reuse a cached JSON-RPC provider.
133
+ * Passing `chainId` enables ethers' `staticNetwork` to skip the `eth_chainId`
134
+ * round-trip on first use.
135
+ *
136
+ * @param rpcUrl RPC endpoint URL — must be a non-empty string.
137
+ * @param chainId Optional chain ID — enables staticNetwork
138
+ * @throws Error with a clear, remediable message when `rpcUrl` is missing or
139
+ * empty. Without this guard, ethers v6 silently defaults to
140
+ * `http://localhost:8545` and surfaces a cryptic
141
+ * `network is not available yet (NETWORK_ERROR)` on the first RPC call.
142
+ */
88
143
  const createProvider = (rpcUrl, chainId) => {
89
144
  if (typeof rpcUrl !== 'string' || rpcUrl.trim().length === 0) {
90
145
  const forChain = chainId ? ` for chain ${chainId}` : '';
@@ -96,6 +151,7 @@ const createProvider = (rpcUrl, chainId) => {
96
151
  const cacheKey = chainId ? `${rpcUrl}|${chainId}` : rpcUrl;
97
152
  if (cache_1.CACHE.has(cacheKey))
98
153
  return cache_1.CACHE.get(cacheKey);
154
+ // batchMaxCount caps server-side batch limits (e.g. rpc.hypurrscan.io > 20).
99
155
  const provider = chainId
100
156
  ? new ethers_1.JsonRpcProvider(rpcUrl, ethers_1.Network.from(chainId), {
101
157
  staticNetwork: ethers_1.Network.from(chainId),
@@ -108,6 +164,10 @@ const createProvider = (rpcUrl, chainId) => {
108
164
  return provider;
109
165
  };
110
166
  exports.createProvider = createProvider;
167
+ /**
168
+ * Create or reuse a cached Infura provider for the specified chain.
169
+ * @param infura Configuration with chain ID and API key
170
+ */
111
171
  const getInfuraProvider = (infura) => {
112
172
  let baseUrl = 'https://';
113
173
  switch (infura.chainId) {
@@ -138,6 +198,19 @@ const getInfuraProvider = (infura) => {
138
198
  exports.getInfuraProvider = getInfuraProvider;
139
199
  var explorer_link_1 = require("./explorer-link");
140
200
  Object.defineProperty(exports, "explorerLink", { enumerable: true, get: function () { return explorer_link_1.explorerLink; } });
201
+ /**
202
+ * Stable per-provider identity for cache keys — prevents cross-chain collisions
203
+ * when the same address represents different tokens on different networks.
204
+ *
205
+ * `provider._network` is a *getter* in ethers v6 that throws
206
+ * `network is not available yet (NETWORK_ERROR)` until the provider has
207
+ * resolved its network (i.e. before its first successful request, when
208
+ * `staticNetwork` was not supplied at construction). Accessing it directly
209
+ * here used to leak that error out of every cached read (`getDecimals`,
210
+ * `getReceiptTokenAddress`, …) and surface as a confusing TVL failure on
211
+ * fresh provider instances. We swallow the throw and fall back to the
212
+ * connection URL — slightly less precise as a cache key but always safe.
213
+ */
141
214
  function providerScope(provider) {
142
215
  let chainId;
143
216
  try {
@@ -146,6 +219,7 @@ function providerScope(provider) {
146
219
  chainId = net?.chainId;
147
220
  }
148
221
  catch {
222
+ // ethers v6 throws when the lazy network hasn't been detected yet.
149
223
  chainId = undefined;
150
224
  }
151
225
  if (chainId !== undefined && chainId !== null) {
@@ -156,7 +230,15 @@ function providerScope(provider) {
156
230
  return `url:${conn.url}`;
157
231
  return 'unknown';
158
232
  }
233
+ /** @internal */
159
234
  const DECIMALS_REQUESTS = new Map();
235
+ /**
236
+ * Fetch token decimals from contract or Solana mint.
237
+ * Results are cached to minimize RPC calls.
238
+ * @param provider Web3 provider
239
+ * @param address Token contract address or Solana mint
240
+ * @returns Number of decimals for the token
241
+ */
160
242
  const getDecimals = async (provider, address, isVault = true) => {
161
243
  if (address === ethers_1.ZeroAddress) {
162
244
  logger_1.Logger.log.info('getDecimals', 'address is zero address');
@@ -205,7 +287,14 @@ const getDecimals = async (provider, address, isVault = true) => {
205
287
  return fetchPromise;
206
288
  };
207
289
  exports.getDecimals = getDecimals;
290
+ /** @internal */
208
291
  const WHITELISTED_ASSETS_REQUESTS = new Map();
292
+ /**
293
+ * Fetch the whitelisted deposit-asset addresses from a vault's whitelist
294
+ * contract. Cached with a 5-minute TTL; a fresh fetch fans out into N
295
+ * decimals/symbol reads downstream.
296
+ * @internal
297
+ */
209
298
  const getWhitelistedAssets = async (provider, whitelistAddress) => {
210
299
  if (!(whitelistAddress && provider)) {
211
300
  throw new errors_1.AugustValidationError('INVALID_INPUT', 'getWhitelistedAssets: provider and whitelistAddress are required');
@@ -231,7 +320,15 @@ const getWhitelistedAssets = async (provider, whitelistAddress) => {
231
320
  return fetchPromise;
232
321
  };
233
322
  exports.getWhitelistedAssets = getWhitelistedAssets;
323
+ /** @internal */
234
324
  const RECEIPT_TOKEN_REQUESTS = new Map();
325
+ /**
326
+ * Fetch receipt token address from tokenized vault contract.
327
+ * Results are cached to minimize RPC calls.
328
+ * @param provider Web3 provider
329
+ * @param address Tokenized vault contract address
330
+ * @returns Receipt token address
331
+ */
235
332
  const getReceiptTokenAddress = async (provider, address) => {
236
333
  if (!(address && provider))
237
334
  return;
@@ -260,7 +357,15 @@ const getReceiptTokenAddress = async (provider, address) => {
260
357
  return fetchPromise;
261
358
  };
262
359
  exports.getReceiptTokenAddress = getReceiptTokenAddress;
360
+ /** @internal */
263
361
  const SYMBOL_REQUESTS = new Map();
362
+ /**
363
+ * Fetch token symbol from contract.
364
+ * Results are cached to minimize RPC calls.
365
+ * @param provider Web3 provider
366
+ * @param address Token contract address
367
+ * @returns Token symbol string
368
+ */
264
369
  const getSymbol = async (provider, address, isVault = true) => {
265
370
  if (address === ethers_1.ZeroAddress) {
266
371
  logger_1.Logger.log.info('getSymbol', 'address is zero address');
@@ -307,6 +412,14 @@ const getSymbol = async (provider, address, isVault = true) => {
307
412
  return fetchPromise;
308
413
  };
309
414
  exports.getSymbol = getSymbol;
415
+ /**
416
+ * Batch fetch multiple token metadata fields in a single call.
417
+ * Efficiently retrieves name, symbol, decimals, and totalSupply.
418
+ * @param provider Web3 provider
419
+ * @param asset Token contract address
420
+ * @param meta Array of metadata fields to fetch
421
+ * @returns Array of metadata values in same order as requested
422
+ */
310
423
  async function getTokenMetadata(provider, asset, meta) {
311
424
  if (!asset)
312
425
  return [];
@@ -340,9 +453,18 @@ async function getTokenMetadata(provider, asset, meta) {
340
453
  return [];
341
454
  }
342
455
  }
456
+ /**
457
+ * Fetch management fee percentage from vault contract.
458
+ * Performs static call first to check if method exists.
459
+ * @todo fix so that when lending pool does not have "managementFeePercent", to not break everything
460
+ * @param provider Web3 provider
461
+ * @param address Vault contract address
462
+ * @returns Management fee as percentage or undefined if not supported
463
+ */
343
464
  const getManagementFeePercent = async (provider, address) => {
344
465
  if (!(address && provider))
345
466
  return;
467
+ // Check if contract supports managementFeePercent method
346
468
  try {
347
469
  const contract = new ethers_1.Contract(address, [web3_1.MIN_ABIS.managementFeePercent], provider);
348
470
  await contract.managementFeePercent.staticCall();
@@ -362,6 +484,15 @@ const getManagementFeePercent = async (provider, address) => {
362
484
  }
363
485
  };
364
486
  exports.getManagementFeePercent = getManagementFeePercent;
487
+ /**
488
+ * Simulate contract transaction without executing on-chain.
489
+ * Useful for testing transaction viability before sending.
490
+ * @param provider Web3 provider
491
+ * @param abi Contract ABI
492
+ * @param functionName Function to simulate
493
+ * @param options Transaction parameters including args, from, to
494
+ * @returns Decoded function result or false if simulation fails
495
+ */
365
496
  async function simulateTransaction(provider, abi, functionName, options) {
366
497
  try {
367
498
  const customInterface = new ethers_1.Interface(abi);
@@ -382,6 +513,13 @@ async function simulateTransaction(provider, abi, functionName, options) {
382
513
  return false;
383
514
  }
384
515
  }
516
+ /**
517
+ * Validate Ethereum address format and checksum.
518
+ * @param address Address string to validate
519
+ * @param logger Optional logger for error messages
520
+ * @param type Context type for logging
521
+ * @returns True if address is valid and checksummed
522
+ */
385
523
  function checkAddress(address, logger, type = 'contract') {
386
524
  const _logger = logger ?? console;
387
525
  if (!address) {
@@ -398,6 +536,15 @@ function checkAddress(address, logger, type = 'contract') {
398
536
  }
399
537
  return true;
400
538
  }
539
+ /**
540
+ * Fetch dynamic fee rate from on-chain oracle contract.
541
+ * Used for calculating loan interest repayment fees.
542
+ * @param provider Web3 provider
543
+ * @param category_id Fee category identifier
544
+ * @param address Context address for fee calculation
545
+ * @param chainId Optional chain ID (auto-detected if not provided)
546
+ * @returns Fee rate as decimal number
547
+ */
401
548
  async function getLoanOracleFeeRate(provider, category_id, address, chainId) {
402
549
  if (!(0, ethers_1.isAddress)(address)) {
403
550
  logger_1.Logger.log.error('getLoanOracleFee', 'address is undefined or not a valid address');
@@ -421,6 +568,19 @@ async function getLoanOracleFeeRate(provider, category_id, address, chainId) {
421
568
  const rawFee = await oracleContract.getContextFeeRate(hashedCategory, (0, ethers_1.getAddress)(address));
422
569
  return Number((0, ethers_1.formatUnits)(rawFee, 6));
423
570
  }
571
+ /**
572
+ * Query historical contract state across a block range.
573
+ * Useful for reconstructing historical data like TVL over time.
574
+ * @param provider Web3 provider
575
+ * @param contractAddress Target contract address
576
+ * @param abi Contract ABI
577
+ * @param methodName View function to call
578
+ * @param args Function arguments
579
+ * @param startBlock Starting block number
580
+ * @param endBlock Ending block number (current block if not specified)
581
+ * @param blockInterval Blocks between each query
582
+ * @returns Array of results with block numbers and timestamps
583
+ */
424
584
  async function getHistoricalContractData(provider, contractAddress, abi, methodName, args = [], startBlock, endBlock, blockInterval = 1000) {
425
585
  const contract = new ethers_1.ethers.Contract(contractAddress, abi, provider);
426
586
  const results = [];
@@ -446,12 +606,26 @@ async function getHistoricalContractData(provider, contractAddress, abi, methodN
446
606
  }
447
607
  return results;
448
608
  }
609
+ /**
610
+ * Query historical contract state at regular time intervals.
611
+ * Uses binary search to find blocks closest to target timestamps.
612
+ * @param provider Web3 provider
613
+ * @param contractAddress Target contract address
614
+ * @param abi Contract ABI
615
+ * @param methodName View function to call
616
+ * @param args Function arguments
617
+ * @param startDate Start date (string or timestamp)
618
+ * @param endDate End date (string or timestamp)
619
+ * @param intervalHours Hours between each query
620
+ * @returns Array of results with dates, blocks, and values
621
+ */
449
622
  async function getHistoricalContractDataByDate(provider, contractAddress, abi, methodName, args = [], startDate, endDate, intervalHours = 24) {
450
623
  const contract = new ethers_1.ethers.Contract(contractAddress, abi, provider);
451
624
  const startTimestamp = Math.floor(new Date(startDate).getTime() / 1000);
452
625
  const endTimestamp = Math.floor(new Date(endDate).getTime() / 1000);
453
626
  const intervalSeconds = intervalHours * 3600;
454
627
  const results = [];
628
+ // Binary search to find block closest to timestamp
455
629
  async function findBlockByTimestamp(targetTimestamp) {
456
630
  let left = 1;
457
631
  let right = await provider.getBlockNumber();
@@ -481,12 +655,15 @@ async function getHistoricalContractDataByDate(provider, contractAddress, abi, m
481
655
  return closestBlock;
482
656
  }
483
657
  try {
658
+ // Loop through time intervals
484
659
  for (let timestamp = startTimestamp; timestamp <= endTimestamp; timestamp += intervalSeconds) {
660
+ // Find closest block to timestamp
485
661
  const block = await findBlockByTimestamp(timestamp);
486
662
  if (!block) {
487
663
  logger_1.Logger.log.warn('getHistoricalContractDataByDate', `No block found for timestamp ${timestamp}`);
488
664
  continue;
489
665
  }
666
+ // Make the contract call
490
667
  const result = await contract[methodName](...args, {
491
668
  blockTag: block.number,
492
669
  });
@@ -1,17 +1,63 @@
1
+ /**
2
+ * Sentry-compatible logger shape — `@sentry/browser` can be passed directly.
3
+ */
1
4
  export type SDKLogger = {
2
5
  setTag: (key: string, value: string) => void;
3
6
  captureException: (err: unknown, context?: Record<string, any>) => void;
4
7
  };
8
+ /**
9
+ * Minimal breadcrumb shape forwarded to the internal Sentry sink. Mirrors the
10
+ * subset of Sentry's `Breadcrumb` the SDK populates, kept local so the logger
11
+ * stays decoupled from `@sentry/*` — and, more importantly, so it never has to
12
+ * import the analytics layer (which imports the logger, and would otherwise
13
+ * form a cycle; see CLAUDE.md §9).
14
+ *
15
+ * @internal
16
+ */
5
17
  export interface SDKBreadcrumb {
18
+ /** Breadcrumb grouping key. Always `'sdk.logger'` for logger-sourced crumbs. */
6
19
  category: string;
20
+ /** Short, low-cardinality label — the call-site tag passed to `Logger.log.*`. */
7
21
  message: string;
22
+ /** Severity. Logger warnings map to `'warning'`. */
8
23
  level: 'info' | 'warning' | 'error';
24
+ /** Already-sanitized structured context. */
9
25
  data?: Record<string, unknown>;
10
26
  }
27
+ /**
28
+ * The SDK's own always-on Sentry sink, wired by `initializeSentry` when
29
+ * analytics is enabled and cleared by `resetAnalytics`. This is deliberately
30
+ * distinct from the integrator-pluggable {@link SDKLogger} / {@link ILogger}
31
+ * slots: those belong to the consuming application, this one is the SDK's
32
+ * internal bridge so its diagnostics reach the partner-usage dashboard without
33
+ * the integrator having to wire anything.
34
+ *
35
+ * Severity policy (implemented in `analytics/sentry.ts`): `error` is captured
36
+ * as a Sentry issue via `captureException`; `warn` becomes a breadcrumb that
37
+ * rides along with the next captured event. `info` is intentionally not
38
+ * forwarded — method-call breadcrumbs from `instrumentClass` already cover the
39
+ * happy path, and forwarding every info line would only add noise/cost.
40
+ *
41
+ * @internal
42
+ */
11
43
  export interface SDKSentrySink {
44
+ /** Forward a (pre-sanitized) error to Sentry as an issue. */
12
45
  captureException: (error: unknown, context?: Record<string, unknown>) => void;
46
+ /** Forward a (pre-sanitized) breadcrumb to the active Sentry scope. */
13
47
  addBreadcrumb: (breadcrumb: SDKBreadcrumb) => void;
14
48
  }
49
+ /**
50
+ * Structured logger interface (debug/info/warn/error). Sanitization runs
51
+ * before any method here is invoked, so implementations needn't scrub secrets.
52
+ *
53
+ * ```ts
54
+ * Logger.setStructuredLogger({
55
+ * info: (tag, ctx) => pino.info({ tag, ...ctx }),
56
+ * warn: (tag, ctx) => pino.warn({ tag, ...ctx }),
57
+ * error: (tag, err, ctx) => pino.error({ tag, err, ...ctx }),
58
+ * });
59
+ * ```
60
+ */
15
61
  export interface ILogger {
16
62
  debug?: (tag: string, context?: Record<string, unknown>) => void;
17
63
  info?: (tag: string, context?: Record<string, unknown>) => void;
@@ -19,9 +65,18 @@ export interface ILogger {
19
65
  error: (tag: string, error: unknown, context?: Record<string, unknown>) => void;
20
66
  }
21
67
  declare function setLogger(customLogger: SDKLogger): void;
68
+ /** Plug in an `ILogger`. Independent of `setLogger`; pass `null` to clear. */
22
69
  declare function setStructuredLogger(custom: ILogger | null): void;
23
70
  declare function getLogger(): SDKLogger | null;
24
71
  declare function getStructuredLogger(): ILogger | null;
72
+ /**
73
+ * Wire (or clear, with `null`) the SDK's internal Sentry sink. Called by
74
+ * `initializeSentry` after a successful Sentry init, and reset by
75
+ * `resetAnalytics`. Not part of the integrator-facing API — applications wire
76
+ * their own logging through {@link setLogger} / {@link setStructuredLogger}.
77
+ *
78
+ * @internal
79
+ */
25
80
  declare function setSentrySink(sink: SDKSentrySink | null): void;
26
81
  declare function setDevMode(devMode: boolean): void;
27
82
  declare function isDevMode(): boolean;
@@ -42,6 +42,7 @@ let isDev = false;
42
42
  function setLogger(customLogger) {
43
43
  logger = customLogger;
44
44
  }
45
+ /** Plug in an `ILogger`. Independent of `setLogger`; pass `null` to clear. */
45
46
  function setStructuredLogger(custom) {
46
47
  structuredLogger = custom;
47
48
  }
@@ -51,6 +52,14 @@ function getLogger() {
51
52
  function getStructuredLogger() {
52
53
  return structuredLogger;
53
54
  }
55
+ /**
56
+ * Wire (or clear, with `null`) the SDK's internal Sentry sink. Called by
57
+ * `initializeSentry` after a successful Sentry init, and reset by
58
+ * `resetAnalytics`. Not part of the integrator-facing API — applications wire
59
+ * their own logging through {@link setLogger} / {@link setStructuredLogger}.
60
+ *
61
+ * @internal
62
+ */
54
63
  function setSentrySink(sink) {
55
64
  sentrySink = sink;
56
65
  }
@@ -60,6 +69,7 @@ function setDevMode(devMode) {
60
69
  function isDevMode() {
61
70
  return isDev;
62
71
  }
72
+ /** Internal logger: DEV mode → console; production → SDKLogger. Sanitized either way. */
63
73
  const log = {
64
74
  info: (tag, ...args) => {
65
75
  const safeArgs = args.map((a) => (0, sanitize_1.sanitizeForLogging)(a));
@@ -75,6 +85,9 @@ const log = {
75
85
  }
76
86
  logger?.setTag('warning', tag);
77
87
  structuredLogger?.warn?.(tag, structuredContext(safeArgs));
88
+ // Warnings ride along as breadcrumbs on the next captured event rather
89
+ // than becoming standalone issues — keeps Sentry volume bounded (see the
90
+ // severity policy on SDKSentrySink).
78
91
  sentrySink?.addBreadcrumb({
79
92
  category: 'sdk.logger',
80
93
  level: 'warning',
@@ -92,9 +105,15 @@ const log = {
92
105
  }
93
106
  logger?.captureException(safeError, { tag, ...safeContext });
94
107
  structuredLogger?.error(tag, safeError, safeContext);
108
+ // The SDK's own bridge to Sentry: errors become issues. `safeError` /
109
+ // `safeContext` are already sanitized above, so the sink forwards as-is.
95
110
  sentrySink?.captureException(safeError, { tag, ...safeContext });
96
111
  },
97
112
  };
113
+ /**
114
+ * Pino-friendly shape: if the first arg is a plain object, pass it through
115
+ * (with subsequent args as `extras`); otherwise wrap as `{ args }`.
116
+ */
98
117
  function structuredContext(args) {
99
118
  if (args.length === 0)
100
119
  return undefined;