upshift-sdk 8.20.1
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.
- package/LICENSE +21 -0
- package/README.md +349 -0
- package/lib/abis/AddressResolver.d.ts +28 -0
- package/lib/abis/AddressResolver.js +23 -0
- package/lib/abis/ChainlinkV3.d.ts +87 -0
- package/lib/abis/ChainlinkV3.js +117 -0
- package/lib/abis/ERC20.d.ts +168 -0
- package/lib/abis/ERC20.js +226 -0
- package/lib/abis/ERC20_Bytes32.d.ts +139 -0
- package/lib/abis/ERC20_Bytes32.js +196 -0
- package/lib/abis/ERC4626.d.ts +364 -0
- package/lib/abis/ERC4626.js +507 -0
- package/lib/abis/ERC721.d.ts +231 -0
- package/lib/abis/ERC721.js +321 -0
- package/lib/abis/FeeOracle.d.ts +120 -0
- package/lib/abis/FeeOracle.js +162 -0
- package/lib/abis/LendingPool.d.ts +1393 -0
- package/lib/abis/LendingPool.js +1807 -0
- package/lib/abis/LendingPoolV2.d.ts +1413 -0
- package/lib/abis/LendingPoolV2.js +1833 -0
- package/lib/abis/LendingPoolV3.d.ts +1677 -0
- package/lib/abis/LendingPoolV3.js +1160 -0
- package/lib/abis/Loan.d.ts +837 -0
- package/lib/abis/Loan.js +1080 -0
- package/lib/abis/MultiAssetNativeDepositWrapper.d.ts +137 -0
- package/lib/abis/MultiAssetNativeDepositWrapper.js +125 -0
- package/lib/abis/Multicall3.d.ts +30 -0
- package/lib/abis/Multicall3.js +97 -0
- package/lib/abis/OFT.d.ts +116 -0
- package/lib/abis/OFT.js +85 -0
- package/lib/abis/PoolAdapter.d.ts +36 -0
- package/lib/abis/PoolAdapter.js +51 -0
- package/lib/abis/RewardDistributor.d.ts +267 -0
- package/lib/abis/RewardDistributor.js +352 -0
- package/lib/abis/RwaRedeemSubaccount.d.ts +747 -0
- package/lib/abis/RwaRedeemSubaccount.js +548 -0
- package/lib/abis/SmartAccount.d.ts +17 -0
- package/lib/abis/SmartAccount.js +19 -0
- package/lib/abis/SwapRouter.d.ts +1043 -0
- package/lib/abis/SwapRouter.js +740 -0
- package/lib/abis/TextResolver.d.ts +16 -0
- package/lib/abis/TextResolver.js +16 -0
- package/lib/abis/TokenizedVaultV2.d.ts +1364 -0
- package/lib/abis/TokenizedVaultV2.js +1041 -0
- package/lib/abis/TokenizedVaultV2DepositWithPermit.d.ts +1456 -0
- package/lib/abis/TokenizedVaultV2DepositWithPermit.js +1878 -0
- package/lib/abis/TokenizedVaultV2Receipt.d.ts +1568 -0
- package/lib/abis/TokenizedVaultV2Receipt.js +1061 -0
- package/lib/abis/TokenizedVaultV2SenderAllocationWhitelist.d.ts +454 -0
- package/lib/abis/TokenizedVaultV2SenderAllocationWhitelist.js +327 -0
- package/lib/abis/TokenizedVaultV2WhitelistedAllocation.d.ts +1466 -0
- package/lib/abis/TokenizedVaultV2WhitelistedAllocation.js +1092 -0
- package/lib/abis/TokenizedVaultV2WhitelistedAssets.d.ts +274 -0
- package/lib/abis/TokenizedVaultV2WhitelistedAssets.js +167 -0
- package/lib/abis/UniversalResolverResolve.d.ts +69 -0
- package/lib/abis/UniversalResolverResolve.js +35 -0
- package/lib/abis/UniversalSignatureValidator.d.ts +17 -0
- package/lib/abis/UniversalSignatureValidator.js +30 -0
- package/lib/abis/WrapperAdapter.d.ts +71 -0
- package/lib/abis/WrapperAdapter.js +77 -0
- package/lib/abis/index.d.ts +34 -0
- package/lib/abis/index.js +51 -0
- package/lib/adapters/evm/getters.d.ts +19 -0
- package/lib/adapters/evm/getters.js +209 -0
- package/lib/adapters/evm/index.d.ts +353 -0
- package/lib/adapters/evm/index.js +434 -0
- package/lib/adapters/evm/utils.d.ts +8 -0
- package/lib/adapters/evm/utils.js +51 -0
- package/lib/adapters/solana/constants.d.ts +33 -0
- package/lib/adapters/solana/constants.js +52 -0
- package/lib/adapters/solana/getters.d.ts +11 -0
- package/lib/adapters/solana/getters.js +165 -0
- package/lib/adapters/solana/idl/vault-idl.d.ts +272 -0
- package/lib/adapters/solana/idl/vault-idl.js +1084 -0
- package/lib/adapters/solana/index.d.ts +233 -0
- package/lib/adapters/solana/index.js +291 -0
- package/lib/adapters/solana/types.d.ts +67 -0
- package/lib/adapters/solana/types.js +3 -0
- package/lib/adapters/solana/utils.d.ts +141 -0
- package/lib/adapters/solana/utils.js +595 -0
- package/lib/adapters/solana/vault.actions.d.ts +57 -0
- package/lib/adapters/solana/vault.actions.js +379 -0
- package/lib/adapters/stellar/actions.d.ts +28 -0
- package/lib/adapters/stellar/actions.js +77 -0
- package/lib/adapters/stellar/constants.d.ts +43 -0
- package/lib/adapters/stellar/constants.js +53 -0
- package/lib/adapters/stellar/getters.d.ts +68 -0
- package/lib/adapters/stellar/getters.js +290 -0
- package/lib/adapters/stellar/index.d.ts +114 -0
- package/lib/adapters/stellar/index.js +175 -0
- package/lib/adapters/stellar/soroban.d.ts +123 -0
- package/lib/adapters/stellar/soroban.js +613 -0
- package/lib/adapters/stellar/submit.d.ts +34 -0
- package/lib/adapters/stellar/submit.js +149 -0
- package/lib/adapters/stellar/types.d.ts +58 -0
- package/lib/adapters/stellar/types.js +6 -0
- package/lib/adapters/stellar/utils.d.ts +24 -0
- package/lib/adapters/stellar/utils.js +34 -0
- package/lib/adapters/sui/constants.d.ts +14 -0
- package/lib/adapters/sui/constants.js +29 -0
- package/lib/adapters/sui/getters.d.ts +9 -0
- package/lib/adapters/sui/getters.js +60 -0
- package/lib/adapters/sui/index.d.ts +45 -0
- package/lib/adapters/sui/index.js +101 -0
- package/lib/adapters/sui/transformer.d.ts +10 -0
- package/lib/adapters/sui/transformer.js +107 -0
- package/lib/adapters/sui/types.d.ts +66 -0
- package/lib/adapters/sui/types.js +3 -0
- package/lib/adapters/sui/utils.d.ts +10 -0
- package/lib/adapters/sui/utils.js +29 -0
- package/lib/core/analytics/chain-name.d.ts +9 -0
- package/lib/core/analytics/chain-name.js +34 -0
- package/lib/core/analytics/constants.d.ts +5 -0
- package/lib/core/analytics/constants.js +9 -0
- package/lib/core/analytics/env.d.ts +29 -0
- package/lib/core/analytics/env.js +59 -0
- package/lib/core/analytics/index.d.ts +36 -0
- package/lib/core/analytics/index.js +79 -0
- package/lib/core/analytics/instrumentation.d.ts +29 -0
- package/lib/core/analytics/instrumentation.js +277 -0
- package/lib/core/analytics/method-taxonomy.d.ts +19 -0
- package/lib/core/analytics/method-taxonomy.js +128 -0
- package/lib/core/analytics/metrics.d.ts +33 -0
- package/lib/core/analytics/metrics.js +116 -0
- package/lib/core/analytics/sanitize.d.ts +44 -0
- package/lib/core/analytics/sanitize.js +260 -0
- package/lib/core/analytics/sentry-runtime.d.ts +15 -0
- package/lib/core/analytics/sentry-runtime.js +97 -0
- package/lib/core/analytics/sentry.d.ts +67 -0
- package/lib/core/analytics/sentry.js +613 -0
- package/lib/core/analytics/types.d.ts +48 -0
- package/lib/core/analytics/types.js +3 -0
- package/lib/core/analytics/user-identity.d.ts +41 -0
- package/lib/core/analytics/user-identity.js +141 -0
- package/lib/core/analytics/version.d.ts +6 -0
- package/lib/core/analytics/version.js +10 -0
- package/lib/core/attribution.d.ts +111 -0
- package/lib/core/attribution.js +142 -0
- package/lib/core/auth/index.d.ts +1 -0
- package/lib/core/auth/index.js +18 -0
- package/lib/core/auth/verify.d.ts +2 -0
- package/lib/core/auth/verify.js +31 -0
- package/lib/core/base.class.d.ts +152 -0
- package/lib/core/base.class.js +172 -0
- package/lib/core/cache.d.ts +9 -0
- package/lib/core/cache.js +31 -0
- package/lib/core/constants/adapters.d.ts +103 -0
- package/lib/core/constants/adapters.js +180 -0
- package/lib/core/constants/core.d.ts +133 -0
- package/lib/core/constants/core.js +209 -0
- package/lib/core/constants/swap-router.d.ts +150 -0
- package/lib/core/constants/swap-router.js +169 -0
- package/lib/core/constants/vaults.d.ts +93 -0
- package/lib/core/constants/vaults.js +273 -0
- package/lib/core/constants/web3.d.ts +91 -0
- package/lib/core/constants/web3.js +229 -0
- package/lib/core/errors/index.d.ts +114 -0
- package/lib/core/errors/index.js +183 -0
- package/lib/core/fetcher.d.ts +198 -0
- package/lib/core/fetcher.js +903 -0
- package/lib/core/helpers/adapters.d.ts +13 -0
- package/lib/core/helpers/adapters.js +39 -0
- package/lib/core/helpers/chain-address.d.ts +13 -0
- package/lib/core/helpers/chain-address.js +47 -0
- package/lib/core/helpers/chain-error.d.ts +207 -0
- package/lib/core/helpers/chain-error.js +682 -0
- package/lib/core/helpers/chain-support.d.ts +80 -0
- package/lib/core/helpers/chain-support.js +115 -0
- package/lib/core/helpers/core.d.ts +68 -0
- package/lib/core/helpers/core.js +285 -0
- package/lib/core/helpers/explorer-link.d.ts +16 -0
- package/lib/core/helpers/explorer-link.js +26 -0
- package/lib/core/helpers/multicall.d.ts +68 -0
- package/lib/core/helpers/multicall.js +103 -0
- package/lib/core/helpers/revert-decode.d.ts +248 -0
- package/lib/core/helpers/revert-decode.js +515 -0
- package/lib/core/helpers/signer.d.ts +52 -0
- package/lib/core/helpers/signer.js +145 -0
- package/lib/core/helpers/swap-router.d.ts +211 -0
- package/lib/core/helpers/swap-router.js +480 -0
- package/lib/core/helpers/vault-version.d.ts +23 -0
- package/lib/core/helpers/vault-version.js +75 -0
- package/lib/core/helpers/vaults.d.ts +89 -0
- package/lib/core/helpers/vaults.js +235 -0
- package/lib/core/helpers/web3.d.ts +353 -0
- package/lib/core/helpers/web3.js +992 -0
- package/lib/core/index.d.ts +23 -0
- package/lib/core/index.js +40 -0
- package/lib/core/logger/index.d.ts +98 -0
- package/lib/core/logger/index.js +144 -0
- package/lib/core/logger/slack.d.ts +16 -0
- package/lib/core/logger/slack.js +57 -0
- package/lib/core/vault-metadata.d.ts +12 -0
- package/lib/core/vault-metadata.js +42 -0
- package/lib/core/version-check.d.ts +58 -0
- package/lib/core/version-check.js +182 -0
- package/lib/evm/index.d.ts +2 -0
- package/lib/evm/index.js +19 -0
- package/lib/evm/methods/crossChainVault.d.ts +128 -0
- package/lib/evm/methods/crossChainVault.js +853 -0
- package/lib/evm/methods/crossChainVaultRegistry.d.ts +93 -0
- package/lib/evm/methods/crossChainVaultRegistry.js +240 -0
- package/lib/evm/methods/index.d.ts +2 -0
- package/lib/evm/methods/index.js +19 -0
- package/lib/evm/types/crossChain.d.ts +363 -0
- package/lib/evm/types/crossChain.js +20 -0
- package/lib/evm/types/index.d.ts +1 -0
- package/lib/evm/types/index.js +18 -0
- package/lib/index.d.ts +30 -0
- package/lib/index.js +52 -0
- package/lib/main.d.ts +527 -0
- package/lib/main.js +601 -0
- package/lib/modules/api/fetcher.d.ts +82 -0
- package/lib/modules/api/fetcher.js +150 -0
- package/lib/modules/api/index.d.ts +1 -0
- package/lib/modules/api/index.js +6 -0
- package/lib/modules/api/main.d.ts +313 -0
- package/lib/modules/api/main.js +479 -0
- package/lib/modules/sub-accounts/fetcher.d.ts +53 -0
- package/lib/modules/sub-accounts/fetcher.js +120 -0
- package/lib/modules/sub-accounts/index.d.ts +2 -0
- package/lib/modules/sub-accounts/index.js +19 -0
- package/lib/modules/sub-accounts/main.d.ts +243 -0
- package/lib/modules/sub-accounts/main.js +205 -0
- package/lib/modules/sub-accounts/utils.d.ts +106 -0
- package/lib/modules/sub-accounts/utils.js +112 -0
- package/lib/modules/vaults/adapter.helpers.d.ts +64 -0
- package/lib/modules/vaults/adapter.helpers.js +184 -0
- package/lib/modules/vaults/fetcher.d.ts +147 -0
- package/lib/modules/vaults/fetcher.js +368 -0
- package/lib/modules/vaults/getters.d.ts +570 -0
- package/lib/modules/vaults/getters.js +3051 -0
- package/lib/modules/vaults/index.d.ts +20 -0
- package/lib/modules/vaults/index.js +44 -0
- package/lib/modules/vaults/main.d.ts +601 -0
- package/lib/modules/vaults/main.js +1623 -0
- package/lib/modules/vaults/prefetch.d.ts +65 -0
- package/lib/modules/vaults/prefetch.js +120 -0
- package/lib/modules/vaults/read.actions.d.ts +225 -0
- package/lib/modules/vaults/read.actions.js +596 -0
- package/lib/modules/vaults/types.d.ts +71 -0
- package/lib/modules/vaults/types.js +3 -0
- package/lib/modules/vaults/utils/call-data-decoder.d.ts +61 -0
- package/lib/modules/vaults/utils/call-data-decoder.js +194 -0
- package/lib/modules/vaults/utils/date-utils.d.ts +50 -0
- package/lib/modules/vaults/utils/date-utils.js +84 -0
- package/lib/modules/vaults/utils.d.ts +140 -0
- package/lib/modules/vaults/utils.js +799 -0
- package/lib/modules/vaults/write.actions.d.ts +529 -0
- package/lib/modules/vaults/write.actions.js +1749 -0
- package/lib/polyfills.d.ts +1 -0
- package/lib/polyfills.js +12 -0
- package/lib/sdk.d.ts +26721 -0
- package/lib/services/coingecko/fetcher.d.ts +15 -0
- package/lib/services/coingecko/fetcher.js +67 -0
- package/lib/services/coingecko/index.d.ts +2 -0
- package/lib/services/coingecko/index.js +19 -0
- package/lib/services/coingecko/utils.d.ts +1 -0
- package/lib/services/coingecko/utils.js +24 -0
- package/lib/services/debank/fetcher.d.ts +126 -0
- package/lib/services/debank/fetcher.js +47 -0
- package/lib/services/debank/index.d.ts +2 -0
- package/lib/services/debank/index.js +19 -0
- package/lib/services/debank/utils.d.ts +38 -0
- package/lib/services/debank/utils.js +297 -0
- package/lib/services/layerzero/deposits.d.ts +49 -0
- package/lib/services/layerzero/deposits.js +166 -0
- package/lib/services/layerzero/redeems.d.ts +20 -0
- package/lib/services/layerzero/redeems.js +92 -0
- package/lib/services/layerzero/utils.d.ts +9 -0
- package/lib/services/layerzero/utils.js +22 -0
- package/lib/services/octavfi/fetcher.d.ts +9 -0
- package/lib/services/octavfi/fetcher.js +103 -0
- package/lib/services/octavfi/index.d.ts +3 -0
- package/lib/services/octavfi/index.js +20 -0
- package/lib/services/octavfi/types.d.ts +34 -0
- package/lib/services/octavfi/types.js +3 -0
- package/lib/services/octavfi/utils.d.ts +16 -0
- package/lib/services/octavfi/utils.js +212 -0
- package/lib/services/subgraph/fetcher.d.ts +2 -0
- package/lib/services/subgraph/fetcher.js +61 -0
- package/lib/services/subgraph/index.d.ts +2 -0
- package/lib/services/subgraph/index.js +19 -0
- package/lib/services/subgraph/schema.d.ts +45 -0
- package/lib/services/subgraph/schema.js +75 -0
- package/lib/services/subgraph/vaults.d.ts +25 -0
- package/lib/services/subgraph/vaults.js +1106 -0
- package/lib/services/swap-quotes/index.d.ts +105 -0
- package/lib/services/swap-quotes/index.js +77 -0
- package/lib/services/swap-quotes/paraswap.d.ts +51 -0
- package/lib/services/swap-quotes/paraswap.js +138 -0
- package/lib/types/api.d.ts +280 -0
- package/lib/types/api.js +3 -0
- package/lib/types/index.d.ts +12 -0
- package/lib/types/index.js +28 -0
- package/lib/types/points.d.ts +28 -0
- package/lib/types/points.js +3 -0
- package/lib/types/pools.d.ts +144 -0
- package/lib/types/pools.js +3 -0
- package/lib/types/staking.d.ts +28 -0
- package/lib/types/staking.js +3 -0
- package/lib/types/sub-accounts.d.ts +140 -0
- package/lib/types/sub-accounts.js +3 -0
- package/lib/types/subgraph.d.ts +74 -0
- package/lib/types/subgraph.js +3 -0
- package/lib/types/typed-contract.d.ts +102 -0
- package/lib/types/typed-contract.js +3 -0
- package/lib/types/user.d.ts +1 -0
- package/lib/types/user.js +3 -0
- package/lib/types/vaults.d.ts +714 -0
- package/lib/types/vaults.js +24 -0
- package/lib/types/web3.d.ts +51 -0
- package/lib/types/web3.js +14 -0
- package/lib/types/webserver.d.ts +698 -0
- package/lib/types/webserver.js +3 -0
- package/package.json +78 -0
|
@@ -0,0 +1,992 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.getManagementFeePercent = exports.getSymbol = exports.getReceiptTokenAddress = exports.getReceiptTokenAddressOrThrow = exports.getWhitelistedAssets = exports.getDecimalsOrThrow = exports.getDecimals = exports.explorerLink = exports.getInfuraProvider = exports.createProvider = exports.getChainId = exports.determineRpcBatchMaxCount = exports.determineBlockSkipInternal = exports.determineSecondsPerBlock = exports.determineBlockCutoff = void 0;
|
|
4
|
+
exports.createContract = createContract;
|
|
5
|
+
exports.getTokenMetadata = getTokenMetadata;
|
|
6
|
+
exports.simulateTransaction = simulateTransaction;
|
|
7
|
+
exports.checkAddress = checkAddress;
|
|
8
|
+
exports.getLoanOracleFeeRate = getLoanOracleFeeRate;
|
|
9
|
+
exports.getHistoricalContractData = getHistoricalContractData;
|
|
10
|
+
exports.getHistoricalContractDataByDate = getHistoricalContractDataByDate;
|
|
11
|
+
const ethers_1 = require("ethers");
|
|
12
|
+
const errors_1 = require("../errors");
|
|
13
|
+
const cache_1 = require("../cache");
|
|
14
|
+
const logger_1 = require("../logger");
|
|
15
|
+
const web3_1 = require("../constants/web3");
|
|
16
|
+
const fetcher_1 = require("../fetcher");
|
|
17
|
+
const chain_address_1 = require("./chain-address");
|
|
18
|
+
const chain_error_1 = require("./chain-error");
|
|
19
|
+
const constants_1 = require("../../adapters/solana/constants");
|
|
20
|
+
const abis_1 = require("../../abis");
|
|
21
|
+
const TokenizedVaultV2_1 = require("../../abis/TokenizedVaultV2");
|
|
22
|
+
const TokenizedVaultV2WhitelistedAssets_1 = require("../../abis/TokenizedVaultV2WhitelistedAssets");
|
|
23
|
+
//import { getVaultVersion } from './helpers.vaults';
|
|
24
|
+
const vault_version_1 = require("./vault-version");
|
|
25
|
+
/**
|
|
26
|
+
* Web3 Helper Utilities
|
|
27
|
+
*
|
|
28
|
+
* Core utilities for blockchain interaction:
|
|
29
|
+
* - Provider Management: createProvider, getInfuraProvider, getChainId
|
|
30
|
+
* - Contract Helpers: createContract, getDecimals, getSymbol, getTokenMetadata
|
|
31
|
+
* - Transaction Utilities: simulateTransaction, checkAddress
|
|
32
|
+
* - Historical Queries: getHistoricalContractData, getHistoricalContractDataByDate
|
|
33
|
+
* - Oracle Integration: getLoanOracleFeeRate
|
|
34
|
+
* - Block Utilities: determineBlockCutoff, determineBlockSkipInternal
|
|
35
|
+
*/
|
|
36
|
+
/**
|
|
37
|
+
* Get maximum block range for historical queries per chain.
|
|
38
|
+
* Prevents RPC timeouts by limiting lookback window.
|
|
39
|
+
* @param chain Chain ID
|
|
40
|
+
* @returns Maximum number of blocks to query
|
|
41
|
+
*/
|
|
42
|
+
const determineBlockCutoff = (chain) => {
|
|
43
|
+
switch (chain) {
|
|
44
|
+
case 56:
|
|
45
|
+
return 120_000;
|
|
46
|
+
case 43114:
|
|
47
|
+
return 120_000;
|
|
48
|
+
case 143:
|
|
49
|
+
return 3_456_000;
|
|
50
|
+
default:
|
|
51
|
+
return 150_000;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
exports.determineBlockCutoff = determineBlockCutoff;
|
|
55
|
+
/**
|
|
56
|
+
* Approximate block time in seconds per chain.
|
|
57
|
+
* Used to estimate time ranges from block counts.
|
|
58
|
+
* @param chain - Chain ID
|
|
59
|
+
* @returns Seconds per block
|
|
60
|
+
*/
|
|
61
|
+
const determineSecondsPerBlock = (chain) => {
|
|
62
|
+
switch (chain) {
|
|
63
|
+
case 143: // Monad ~500ms
|
|
64
|
+
return 0.5;
|
|
65
|
+
case 56: // BSC ~2s
|
|
66
|
+
case 43114: // Avalanche ~2s
|
|
67
|
+
return 2;
|
|
68
|
+
default: // Ethereum ~12s
|
|
69
|
+
return 12;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
exports.determineSecondsPerBlock = determineSecondsPerBlock;
|
|
73
|
+
/**
|
|
74
|
+
* Get block interval for paginated historical queries per chain.
|
|
75
|
+
* Respects RPC eth_getLogs range limits.
|
|
76
|
+
* @param chain Chain ID
|
|
77
|
+
* @returns Block interval for pagination
|
|
78
|
+
*/
|
|
79
|
+
const determineBlockSkipInternal = (chain) => {
|
|
80
|
+
switch (chain) {
|
|
81
|
+
case 43114:
|
|
82
|
+
return 8_000;
|
|
83
|
+
case 56:
|
|
84
|
+
return 8_000;
|
|
85
|
+
case 143: // Monad — Alchemy limits eth_getLogs to 1000 blocks
|
|
86
|
+
return 1_000;
|
|
87
|
+
case 999: // HyperEVM — rpc.hypurrscan.io limits eth_getLogs to 1000 blocks
|
|
88
|
+
return 1_000;
|
|
89
|
+
default:
|
|
90
|
+
// 10k blocks is the eth_getLogs range cap enforced by every mainstream
|
|
91
|
+
// provider (Alchemy, Infura, dRPC, QuickNode). The previous 50k default
|
|
92
|
+
// was rejected outright with JSON-RPC -32600 ("You can make eth_getLogs
|
|
93
|
+
// requests with up to a 10000 block range") on Ethereum mainnet, which
|
|
94
|
+
// failed `getVaultRedemptionHistory` for every vault on an unlisted
|
|
95
|
+
// chain. RPC-count impact: a 150k-block cutoff now costs 15 getLogs
|
|
96
|
+
// calls instead of 3, batched 20-concurrent, so still one round trip.
|
|
97
|
+
return 10_000;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
exports.determineBlockSkipInternal = determineBlockSkipInternal;
|
|
101
|
+
/**
|
|
102
|
+
* Default batch cap. Chosen to stay under the smallest limit among the
|
|
103
|
+
* providers we route to by default (e.g. rpc.hypurrscan.io rejects > 20).
|
|
104
|
+
*/
|
|
105
|
+
const DEFAULT_RPC_BATCH_MAX_COUNT = 10;
|
|
106
|
+
/**
|
|
107
|
+
* Maximum JSON-RPC calls ethers may coalesce into a single batched HTTP
|
|
108
|
+
* request for a given endpoint.
|
|
109
|
+
*
|
|
110
|
+
* Providers advertise wildly different batch limits and reject the whole batch
|
|
111
|
+
* — not the excess — when exceeded, so one oversized batch fails every call
|
|
112
|
+
* inside it. dRPC's free tier caps batches at 3, which made every Mezo read
|
|
113
|
+
* fail with `server response 500 … "Batch of more than 3 requests are not
|
|
114
|
+
* allowed"` (the single highest-volume SDK error in production).
|
|
115
|
+
*
|
|
116
|
+
* Detection is host-based rather than chain-based because the limit is a
|
|
117
|
+
* property of the endpoint, not the chain: the same chain served by a
|
|
118
|
+
* self-hosted node has no such cap.
|
|
119
|
+
*
|
|
120
|
+
* @param rpcUrl - The RPC endpoint URL. Unparseable values fall back to the
|
|
121
|
+
* conservative default rather than throwing.
|
|
122
|
+
* @returns Batch size cap to pass to ethers as `batchMaxCount`.
|
|
123
|
+
*/
|
|
124
|
+
const determineRpcBatchMaxCount = (rpcUrl) => {
|
|
125
|
+
let host = '';
|
|
126
|
+
try {
|
|
127
|
+
host = new URL(rpcUrl).hostname.toLowerCase();
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return DEFAULT_RPC_BATCH_MAX_COUNT;
|
|
131
|
+
}
|
|
132
|
+
// dRPC free tier: "Batch of more than 3 requests are not allowed".
|
|
133
|
+
if (host === 'drpc.org' || host.endsWith('.drpc.org'))
|
|
134
|
+
return 3;
|
|
135
|
+
return DEFAULT_RPC_BATCH_MAX_COUNT;
|
|
136
|
+
};
|
|
137
|
+
exports.determineRpcBatchMaxCount = determineRpcBatchMaxCount;
|
|
138
|
+
/**
|
|
139
|
+
* Retrieve chain ID from web3 provider.
|
|
140
|
+
* Handles both initialized and uninitialized provider states.
|
|
141
|
+
* @param provider Web3 provider instance
|
|
142
|
+
* @returns Numeric chain ID
|
|
143
|
+
*/
|
|
144
|
+
const getChainId = async (provider) => {
|
|
145
|
+
try {
|
|
146
|
+
if (!provider?._network) {
|
|
147
|
+
return Number((await provider.getNetwork()).chainId);
|
|
148
|
+
}
|
|
149
|
+
else {
|
|
150
|
+
return Number(provider?._network.chainId);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
return Number((await provider.getNetwork()).chainId);
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
exports.getChainId = getChainId;
|
|
158
|
+
/**
|
|
159
|
+
* Create ethers contract instance with address validation.
|
|
160
|
+
* @param provider Web3 provider for contract calls
|
|
161
|
+
* @param address Contract address (must be checksummed)
|
|
162
|
+
* @param abi Contract ABI (must be declared with `as const`)
|
|
163
|
+
* @returns Strongly-typed contract instance or undefined if address invalid
|
|
164
|
+
*/
|
|
165
|
+
function createContract({ provider, address, abi, }) {
|
|
166
|
+
const goodAddress = checkAddress(address);
|
|
167
|
+
if (!goodAddress)
|
|
168
|
+
return;
|
|
169
|
+
const contract = new ethers_1.Contract(address, abi, provider);
|
|
170
|
+
if (!contract) {
|
|
171
|
+
logger_1.Logger.log.error('createContract', 'contract does not exist on connected chain');
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
return contract;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Create or reuse a cached JSON-RPC provider.
|
|
178
|
+
* Passing `chainId` enables ethers' `staticNetwork` to skip the `eth_chainId`
|
|
179
|
+
* round-trip on first use.
|
|
180
|
+
*
|
|
181
|
+
* @param rpcUrl RPC endpoint URL — must be a non-empty string.
|
|
182
|
+
* @param chainId Optional chain ID — enables staticNetwork
|
|
183
|
+
* @throws Error with a clear, remediable message when `rpcUrl` is missing or
|
|
184
|
+
* empty. Without this guard, ethers v6 silently defaults to
|
|
185
|
+
* `http://localhost:8545` and surfaces a cryptic
|
|
186
|
+
* `network is not available yet (NETWORK_ERROR)` on the first RPC call.
|
|
187
|
+
*/
|
|
188
|
+
const createProvider = (rpcUrl, chainId) => {
|
|
189
|
+
if (typeof rpcUrl !== 'string' || rpcUrl.trim().length === 0) {
|
|
190
|
+
const forChain = chainId ? ` for chain ${chainId}` : '';
|
|
191
|
+
throw new Error(`createProvider: no RPC URL provided${forChain}. ` +
|
|
192
|
+
'Pass an RPC URL when constructing AugustSDK ' +
|
|
193
|
+
'(`new AugustSDK({ providers: { [chainId]: url } })`), ' +
|
|
194
|
+
`or set the AUGUST_RPC_${chainId ?? '<chainId>'} environment variable.`);
|
|
195
|
+
}
|
|
196
|
+
const cacheKey = chainId ? `${rpcUrl}|${chainId}` : rpcUrl;
|
|
197
|
+
if (cache_1.CACHE.has(cacheKey))
|
|
198
|
+
return cache_1.CACHE.get(cacheKey);
|
|
199
|
+
// batchMaxCount respects server-side batch limits — providers reject the
|
|
200
|
+
// entire batch when it is exceeded (see determineRpcBatchMaxCount).
|
|
201
|
+
const batchMaxCount = (0, exports.determineRpcBatchMaxCount)(rpcUrl);
|
|
202
|
+
const provider = chainId
|
|
203
|
+
? new ethers_1.JsonRpcProvider(rpcUrl, ethers_1.Network.from(chainId), {
|
|
204
|
+
staticNetwork: ethers_1.Network.from(chainId),
|
|
205
|
+
batchMaxCount,
|
|
206
|
+
})
|
|
207
|
+
: new ethers_1.JsonRpcProvider(rpcUrl, undefined, {
|
|
208
|
+
batchMaxCount,
|
|
209
|
+
});
|
|
210
|
+
cache_1.CACHE.set(cacheKey, provider);
|
|
211
|
+
return provider;
|
|
212
|
+
};
|
|
213
|
+
exports.createProvider = createProvider;
|
|
214
|
+
/**
|
|
215
|
+
* Create or reuse a cached Infura provider for the specified chain.
|
|
216
|
+
* @param infura Configuration with chain ID and API key
|
|
217
|
+
*/
|
|
218
|
+
const getInfuraProvider = (infura) => {
|
|
219
|
+
let baseUrl = 'https://';
|
|
220
|
+
switch (infura.chainId) {
|
|
221
|
+
case 8453: {
|
|
222
|
+
baseUrl = baseUrl + 'base-mainnet';
|
|
223
|
+
break;
|
|
224
|
+
}
|
|
225
|
+
case 43114: {
|
|
226
|
+
baseUrl = baseUrl + 'avalanche-mainnet';
|
|
227
|
+
break;
|
|
228
|
+
}
|
|
229
|
+
case 137: {
|
|
230
|
+
baseUrl = baseUrl + 'polygon-mainnet';
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
case 42161: {
|
|
234
|
+
baseUrl = baseUrl + 'arbitrum-mainnet';
|
|
235
|
+
break;
|
|
236
|
+
}
|
|
237
|
+
default: {
|
|
238
|
+
baseUrl = baseUrl + 'mainnet';
|
|
239
|
+
break;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
const url = `${baseUrl}.infura.io/v3/${infura.apiKey}`;
|
|
243
|
+
return (0, exports.createProvider)(url, infura.chainId);
|
|
244
|
+
};
|
|
245
|
+
exports.getInfuraProvider = getInfuraProvider;
|
|
246
|
+
var explorer_link_1 = require("./explorer-link");
|
|
247
|
+
Object.defineProperty(exports, "explorerLink", { enumerable: true, get: function () { return explorer_link_1.explorerLink; } });
|
|
248
|
+
/**
|
|
249
|
+
* Stable per-provider identity for cache keys, or `null` when the chain cannot
|
|
250
|
+
* be determined at all — the distinction callers need to decide whether a cache
|
|
251
|
+
* key is trustworthy.
|
|
252
|
+
*
|
|
253
|
+
* `provider._network` is a *getter* in ethers v6 that throws
|
|
254
|
+
* `network is not available yet (NETWORK_ERROR)` until the provider has
|
|
255
|
+
* resolved its network (i.e. before its first successful request, when
|
|
256
|
+
* `staticNetwork` was not supplied at construction). Accessing it directly
|
|
257
|
+
* here used to leak that error out of every cached read (`getDecimals`,
|
|
258
|
+
* `getReceiptTokenAddress`, …) and surface as a confusing TVL failure on
|
|
259
|
+
* fresh provider instances. We swallow the throw and fall back to the
|
|
260
|
+
* connection URL — slightly less precise as a cache key but always safe.
|
|
261
|
+
*
|
|
262
|
+
* The runner is unwrapped to its provider first. An `IContractRunner` is either
|
|
263
|
+
* a `Provider` or a `Signer`, and a `Signer` carries the network on
|
|
264
|
+
* `signer.provider`, not on itself — without the unwrap every signer-backed
|
|
265
|
+
* read scoped to `'unknown'` and could never share a cache entry with the
|
|
266
|
+
* provider-backed read of the same token. The unwrap is a **no-op for
|
|
267
|
+
* providers**: ethers' `AbstractProvider` defines `get provider() { return
|
|
268
|
+
* this; }`, so read callers resolve to exactly the scope they did before.
|
|
269
|
+
*
|
|
270
|
+
* @returns `chain:<id>`, `url:<endpoint>`, or `null` when neither is available.
|
|
271
|
+
*/
|
|
272
|
+
function resolveProviderScope(runner) {
|
|
273
|
+
const provider = runner?.provider ?? runner;
|
|
274
|
+
let chainId;
|
|
275
|
+
try {
|
|
276
|
+
const net = provider
|
|
277
|
+
._network;
|
|
278
|
+
chainId = net?.chainId;
|
|
279
|
+
}
|
|
280
|
+
catch {
|
|
281
|
+
// ethers v6 throws when the lazy network hasn't been detected yet.
|
|
282
|
+
chainId = undefined;
|
|
283
|
+
}
|
|
284
|
+
if (chainId !== undefined && chainId !== null) {
|
|
285
|
+
return `chain:${String(chainId)}`;
|
|
286
|
+
}
|
|
287
|
+
const conn = provider._getConnection?.();
|
|
288
|
+
if (conn?.url)
|
|
289
|
+
return `url:${conn.url}`;
|
|
290
|
+
return null;
|
|
291
|
+
}
|
|
292
|
+
/**
|
|
293
|
+
* Scope string for cache keys, collapsing an unresolvable runner to the
|
|
294
|
+
* literal `'unknown'` bucket.
|
|
295
|
+
*
|
|
296
|
+
* This is the long-standing behaviour of every cached read in this module and
|
|
297
|
+
* is deliberately preserved: read callers keep keying exactly as they always
|
|
298
|
+
* have, `decimals-unknown-…` entries included. Only {@link getDecimalsOrThrow}
|
|
299
|
+
* treats an unresolvable scope specially — see the note there on why the write
|
|
300
|
+
* path holds itself to a higher bar than the read path.
|
|
301
|
+
*/
|
|
302
|
+
function providerScope(runner) {
|
|
303
|
+
return resolveProviderScope(runner) ?? 'unknown';
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Cache key for a token's `decimals()`, shared by **every** decimals reader in
|
|
307
|
+
* the SDK — the lenient {@link getDecimals} used by read paths and the strict
|
|
308
|
+
* {@link getDecimalsOrThrow} used by write paths. One namespace is the point:
|
|
309
|
+
* a page that reads a vault and then deposits into it must not pay the RPC
|
|
310
|
+
* twice (CLAUDE.md §4.1, "reuse results across functions").
|
|
311
|
+
*
|
|
312
|
+
* **What the entry holds is the *effective share-scale* decimals for `address`,
|
|
313
|
+
* not necessarily `address`'s own `decimals()`.** {@link fetchDecimals} with
|
|
314
|
+
* `isVault` redirects an `evm-2` vault to its receipt token, and the result is
|
|
315
|
+
* still stored under the vault's key — that redirect is the whole point of the
|
|
316
|
+
* flag, and every reader of a vault address wants the receipt token's scale.
|
|
317
|
+
* Consequence for future callers: `getDecimalsOrThrow(runner, evm2VaultAddr)`
|
|
318
|
+
* reads directly (`isVault: false`) but can be served the receipt token's value
|
|
319
|
+
* from this shared entry. Write paths therefore pass the receipt-token address
|
|
320
|
+
* explicitly for `evm-2` vaults; do not add a caller that expects an `evm-2`
|
|
321
|
+
* vault's own `decimals()` back out of this cache.
|
|
322
|
+
*
|
|
323
|
+
* @param scope - Result of {@link providerScope} / {@link resolveProviderScope}.
|
|
324
|
+
* @param address - Token address, or a vault address whose entry holds the
|
|
325
|
+
* share-scale token's decimals (see above).
|
|
326
|
+
*/
|
|
327
|
+
function decimalsCacheKey(scope, address) {
|
|
328
|
+
return `decimals-${scope}-${address}`;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* In-flight `decimals()` reads, keyed exactly as the cache. Collapses a
|
|
332
|
+
* stampede of concurrent callers for the same uncached token into one RPC.
|
|
333
|
+
*
|
|
334
|
+
* The stored promise **may reject** — strict callers need the original error.
|
|
335
|
+
* Lenient callers therefore must not return it raw; {@link getDecimals} awaits
|
|
336
|
+
* it inside a `try`.
|
|
337
|
+
* @internal
|
|
338
|
+
*/
|
|
339
|
+
const DECIMALS_REQUESTS = new Map();
|
|
340
|
+
/**
|
|
341
|
+
* Run (or join) the single in-flight `decimals()` read for `key`, caching the
|
|
342
|
+
* result on success. Failures are never cached, so a transient outage does not
|
|
343
|
+
* poison the entry.
|
|
344
|
+
*
|
|
345
|
+
* @param key - Cache key from {@link decimalsCacheKey}.
|
|
346
|
+
* @param fetch - Performs the actual read. Only invoked on a miss with nothing
|
|
347
|
+
* already in flight. Whichever caller registers the in-flight promise first
|
|
348
|
+
* supplies this closure — a concurrent {@link getDecimalsOrThrow} joining a
|
|
349
|
+
* {@link getDecimals}-initiated request inherits the lenient, no-retry read
|
|
350
|
+
* instead of its own `retryOnTransientRpc` wrap. Not a correctness bug (the
|
|
351
|
+
* strict caller still throws the original error), just a narrow window
|
|
352
|
+
* where the strict path's transient-retry guarantee is momentarily lost.
|
|
353
|
+
* @returns The decimals value.
|
|
354
|
+
* @throws Whatever `fetch` throws — callers that must not throw wrap this.
|
|
355
|
+
*/
|
|
356
|
+
function sharedDecimalsRequest(key, fetch) {
|
|
357
|
+
const inflight = DECIMALS_REQUESTS.get(key);
|
|
358
|
+
if (inflight)
|
|
359
|
+
return inflight;
|
|
360
|
+
const request = (async () => {
|
|
361
|
+
const decimals = await fetch();
|
|
362
|
+
cache_1.CACHE.set(key, decimals);
|
|
363
|
+
return decimals;
|
|
364
|
+
})().finally(() => {
|
|
365
|
+
DECIMALS_REQUESTS.delete(key);
|
|
366
|
+
});
|
|
367
|
+
DECIMALS_REQUESTS.set(key, request);
|
|
368
|
+
return request;
|
|
369
|
+
}
|
|
370
|
+
/**
|
|
371
|
+
* Read `decimals()` off an ERC-20 at `address`, or — when `isVault` and the
|
|
372
|
+
* vault is `evm-2` — off its receipt token, which is where the share scale
|
|
373
|
+
* actually lives.
|
|
374
|
+
*
|
|
375
|
+
* @param runner - Provider or signer to read through.
|
|
376
|
+
* @param address - Token or vault address.
|
|
377
|
+
* @param isVault - Resolve `address` as a vault (may cost a backend metadata
|
|
378
|
+
* fetch plus a `lpTokenAddress()` read) rather than reading it directly.
|
|
379
|
+
* @returns The decimals value.
|
|
380
|
+
* @throws Whatever the underlying read throws.
|
|
381
|
+
*/
|
|
382
|
+
async function fetchDecimals(runner, address, isVault) {
|
|
383
|
+
let realAddress = address;
|
|
384
|
+
if (isVault) {
|
|
385
|
+
const tokenizedVault = (await (0, fetcher_1.fetchTokenizedVault)(address))?.[0];
|
|
386
|
+
const version = (0, vault_version_1.getVaultVersionV2)(tokenizedVault);
|
|
387
|
+
if (version === 'evm-2') {
|
|
388
|
+
realAddress = await (0, exports.getReceiptTokenAddress)(runner, address);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
const contract = new ethers_1.Contract(realAddress, [web3_1.MIN_ABIS.decimals], runner);
|
|
392
|
+
return Number(await contract.decimals());
|
|
393
|
+
}
|
|
394
|
+
/**
|
|
395
|
+
* Fetch token decimals from contract or Solana mint.
|
|
396
|
+
* Results are cached to minimize RPC calls.
|
|
397
|
+
*
|
|
398
|
+
* **Never throws** — a failed read logs at error level and resolves
|
|
399
|
+
* `undefined`. Callers that must not silently proceed on an unknown scale (any
|
|
400
|
+
* path that encodes an amount) should use {@link getDecimalsOrThrow} instead:
|
|
401
|
+
* feeding `undefined` into `toNormalizedBn` silently defaults to 18 decimals.
|
|
402
|
+
*
|
|
403
|
+
* @param provider Web3 provider
|
|
404
|
+
* @param address Token contract address or Solana mint
|
|
405
|
+
* @param isVault Resolve `address` as a vault (evm-2 vaults redirect to the
|
|
406
|
+
* receipt token) rather than reading it as a plain ERC-20. Defaults to `true`.
|
|
407
|
+
* @returns Number of decimals for the token, or `undefined` when the read failed.
|
|
408
|
+
*/
|
|
409
|
+
const getDecimals = async (provider, address, isVault = true) => {
|
|
410
|
+
if (address === ethers_1.ZeroAddress) {
|
|
411
|
+
logger_1.Logger.log.info('getDecimals', 'address is zero address');
|
|
412
|
+
return 0;
|
|
413
|
+
}
|
|
414
|
+
if ((0, chain_address_1.isSolanaAddress)(address))
|
|
415
|
+
return constants_1.fallbackDecimals;
|
|
416
|
+
if (!(address && provider))
|
|
417
|
+
return;
|
|
418
|
+
const key = decimalsCacheKey(providerScope(provider), address);
|
|
419
|
+
if (cache_1.CACHE.has(key))
|
|
420
|
+
return cache_1.CACHE.get(key);
|
|
421
|
+
try {
|
|
422
|
+
return await sharedDecimalsRequest(key, () => fetchDecimals(provider, address, isVault));
|
|
423
|
+
}
|
|
424
|
+
catch (e) {
|
|
425
|
+
logger_1.Logger.log.error('getDecimals', `${address}::${e}`);
|
|
426
|
+
return undefined;
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
exports.getDecimals = getDecimals;
|
|
430
|
+
/**
|
|
431
|
+
* `decimals()` — `keccak256("decimals()")[0..4]`. Scopes the empty-view-response
|
|
432
|
+
* retry to exactly the call this reader makes.
|
|
433
|
+
*/
|
|
434
|
+
const DECIMALS_SELECTOR = '0x313ce567';
|
|
435
|
+
/**
|
|
436
|
+
* Read a token's `decimals()` with the **same cache and stampede protection as
|
|
437
|
+
* {@link getDecimals}**, but surfacing failures instead of swallowing them, and
|
|
438
|
+
* retrying the transient ones.
|
|
439
|
+
*
|
|
440
|
+
* Two reasons this exists rather than a flag on `getDecimals`:
|
|
441
|
+
*
|
|
442
|
+
* 1. **`getDecimals` must keep returning `undefined` on failure** — a dozen
|
|
443
|
+
* read paths depend on that. Amount-encoding paths need the opposite: an
|
|
444
|
+
* `undefined` reaching `toNormalizedBn` silently means 18 decimals, which
|
|
445
|
+
* misencodes the transaction. Here the original error propagates, so the
|
|
446
|
+
* caller's `AugustSDKError` keeps its cause and its Sentry grouping.
|
|
447
|
+
* 2. **Retry.** Providers intermittently return an empty response to
|
|
448
|
+
* `decimals()`, which ethers reports as
|
|
449
|
+
* `missing revert data (action="call", data="0x313ce567", …)` — a shape a
|
|
450
|
+
* deployed ERC-20 cannot legitimately produce, since `decimals()` takes no
|
|
451
|
+
* arguments. That is retried here via {@link isEmptyViewResponse} scoped to
|
|
452
|
+
* this exact selector, alongside ordinary transport faults
|
|
453
|
+
* ({@link isRetryableRpcError}). The empty-view widening applies **only**
|
|
454
|
+
* here; everywhere else the strict transport definition stands. A genuine
|
|
455
|
+
* revert (`CALL_EXCEPTION` carrying revert data) is never retried.
|
|
456
|
+
*
|
|
457
|
+
* Cache is shared with `getDecimals`, so a read-then-write flow against the
|
|
458
|
+
* same token costs one `decimals()` RPC in total, and N concurrent callers for
|
|
459
|
+
* an uncached token collapse to one.
|
|
460
|
+
*
|
|
461
|
+
* **Exception — an unresolvable chain scope bypasses the cache entirely.** When
|
|
462
|
+
* {@link resolveProviderScope} cannot determine the chain (a runner with no
|
|
463
|
+
* resolved network and no connection URL, e.g. a browser provider before its
|
|
464
|
+
* first request), the only available key is the shared `unknown` bucket. Read
|
|
465
|
+
* paths happily use that bucket, and this function deliberately does not: the
|
|
466
|
+
* two paths have different blast radii. A wrong cached `decimals` on a read
|
|
467
|
+
* renders a wrong number on screen; on a write it misencodes an amount the user
|
|
468
|
+
* then *signs*. The collision needed — the same address being a different token
|
|
469
|
+
* with different decimals on two chains, within one process, across a
|
|
470
|
+
* mid-session chain switch — is narrow, but "no worse than the read path" is
|
|
471
|
+
* not the bar for a value that ends up in a transaction. In that case the read
|
|
472
|
+
* is neither served from nor written to the cache, and it also skips the
|
|
473
|
+
* in-flight dedup map, since joining another caller under an untrusted key
|
|
474
|
+
* would reintroduce exactly the collision being avoided. Retries still apply;
|
|
475
|
+
* the only thing forgone is the RPC saving.
|
|
476
|
+
*
|
|
477
|
+
* RPC cost: 1 on a cache miss, 0 on a hit, up to 3 on a miss that keeps
|
|
478
|
+
* faulting (~750ms of added latency in the worst case before it gives up).
|
|
479
|
+
* Always ≥1 when the chain scope is unresolvable.
|
|
480
|
+
*
|
|
481
|
+
* @param runner - Provider or signer to read through. A signer is unwrapped to
|
|
482
|
+
* its provider for cache scoping, so it shares entries with reads on the
|
|
483
|
+
* same chain.
|
|
484
|
+
* @param address - Token address. Read directly as an ERC-20 — pass the
|
|
485
|
+
* receipt-token address yourself for an `evm-2` vault's share scale.
|
|
486
|
+
* @param tag - Low-cardinality label for retry breadcrumbs (e.g.
|
|
487
|
+
* `'vaultDeposit:poolDecimals'`).
|
|
488
|
+
* @returns The token's decimals.
|
|
489
|
+
* @throws The underlying read error once retries are exhausted, or immediately
|
|
490
|
+
* when the failure is neither a transport fault nor an empty view response.
|
|
491
|
+
*
|
|
492
|
+
* @example
|
|
493
|
+
* ```ts
|
|
494
|
+
* // Amount encoding must not proceed on a guessed scale.
|
|
495
|
+
* const decimals = await getDecimalsOrThrow(signer, token, 'deposit:decimals');
|
|
496
|
+
* const amount = toNormalizedBn(userInput, decimals);
|
|
497
|
+
* ```
|
|
498
|
+
*/
|
|
499
|
+
const getDecimalsOrThrow = async (runner, address, tag) => {
|
|
500
|
+
const read = () => (0, chain_error_1.retryOnTransientRpc)(tag, () => fetchDecimals(runner, address, false), { address }, (error) => (0, chain_error_1.isRetryableRpcError)(error) ||
|
|
501
|
+
(0, chain_error_1.isEmptyViewResponse)(error, DECIMALS_SELECTOR));
|
|
502
|
+
const scope = resolveProviderScope(runner);
|
|
503
|
+
if (scope === null) {
|
|
504
|
+
// Untrusted key: no cache read, no cache write, no dedup. See the note
|
|
505
|
+
// above — a mis-scoped decimals value here gets signed into a transaction.
|
|
506
|
+
logger_1.Logger.log.warn(tag, 'decimals cache bypassed: chain scope unresolved', {
|
|
507
|
+
address,
|
|
508
|
+
});
|
|
509
|
+
return read();
|
|
510
|
+
}
|
|
511
|
+
const key = decimalsCacheKey(scope, address);
|
|
512
|
+
if (cache_1.CACHE.has(key))
|
|
513
|
+
return cache_1.CACHE.get(key);
|
|
514
|
+
return sharedDecimalsRequest(key, read);
|
|
515
|
+
};
|
|
516
|
+
exports.getDecimalsOrThrow = getDecimalsOrThrow;
|
|
517
|
+
/** @internal */
|
|
518
|
+
const WHITELISTED_ASSETS_REQUESTS = new Map();
|
|
519
|
+
/**
|
|
520
|
+
* Fetch the whitelisted deposit-asset addresses from a vault's whitelist
|
|
521
|
+
* contract. Cached with a 5-minute TTL; a fresh fetch fans out into N
|
|
522
|
+
* decimals/symbol reads downstream.
|
|
523
|
+
* @internal
|
|
524
|
+
*/
|
|
525
|
+
const getWhitelistedAssets = async (provider, whitelistAddress) => {
|
|
526
|
+
if (!(whitelistAddress && provider)) {
|
|
527
|
+
throw new errors_1.AugustValidationError('INVALID_INPUT', 'getWhitelistedAssets: provider and whitelistAddress are required');
|
|
528
|
+
}
|
|
529
|
+
const key = `whitelisted-assets-${providerScope(provider)}-${whitelistAddress}`;
|
|
530
|
+
if (cache_1.CACHE.has(key))
|
|
531
|
+
return cache_1.CACHE.get(key);
|
|
532
|
+
const inflight = WHITELISTED_ASSETS_REQUESTS.get(key);
|
|
533
|
+
if (inflight)
|
|
534
|
+
return inflight;
|
|
535
|
+
const fetchPromise = (async () => {
|
|
536
|
+
try {
|
|
537
|
+
const contract = new ethers_1.Contract(whitelistAddress, TokenizedVaultV2WhitelistedAssets_1.ABI_TOKENIZED_VAULT_V2_WHITELISTED_ASSETS, provider);
|
|
538
|
+
const list = (await contract.getWhitelistedAssets());
|
|
539
|
+
cache_1.CACHE.set(key, list, { ttl: 5 * 60 * 1000 });
|
|
540
|
+
return list;
|
|
541
|
+
}
|
|
542
|
+
finally {
|
|
543
|
+
WHITELISTED_ASSETS_REQUESTS.delete(key);
|
|
544
|
+
}
|
|
545
|
+
})();
|
|
546
|
+
WHITELISTED_ASSETS_REQUESTS.set(key, fetchPromise);
|
|
547
|
+
return fetchPromise;
|
|
548
|
+
};
|
|
549
|
+
exports.getWhitelistedAssets = getWhitelistedAssets;
|
|
550
|
+
/**
|
|
551
|
+
* Read an `evm-2` vault's receipt (LP) token address via `lpTokenAddress()`,
|
|
552
|
+
* retrying only the transient transport faults and surfacing everything else
|
|
553
|
+
* unchanged.
|
|
554
|
+
*
|
|
555
|
+
* Why this exists: `lpTokenAddress()` sits immediately before the receipt-token
|
|
556
|
+
* `decimals()` read on every `evm-2` write path (approve / deposit / request
|
|
557
|
+
* redeem / swap-router deposit). Those `decimals()` reads were hardened against
|
|
558
|
+
* provider blips ({@link getDecimalsOrThrow}); the `lpTokenAddress()` read one
|
|
559
|
+
* line above them was not, so a single truncated `eth_call` response still
|
|
560
|
+
* failed the whole write with
|
|
561
|
+
* `missing revert data (action="call", data="0xf5ae497a", …)` — observed in
|
|
562
|
+
* production against a mainnet vault whose `lpTokenAddress()` demonstrably
|
|
563
|
+
* returns a real address when the provider is healthy.
|
|
564
|
+
*
|
|
565
|
+
* **This must never hide a misrouted vault, and does not.** `lpTokenAddress()`
|
|
566
|
+
* exists *only* on `evm-2` vaults. A vault wrongly classified as `evm-2` returns
|
|
567
|
+
* empty returndata for it, deterministically and forever, and that empty
|
|
568
|
+
* response is byte-identical to the transient one — it is the *only* signal the
|
|
569
|
+
* SDK gets that its version routing was wrong. So the retry here is deliberately
|
|
570
|
+
* shaped to preserve that signal:
|
|
571
|
+
*
|
|
572
|
+
* - it is **bounded** (3 attempts, ~750ms of backoff in total — see
|
|
573
|
+
* `retryOnTransientRpc`), never open-ended;
|
|
574
|
+
* - on exhaustion it **rethrows the original error object**, with its identity,
|
|
575
|
+
* message, `code` and `transaction.data` intact, so the caller's
|
|
576
|
+
* `AugustSDKError` cause and Sentry grouping are exactly what they are today;
|
|
577
|
+
* - it has **no fallback**: it never substitutes another address, never resolves
|
|
578
|
+
* the vault address itself, and never resolves `null`/`undefined`. It either
|
|
579
|
+
* returns a real receipt-token address or throws.
|
|
580
|
+
*
|
|
581
|
+
* Net effect: a blip costs a retry, a misroute costs three `eth_call`s and then
|
|
582
|
+
* fails exactly as loudly as before.
|
|
583
|
+
*
|
|
584
|
+
* **Deliberately not cached.** Unlike `decimals()`, the vault→receipt-token
|
|
585
|
+
* mapping is not memoized here. Caching it would make a misroute's first
|
|
586
|
+
* (failed) probe and every subsequent one diverge, and would put a
|
|
587
|
+
* vault-identity mapping in the cache on the money path. The lenient, cached
|
|
588
|
+
* reader is {@link getReceiptTokenAddress} — use that on read paths that can
|
|
589
|
+
* tolerate `undefined`.
|
|
590
|
+
*
|
|
591
|
+
* RPC cost: exactly 1 `eth_call` on success; at most 3 when the provider keeps
|
|
592
|
+
* faulting.
|
|
593
|
+
*
|
|
594
|
+
* @param runner - Provider or signer to read through.
|
|
595
|
+
* @param vault - Address of the `evm-2` tokenized vault.
|
|
596
|
+
* @param tag - Low-cardinality label for retry breadcrumbs (e.g.
|
|
597
|
+
* `'vaultRequestRedeem:receiptToken'`).
|
|
598
|
+
* @returns The vault's receipt (LP) token address. Never `null`/`undefined`.
|
|
599
|
+
* @throws The underlying read error, unmodified, once the bounded retries are
|
|
600
|
+
* exhausted — or immediately when the failure is neither a transport fault nor
|
|
601
|
+
* an empty response to this exact selector (e.g. a genuine revert carrying
|
|
602
|
+
* revert data).
|
|
603
|
+
*
|
|
604
|
+
* @example
|
|
605
|
+
* ```ts
|
|
606
|
+
* const receiptToken = await getReceiptTokenAddressOrThrow(
|
|
607
|
+
* signer,
|
|
608
|
+
* vault,
|
|
609
|
+
* 'vaultRequestRedeem:receiptToken',
|
|
610
|
+
* );
|
|
611
|
+
* const decimals = await getDecimalsOrThrow(signer, receiptToken, 'tag');
|
|
612
|
+
* ```
|
|
613
|
+
*/
|
|
614
|
+
const getReceiptTokenAddressOrThrow = async (runner, vault, tag) => {
|
|
615
|
+
const contract = new ethers_1.Contract(vault, TokenizedVaultV2_1.ABI_TOKENIZED_VAULT_V2, runner);
|
|
616
|
+
return (0, chain_error_1.retryOnTransientRpc)(tag, () => contract.lpTokenAddress(), { vault }, (error) => (0, chain_error_1.isRetryableRpcError)(error) ||
|
|
617
|
+
(0, chain_error_1.isEmptyViewResponse)(error, chain_error_1.LP_TOKEN_ADDRESS_SELECTOR));
|
|
618
|
+
};
|
|
619
|
+
exports.getReceiptTokenAddressOrThrow = getReceiptTokenAddressOrThrow;
|
|
620
|
+
/** @internal */
|
|
621
|
+
const RECEIPT_TOKEN_REQUESTS = new Map();
|
|
622
|
+
/**
|
|
623
|
+
* Fetch receipt token address from tokenized vault contract.
|
|
624
|
+
* Results are cached to minimize RPC calls.
|
|
625
|
+
*
|
|
626
|
+
* **Never throws** — a failed read logs at error level and resolves
|
|
627
|
+
* `undefined`, which several read paths depend on. The underlying
|
|
628
|
+
* `lpTokenAddress()` call is made through
|
|
629
|
+
* {@link getReceiptTokenAddressOrThrow}, so a transient provider blip is
|
|
630
|
+
* absorbed by a bounded retry before that happens; a deterministic failure (a
|
|
631
|
+
* vault that has no `lpTokenAddress()` because it is not `evm-2`) still resolves
|
|
632
|
+
* `undefined` after the attempts are spent, exactly as before. Callers on a
|
|
633
|
+
* money path must use {@link getReceiptTokenAddressOrThrow} directly instead —
|
|
634
|
+
* an `undefined` receipt-token address there would silently mis-address a
|
|
635
|
+
* `decimals()` read.
|
|
636
|
+
*
|
|
637
|
+
* @param provider Web3 provider
|
|
638
|
+
* @param address Tokenized vault contract address
|
|
639
|
+
* @returns Receipt token address, or `undefined` when the read failed.
|
|
640
|
+
*/
|
|
641
|
+
const getReceiptTokenAddress = async (provider, address) => {
|
|
642
|
+
if (!(address && provider))
|
|
643
|
+
return;
|
|
644
|
+
const key = `receipt-token-${providerScope(provider)}-${address}`;
|
|
645
|
+
if (cache_1.CACHE.has(key))
|
|
646
|
+
return cache_1.CACHE.get(key);
|
|
647
|
+
const inflight = RECEIPT_TOKEN_REQUESTS.get(key);
|
|
648
|
+
if (inflight)
|
|
649
|
+
return inflight;
|
|
650
|
+
const fetchPromise = (async () => {
|
|
651
|
+
try {
|
|
652
|
+
const receiptToken = await (0, exports.getReceiptTokenAddressOrThrow)(provider, address, 'getReceiptTokenAddress');
|
|
653
|
+
cache_1.CACHE.set(key, receiptToken);
|
|
654
|
+
return receiptToken;
|
|
655
|
+
}
|
|
656
|
+
catch (e) {
|
|
657
|
+
logger_1.Logger.log.error('getReceiptTokenAddress', e);
|
|
658
|
+
return undefined;
|
|
659
|
+
}
|
|
660
|
+
finally {
|
|
661
|
+
RECEIPT_TOKEN_REQUESTS.delete(key);
|
|
662
|
+
}
|
|
663
|
+
})();
|
|
664
|
+
RECEIPT_TOKEN_REQUESTS.set(key, fetchPromise);
|
|
665
|
+
return fetchPromise;
|
|
666
|
+
};
|
|
667
|
+
exports.getReceiptTokenAddress = getReceiptTokenAddress;
|
|
668
|
+
/** @internal */
|
|
669
|
+
const SYMBOL_REQUESTS = new Map();
|
|
670
|
+
/**
|
|
671
|
+
* Fetch token symbol from contract.
|
|
672
|
+
* Results are cached to minimize RPC calls.
|
|
673
|
+
* @param provider Web3 provider
|
|
674
|
+
* @param address Token contract address
|
|
675
|
+
* @returns Token symbol string
|
|
676
|
+
*/
|
|
677
|
+
const getSymbol = async (provider, address, isVault = true) => {
|
|
678
|
+
if (address === ethers_1.ZeroAddress) {
|
|
679
|
+
logger_1.Logger.log.info('getSymbol', 'address is zero address');
|
|
680
|
+
return 'N/A';
|
|
681
|
+
}
|
|
682
|
+
if (!(address && provider))
|
|
683
|
+
return;
|
|
684
|
+
const key = `symbol-${providerScope(provider)}-${address}`;
|
|
685
|
+
if (cache_1.CACHE.has(key))
|
|
686
|
+
return cache_1.CACHE.get(key);
|
|
687
|
+
const inflight = SYMBOL_REQUESTS.get(key);
|
|
688
|
+
if (inflight)
|
|
689
|
+
return inflight;
|
|
690
|
+
const fetchPromise = (async () => {
|
|
691
|
+
try {
|
|
692
|
+
if (isVault) {
|
|
693
|
+
const tokenizedVault = (await (0, fetcher_1.fetchTokenizedVault)(address))?.[0];
|
|
694
|
+
const version = (0, vault_version_1.getVaultVersionV2)(tokenizedVault);
|
|
695
|
+
let realAddress = address;
|
|
696
|
+
if (version === 'evm-2') {
|
|
697
|
+
realAddress = await (0, exports.getReceiptTokenAddress)(provider, address);
|
|
698
|
+
}
|
|
699
|
+
const contract = new ethers_1.Contract(realAddress, [web3_1.MIN_ABIS.symbol], provider);
|
|
700
|
+
const symbol = (await contract.symbol());
|
|
701
|
+
cache_1.CACHE.set(key, symbol);
|
|
702
|
+
return symbol;
|
|
703
|
+
}
|
|
704
|
+
else {
|
|
705
|
+
const contract = new ethers_1.Contract(address, [web3_1.MIN_ABIS.symbol], provider);
|
|
706
|
+
const symbol = (await contract.symbol());
|
|
707
|
+
cache_1.CACHE.set(key, symbol);
|
|
708
|
+
return symbol;
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
catch (e) {
|
|
712
|
+
logger_1.Logger.log.error('getSymbol', `${address}::${e}`);
|
|
713
|
+
return undefined;
|
|
714
|
+
}
|
|
715
|
+
finally {
|
|
716
|
+
SYMBOL_REQUESTS.delete(key);
|
|
717
|
+
}
|
|
718
|
+
})();
|
|
719
|
+
SYMBOL_REQUESTS.set(key, fetchPromise);
|
|
720
|
+
return fetchPromise;
|
|
721
|
+
};
|
|
722
|
+
exports.getSymbol = getSymbol;
|
|
723
|
+
/**
|
|
724
|
+
* Batch fetch multiple token metadata fields in a single call.
|
|
725
|
+
* Efficiently retrieves name, symbol, decimals, and totalSupply.
|
|
726
|
+
* @param provider Web3 provider
|
|
727
|
+
* @param asset Token contract address
|
|
728
|
+
* @param meta Array of metadata fields to fetch
|
|
729
|
+
* @returns Array of metadata values in same order as requested
|
|
730
|
+
*/
|
|
731
|
+
async function getTokenMetadata(provider, asset, meta) {
|
|
732
|
+
if (!asset)
|
|
733
|
+
return [];
|
|
734
|
+
function buildAbi() {
|
|
735
|
+
const abiArr = [];
|
|
736
|
+
if (meta?.includes('name'))
|
|
737
|
+
abiArr.push(web3_1.MIN_ABIS.name);
|
|
738
|
+
if (meta?.includes('symbol'))
|
|
739
|
+
abiArr.push(web3_1.MIN_ABIS.symbol);
|
|
740
|
+
if (meta?.includes('decimals'))
|
|
741
|
+
abiArr.push(web3_1.MIN_ABIS.decimals);
|
|
742
|
+
if (meta?.includes('totalSupply'))
|
|
743
|
+
abiArr.push(web3_1.MIN_ABIS.totalSupply);
|
|
744
|
+
return abiArr;
|
|
745
|
+
}
|
|
746
|
+
try {
|
|
747
|
+
const contract = new ethers_1.Contract(asset, buildAbi(), provider);
|
|
748
|
+
const getterArr = [];
|
|
749
|
+
if (meta?.includes('name'))
|
|
750
|
+
getterArr.push(contract.name());
|
|
751
|
+
if (meta?.includes('symbol'))
|
|
752
|
+
getterArr.push(contract.symbol());
|
|
753
|
+
if (meta?.includes('decimals'))
|
|
754
|
+
getterArr.push(contract.decimals());
|
|
755
|
+
if (meta?.includes('totalSupply'))
|
|
756
|
+
getterArr.push(contract.totalSupply());
|
|
757
|
+
return await Promise.all(getterArr);
|
|
758
|
+
}
|
|
759
|
+
catch (e) {
|
|
760
|
+
logger_1.Logger.log.error('getTokenMetadata', e);
|
|
761
|
+
return [];
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
/**
|
|
765
|
+
* Fetch management fee percentage from vault contract.
|
|
766
|
+
* Performs static call first to check if method exists.
|
|
767
|
+
* @todo fix so that when lending pool does not have "managementFeePercent", to not break everything
|
|
768
|
+
* @param provider Web3 provider
|
|
769
|
+
* @param address Vault contract address
|
|
770
|
+
* @returns Management fee as percentage or undefined if not supported
|
|
771
|
+
*/
|
|
772
|
+
const getManagementFeePercent = async (provider, address) => {
|
|
773
|
+
if (!(address && provider))
|
|
774
|
+
return;
|
|
775
|
+
// Check if contract supports managementFeePercent method
|
|
776
|
+
try {
|
|
777
|
+
const contract = new ethers_1.Contract(address, [web3_1.MIN_ABIS.managementFeePercent], provider);
|
|
778
|
+
await contract.managementFeePercent.staticCall();
|
|
779
|
+
}
|
|
780
|
+
catch (e) {
|
|
781
|
+
logger_1.Logger.log.error('getManagementFeePercent:simulate', e);
|
|
782
|
+
return undefined;
|
|
783
|
+
}
|
|
784
|
+
try {
|
|
785
|
+
const contract = new ethers_1.Contract(address, [web3_1.MIN_ABIS.managementFeePercent], provider);
|
|
786
|
+
const fee = (await contract.managementFeePercent());
|
|
787
|
+
return Number(fee) / 100;
|
|
788
|
+
}
|
|
789
|
+
catch (e) {
|
|
790
|
+
logger_1.Logger.log.error('getManagementFeePercent', e);
|
|
791
|
+
return undefined;
|
|
792
|
+
}
|
|
793
|
+
};
|
|
794
|
+
exports.getManagementFeePercent = getManagementFeePercent;
|
|
795
|
+
/**
|
|
796
|
+
* Simulate contract transaction without executing on-chain.
|
|
797
|
+
* Useful for testing transaction viability before sending.
|
|
798
|
+
* @param provider Web3 provider
|
|
799
|
+
* @param abi Contract ABI
|
|
800
|
+
* @param functionName Function to simulate
|
|
801
|
+
* @param options Transaction parameters including args, from, to
|
|
802
|
+
* @returns Decoded function result or false if simulation fails
|
|
803
|
+
*/
|
|
804
|
+
async function simulateTransaction(provider, abi, functionName, options) {
|
|
805
|
+
try {
|
|
806
|
+
const customInterface = new ethers_1.Interface(abi);
|
|
807
|
+
const callData = customInterface.encodeFunctionData(functionName, options?.args);
|
|
808
|
+
const response = await provider.call({
|
|
809
|
+
from: options?.from,
|
|
810
|
+
to: options?.to,
|
|
811
|
+
data: callData,
|
|
812
|
+
});
|
|
813
|
+
if (!response)
|
|
814
|
+
return false;
|
|
815
|
+
return customInterface.decodeFunctionResult(functionName, response);
|
|
816
|
+
}
|
|
817
|
+
catch (e) {
|
|
818
|
+
logger_1.Logger.log.error('simulateTransaction', e);
|
|
819
|
+
if (String(e).includes('reverted with reason string "denied"'))
|
|
820
|
+
return true;
|
|
821
|
+
return false;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
/**
|
|
825
|
+
* Validate Ethereum address format and checksum.
|
|
826
|
+
* @param address Address string to validate
|
|
827
|
+
* @param logger Optional logger for error messages
|
|
828
|
+
* @param type Context type for logging
|
|
829
|
+
* @returns True if address is valid and checksummed
|
|
830
|
+
*/
|
|
831
|
+
function checkAddress(address, logger, type = 'contract') {
|
|
832
|
+
const _logger = logger ?? console;
|
|
833
|
+
if (!address) {
|
|
834
|
+
_logger.error(type, 'address is undefined');
|
|
835
|
+
return false;
|
|
836
|
+
}
|
|
837
|
+
if (typeof address !== 'string') {
|
|
838
|
+
_logger.error(type, 'address not of string type:', String(typeof address), String(address));
|
|
839
|
+
return false;
|
|
840
|
+
}
|
|
841
|
+
if (!(0, ethers_1.isAddress)(address)) {
|
|
842
|
+
_logger.error(type, 'address not checksummed:', String(address));
|
|
843
|
+
return false;
|
|
844
|
+
}
|
|
845
|
+
return true;
|
|
846
|
+
}
|
|
847
|
+
/**
|
|
848
|
+
* Fetch dynamic fee rate from on-chain oracle contract.
|
|
849
|
+
* Used for calculating loan interest repayment fees.
|
|
850
|
+
* @param provider Web3 provider
|
|
851
|
+
* @param category_id Fee category identifier
|
|
852
|
+
* @param address Context address for fee calculation
|
|
853
|
+
* @param chainId Optional chain ID (auto-detected if not provided)
|
|
854
|
+
* @returns Fee rate as decimal number
|
|
855
|
+
*/
|
|
856
|
+
async function getLoanOracleFeeRate(provider, category_id, address, chainId) {
|
|
857
|
+
if (!(0, ethers_1.isAddress)(address)) {
|
|
858
|
+
logger_1.Logger.log.error('getLoanOracleFee', 'address is undefined or not a valid address');
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
let _chainId = chainId;
|
|
862
|
+
if (!chainId) {
|
|
863
|
+
const chainIdRes = await (0, exports.getChainId)(provider);
|
|
864
|
+
_chainId = Number(chainIdRes);
|
|
865
|
+
}
|
|
866
|
+
if (!web3_1.ORACLE_CONTRACTS?.[_chainId]) {
|
|
867
|
+
logger_1.Logger.log.warn('getLoanOracleFeeRate', 'no oracle address for', _chainId);
|
|
868
|
+
return Number(0);
|
|
869
|
+
}
|
|
870
|
+
const oracleContract = createContract({
|
|
871
|
+
provider,
|
|
872
|
+
address: web3_1.ORACLE_CONTRACTS[_chainId],
|
|
873
|
+
abi: abis_1.ABI_FEE_ORACLE,
|
|
874
|
+
});
|
|
875
|
+
const hashedCategory = (0, ethers_1.keccak256)((0, ethers_1.toUtf8Bytes)(category_id));
|
|
876
|
+
const rawFee = await oracleContract.getContextFeeRate(hashedCategory, (0, ethers_1.getAddress)(address));
|
|
877
|
+
return Number((0, ethers_1.formatUnits)(rawFee, 6));
|
|
878
|
+
}
|
|
879
|
+
/**
|
|
880
|
+
* Query historical contract state across a block range.
|
|
881
|
+
* Useful for reconstructing historical data like TVL over time.
|
|
882
|
+
* @param provider Web3 provider
|
|
883
|
+
* @param contractAddress Target contract address
|
|
884
|
+
* @param abi Contract ABI
|
|
885
|
+
* @param methodName View function to call
|
|
886
|
+
* @param args Function arguments
|
|
887
|
+
* @param startBlock Starting block number
|
|
888
|
+
* @param endBlock Ending block number (current block if not specified)
|
|
889
|
+
* @param blockInterval Blocks between each query
|
|
890
|
+
* @returns Array of results with block numbers and timestamps
|
|
891
|
+
*/
|
|
892
|
+
async function getHistoricalContractData(provider, contractAddress, abi, methodName, args = [], startBlock, endBlock, blockInterval = 1000) {
|
|
893
|
+
const contract = new ethers_1.ethers.Contract(contractAddress, abi, provider);
|
|
894
|
+
const results = [];
|
|
895
|
+
if (!endBlock) {
|
|
896
|
+
endBlock = await provider.getBlockNumber();
|
|
897
|
+
}
|
|
898
|
+
for (let blockNumber = startBlock; blockNumber <= endBlock; blockNumber += blockInterval) {
|
|
899
|
+
try {
|
|
900
|
+
const contractAtBlock = contract.connect(provider);
|
|
901
|
+
const result = await contractAtBlock[methodName](...args, {
|
|
902
|
+
blockTag: blockNumber,
|
|
903
|
+
});
|
|
904
|
+
const block = await provider.getBlock(blockNumber);
|
|
905
|
+
results.push({
|
|
906
|
+
blockNumber,
|
|
907
|
+
timestamp: block.timestamp,
|
|
908
|
+
result: result.toString(),
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
catch (error) {
|
|
912
|
+
logger_1.Logger.log.error('getHistoricalContractData', `Error at block ${blockNumber}`, error);
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
return results;
|
|
916
|
+
}
|
|
917
|
+
/**
|
|
918
|
+
* Query historical contract state at regular time intervals.
|
|
919
|
+
* Uses binary search to find blocks closest to target timestamps.
|
|
920
|
+
* @param provider Web3 provider
|
|
921
|
+
* @param contractAddress Target contract address
|
|
922
|
+
* @param abi Contract ABI
|
|
923
|
+
* @param methodName View function to call
|
|
924
|
+
* @param args Function arguments
|
|
925
|
+
* @param startDate Start date (string or timestamp)
|
|
926
|
+
* @param endDate End date (string or timestamp)
|
|
927
|
+
* @param intervalHours Hours between each query
|
|
928
|
+
* @returns Array of results with dates, blocks, and values
|
|
929
|
+
*/
|
|
930
|
+
async function getHistoricalContractDataByDate(provider, contractAddress, abi, methodName, args = [], startDate, endDate, intervalHours = 24) {
|
|
931
|
+
const contract = new ethers_1.ethers.Contract(contractAddress, abi, provider);
|
|
932
|
+
const startTimestamp = Math.floor(new Date(startDate).getTime() / 1000);
|
|
933
|
+
const endTimestamp = Math.floor(new Date(endDate).getTime() / 1000);
|
|
934
|
+
const intervalSeconds = intervalHours * 3600;
|
|
935
|
+
const results = [];
|
|
936
|
+
// Binary search to find block closest to timestamp
|
|
937
|
+
async function findBlockByTimestamp(targetTimestamp) {
|
|
938
|
+
let left = 1;
|
|
939
|
+
let right = await provider.getBlockNumber();
|
|
940
|
+
let closestBlock = null;
|
|
941
|
+
while (left <= right) {
|
|
942
|
+
const mid = Math.floor((left + right) / 2);
|
|
943
|
+
const block = await provider.getBlock(mid);
|
|
944
|
+
if (!block) {
|
|
945
|
+
right = mid - 1;
|
|
946
|
+
continue;
|
|
947
|
+
}
|
|
948
|
+
if (block.timestamp === targetTimestamp) {
|
|
949
|
+
return block;
|
|
950
|
+
}
|
|
951
|
+
if (!closestBlock ||
|
|
952
|
+
Math.abs(block.timestamp - targetTimestamp) <
|
|
953
|
+
Math.abs(closestBlock.timestamp - targetTimestamp)) {
|
|
954
|
+
closestBlock = block;
|
|
955
|
+
}
|
|
956
|
+
if (block.timestamp < targetTimestamp) {
|
|
957
|
+
left = mid + 1;
|
|
958
|
+
}
|
|
959
|
+
else {
|
|
960
|
+
right = mid - 1;
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
return closestBlock;
|
|
964
|
+
}
|
|
965
|
+
try {
|
|
966
|
+
// Loop through time intervals
|
|
967
|
+
for (let timestamp = startTimestamp; timestamp <= endTimestamp; timestamp += intervalSeconds) {
|
|
968
|
+
// Find closest block to timestamp
|
|
969
|
+
const block = await findBlockByTimestamp(timestamp);
|
|
970
|
+
if (!block) {
|
|
971
|
+
logger_1.Logger.log.warn('getHistoricalContractDataByDate', `No block found for timestamp ${timestamp}`);
|
|
972
|
+
continue;
|
|
973
|
+
}
|
|
974
|
+
// Make the contract call
|
|
975
|
+
const result = await contract[methodName](...args, {
|
|
976
|
+
blockTag: block.number,
|
|
977
|
+
});
|
|
978
|
+
results.push({
|
|
979
|
+
date: new Date(timestamp * 1000).toISOString(),
|
|
980
|
+
blockNumber: block.number,
|
|
981
|
+
timestamp,
|
|
982
|
+
result: result.toString(),
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
return results;
|
|
986
|
+
}
|
|
987
|
+
catch (error) {
|
|
988
|
+
logger_1.Logger.log.error('getHistoricalContractDataByDate', error);
|
|
989
|
+
throw error;
|
|
990
|
+
}
|
|
991
|
+
}
|
|
992
|
+
//# sourceMappingURL=web3.js.map
|