@steerprotocol/sdk 1.30.3 → 1.30.5
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/dist/cjs/const/amm/configs/ammConfig.js +33 -34
- package/dist/cjs/const/amm/configs/ammConfig.js.map +1 -1
- package/dist/cjs/const/amm/configs/protocols/index.js +0 -39
- package/dist/cjs/const/amm/configs/protocols/index.js.map +1 -1
- package/dist/cjs/const/stabilityVaults/index.js +1 -1
- package/dist/cjs/const/stabilityVaults/index.js.map +1 -1
- package/dist/esm/base/FeeManagerClient.js +26 -22
- package/dist/esm/base/FeeManagerClient.js.map +1 -1
- package/dist/esm/base/PoolClient.js +19 -15
- package/dist/esm/base/PoolClient.js.map +1 -1
- package/dist/esm/base/SmartRewardClient.js +10 -6
- package/dist/esm/base/SmartRewardClient.js.map +1 -1
- package/dist/esm/base/SmartRewards.js +11 -7
- package/dist/esm/base/SmartRewards.js.map +1 -1
- package/dist/esm/base/StakingClient.js +18 -14
- package/dist/esm/base/StakingClient.js.map +1 -1
- package/dist/esm/base/SubgraphClient.js +8 -4
- package/dist/esm/base/SubgraphClient.js.map +1 -1
- package/dist/esm/base/VaultClient.js +55 -37
- package/dist/esm/base/VaultClient.js.map +1 -1
- package/dist/esm/base/vault/deposit/index.js +42 -38
- package/dist/esm/base/vault/deposit/index.js.map +1 -1
- package/dist/esm/base/vault/deposit/types.js +2 -1
- package/dist/esm/base/vault/single-asset/calculateLimitPrice.js +39 -32
- package/dist/esm/base/vault/single-asset/calculateLimitPrice.js.map +1 -1
- package/dist/esm/base/vault/single-asset/calculateSwapAmount.js +8 -5
- package/dist/esm/base/vault/single-asset/calculateSwapAmount.js.map +1 -1
- package/dist/esm/base/vault/single-asset/estimateLpTokens.js +12 -7
- package/dist/esm/base/vault/single-asset/estimateLpTokens.js.map +1 -1
- package/dist/esm/base/vault/single-asset/index.js +32 -6
- package/dist/esm/base/vault/single-asset/index.js.map +1 -1
- package/dist/esm/base/vault/single-asset/simulateSwap.js +30 -24
- package/dist/esm/base/vault/single-asset/simulateSwap.js.map +1 -1
- package/dist/esm/base/vault/single-asset/singleAssetDeposit.js +33 -29
- package/dist/esm/base/vault/single-asset/singleAssetDeposit.js.map +1 -1
- package/dist/esm/base/vault/single-asset/types.js +5 -2
- package/dist/esm/base/vault/single-asset/types.js.map +1 -1
- package/dist/esm/base/vault/utils.js +16 -7
- package/dist/esm/base/vault/utils.js.map +1 -1
- package/dist/esm/base/vault/withdraw/index.js +10 -6
- package/dist/esm/base/vault/withdraw/index.js.map +1 -1
- package/dist/esm/base/vault/withdraw/types.js +2 -1
- package/dist/esm/client.js +15 -11
- package/dist/esm/client.js.map +1 -1
- package/dist/esm/const/abis/UniswapPool.js +4 -1
- package/dist/esm/const/abis/UniswapPool.js.map +1 -1
- package/dist/esm/const/abis/erc1155.js +4 -1
- package/dist/esm/const/abis/erc1155.js.map +1 -1
- package/dist/esm/const/abis/erc20.js +4 -1
- package/dist/esm/const/abis/erc20.js.map +1 -1
- package/dist/esm/const/abis/erc721.js +4 -1
- package/dist/esm/const/abis/erc721.js.map +1 -1
- package/dist/esm/const/abis/feeManager.js +4 -1
- package/dist/esm/const/abis/feeManager.js.map +1 -1
- package/dist/esm/const/abis/index.js +24 -8
- package/dist/esm/const/abis/index.js.map +1 -1
- package/dist/esm/const/abis/quoter.js +9 -6
- package/dist/esm/const/abis/quoter.js.map +1 -1
- package/dist/esm/const/abis/singleTokenDeposit.js +4 -1
- package/dist/esm/const/abis/singleTokenDeposit.js.map +1 -1
- package/dist/esm/const/abis/vaultFees.js +4 -1
- package/dist/esm/const/abis/vaultFees.js.map +1 -1
- package/dist/esm/const/amm/configs/ammConfig.js +98 -95
- package/dist/esm/const/amm/configs/ammConfig.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/aerodrome-v2.js +12 -8
- package/dist/esm/const/amm/configs/protocols/aerodrome-v2.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/aerodrome.js +12 -8
- package/dist/esm/const/amm/configs/protocols/aerodrome.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/arthswap.js +14 -10
- package/dist/esm/const/amm/configs/protocols/arthswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/baseswap.js +11 -7
- package/dist/esm/const/amm/configs/protocols/baseswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/basex.js +12 -8
- package/dist/esm/const/amm/configs/protocols/basex.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/beam.js +11 -7
- package/dist/esm/const/amm/configs/protocols/beam.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/beamswap.js +11 -7
- package/dist/esm/const/amm/configs/protocols/beamswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/blackhole.js +12 -8
- package/dist/esm/const/amm/configs/protocols/blackhole.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/camelot.js +17 -13
- package/dist/esm/const/amm/configs/protocols/camelot.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/crust.js +11 -7
- package/dist/esm/const/amm/configs/protocols/crust.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/cypher.js +13 -9
- package/dist/esm/const/amm/configs/protocols/cypher.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/dodo.js +11 -7
- package/dist/esm/const/amm/configs/protocols/dodo.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/dragonswap.js +11 -7
- package/dist/esm/const/amm/configs/protocols/dragonswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/eddy.js +11 -7
- package/dist/esm/const/amm/configs/protocols/eddy.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/equilibre.js +11 -7
- package/dist/esm/const/amm/configs/protocols/equilibre.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/fenix.js +11 -7
- package/dist/esm/const/amm/configs/protocols/fenix.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/forge.js +13 -9
- package/dist/esm/const/amm/configs/protocols/forge.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/fusionx.js +12 -8
- package/dist/esm/const/amm/configs/protocols/fusionx.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/glyph.js +13 -9
- package/dist/esm/const/amm/configs/protocols/glyph.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/henjin.js +11 -7
- package/dist/esm/const/amm/configs/protocols/henjin.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/hercules.js +11 -7
- package/dist/esm/const/amm/configs/protocols/hercules.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/horiza.js +13 -9
- package/dist/esm/const/amm/configs/protocols/horiza.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/index.js +56 -79
- package/dist/esm/const/amm/configs/protocols/index.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/katana.js +10 -6
- package/dist/esm/const/amm/configs/protocols/katana.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/katanaIntegral.js +10 -6
- package/dist/esm/const/amm/configs/protocols/katanaIntegral.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/kim.js +15 -11
- package/dist/esm/const/amm/configs/protocols/kim.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/kinetix.js +14 -10
- package/dist/esm/const/amm/configs/protocols/kinetix.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/kodiak.js +14 -10
- package/dist/esm/const/amm/configs/protocols/kodiak.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/kyo.js +12 -8
- package/dist/esm/const/amm/configs/protocols/kyo.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/linehub.js +11 -7
- package/dist/esm/const/amm/configs/protocols/linehub.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/lynex.js +13 -9
- package/dist/esm/const/amm/configs/protocols/lynex.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/machinex.js +13 -9
- package/dist/esm/const/amm/configs/protocols/machinex.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/maia.js +13 -9
- package/dist/esm/const/amm/configs/protocols/maia.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/metavault.js +16 -12
- package/dist/esm/const/amm/configs/protocols/metavault.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/nest.js +12 -8
- package/dist/esm/const/amm/configs/protocols/nest.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/novaswap.js +11 -7
- package/dist/esm/const/amm/configs/protocols/novaswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/ocelex.js +11 -7
- package/dist/esm/const/amm/configs/protocols/ocelex.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/pancakeswap.js +17 -13
- package/dist/esm/const/amm/configs/protocols/pancakeswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/poolshark.js +11 -7
- package/dist/esm/const/amm/configs/protocols/poolshark.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/quickswap-algebra.js +12 -8
- package/dist/esm/const/amm/configs/protocols/quickswap-algebra.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/quickswap-integral.js +17 -13
- package/dist/esm/const/amm/configs/protocols/quickswap-integral.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/quickswap-univ3.js +20 -16
- package/dist/esm/const/amm/configs/protocols/quickswap-univ3.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/quickswap.js +18 -14
- package/dist/esm/const/amm/configs/protocols/quickswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/retro.js +13 -9
- package/dist/esm/const/amm/configs/protocols/retro.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/sailor.js +11 -7
- package/dist/esm/const/amm/configs/protocols/sailor.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/shadow.js +13 -9
- package/dist/esm/const/amm/configs/protocols/shadow.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/silverswap.js +15 -11
- package/dist/esm/const/amm/configs/protocols/silverswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/spark-integral.js +12 -8
- package/dist/esm/const/amm/configs/protocols/spark-integral.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/spark.js +11 -7
- package/dist/esm/const/amm/configs/protocols/spark.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/spark32.js +11 -7
- package/dist/esm/const/amm/configs/protocols/spark32.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/spookyswap.js +11 -7
- package/dist/esm/const/amm/configs/protocols/spookyswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/stellaswap.js +13 -9
- package/dist/esm/const/amm/configs/protocols/stellaswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/supswap.js +11 -7
- package/dist/esm/const/amm/configs/protocols/supswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/sushi.js +73 -69
- package/dist/esm/const/amm/configs/protocols/sushi.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/swapmode.js +11 -7
- package/dist/esm/const/amm/configs/protocols/swapmode.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/swapsicle.js +11 -7
- package/dist/esm/const/amm/configs/protocols/swapsicle.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/thena.js +13 -9
- package/dist/esm/const/amm/configs/protocols/thena.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/thick.js +12 -8
- package/dist/esm/const/amm/configs/protocols/thick.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/thickv2.js +12 -8
- package/dist/esm/const/amm/configs/protocols/thickv2.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/thruster.js +12 -8
- package/dist/esm/const/amm/configs/protocols/thruster.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/uniswap.js +83 -79
- package/dist/esm/const/amm/configs/protocols/uniswap.js.map +1 -1
- package/dist/esm/const/amm/configs/protocols/wasabee.js +11 -7
- package/dist/esm/const/amm/configs/protocols/wasabee.js.map +1 -1
- package/dist/esm/const/amm/index.js +19 -3
- package/dist/esm/const/amm/index.js.map +1 -1
- package/dist/esm/const/amm/utils/beacon.js +76 -70
- package/dist/esm/const/amm/utils/beacon.js.map +1 -1
- package/dist/esm/const/amm/utils/contracts.js +26 -16
- package/dist/esm/const/amm/utils/contracts.js.map +1 -1
- package/dist/esm/const/amm/utils/index.js +46 -22
- package/dist/esm/const/amm/utils/index.js.map +1 -1
- package/dist/esm/const/amm/utils/protocol.js +24 -16
- package/dist/esm/const/amm/utils/protocol.js.map +1 -1
- package/dist/esm/const/api.js +7 -3
- package/dist/esm/const/api.js.map +1 -1
- package/dist/esm/const/capabilities.js +20 -15
- package/dist/esm/const/capabilities.js.map +1 -1
- package/dist/esm/const/chain.js +12 -9
- package/dist/esm/const/chain.js.map +1 -1
- package/dist/esm/const/deployments/abis.js +4 -1
- package/dist/esm/const/deployments/abis.js.map +1 -1
- package/dist/esm/const/deployments/apechain.js +4 -1
- package/dist/esm/const/deployments/apechain.js.map +1 -1
- package/dist/esm/const/deployments/arbitrum.js +4 -1
- package/dist/esm/const/deployments/arbitrum.js.map +1 -1
- package/dist/esm/const/deployments/arbitrumgoerli.js +4 -1
- package/dist/esm/const/deployments/arbitrumgoerli.js.map +1 -1
- package/dist/esm/const/deployments/astar.js +4 -1
- package/dist/esm/const/deployments/astar.js.map +1 -1
- package/dist/esm/const/deployments/astarzkevm.js +4 -1
- package/dist/esm/const/deployments/astarzkevm.js.map +1 -1
- package/dist/esm/const/deployments/avalanche.js +4 -1
- package/dist/esm/const/deployments/avalanche.js.map +1 -1
- package/dist/esm/const/deployments/bartiotest.js +4 -1
- package/dist/esm/const/deployments/bartiotest.js.map +1 -1
- package/dist/esm/const/deployments/base.js +4 -1
- package/dist/esm/const/deployments/base.js.map +1 -1
- package/dist/esm/const/deployments/bera.js +4 -1
- package/dist/esm/const/deployments/bera.js.map +1 -1
- package/dist/esm/const/deployments/berachainbartio.js +4 -1
- package/dist/esm/const/deployments/berachainbartio.js.map +1 -1
- package/dist/esm/const/deployments/blast.js +4 -1
- package/dist/esm/const/deployments/blast.js.map +1 -1
- package/dist/esm/const/deployments/bsc.js +4 -1
- package/dist/esm/const/deployments/bsc.js.map +1 -1
- package/dist/esm/const/deployments/celo.js +4 -1
- package/dist/esm/const/deployments/celo.js.map +1 -1
- package/dist/esm/const/deployments/core.js +4 -1
- package/dist/esm/const/deployments/core.js.map +1 -1
- package/dist/esm/const/deployments/eth.js +4 -1
- package/dist/esm/const/deployments/eth.js.map +1 -1
- package/dist/esm/const/deployments/evmos.js +4 -1
- package/dist/esm/const/deployments/evmos.js.map +1 -1
- package/dist/esm/const/deployments/fantom.js +4 -1
- package/dist/esm/const/deployments/fantom.js.map +1 -1
- package/dist/esm/const/deployments/filecoin.js +4 -1
- package/dist/esm/const/deployments/filecoin.js.map +1 -1
- package/dist/esm/const/deployments/flare.js +4 -1
- package/dist/esm/const/deployments/flare.js.map +1 -1
- package/dist/esm/const/deployments/goerli.js +4 -1
- package/dist/esm/const/deployments/goerli.js.map +1 -1
- package/dist/esm/const/deployments/hemi.js +4 -1
- package/dist/esm/const/deployments/hemi.js.map +1 -1
- package/dist/esm/const/deployments/hyperevm.js +4 -1
- package/dist/esm/const/deployments/hyperevm.js.map +1 -1
- package/dist/esm/const/deployments/index.js +99 -48
- package/dist/esm/const/deployments/index.js.map +1 -1
- package/dist/esm/const/deployments/katana.js +4 -1
- package/dist/esm/const/deployments/katana.js.map +1 -1
- package/dist/esm/const/deployments/kava.js +4 -1
- package/dist/esm/const/deployments/kava.js.map +1 -1
- package/dist/esm/const/deployments/linea.js +4 -1
- package/dist/esm/const/deployments/linea.js.map +1 -1
- package/dist/esm/const/deployments/localhost.js +4 -1
- package/dist/esm/const/deployments/localhost.js.map +1 -1
- package/dist/esm/const/deployments/manta.js +4 -1
- package/dist/esm/const/deployments/manta.js.map +1 -1
- package/dist/esm/const/deployments/mantle.js +4 -1
- package/dist/esm/const/deployments/mantle.js.map +1 -1
- package/dist/esm/const/deployments/metis.js +4 -1
- package/dist/esm/const/deployments/metis.js.map +1 -1
- package/dist/esm/const/deployments/mode.js +4 -1
- package/dist/esm/const/deployments/mode.js.map +1 -1
- package/dist/esm/const/deployments/moonbeam.js +4 -1
- package/dist/esm/const/deployments/moonbeam.js.map +1 -1
- package/dist/esm/const/deployments/mumbai.js +4 -1
- package/dist/esm/const/deployments/mumbai.js.map +1 -1
- package/dist/esm/const/deployments/nibiru.js +4 -1
- package/dist/esm/const/deployments/nibiru.js.map +1 -1
- package/dist/esm/const/deployments/okxtestnet.js +4 -1
- package/dist/esm/const/deployments/okxtestnet.js.map +1 -1
- package/dist/esm/const/deployments/optimism.js +4 -1
- package/dist/esm/const/deployments/optimism.js.map +1 -1
- package/dist/esm/const/deployments/optimismgoerli.js +4 -1
- package/dist/esm/const/deployments/optimismgoerli.js.map +1 -1
- package/dist/esm/const/deployments/peaq.js +4 -1
- package/dist/esm/const/deployments/peaq.js.map +1 -1
- package/dist/esm/const/deployments/polygon.js +4 -1
- package/dist/esm/const/deployments/polygon.js.map +1 -1
- package/dist/esm/const/deployments/polyzkevm.js +4 -1
- package/dist/esm/const/deployments/polyzkevm.js.map +1 -1
- package/dist/esm/const/deployments/pyzkevm.js +4 -1
- package/dist/esm/const/deployments/pyzkevm.js.map +1 -1
- package/dist/esm/const/deployments/ronin.js +4 -1
- package/dist/esm/const/deployments/ronin.js.map +1 -1
- package/dist/esm/const/deployments/rootstock.js +4 -1
- package/dist/esm/const/deployments/rootstock.js.map +1 -1
- package/dist/esm/const/deployments/saga.js +4 -1
- package/dist/esm/const/deployments/saga.js.map +1 -1
- package/dist/esm/const/deployments/scroll.js +4 -1
- package/dist/esm/const/deployments/scroll.js.map +1 -1
- package/dist/esm/const/deployments/sei.js +4 -1
- package/dist/esm/const/deployments/sei.js.map +1 -1
- package/dist/esm/const/deployments/soneium.js +4 -1
- package/dist/esm/const/deployments/soneium.js.map +1 -1
- package/dist/esm/const/deployments/sonic.js +4 -1
- package/dist/esm/const/deployments/sonic.js.map +1 -1
- package/dist/esm/const/deployments/taiko.js +4 -1
- package/dist/esm/const/deployments/taiko.js.map +1 -1
- package/dist/esm/const/deployments/tataratestnet.js +4 -1
- package/dist/esm/const/deployments/tataratestnet.js.map +1 -1
- package/dist/esm/const/deployments/telos.js +4 -1
- package/dist/esm/const/deployments/telos.js.map +1 -1
- package/dist/esm/const/deployments/thundercore.js +4 -1
- package/dist/esm/const/deployments/thundercore.js.map +1 -1
- package/dist/esm/const/deployments/uni.js +4 -1
- package/dist/esm/const/deployments/uni.js.map +1 -1
- package/dist/esm/const/deployments/xlayer.js +4 -1
- package/dist/esm/const/deployments/xlayer.js.map +1 -1
- package/dist/esm/const/deployments/zeta.js +4 -1
- package/dist/esm/const/deployments/zeta.js.map +1 -1
- package/dist/esm/const/deployments/zircuit.js +4 -1
- package/dist/esm/const/deployments/zircuit.js.map +1 -1
- package/dist/esm/const/deployments/zklinknova.js +4 -1
- package/dist/esm/const/deployments/zklinknova.js.map +1 -1
- package/dist/esm/const/index.js +28 -12
- package/dist/esm/const/index.js.map +1 -1
- package/dist/esm/const/network.js +232 -223
- package/dist/esm/const/network.js.map +1 -1
- package/dist/esm/const/protocol.js +97 -83
- package/dist/esm/const/protocol.js.map +1 -1
- package/dist/esm/const/quoter.js +53 -42
- package/dist/esm/const/quoter.js.map +1 -1
- package/dist/esm/const/stabilityVaults/index.js +17 -1
- package/dist/esm/const/stabilityVaults/index.js.map +1 -1
- package/dist/esm/const/stabilityVaults/stabilityVaultsConfig.js +15 -10
- package/dist/esm/const/stabilityVaults/stabilityVaultsConfig.js.map +1 -1
- package/dist/esm/const/subgraph.js +60 -56
- package/dist/esm/const/subgraph.js.map +1 -1
- package/dist/esm/const/thegraph.js +5 -1
- package/dist/esm/const/thegraph.js.map +1 -1
- package/dist/esm/index.js +31 -12
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/scripts/processDeployments.js +15 -10
- package/dist/esm/scripts/processDeployments.js.map +1 -1
- package/dist/esm/types.js +2 -1
- package/dist/esm/utils/PoolQueryAdapter.js +44 -38
- package/dist/esm/utils/PoolQueryAdapter.js.map +1 -1
- package/dist/esm/utils/SubgraphVaultClient.js +10 -6
- package/dist/esm/utils/SubgraphVaultClient.js.map +1 -1
- package/dist/esm/utils/subgraph-types.js +2 -1
- package/dist/types/const/amm/configs/ammConfig.d.ts.map +1 -1
- package/dist/types/const/amm/configs/protocols/index.d.ts +0 -39
- package/dist/types/const/amm/configs/protocols/index.d.ts.map +1 -1
- package/dist/types/const/stabilityVaults/index.d.ts +1 -1
- package/dist/types/const/stabilityVaults/index.d.ts.map +1 -1
- package/package.json +6 -11
- package/src/const/amm/configs/ammConfig.ts +2 -3
- package/src/const/amm/configs/protocols/index.ts +1 -40
- package/src/const/stabilityVaults/index.ts +1 -1
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.PoolClient = void 0;
|
|
4
|
+
const SubgraphClient_js_1 = require("./SubgraphClient.js");
|
|
5
|
+
const index_js_1 = require("../const/index.js");
|
|
6
|
+
const protocol_js_1 = require("../const/protocol.js");
|
|
7
|
+
const PoolQueryAdapter_js_1 = require("../utils/PoolQueryAdapter.js");
|
|
5
8
|
/**
|
|
6
9
|
* Client for fetching pool data from various DEX protocol subgraphs
|
|
7
10
|
*
|
|
@@ -25,7 +28,7 @@ import { getTopPoolsQuery, getTokenPoolsQueryByAddress, getPoolDetailsQuery } fr
|
|
|
25
28
|
* @extends SubgraphClient
|
|
26
29
|
* @group Pool
|
|
27
30
|
*/
|
|
28
|
-
|
|
31
|
+
class PoolClient extends SubgraphClient_js_1.SubgraphClient {
|
|
29
32
|
/**
|
|
30
33
|
* Creates a new PoolClient instance
|
|
31
34
|
*
|
|
@@ -90,8 +93,8 @@ export class PoolClient extends SubgraphClient {
|
|
|
90
93
|
*/
|
|
91
94
|
async fetchFromGraph(query, variables, protocol, chainId) {
|
|
92
95
|
try {
|
|
93
|
-
const chainName = chainIdToName(chainId);
|
|
94
|
-
const endpoint = getProtocolSubgraphURL(protocol, chainName, this.subgraphStudioKey);
|
|
96
|
+
const chainName = (0, index_js_1.chainIdToName)(chainId);
|
|
97
|
+
const endpoint = (0, index_js_1.getProtocolSubgraphURL)(protocol, chainName, this.subgraphStudioKey);
|
|
95
98
|
if (!endpoint) {
|
|
96
99
|
throw new Error(`No subgraph endpoint available for protocol ${protocol} on chain ${chainName}`);
|
|
97
100
|
}
|
|
@@ -166,8 +169,8 @@ export class PoolClient extends SubgraphClient {
|
|
|
166
169
|
*/
|
|
167
170
|
async getTopPools(count = 500, protocol, chainId) {
|
|
168
171
|
try {
|
|
169
|
-
const isAlgebraPool = isAlgebraProtocol(protocol);
|
|
170
|
-
const query = getTopPoolsQuery(protocol, isAlgebraPool);
|
|
172
|
+
const isAlgebraPool = (0, protocol_js_1.isAlgebraProtocol)(protocol);
|
|
173
|
+
const query = (0, PoolQueryAdapter_js_1.getTopPoolsQuery)(protocol, isAlgebraPool);
|
|
171
174
|
console.log(`[Chain ${chainId}] [Protocol ${protocol}] 📊 Fetching top ${count} pools from the subgraph...`);
|
|
172
175
|
const response = await this.fetchFromGraph(query, { limit: count }, protocol, chainId);
|
|
173
176
|
if (!response.success || !response.data) {
|
|
@@ -222,8 +225,8 @@ export class PoolClient extends SubgraphClient {
|
|
|
222
225
|
*/
|
|
223
226
|
async getPoolById(poolId, protocol, chainId) {
|
|
224
227
|
try {
|
|
225
|
-
const isAlgebraPool = isAlgebraProtocol(protocol);
|
|
226
|
-
const query = getPoolDetailsQuery(isAlgebraPool, protocol);
|
|
228
|
+
const isAlgebraPool = (0, protocol_js_1.isAlgebraProtocol)(protocol);
|
|
229
|
+
const query = (0, PoolQueryAdapter_js_1.getPoolDetailsQuery)(isAlgebraPool, protocol);
|
|
227
230
|
const response = await this.fetchFromGraph(query, { pool: poolId }, protocol, chainId);
|
|
228
231
|
if (!response.success || !response.data) {
|
|
229
232
|
throw new Error(response.error || 'Failed to fetch pool');
|
|
@@ -282,7 +285,7 @@ export class PoolClient extends SubgraphClient {
|
|
|
282
285
|
}
|
|
283
286
|
console.log(`\n🔍 Batch Pool Fetch Summary:`);
|
|
284
287
|
console.log(`📥 Total tokens to process: ${tokenAddresses.length}`);
|
|
285
|
-
const isAlgebraPool = isAlgebraProtocol(protocol);
|
|
288
|
+
const isAlgebraPool = (0, protocol_js_1.isAlgebraProtocol)(protocol);
|
|
286
289
|
const normalizedAddresses = tokenAddresses.map(addr => addr.toLowerCase());
|
|
287
290
|
// Split into chunks
|
|
288
291
|
const chunkSize = batchSize;
|
|
@@ -297,7 +300,7 @@ export class PoolClient extends SubgraphClient {
|
|
|
297
300
|
console.log(`\n🔄 Processing chunk ${chunkIndex + 1}/${addressChunks.length} with ${chunk.length} tokens`);
|
|
298
301
|
const chunkResults = await Promise.all(chunk.map(async (token) => {
|
|
299
302
|
try {
|
|
300
|
-
const query = getTokenPoolsQueryByAddress(isAlgebraPool, protocol);
|
|
303
|
+
const query = (0, PoolQueryAdapter_js_1.getTokenPoolsQueryByAddress)(isAlgebraPool, protocol);
|
|
301
304
|
const queryStartTime = performance.now();
|
|
302
305
|
const response = await this.fetchFromGraph(query, { token }, protocol, chainId);
|
|
303
306
|
const queryTime = performance.now() - queryStartTime;
|
|
@@ -376,8 +379,8 @@ export class PoolClient extends SubgraphClient {
|
|
|
376
379
|
*/
|
|
377
380
|
async fetchPoolsForToken(tokenAddress, protocol, chainId) {
|
|
378
381
|
try {
|
|
379
|
-
const isAlgebraPool = isAlgebraProtocol(protocol);
|
|
380
|
-
const query = getTokenPoolsQueryByAddress(isAlgebraPool, protocol);
|
|
382
|
+
const isAlgebraPool = (0, protocol_js_1.isAlgebraProtocol)(protocol);
|
|
383
|
+
const query = (0, PoolQueryAdapter_js_1.getTokenPoolsQueryByAddress)(isAlgebraPool, protocol);
|
|
381
384
|
const response = await this.fetchFromGraph(query, { token: tokenAddress.toLowerCase() }, protocol, chainId);
|
|
382
385
|
if (!response.success || !response.data) {
|
|
383
386
|
throw new Error(response.error || 'Failed to fetch pools for token');
|
|
@@ -448,4 +451,5 @@ export class PoolClient extends SubgraphClient {
|
|
|
448
451
|
});
|
|
449
452
|
}
|
|
450
453
|
}
|
|
454
|
+
exports.PoolClient = PoolClient;
|
|
451
455
|
//# sourceMappingURL=PoolClient.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"PoolClient.js","sourceRoot":"","sources":["../../../src/base/PoolClient.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAKrD,OAAO,EACL,aAAa,EACb,sBAAsB,EACvB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AACzD,OAAO,EAAE,gBAAgB,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,MAAM,8BAA8B,CAAC;AAmHlH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,OAAO,UAAW,SAAQ,cAAc;IAU5C;;;;;;;;;;OAUG;IACH,YACE,MAAmC,EACnC,oBAA4B,EAAE;QAE9B,KAAK,CAAC,MAAM,CAAC,CAAC;QAtBhB,0DAA0D;QACzC,mBAAc,GAAW,KAAK,CAAC;QAChD,4CAA4C;QACpC,iBAAY,GAAW,CAAC,CAAC;QAoB/B,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACI,YAAY;QACjB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;IACxB,CAAC;IAED;;;;;;;;;;OAUG;IACI,UAAU;QACf,OAAO;YACL,YAAY,EAAE,IAAI,CAAC,YAAY;SAChC,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACK,KAAK,CAAC,cAAc,CAC1B,KAAa,EACb,SAAkC,E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AK,CAAC,IAAI,CAAC;gBACX,KAAK,CAAC,SAAS,CAAC;gBAChB,SAAS,IAAI,CAAC;gBACd,IAAI,IAAI,QAAQ,GAAG,mBAAmB;gBACtC,IAAI,IAAI,QAAQ,GAAG,mBAAmB,EACtC,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,OAAO,IAAI,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["import type { PublicClient, WalletClient } from 'viem';\nimport { PoolData, SteerResponse } from '../types.js';\nimport { SubgraphClient } from './SubgraphClient.js';\nimport { \n Protocol, \n Chain\n} from '../const/chain.js';\nimport { \n chainIdToName, \n getProtocolSubgraphURL\n} from '../const/index.js';\nimport { isAlgebraProtocol } from '../const/protocol.js';\nimport { getTopPoolsQuery, getTokenPoolsQueryByAddress, getPoolDetailsQuery } from '../utils/PoolQueryAdapter.js';\n\n/**\n * GraphQL token data interface representing token information from subgraph responses\n * @interface GraphQLTokenData\n */\nexport interface GraphQLTokenData {\n /** Token symbol (e.g., \"ETH\", \"USDC\") */\n symbol: string;\n /** Token contract address */\n id: string;\n /** Number of decimal places for the token */\n decimals: string;\n /** Human-readable token name */\n name: string;\n}\n\n/**\n * GraphQL pool data interface representing pool information from subgraph responses\n * @interface GraphQLPoolData\n */\nexport interface GraphQLPoolData {\n /** Pool contract address */\n id: string;\n /** First token in the pool */\n token0: GraphQLTokenData;\n /** Second token in the pool */\n token1: GraphQLTokenData;\n /** 24-hour trading volume in USD */\n volumeUSD: string;\n /** Current tick of the pool */\n tick: string;\n /** Total liquidity in the pool */\n liquidity: string;\n /** Fee tier for the pool (optional) */\n feeTier?: string;\n /** 24-hour volume of token0 (optional) */\n volumeToken0?: string;\n /** 24-hour volume of token1 (optional) */\n volumeToken1?: string;\n /** Total value locked in ETH (optional) */\n totalValueLockedETH?: string;\n /** Alternative field name for volume USD (optional) */\n volumeUsd?: string;\n /** Alternative field name for TVL in ETH (optional) */\n totalValueLockedEth?: string;\n}\n\n/**\n * Filter criteria for querying pools\n * @interface PoolFilter\n */\nexport interface PoolFilter {\n /** Chain ID to filter pools by */\n chainId?: number;\n /** Protocol to filter pools by */\n protocol?: Protocol;\n /** Minimum volume in USD to filter pools */\n minVolumeUSD?: number;\n /** Token address to find pools containing this token */\n tokenAddress?: string;\n /** Maximum number of pools to return */\n limit?: number;\n}\n\n// GraphQL response interfaces (currently unused but kept for future use)\n// interface GraphQLResponse<T> {\n// data: T;\n// errors?: Array<{ message: string }>;\n// }\n\n/**\n * Response interface for top pools query\n * @interface TopPoolsResponse\n * @internal\n */\ninterface TopPoolsResponse {\n /** Standard pools array */\n pools: GraphQLPoolData[];\n /** Limit pools array (used by some protocols) */\n limitPools?: GraphQLPoolData[];\n /** CL pools array (used by some protocols) */\n clPools?: GraphQLPoolData[];\n}\n\n/**\n * Response interface for pool details query\n * @interface PoolDetailsResponse\n * @internal\n */\ninterface PoolDetailsResponse {\n /** Single pool data */\n pool: GraphQLPoolData;\n /** Single limit pool data (used by some protocols) */\n limitPool?: GraphQLPoolData;\n /** Single CL pool data (used by some protocols) */\n clPool?: GraphQLPoolData;\n}\n\n/**\n * Response interface for pools by token query\n * @interface PoolsByTokenResponse\n * @internal\n */\ninterface PoolsByTokenResponse {\n /** Standard pools array */\n pools?: GraphQLPoolData[];\n /** Limit pools array (used by some protocols) */\n limitPools?: GraphQLPoolData[];\n /** Token pools array (used by some protocols) */\n tokenPools?: GraphQLPoolData[];\n /** CL pools array (used by some protocols) */\n clPools?: GraphQLPoolData[];\n}\n\n/**\n * Client for fetching pool data from various DEX protocol subgraphs\n * \n * @example\n * ```typescript\n * import { createPublicClient, createWalletClient, http } from 'viem';\n * import { mainnet } from 'viem/chains';\n * import { PoolClient } from '@steerprotocol/sdk';\n * \n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http()\n * }) as PublicClient & WalletClient;\n * \n * const poolClient = new PoolClient(client, 'your-subgraph-studio-key');\n * \n * // Fetch top pools\n * const topPools = await poolClient.getTopPools(100, Protocol.UniswapV3, 1);\n * ```\n * \n * @extends SubgraphClient\n * @group Pool\n */\nexport class PoolClient extends SubgraphClient {\n /** Public client for blockchain interactions */\n protected readonly publicClient: PublicClient;\n /** Default timeout for GraphQL queries in milliseconds */\n private readonly defaultTimeout: number = 60000;\n /** Counter for tracking API call metrics */\n private apiCallCount: number = 0;\n /** Subgraph Studio API key for rate limiting */\n private readonly subgraphStudioKey: string;\n\n /**\n * Creates a new PoolClient instance\n * \n * @param client - Combined public and wallet client for blockchain interactions\n * @param subgraphStudioKey - Optional Subgraph Studio API key for higher rate limits\n * \n * @example\n * ```typescript\n * const poolClient = new PoolClient(client, 'your-api-key');\n * ```\n */\n constructor(\n client: PublicClient & WalletClient,\n subgraphStudioKey: string = ''\n ) {\n super(client);\n this.publicClient = client;\n this.subgraphStudioKey = subgraphStudioKey;\n }\n\n /**\n * Resets the API call counter for metrics tracking\n * \n * @example\n * ```typescript\n * poolClient.resetMetrics();\n * ```\n */\n public resetMetrics(): void {\n this.apiCallCount = 0;\n }\n\n /**\n * Gets current metrics for monitoring API usage\n * \n * @returns Object containing current metrics\n * \n * @example\n * ```typescript\n * const metrics = poolClient.getMetrics();\n * console.log(`API calls made: ${metrics.apiCallCount}`);\n * ```\n */\n public getMetrics(): { apiCallCount: number } {\n return {\n apiCallCount: this.apiCallCount,\n };\n }\n\n /**\n * Fetches data from GraphQL endpoint with retry logic for rate limits\n * \n * @param query - GraphQL query string\n * @param variables - Variables for the GraphQL query\n * @param protocol - Protocol to query\n * @param chainId - Chain ID to query\n * @returns Promise containing the response data\n * \n * @throws {Error} When subgraph endpoint is not available\n * @throws {Error} When rate limit is exceeded after max retries\n * @throws {Error} When GraphQL query times out\n * \n * @internal\n */\n private async fetchFromGraph<T>(\n query: string,\n variables: Record<string, unknown>,\n protocol: Protocol,\n chainId: number\n ): Promise<SteerResponse<T>> {\n try {\n const chainName = chainIdToName(chainId);\n const endpoint = getProtocolSubgraphURL(protocol, chainName as Chain, this.subgraphStudioKey);\n\n if (!endpoint) {\n throw new Error(`No subgraph endpoint available for protocol ${protocol} on chain ${chainName}`);\n }\n\n const MAX_RETRIES = 3;\n const RETRY_DELAY_MS = 11000;\n\n const fetchWithRetry = async (retries = 0): Promise<T> => {\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ query, variables }),\n });\n\n const data = await response.json() as { data: T; error?: string; errors?: Array<{ message: string }> };\n\n if (data.error && typeof data.error === \"string\" && data.error.includes(\"surpassed your query allowance\")) {\n if (retries < MAX_RETRIES) {\n console.warn(`Rate limit hit for ${endpoint}, retrying in ${RETRY_DELAY_MS / 1000}s (attempt ${retries + 1})`);\n await new Promise(res => setTimeout(res, RETRY_DELAY_MS));\n return fetchWithRetry(retries + 1);\n } else {\n throw new Error(`Rate limit exceeded after ${MAX_RETRIES} retries: ${data.error}`);\n }\n }\n\n if (data.error) {\n throw new Error(`GraphQL endpoint error: ${data.error}`);\n }\n\n if (data.errors) {\n throw new Error(`GraphQL errors: ${JSON.stringify(data.errors)}`);\n }\n\n return data.data;\n };\n\n this.apiCallCount++;\n console.log(\"Total API calls:\", this.apiCallCount);\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(\n () => reject(new Error(\"GraphQL query timeout\")),\n this.defaultTimeout\n );\n });\n\n const data = await Promise.race([fetchWithRetry(), timeoutPromise]);\n\n return {\n data: data as T,\n status: 200,\n success: true,\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Fetches the top pools for a specific protocol by trading volume\n * \n * @param count - Number of pools to fetch (default: 500)\n * @param protocol - Protocol to fetch pools from\n * @param chainId - Chain ID to fetch pools from\n * @returns Promise containing an array of top pools\n * \n * @example\n * ```typescript\n * // Get top 100 Uniswap V3 pools on Ethereum\n * const topPools = await poolClient.getTopPools(100, Protocol.UniswapV3, 1);\n * if (topPools.success) {\n * console.log(`Found ${topPools.data.length} pools`);\n * }\n * ```\n * \n * @throws {Error} When failed to fetch pools from subgraph\n */\n public async getTopPools(\n count: number = 500,\n protocol: Protocol,\n chainId: number\n ): Promise<SteerResponse<GraphQLPoolData[]>> {\n try {\n const isAlgebraPool = isAlgebraProtocol(protocol);\n const query = getTopPoolsQuery(protocol, isAlgebraPool);\n\n console.log(`[Chain ${chainId}] [Protocol ${protocol}] 📊 Fetching top ${count} pools from the subgraph...`);\n\n const response = await this.fetchFromGraph<TopPoolsResponse>(\n query,\n { limit: count },\n protocol,\n chainId\n );\n\n if (!response.success || !response.data) {\n throw new Error(response.error || 'Failed to fetch pools');\n }\n\n const pools = response.data.pools || response.data.limitPools || response.data.clPools || [];\n \n console.log(`[Chain ${chainId}] [Protocol ${protocol}] ✅ Received ${pools.length} pools from the subgraph`);\n\n // Filter out pools with invalid volumeUSD\n const validPools = pools.filter(pool => {\n const volumeUSD = parseFloat(pool.volumeUSD || pool.volumeUsd || \"0\");\n return !isNaN(volumeUSD) && volumeUSD > 0;\n });\n\n console.log(`[Chain ${chainId}] [Protocol ${protocol}] ✅ Found ${validPools.length} valid pools with positive volumeUSD`);\n\n return {\n data: validPools,\n status: 200,\n success: true,\n };\n } catch (error) {\n console.error(`[Chain ${chainId}] [Protocol ${protocol}] Error in getTopPools:`, error);\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Fetches detailed information for a specific pool by its ID\n * \n * @param poolId - Pool contract address to fetch\n * @param protocol - Protocol the pool belongs to\n * @param chainId - Chain ID where the pool exists\n * @returns Promise containing pool details or null if not found\n * \n * @example\n * ```typescript\n * // Get specific pool details\n * const poolDetails = await poolClient.getPoolById(\n * '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640',\n * Protocol.UniswapV3,\n * 1\n * );\n * if (poolDetails.success && poolDetails.data) {\n * console.log(`Pool: ${poolDetails.data.token0.symbol}/${poolDetails.data.token1.symbol}`);\n * }\n * ```\n * \n * @throws {Error} When failed to fetch pool from subgraph\n */\n public async getPoolById(\n poolId: string,\n protocol: Protocol,\n chainId: number\n ): Promise<SteerResponse<GraphQLPoolData | null>> {\n try {\n\n const isAlgebraPool = isAlgebraProtocol(protocol);\n const query = getPoolDetailsQuery(isAlgebraPool, protocol);\n\n \n const response = await this.fetchFromGraph<PoolDetailsResponse>(\n query,\n { pool: poolId },\n protocol,\n chainId\n );\n\n if (!response.success || !response.data) {\n throw new Error(response.error || 'Failed to fetch pool');\n }\n\n const pool = response.data.pool || response.data.clPool || response.data.limitPool || null;\n\n\n return {\n data: pool,\n status: 200,\n success: true,\n };\n } catch (error) {\n console.error(`Error fetching pool ${poolId}:`, error);\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Fetches pools containing multiple tokens in batches for better performance\n * \n * @param tokenAddresses - Array of token contract addresses\n * @param protocol - Protocol to fetch pools from\n * @param chainId - Chain ID to fetch pools from\n * @param batchSize - Number of tokens to process in each batch (default: 10)\n * @returns Promise containing all pools found for the tokens\n * \n * @example\n * ```typescript\n * // Get pools for multiple tokens\n * const tokenAddresses = [\n * '0xa0b86a33e6f8b07b71c3a39ef77a6b6e8f1b7b7e', // USDC\n * '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' // WETH\n * ];\n * const pools = await poolClient.fetchPoolsForTokensBatch(\n * tokenAddresses,\n * Protocol.UniswapV3,\n * 1,\n * 5\n * );\n * ```\n * \n * @throws {Error} When batch processing fails\n */\n public async fetchPoolsForTokensBatch(\n tokenAddresses: string[],\n protocol: Protocol,\n chainId: number,\n batchSize: number = 10\n ): Promise<SteerResponse<GraphQLPoolData[]>> {\n try {\n if (tokenAddresses.length === 0) {\n return {\n data: [],\n status: 200,\n success: true,\n };\n }\n\n console.log(`\\n🔍 Batch Pool Fetch Summary:`);\n console.log(`📥 Total tokens to process: ${tokenAddresses.length}`);\n\n const isAlgebraPool = isAlgebraProtocol(protocol);\n const normalizedAddresses = tokenAddresses.map(addr => addr.toLowerCase());\n\n // Split into chunks\n const chunkSize = batchSize;\n const addressChunks = [];\n for (let i = 0; i < normalizedAddresses.length; i += chunkSize) {\n addressChunks.push(normalizedAddresses.slice(i, i + chunkSize));\n }\n\n console.log(`📦 Processing ${addressChunks.length} chunks of max ${chunkSize} tokens each`);\n\n const allPools: GraphQLPoolData[] = [];\n\n // Process chunks in parallel\n const results = await Promise.all(\n addressChunks.map(async (chunk, chunkIndex) => {\n console.log(`\\n🔄 Processing chunk ${chunkIndex + 1}/${addressChunks.length} with ${chunk.length} tokens`);\n\n const chunkResults = await Promise.all(\n chunk.map(async (token) => {\n try {\n const query = getTokenPoolsQueryByAddress(isAlgebraPool, protocol);\n const queryStartTime = performance.now();\n \n const response = await this.fetchFromGraph<PoolsByTokenResponse>(\n query,\n { token },\n protocol,\n chainId\n );\n\n const queryTime = performance.now() - queryStartTime;\n console.log(`⏱️ GraphQL query for token ${token.slice(0, 6)}... completed in ${queryTime.toFixed(2)}ms`);\n\n if (!response.success || !response.data) {\n console.error(`❌ No pools found for token: ${token} on chainId: ${chainId}`);\n return [];\n }\n\n // Extract pools from different possible response structures\n let pools: GraphQLPoolData[] = [];\n if (response.data.pools) {\n pools = response.data.pools;\n } else if (response.data.clPools) {\n pools = response.data.clPools;\n } else if (response.data.limitPools) {\n pools = response.data.limitPools;\n } else if (response.data.tokenPools) {\n pools = response.data.tokenPools;\n }\n\n if (pools.length === 0) {\n console.error(`❌ No pools found for token: ${token} on chainId: ${chainId}`);\n return [];\n }\n\n return pools;\n } catch (error) {\n console.error(`❌ Error fetching pools for token: ${token} on chainId: ${chainId}`, error);\n return [];\n }\n })\n );\n\n return chunkResults.flat();\n })\n );\n\n // Flatten all results\n allPools.push(...results.flat());\n\n return {\n data: allPools,\n status: 200,\n success: true,\n };\n } catch (error) {\n console.error(\"Error in fetchPoolsForTokensBatch:\", error);\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Fetches all pools containing a specific token\n * \n * @param tokenAddress - Token contract address\n * @param protocol - Protocol to fetch pools from\n * @param chainId - Chain ID to fetch pools from\n * @returns Promise containing pools that include the specified token\n * \n * @example\n * ```typescript\n * // Get all USDC pools on Uniswap V3\n * const usdcPools = await poolClient.fetchPoolsForToken(\n * '0xa0b86a33e6f8b07b71c3a39ef77a6b6e8f1b7b7e',\n * Protocol.UniswapV3,\n * 1\n * );\n * if (usdcPools.success) {\n * console.log(`Found ${usdcPools.data.length} USDC pools`);\n * }\n * ```\n * \n * @throws {Error} When failed to fetch pools for token\n */\n public async fetchPoolsForToken(\n tokenAddress: string,\n protocol: Protocol,\n chainId: number\n ): Promise<SteerResponse<GraphQLPoolData[]>> {\n try {\n const isAlgebraPool = isAlgebraProtocol(protocol);\n const query = getTokenPoolsQueryByAddress(isAlgebraPool, protocol);\n\n const response = await this.fetchFromGraph<PoolsByTokenResponse>(\n query,\n { token: tokenAddress.toLowerCase() },\n protocol,\n chainId\n );\n\n if (!response.success || !response.data) {\n throw new Error(response.error || 'Failed to fetch pools for token');\n }\n\n // Extract pools from different possible response structures\n let pools: GraphQLPoolData[] = [];\n if (response.data.pools) {\n pools = response.data.pools;\n } else if (response.data.limitPools) {\n pools = response.data.limitPools;\n } else if (response.data.tokenPools) {\n pools = response.data.tokenPools;\n } else if (response.data.clPools) {\n pools = response.data.clPools;\n }\n\n return {\n data: pools,\n status: 200,\n success: true,\n };\n } catch (error) {\n console.error(`Error fetching pools for token ${tokenAddress}:`, error);\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Filters pools based on validity criteria such as tick range and liquidity\n * \n * @param pools - Array of pools to filter\n * @returns Array of valid pools that meet the criteria\n * \n * @example\n * ```typescript\n * const validPools = poolClient.filterValidPools(allPools);\n * console.log(`Filtered down to ${validPools.length} valid pools`);\n * ```\n */\n public filterValidPools(pools: PoolData[]): PoolData[] {\n return pools.filter(pool => {\n // Check for required fields\n if (!pool.id || !pool.tick || !pool.liquidity) {\n return false;\n }\n\n // Parse values\n const tick = parseInt(pool.tick);\n const liquidity = parseFloat(pool.liquidity);\n\n // Check for valid tick range and liquidity\n const TICK_MIN = -887272;\n const TICK_MAX = 887272;\n const TICK_EDGE_THRESHOLD = 1;\n\n if (\n isNaN(tick) ||\n isNaN(liquidity) ||\n liquidity <= 0 ||\n tick <= TICK_MIN + TICK_EDGE_THRESHOLD ||\n tick >= TICK_MAX - TICK_EDGE_THRESHOLD\n ) {\n return false;\n }\n\n return true;\n });\n }\n} "]}
|
|
1
|
+
{"version":3,"file":"PoolClient.js","sourceRoot":"","sources":["../../../src/base/PoolClient.ts"],"names":[],"mappings":";;;AAEA,2DAAqD;AAKrD,gDAG2B;AAC3B,sDAAyD;AACzD,sEAAkH;AAmHlH;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAa,UAAW,SAAQ,kCAAc;IAU5C;;;;;;;;;;OAUG;IACH,YACE,MAAmC,EACnC,oBAA4B,EAAE;QAE9B,KAAK,CAAC,MAAM,CAAC,CAAC;QAtBhB,0DAA0D;QACzC,mBAAc,GAAW,KAAK,CAAC;QAChD,4CAA4C;QACpC,iBAAY,GAAW,CAAC,CAAC;QAoB/B,IAAI,CAAC,YAAY,GAAG,MAAM,CAAC;QAC3B,IAAI,CAAC,iBAAiB,GAAG,iBAAiB,CAAC;IAC7C,CAAC;IAED;;;;;;;OAOG;IACI,YAAY;QACjB,IAAI,CAAC,YAAY,GAAG,CAAC,CAAC;IACxB,CAAC;IAED;;;;;;;;;;OAUG;IACI,UAAU;QACf,OAAO;YACL,YAAY,EAAE,IAAI,CAAC,YAAY;SAChC,CAAC;IACJ,CAAC;IAED;;;;;;;;;;;;;;OAcG;IACK,KAAK,CAAC,cAAc,CAC1B,KAAa,EACb,SAAkC,EAClC,QAAkB,EAClB,O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,mBAAmB,GAAG,CAAC,CAAC;YAE9B,IACE,KAAK,CAAC,IAAI,CAAC;gBACX,KAAK,CAAC,SAAS,CAAC;gBAChB,SAAS,IAAI,CAAC;gBACd,IAAI,IAAI,QAAQ,GAAG,mBAAmB;gBACtC,IAAI,IAAI,QAAQ,GAAG,mBAAmB,EACtC,CAAC;gBACD,OAAO,KAAK,CAAC;YACf,CAAC;YAED,OAAO,IAAI,CAAC;QACd,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA/gBD,gCA+gBC","sourcesContent":["import type { PublicClient, WalletClient } from 'viem';\nimport { PoolData, SteerResponse } from '../types.js';\nimport { SubgraphClient } from './SubgraphClient.js';\nimport { \n Protocol, \n Chain\n} from '../const/chain.js';\nimport { \n chainIdToName, \n getProtocolSubgraphURL\n} from '../const/index.js';\nimport { isAlgebraProtocol } from '../const/protocol.js';\nimport { getTopPoolsQuery, getTokenPoolsQueryByAddress, getPoolDetailsQuery } from '../utils/PoolQueryAdapter.js';\n\n/**\n * GraphQL token data interface representing token information from subgraph responses\n * @interface GraphQLTokenData\n */\nexport interface GraphQLTokenData {\n /** Token symbol (e.g., \"ETH\", \"USDC\") */\n symbol: string;\n /** Token contract address */\n id: string;\n /** Number of decimal places for the token */\n decimals: string;\n /** Human-readable token name */\n name: string;\n}\n\n/**\n * GraphQL pool data interface representing pool information from subgraph responses\n * @interface GraphQLPoolData\n */\nexport interface GraphQLPoolData {\n /** Pool contract address */\n id: string;\n /** First token in the pool */\n token0: GraphQLTokenData;\n /** Second token in the pool */\n token1: GraphQLTokenData;\n /** 24-hour trading volume in USD */\n volumeUSD: string;\n /** Current tick of the pool */\n tick: string;\n /** Total liquidity in the pool */\n liquidity: string;\n /** Fee tier for the pool (optional) */\n feeTier?: string;\n /** 24-hour volume of token0 (optional) */\n volumeToken0?: string;\n /** 24-hour volume of token1 (optional) */\n volumeToken1?: string;\n /** Total value locked in ETH (optional) */\n totalValueLockedETH?: string;\n /** Alternative field name for volume USD (optional) */\n volumeUsd?: string;\n /** Alternative field name for TVL in ETH (optional) */\n totalValueLockedEth?: string;\n}\n\n/**\n * Filter criteria for querying pools\n * @interface PoolFilter\n */\nexport interface PoolFilter {\n /** Chain ID to filter pools by */\n chainId?: number;\n /** Protocol to filter pools by */\n protocol?: Protocol;\n /** Minimum volume in USD to filter pools */\n minVolumeUSD?: number;\n /** Token address to find pools containing this token */\n tokenAddress?: string;\n /** Maximum number of pools to return */\n limit?: number;\n}\n\n// GraphQL response interfaces (currently unused but kept for future use)\n// interface GraphQLResponse<T> {\n// data: T;\n// errors?: Array<{ message: string }>;\n// }\n\n/**\n * Response interface for top pools query\n * @interface TopPoolsResponse\n * @internal\n */\ninterface TopPoolsResponse {\n /** Standard pools array */\n pools: GraphQLPoolData[];\n /** Limit pools array (used by some protocols) */\n limitPools?: GraphQLPoolData[];\n /** CL pools array (used by some protocols) */\n clPools?: GraphQLPoolData[];\n}\n\n/**\n * Response interface for pool details query\n * @interface PoolDetailsResponse\n * @internal\n */\ninterface PoolDetailsResponse {\n /** Single pool data */\n pool: GraphQLPoolData;\n /** Single limit pool data (used by some protocols) */\n limitPool?: GraphQLPoolData;\n /** Single CL pool data (used by some protocols) */\n clPool?: GraphQLPoolData;\n}\n\n/**\n * Response interface for pools by token query\n * @interface PoolsByTokenResponse\n * @internal\n */\ninterface PoolsByTokenResponse {\n /** Standard pools array */\n pools?: GraphQLPoolData[];\n /** Limit pools array (used by some protocols) */\n limitPools?: GraphQLPoolData[];\n /** Token pools array (used by some protocols) */\n tokenPools?: GraphQLPoolData[];\n /** CL pools array (used by some protocols) */\n clPools?: GraphQLPoolData[];\n}\n\n/**\n * Client for fetching pool data from various DEX protocol subgraphs\n * \n * @example\n * ```typescript\n * import { createPublicClient, createWalletClient, http } from 'viem';\n * import { mainnet } from 'viem/chains';\n * import { PoolClient } from '@steerprotocol/sdk';\n * \n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http()\n * }) as PublicClient & WalletClient;\n * \n * const poolClient = new PoolClient(client, 'your-subgraph-studio-key');\n * \n * // Fetch top pools\n * const topPools = await poolClient.getTopPools(100, Protocol.UniswapV3, 1);\n * ```\n * \n * @extends SubgraphClient\n * @group Pool\n */\nexport class PoolClient extends SubgraphClient {\n /** Public client for blockchain interactions */\n protected readonly publicClient: PublicClient;\n /** Default timeout for GraphQL queries in milliseconds */\n private readonly defaultTimeout: number = 60000;\n /** Counter for tracking API call metrics */\n private apiCallCount: number = 0;\n /** Subgraph Studio API key for rate limiting */\n private readonly subgraphStudioKey: string;\n\n /**\n * Creates a new PoolClient instance\n * \n * @param client - Combined public and wallet client for blockchain interactions\n * @param subgraphStudioKey - Optional Subgraph Studio API key for higher rate limits\n * \n * @example\n * ```typescript\n * const poolClient = new PoolClient(client, 'your-api-key');\n * ```\n */\n constructor(\n client: PublicClient & WalletClient,\n subgraphStudioKey: string = ''\n ) {\n super(client);\n this.publicClient = client;\n this.subgraphStudioKey = subgraphStudioKey;\n }\n\n /**\n * Resets the API call counter for metrics tracking\n * \n * @example\n * ```typescript\n * poolClient.resetMetrics();\n * ```\n */\n public resetMetrics(): void {\n this.apiCallCount = 0;\n }\n\n /**\n * Gets current metrics for monitoring API usage\n * \n * @returns Object containing current metrics\n * \n * @example\n * ```typescript\n * const metrics = poolClient.getMetrics();\n * console.log(`API calls made: ${metrics.apiCallCount}`);\n * ```\n */\n public getMetrics(): { apiCallCount: number } {\n return {\n apiCallCount: this.apiCallCount,\n };\n }\n\n /**\n * Fetches data from GraphQL endpoint with retry logic for rate limits\n * \n * @param query - GraphQL query string\n * @param variables - Variables for the GraphQL query\n * @param protocol - Protocol to query\n * @param chainId - Chain ID to query\n * @returns Promise containing the response data\n * \n * @throws {Error} When subgraph endpoint is not available\n * @throws {Error} When rate limit is exceeded after max retries\n * @throws {Error} When GraphQL query times out\n * \n * @internal\n */\n private async fetchFromGraph<T>(\n query: string,\n variables: Record<string, unknown>,\n protocol: Protocol,\n chainId: number\n ): Promise<SteerResponse<T>> {\n try {\n const chainName = chainIdToName(chainId);\n const endpoint = getProtocolSubgraphURL(protocol, chainName as Chain, this.subgraphStudioKey);\n\n if (!endpoint) {\n throw new Error(`No subgraph endpoint available for protocol ${protocol} on chain ${chainName}`);\n }\n\n const MAX_RETRIES = 3;\n const RETRY_DELAY_MS = 11000;\n\n const fetchWithRetry = async (retries = 0): Promise<T> => {\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify({ query, variables }),\n });\n\n const data = await response.json() as { data: T; error?: string; errors?: Array<{ message: string }> };\n\n if (data.error && typeof data.error === \"string\" && data.error.includes(\"surpassed your query allowance\")) {\n if (retries < MAX_RETRIES) {\n console.warn(`Rate limit hit for ${endpoint}, retrying in ${RETRY_DELAY_MS / 1000}s (attempt ${retries + 1})`);\n await new Promise(res => setTimeout(res, RETRY_DELAY_MS));\n return fetchWithRetry(retries + 1);\n } else {\n throw new Error(`Rate limit exceeded after ${MAX_RETRIES} retries: ${data.error}`);\n }\n }\n\n if (data.error) {\n throw new Error(`GraphQL endpoint error: ${data.error}`);\n }\n\n if (data.errors) {\n throw new Error(`GraphQL errors: ${JSON.stringify(data.errors)}`);\n }\n\n return data.data;\n };\n\n this.apiCallCount++;\n console.log(\"Total API calls:\", this.apiCallCount);\n\n const timeoutPromise = new Promise<never>((_, reject) => {\n setTimeout(\n () => reject(new Error(\"GraphQL query timeout\")),\n this.defaultTimeout\n );\n });\n\n const data = await Promise.race([fetchWithRetry(), timeoutPromise]);\n\n return {\n data: data as T,\n status: 200,\n success: true,\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Fetches the top pools for a specific protocol by trading volume\n * \n * @param count - Number of pools to fetch (default: 500)\n * @param protocol - Protocol to fetch pools from\n * @param chainId - Chain ID to fetch pools from\n * @returns Promise containing an array of top pools\n * \n * @example\n * ```typescript\n * // Get top 100 Uniswap V3 pools on Ethereum\n * const topPools = await poolClient.getTopPools(100, Protocol.UniswapV3, 1);\n * if (topPools.success) {\n * console.log(`Found ${topPools.data.length} pools`);\n * }\n * ```\n * \n * @throws {Error} When failed to fetch pools from subgraph\n */\n public async getTopPools(\n count: number = 500,\n protocol: Protocol,\n chainId: number\n ): Promise<SteerResponse<GraphQLPoolData[]>> {\n try {\n const isAlgebraPool = isAlgebraProtocol(protocol);\n const query = getTopPoolsQuery(protocol, isAlgebraPool);\n\n console.log(`[Chain ${chainId}] [Protocol ${protocol}] 📊 Fetching top ${count} pools from the subgraph...`);\n\n const response = await this.fetchFromGraph<TopPoolsResponse>(\n query,\n { limit: count },\n protocol,\n chainId\n );\n\n if (!response.success || !response.data) {\n throw new Error(response.error || 'Failed to fetch pools');\n }\n\n const pools = response.data.pools || response.data.limitPools || response.data.clPools || [];\n \n console.log(`[Chain ${chainId}] [Protocol ${protocol}] ✅ Received ${pools.length} pools from the subgraph`);\n\n // Filter out pools with invalid volumeUSD\n const validPools = pools.filter(pool => {\n const volumeUSD = parseFloat(pool.volumeUSD || pool.volumeUsd || \"0\");\n return !isNaN(volumeUSD) && volumeUSD > 0;\n });\n\n console.log(`[Chain ${chainId}] [Protocol ${protocol}] ✅ Found ${validPools.length} valid pools with positive volumeUSD`);\n\n return {\n data: validPools,\n status: 200,\n success: true,\n };\n } catch (error) {\n console.error(`[Chain ${chainId}] [Protocol ${protocol}] Error in getTopPools:`, error);\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Fetches detailed information for a specific pool by its ID\n * \n * @param poolId - Pool contract address to fetch\n * @param protocol - Protocol the pool belongs to\n * @param chainId - Chain ID where the pool exists\n * @returns Promise containing pool details or null if not found\n * \n * @example\n * ```typescript\n * // Get specific pool details\n * const poolDetails = await poolClient.getPoolById(\n * '0x88e6a0c2ddd26feeb64f039a2c41296fcb3f5640',\n * Protocol.UniswapV3,\n * 1\n * );\n * if (poolDetails.success && poolDetails.data) {\n * console.log(`Pool: ${poolDetails.data.token0.symbol}/${poolDetails.data.token1.symbol}`);\n * }\n * ```\n * \n * @throws {Error} When failed to fetch pool from subgraph\n */\n public async getPoolById(\n poolId: string,\n protocol: Protocol,\n chainId: number\n ): Promise<SteerResponse<GraphQLPoolData | null>> {\n try {\n\n const isAlgebraPool = isAlgebraProtocol(protocol);\n const query = getPoolDetailsQuery(isAlgebraPool, protocol);\n\n \n const response = await this.fetchFromGraph<PoolDetailsResponse>(\n query,\n { pool: poolId },\n protocol,\n chainId\n );\n\n if (!response.success || !response.data) {\n throw new Error(response.error || 'Failed to fetch pool');\n }\n\n const pool = response.data.pool || response.data.clPool || response.data.limitPool || null;\n\n\n return {\n data: pool,\n status: 200,\n success: true,\n };\n } catch (error) {\n console.error(`Error fetching pool ${poolId}:`, error);\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Fetches pools containing multiple tokens in batches for better performance\n * \n * @param tokenAddresses - Array of token contract addresses\n * @param protocol - Protocol to fetch pools from\n * @param chainId - Chain ID to fetch pools from\n * @param batchSize - Number of tokens to process in each batch (default: 10)\n * @returns Promise containing all pools found for the tokens\n * \n * @example\n * ```typescript\n * // Get pools for multiple tokens\n * const tokenAddresses = [\n * '0xa0b86a33e6f8b07b71c3a39ef77a6b6e8f1b7b7e', // USDC\n * '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2' // WETH\n * ];\n * const pools = await poolClient.fetchPoolsForTokensBatch(\n * tokenAddresses,\n * Protocol.UniswapV3,\n * 1,\n * 5\n * );\n * ```\n * \n * @throws {Error} When batch processing fails\n */\n public async fetchPoolsForTokensBatch(\n tokenAddresses: string[],\n protocol: Protocol,\n chainId: number,\n batchSize: number = 10\n ): Promise<SteerResponse<GraphQLPoolData[]>> {\n try {\n if (tokenAddresses.length === 0) {\n return {\n data: [],\n status: 200,\n success: true,\n };\n }\n\n console.log(`\\n🔍 Batch Pool Fetch Summary:`);\n console.log(`📥 Total tokens to process: ${tokenAddresses.length}`);\n\n const isAlgebraPool = isAlgebraProtocol(protocol);\n const normalizedAddresses = tokenAddresses.map(addr => addr.toLowerCase());\n\n // Split into chunks\n const chunkSize = batchSize;\n const addressChunks = [];\n for (let i = 0; i < normalizedAddresses.length; i += chunkSize) {\n addressChunks.push(normalizedAddresses.slice(i, i + chunkSize));\n }\n\n console.log(`📦 Processing ${addressChunks.length} chunks of max ${chunkSize} tokens each`);\n\n const allPools: GraphQLPoolData[] = [];\n\n // Process chunks in parallel\n const results = await Promise.all(\n addressChunks.map(async (chunk, chunkIndex) => {\n console.log(`\\n🔄 Processing chunk ${chunkIndex + 1}/${addressChunks.length} with ${chunk.length} tokens`);\n\n const chunkResults = await Promise.all(\n chunk.map(async (token) => {\n try {\n const query = getTokenPoolsQueryByAddress(isAlgebraPool, protocol);\n const queryStartTime = performance.now();\n \n const response = await this.fetchFromGraph<PoolsByTokenResponse>(\n query,\n { token },\n protocol,\n chainId\n );\n\n const queryTime = performance.now() - queryStartTime;\n console.log(`⏱️ GraphQL query for token ${token.slice(0, 6)}... completed in ${queryTime.toFixed(2)}ms`);\n\n if (!response.success || !response.data) {\n console.error(`❌ No pools found for token: ${token} on chainId: ${chainId}`);\n return [];\n }\n\n // Extract pools from different possible response structures\n let pools: GraphQLPoolData[] = [];\n if (response.data.pools) {\n pools = response.data.pools;\n } else if (response.data.clPools) {\n pools = response.data.clPools;\n } else if (response.data.limitPools) {\n pools = response.data.limitPools;\n } else if (response.data.tokenPools) {\n pools = response.data.tokenPools;\n }\n\n if (pools.length === 0) {\n console.error(`❌ No pools found for token: ${token} on chainId: ${chainId}`);\n return [];\n }\n\n return pools;\n } catch (error) {\n console.error(`❌ Error fetching pools for token: ${token} on chainId: ${chainId}`, error);\n return [];\n }\n })\n );\n\n return chunkResults.flat();\n })\n );\n\n // Flatten all results\n allPools.push(...results.flat());\n\n return {\n data: allPools,\n status: 200,\n success: true,\n };\n } catch (error) {\n console.error(\"Error in fetchPoolsForTokensBatch:\", error);\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Fetches all pools containing a specific token\n * \n * @param tokenAddress - Token contract address\n * @param protocol - Protocol to fetch pools from\n * @param chainId - Chain ID to fetch pools from\n * @returns Promise containing pools that include the specified token\n * \n * @example\n * ```typescript\n * // Get all USDC pools on Uniswap V3\n * const usdcPools = await poolClient.fetchPoolsForToken(\n * '0xa0b86a33e6f8b07b71c3a39ef77a6b6e8f1b7b7e',\n * Protocol.UniswapV3,\n * 1\n * );\n * if (usdcPools.success) {\n * console.log(`Found ${usdcPools.data.length} USDC pools`);\n * }\n * ```\n * \n * @throws {Error} When failed to fetch pools for token\n */\n public async fetchPoolsForToken(\n tokenAddress: string,\n protocol: Protocol,\n chainId: number\n ): Promise<SteerResponse<GraphQLPoolData[]>> {\n try {\n const isAlgebraPool = isAlgebraProtocol(protocol);\n const query = getTokenPoolsQueryByAddress(isAlgebraPool, protocol);\n\n const response = await this.fetchFromGraph<PoolsByTokenResponse>(\n query,\n { token: tokenAddress.toLowerCase() },\n protocol,\n chainId\n );\n\n if (!response.success || !response.data) {\n throw new Error(response.error || 'Failed to fetch pools for token');\n }\n\n // Extract pools from different possible response structures\n let pools: GraphQLPoolData[] = [];\n if (response.data.pools) {\n pools = response.data.pools;\n } else if (response.data.limitPools) {\n pools = response.data.limitPools;\n } else if (response.data.tokenPools) {\n pools = response.data.tokenPools;\n } else if (response.data.clPools) {\n pools = response.data.clPools;\n }\n\n return {\n data: pools,\n status: 200,\n success: true,\n };\n } catch (error) {\n console.error(`Error fetching pools for token ${tokenAddress}:`, error);\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred',\n };\n }\n }\n\n /**\n * Filters pools based on validity criteria such as tick range and liquidity\n * \n * @param pools - Array of pools to filter\n * @returns Array of valid pools that meet the criteria\n * \n * @example\n * ```typescript\n * const validPools = poolClient.filterValidPools(allPools);\n * console.log(`Filtered down to ${validPools.length} valid pools`);\n * ```\n */\n public filterValidPools(pools: PoolData[]): PoolData[] {\n return pools.filter(pool => {\n // Check for required fields\n if (!pool.id || !pool.tick || !pool.liquidity) {\n return false;\n }\n\n // Parse values\n const tick = parseInt(pool.tick);\n const liquidity = parseFloat(pool.liquidity);\n\n // Check for valid tick range and liquidity\n const TICK_MIN = -887272;\n const TICK_MAX = 887272;\n const TICK_EDGE_THRESHOLD = 1;\n\n if (\n isNaN(tick) ||\n isNaN(liquidity) ||\n liquidity <= 0 ||\n tick <= TICK_MIN + TICK_EDGE_THRESHOLD ||\n tick >= TICK_MAX - TICK_EDGE_THRESHOLD\n ) {\n return false;\n }\n\n return true;\n });\n }\n} "]}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SmartRewardsClient = void 0;
|
|
4
|
+
const api_sdk_1 = require("@steerprotocol/api-sdk");
|
|
5
|
+
const SmartRewards_js_1 = require("./SmartRewards.js");
|
|
6
|
+
const api_js_1 = require("../const/api.js");
|
|
4
7
|
/**
|
|
5
8
|
* Client for interacting with Steer Protocol's Smart Rewards system.
|
|
6
9
|
* This client provides functionality for managing rewards, claims, and campaigns.
|
|
@@ -34,7 +37,7 @@ import { getApiUrl } from '../const/api.js';
|
|
|
34
37
|
*
|
|
35
38
|
* @group Client
|
|
36
39
|
*/
|
|
37
|
-
|
|
40
|
+
class SmartRewardsClient extends SmartRewards_js_1.SmartRewards {
|
|
38
41
|
/**
|
|
39
42
|
* Creates a new instance of SmartRewardsClient
|
|
40
43
|
* @param publicClient - The public client for reading from the blockchain
|
|
@@ -43,9 +46,10 @@ export class SmartRewardsClient extends SmartRewards {
|
|
|
43
46
|
* @param version - Optional API version to use (defaults to 'v1')
|
|
44
47
|
*/
|
|
45
48
|
constructor(publicClient, walletClient, environment, version = 'v1') {
|
|
46
|
-
const apiUrl = getApiUrl(environment, version);
|
|
47
|
-
const apiClient = createClient(apiUrl);
|
|
49
|
+
const apiUrl = (0, api_js_1.getApiUrl)(environment, version);
|
|
50
|
+
const apiClient = (0, api_sdk_1.createClient)(apiUrl);
|
|
48
51
|
super(apiClient, publicClient, walletClient);
|
|
49
52
|
}
|
|
50
53
|
}
|
|
54
|
+
exports.SmartRewardsClient = SmartRewardsClient;
|
|
51
55
|
//# sourceMappingURL=SmartRewardClient.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SmartRewardClient.js","sourceRoot":"","sources":["../../../src/base/SmartRewardClient.ts"],"names":[],"mappings":"AAAA,
|
|
1
|
+
{"version":3,"file":"SmartRewardClient.js","sourceRoot":"","sources":["../../../src/base/SmartRewardClient.ts"],"names":[],"mappings":";;;AAAA,oDAAsD;AAEtD,uDAAiD;AACjD,4CAA4C;AAE5C;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,MAAa,kBAAmB,SAAQ,8BAAY;IAClD;;;;;;OAMG;IACH,YACE,YAA0B,EAC1B,YAA0B,EAC1B,WAAyC,EACzC,UAAgB,IAAI;QAEpB,MAAM,MAAM,GAAG,IAAA,kBAAS,EAAC,WAAW,EAAE,OAAO,CAAC,CAAC;QAC/C,MAAM,SAAS,GAAG,IAAA,sBAAY,EAAC,MAAM,CAAC,CAAC;QACvC,KAAK,CAAC,SAAS,EAAE,YAAY,EAAE,YAAY,CAAC,CAAC;IAC/C,CAAC;CACF;AAlBD,gDAkBC","sourcesContent":["import { createClient } from '@steerprotocol/api-sdk';\nimport type { PublicClient, WalletClient } from 'viem';\nimport { SmartRewards } from './SmartRewards.js';\nimport { getApiUrl } from '../const/api.js';\n\n/**\n * Client for interacting with Steer Protocol's Smart Rewards system.\n * This client provides functionality for managing rewards, claims, and campaigns.\n * \n * @example\n * ```typescript\n * import { createPublicClient, createWalletClient, http } from 'viem';\n * import { mainnet } from 'viem/chains';\n * import { SmartRewardsClient } from '@steerprotocol/sdk';\n * \n * // Create viem clients\n * const publicClient = createPublicClient({\n * chain: mainnet,\n * transport: http()\n * });\n * \n * const walletClient = createWalletClient({\n * chain: mainnet,\n * transport: http()\n * });\n * \n * // Initialize the Smart Rewards client\n * const rewardsClient = new SmartRewardsClient(publicClient, walletClient, 'production');\n * \n * // Get user's reward summary\n * const summary = await rewardsClient.getRewardSummary(userAddress, chainId);\n * \n * // Claim rewards\n * const tx = await rewardsClient.claimCampaignRewards(userAddress, chainId);\n * ```\n * \n * @group Client\n */\nexport class SmartRewardsClient extends SmartRewards {\n /**\n * Creates a new instance of SmartRewardsClient\n * @param publicClient - The public client for reading from the blockchain\n * @param walletClient - The wallet client for writing to the blockchain\n * @param environment - The environment to use ('production' or 'development')\n * @param version - Optional API version to use (defaults to 'v1')\n */\n constructor(\n publicClient: PublicClient, \n walletClient: WalletClient,\n environment: 'production' | 'development',\n version: 'v1' = 'v1'\n ) {\n const apiUrl = getApiUrl(environment, version);\n const apiClient = createClient(apiUrl);\n super(apiClient, publicClient, walletClient);\n }\n}"]}
|
|
@@ -1,6 +1,9 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.SmartRewards = void 0;
|
|
4
|
+
const viem_1 = require("viem");
|
|
5
|
+
const subgraph_js_1 = require("../const/subgraph.js");
|
|
6
|
+
class SmartRewards {
|
|
4
7
|
constructor(client, publicClient, walletClient) {
|
|
5
8
|
this.client = client;
|
|
6
9
|
this.publicClient = publicClient;
|
|
@@ -220,15 +223,15 @@ export class SmartRewards {
|
|
|
220
223
|
const summary = {
|
|
221
224
|
totalEarned: {
|
|
222
225
|
native: totalAmount,
|
|
223
|
-
formatted: formatUnits(totalAmount, decimals)
|
|
226
|
+
formatted: (0, viem_1.formatUnits)(totalAmount, decimals)
|
|
224
227
|
},
|
|
225
228
|
totalClaimed: {
|
|
226
229
|
native: claimedAmount,
|
|
227
|
-
formatted: formatUnits(claimedAmount, decimals)
|
|
230
|
+
formatted: (0, viem_1.formatUnits)(claimedAmount, decimals)
|
|
228
231
|
},
|
|
229
232
|
claimable: {
|
|
230
233
|
native: claimableAmount,
|
|
231
|
-
formatted: formatUnits(claimableAmount, decimals)
|
|
234
|
+
formatted: (0, viem_1.formatUnits)(claimableAmount, decimals)
|
|
232
235
|
}
|
|
233
236
|
};
|
|
234
237
|
return {
|
|
@@ -550,7 +553,8 @@ export class SmartRewards {
|
|
|
550
553
|
* @returns boolean indicating if the chain is supported
|
|
551
554
|
*/
|
|
552
555
|
supportsChain(chainId) {
|
|
553
|
-
return getSubgraphUrlByChainId(chainId) !== undefined;
|
|
556
|
+
return (0, subgraph_js_1.getSubgraphUrlByChainId)(chainId) !== undefined;
|
|
554
557
|
}
|
|
555
558
|
}
|
|
559
|
+
exports.SmartRewards = SmartRewards;
|
|
556
560
|
//# sourceMappingURL=SmartRewards.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"SmartRewards.js","sourceRoot":"","sources":["../../../src/base/SmartRewards.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AAEnC,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC;AA4H/D,MAAM,OAAgB,YAAY;IAKhC,YACE,MAAuC,EACvC,YAA0B,EAC1B,YAA0B;QAE1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,CAAC;IAEM,KAAK,CAAC,YAAY,CAAC,OAAe;QACvC,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC;YAC5C,MAAM,EAAE;gBACN,OAAO;aACR;SACF,CAAC,CA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YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,wBAAwB;aACzE,CAAC;QACJ,CAAC;IACH,CAAC;IAED;;;;OAIG;IACI,aAAa,CAAC,OAAe;QAClC,OAAO,uBAAuB,CAAC,OAAO,CAAC,KAAK,SAAS,CAAC;IACxD,CAAC;CACF","sourcesContent":["import { Campaign, createClient } from '@steerprotocol/api-sdk';\nimport type { Address, Hash, PublicClient, WalletClient } from 'viem';\nimport { formatUnits } from 'viem';\nimport { SteerResponse } from '../types.js';\nimport { getSubgraphUrlByChainId } from '../const/subgraph.js';\n\n/**\n * Represents a node in the claim proof data structure\n * @property chainId - The ID of the chain where the claim exists\n * @property lastBlockUpdatedTo - The last block number this claim was updated to\n * @property user - The address of the user who can claim\n * @property campaignId - The ID of the campaign this claim belongs to\n * @property amount - The claimable amount as a string (may include decimals)\n * @property proof - The merkle proof array required for claiming\n */\nexport interface ClaimProofNode {\n chainId: number;\n lastBlockUpdatedTo: number;\n user: string;\n campaignId: number;\n amount: string;\n proof: readonly string[];\n}\n\nexport interface ClaimProofEdge {\n node: ClaimProofNode;\n cursor: string;\n}\n\n/**\n * Represents a historical claim reward record\n * @property id - Unique identifier for the claim\n * @property user - Address of the user who claimed\n * @property amount - Amount that was claimed (may include decimals)\n * @property campaign - Campaign identifier\n * @property chainId - Chain ID where the claim occurred\n * @property timestamp - Unix timestamp of when the claim occurred\n */\nexport interface ClaimRewardNode {\n id: string;\n user: string;\n amount: string;\n campaign: string;\n chainId: number;\n timestamp: number;\n}\n\nexport interface ClaimRewardEdge {\n cursor: string;\n node: ClaimRewardNode;\n}\n\n/**\n * Pagination information for paginated queries\n * @property hasNextPage - Whether there are more results available\n * @property endCursor - Cursor to use for fetching next page, if available\n */\nexport interface PageInfo {\n hasNextPage: boolean;\n endCursor: string | null | undefined;\n}\n\n/**\n * Connection type for claim rewards, following the Relay specification\n * @property edges - Array of claim reward records with cursors\n * @property pageInfo - Pagination information\n * @property totalCount - Total number of records available\n */\nexport interface ClaimRewardsConnection {\n edges: readonly ClaimRewardEdge[];\n pageInfo: PageInfo;\n totalCount: number;\n}\n\nexport interface ClaimProofsPageInfo {\n hasNextPage: boolean;\n endCursor?: string;\n}\n\nexport interface ClaimProofsResponse {\n totalCount: number;\n edges: readonly ClaimProofEdge[];\n pageInfo: ClaimProofsPageInfo;\n}\n\nexport interface SmartRewarderContract {\n chainId: number;\n address: string;\n}\n\n/**\n * Parameters required for claiming rewards\n * @property users - Array of user addresses who are claiming\n * @property campaignIds - Array of campaign IDs corresponding to each claim\n * @property amounts - Array of amounts to claim\n * @property proofs - Array of merkle proofs for verification\n * @property rewarderAddress - Address of the smart rewarder contract\n */\nexport interface ClaimRewardParams {\n users: readonly Address[];\n campaignIds: readonly bigint[];\n amounts: readonly bigint[];\n proofs: readonly (readonly `0x${string}`[])[];\n rewarderAddress: Address;\n}\n\n/**\n * Represents a reward balance with both native and formatted values\n * @property formatted - Human-readable string format with proper decimals\n * @property native - Raw bigint value\n */\nexport interface RewardBalance {\n formatted: string;\n native: bigint;\n}\n\n/**\n * Comprehensive summary of a user's reward status\n * @property totalEarned - Total rewards earned (claimed + claimable)\n * @property totalClaimed - Total rewards already claimed\n * @property claimable - Rewards available to claim\n */\nexport interface RewardSummary {\n totalEarned: RewardBalance;\n totalClaimed: RewardBalance;\n claimable: RewardBalance;\n}\n\nexport abstract class SmartRewards {\n protected readonly client: ReturnType<typeof createClient>;\n protected readonly publicClient: PublicClient;\n protected readonly walletClient: WalletClient;\n\n constructor(\n client: ReturnType<typeof createClient>,\n publicClient: PublicClient,\n walletClient: WalletClient\n ) {\n this.client = client;\n this.publicClient = publicClient;\n this.walletClient = walletClient;\n }\n\n public async getCampaigns(chainId: number): Promise<SteerResponse<Campaign[]>> {\n const campaigns = await this.client.campaigns({\n filter: {\n chainId,\n },\n });\n\n return {\n data: (campaigns.data?.campaigns.edges.map((edge) => ({\n ...edge.node,\n vaults: edge.node.vaults?.map(vault => ({\n ...vault,\n beaconName: vault.beaconName || '',\n name: vault.name || '',\n protocol: vault.protocol || '',\n protocolBaseType: vault.protocolBaseType || '',\n targetProtocol: vault.targetProtocol || ''\n })) || []\n })) || []) as Campaign[],\n status: campaigns.status,\n success: true,\n };\n }\n\n /**\n * Retrieves campaigns associated with a specific pool address\n * @param poolAddress - The address of the pool to get campaigns for\n * @param chainId - Chain ID where the pool exists\n * @returns Promise resolving to an array of campaigns associated with the pool\n * \n * @example\n * ```typescript\n * // Get campaigns for a pool on a specific chain\n * const campaigns = await smartRewards.campaignsByPool('0x...', 1);\n * ```\n */\n public async campaignsByPool(\n poolAddress: string,\n chainId: number\n ): Promise<SteerResponse<Campaign[]>> {\n try {\n const campaigns = await this.client.campaignsByPool({\n pool: poolAddress,\n chainId\n });\n\n return {\n data: (campaigns.data?.campaignsByPool?.map(campaign => campaign ? {\n ...campaign,\n vaults: campaign.vaults?.map(vault => vault ? {\n ...vault,\n beaconName: vault.beaconName || '',\n name: vault.name || '',\n protocol: vault.protocol || '',\n protocolBaseType: vault.protocolBaseType || '',\n targetProtocol: vault.targetProtocol || ''\n } : null).filter((v): v is NonNullable<typeof v> => v !== null) || []\n } : null).filter((c): c is NonNullable<typeof c> => c !== null) || []) as Campaign[],\n status: campaigns.status,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Retrieves claim proofs for a user that can be used to claim rewards\n * @param user - Address of the user to get proofs for\n * @param chainId - Chain ID where the claims exist\n * @param campaignId - Optional campaign ID to filter claims\n * @returns Promise resolving to claim proof data with pagination support\n */\n public async getClaimProofs(\n user: Address,\n chainId: number,\n campaignId?: number\n ): Promise<SteerResponse<ClaimProofsResponse>> {\n try {\n const normalizedUser = user.toLowerCase() as Address;\n const response = await this.client.claimProofs({\n user: normalizedUser,\n filter: {\n chainId,\n campaignId\n }\n });\n\n if (!response.data?.claimProofs) {\n return {\n data: null,\n status: response.status,\n success: true\n };\n }\n\n const transformedResponse: ClaimProofsResponse = {\n totalCount: response.data.claimProofs.totalCount,\n pageInfo: {\n hasNextPage: response.data.claimProofs.pageInfo.hasNextPage,\n endCursor: response.data.claimProofs.pageInfo.endCursor || undefined\n },\n edges: response.data.claimProofs.edges.map(edge => ({\n cursor: edge.cursor,\n node: {\n ...edge.node,\n proof: edge.node.proof?.filter((p): p is string => p !== null) || []\n }\n }))\n };\n\n return {\n data: transformedResponse,\n status: response.status,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Retrieves historical claim data for a specific pool\n * @param chainId - Chain ID where the pool exists\n * @param pool - Address or identifier of the pool\n * @param user - Optional user address to filter claims\n * @returns Promise resolving to paginated claim history data\n * \n * @example\n * ```typescript\n * // Get all claims for a pool\n * const allClaims = await smartRewards.getClaimRewardsByPool(1, poolAddress);\n * \n * // Get claims for a specific user in a pool\n * const userClaims = await smartRewards.getClaimRewardsByPool(1, poolAddress, userAddress);\n * ```\n */\n public async getClaimedRewardsByPool(\n chainId: number,\n pool: string,\n user?: Address\n ): Promise<SteerResponse<ClaimRewardsConnection>> {\n try {\n const normalizedPool = pool.toLowerCase();\n const normalizedUser = user ? user.toLowerCase() as Address : undefined;\n \n const response = await this.client.claimRewards({\n poolId: normalizedPool,\n chainId,\n filter: normalizedUser ? { user: normalizedUser } : undefined\n });\n\n if (!response.data?.claimRewards) {\n return {\n data: null,\n status: response.status,\n success: true\n };\n }\n\n const transformedResponse: ClaimRewardsConnection = {\n totalCount: response.data.claimRewards.totalCount,\n pageInfo: {\n hasNextPage: response.data.claimRewards.pageInfo.hasNextPage,\n endCursor: response.data.claimRewards.pageInfo.endCursor\n },\n edges: response.data.claimRewards.edges.map(edge => ({\n cursor: edge.cursor,\n node: {\n ...edge.node,\n timestamp: Number(edge.node.timestamp)\n }\n }))\n };\n\n return {\n data: transformedResponse,\n status: response.status,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n \n\n /**\n * Gets a comprehensive summary of a user's reward status\n * @param user - Address of the user\n * @param chainId - Chain ID to check rewards on\n * @param campaignId - Optional campaign ID to filter rewards\n * @param decimals - Number of decimals for formatting (default: 18)\n * @returns Promise resolving to reward summary with both native and formatted values\n * \n * @example\n * ```typescript\n * const summary = await smartRewards.getRewardSummary(userAddress, chainId);\n * console.log('Total earned:', summary.data.totalEarned.formatted);\n * console.log('Available to claim:', summary.data.claimable.formatted);\n * ```\n */\n public async getRewardSummary(\n user: Address,\n poolAddress: string,\n chainId: number,\n campaignId: number,\n decimals: number = 18\n ): Promise<SteerResponse<RewardSummary>> {\n try {\n // Lowercase addresses\n const normalizedUser = user.toLowerCase() as Address;\n const normalizedPoolAddress = poolAddress.toLowerCase();\n\n // Get claimable rewards\n const claimProofs = await this.getClaimProofs(normalizedUser, chainId, campaignId);\n\n // Filter claim proofs by campaignId for additional safety\n const filteredClaimProofs = claimProofs.data?.edges.filter(\n edge => edge.node.campaignId === campaignId\n ) || [];\n\n const totalAmount = filteredClaimProofs.reduce(\n (sum, edge) => sum + BigInt(edge.node.amount.split('.')[0]),\n 0n\n ) || 0n;\n\n // Get claimed rewards\n const claimedRewards = await this.getClaimedRewardsByPool(chainId, normalizedPoolAddress, normalizedUser);\n\n // Filter claimed rewards by campaign ID\n const filteredClaimedRewards = claimedRewards.data?.edges.filter(\n edge => Number(edge.node.campaign) === campaignId\n ) || [];\n\n const claimedAmount = filteredClaimedRewards.reduce(\n (sum, edge) => sum + BigInt(edge.node.amount.split('.')[0]),\n 0n\n ) || 0n;\n\n // Calculate totals\n const claimableAmount = totalAmount - claimedAmount;\n\n const summary: RewardSummary = {\n totalEarned: {\n native: totalAmount,\n formatted: formatUnits(totalAmount, decimals)\n },\n totalClaimed: {\n native: claimedAmount,\n formatted: formatUnits(claimedAmount, decimals)\n },\n claimable: {\n native: claimableAmount,\n formatted: formatUnits(claimableAmount, decimals)\n }\n };\n\n return {\n data: summary,\n status: 200,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n public async getSmartRewarderContracts(): Promise<SteerResponse<readonly SmartRewarderContract[]>> {\n try {\n const response = await this.client.smartRewarderContracts();\n\n return {\n data: response.data?.smartRewarderContracts || [],\n status: response.status,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Claims rewards from the smart rewarder contract\n * @param params - Parameters required for claiming rewards\n * @returns Promise resolving to transaction hash if successful\n * \n * @remarks\n * This method handles the low-level interaction with the smart contract.\n * For a higher-level interface, consider using {@link claimCampaignRewards} instead.\n * \n * @example\n * ```typescript\n * // Get claim proofs\n * const claimProofs = await smartRewards.getClaimProofs(userAddress, chainId, campaignId);\n * \n * // Get smart rewarder contract\n * const rewarders = await smartRewards.getSmartRewarderContracts();\n * const rewarder = rewarders.data?.find(r => r.chainId === chainId);\n * \n * if (claimProofs.data && rewarder) {\n * // Prepare claim data\n * const claimData = smartRewards.prepareClaimData(claimProofs.data);\n * claimData.rewarderAddress = rewarder.address as Address;\n * \n * // Claim rewards\n * const tx = await smartRewards.claimReward(claimData);\n * }\n * ```\n * \n * @throws Will throw an error if no wallet account is found\n * @throws Will throw an error if contract simulation fails\n */\n public async claimReward(params: ClaimRewardParams): Promise<SteerResponse<Hash>> {\n try {\n const account = await this.walletClient.getAddresses();\n if (!account[0]) throw new Error('No account found');\n\n // Normalize addresses\n const normalizedParams = {\n ...params,\n users: params.users.map(user => user.toLowerCase() as Address),\n rewarderAddress: params.rewarderAddress.toLowerCase() as Address\n };\n\n const { request } = await this.publicClient.simulateContract({\n address: normalizedParams.rewarderAddress,\n abi: [{\n type: 'function',\n inputs: [\n { name: 'users', internalType: 'address[]', type: 'address[]' },\n { name: 'campaignIds', internalType: 'uint256[]', type: 'uint256[]' },\n { name: 'amounts', internalType: 'uint256[]', type: 'uint256[]' },\n { name: 'proofs', internalType: 'bytes32[][]', type: 'bytes32[][]' }\n ],\n name: 'claim',\n outputs: [],\n stateMutability: 'nonpayable'\n }],\n functionName: 'claim',\n args: [\n normalizedParams.users,\n normalizedParams.campaignIds,\n normalizedParams.amounts,\n normalizedParams.proofs\n ],\n account: account[0]\n });\n\n const hash = await this.walletClient.writeContract(request);\n\n return {\n data: hash,\n status: 200,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Helper function to prepare claim data from claim proofs\n * @param proofs - The claim proofs response from getClaimProofs\n * @returns ClaimRewardParams object ready for use with claimReward\n * \n * @remarks\n * This helper function transforms the claim proofs into the format required by the smart contract.\n * Note that the returned object's rewarderAddress is empty and must be set before using with claimReward.\n * \n * @example\n * ```typescript\n * // Get claim proofs and rewarder contract\n * const proofs = await smartRewards.getClaimProofs(userAddress, chainId);\n * const rewarders = await smartRewards.getSmartRewarderContracts();\n * const rewarder = rewarders.data?.find(r => r.chainId === chainId);\n * \n * if (proofs.data && rewarder) {\n * // Prepare the claim data\n * const claimData = smartRewards.prepareClaimData(proofs.data);\n * \n * // Set the rewarder address (required)\n * claimData.rewarderAddress = rewarder.address as Address;\n * \n * // Now the data is ready for claiming\n * const tx = await smartRewards.claimReward(claimData);\n * }\n * ```\n */\n public prepareClaimData(proofs: ClaimProofsResponse): ClaimRewardParams {\n return {\n users: proofs.edges.map(edge => edge.node.user.toLowerCase() as Address),\n campaignIds: proofs.edges.map(edge => BigInt(edge.node.campaignId)),\n amounts: proofs.edges.map(edge => BigInt(edge.node.amount.split('.')[0])),\n proofs: proofs.edges.map(edge => edge.node.proof as readonly `0x${string}`[]),\n rewarderAddress: '' as Address\n };\n }\n\n /**\n * Convenience function to handle the entire claim process\n * @param userAddress The address of the user claiming rewards\n * @param chainId The chain ID where the campaign exists\n * @param campaignId Optional campaign ID to filter claims\n * @returns Transaction hash if successful, or error details if failed\n */\n public async claimCampaignRewards(\n userAddress: Address,\n chainId: number,\n campaignId?: number\n ): Promise<SteerResponse<Hash>> {\n try {\n const normalizedUser = userAddress.toLowerCase() as Address;\n \n // Get claim proofs\n const claimProofsResponse = await this.getClaimProofs(normalizedUser, chainId, campaignId);\n if (!claimProofsResponse.data || claimProofsResponse.data.edges.length === 0) {\n return {\n data: null,\n status: 400,\n success: false,\n error: 'No claim proofs found'\n };\n }\n\n // Filter claim proofs by campaignId if specified\n let filteredClaimProofs = claimProofsResponse.data;\n if (campaignId !== undefined) {\n filteredClaimProofs = {\n ...claimProofsResponse.data,\n edges: claimProofsResponse.data.edges.filter(edge => edge.node.campaignId === campaignId)\n };\n \n // If no matching campaign proofs found after filtering\n if (filteredClaimProofs.edges.length === 0) {\n return {\n data: null,\n status: 400,\n success: false,\n error: `No claim proofs found for campaign ID ${campaignId}`\n };\n }\n }\n\n // Get smart rewarder contract\n const rewarderResponse = await this.getSmartRewarderContracts();\n const rewarder = rewarderResponse.data?.find(r => r.chainId === chainId);\n if (!rewarder) {\n return {\n data: null,\n status: 400,\n success: false,\n error: `No smart rewarder contract found for chain ${chainId}`\n };\n }\n\n // Prepare claim data\n const claimData = this.prepareClaimData(filteredClaimProofs);\n claimData.rewarderAddress = rewarder.address as Address;\n\n // Execute claim\n return await this.claimReward(claimData);\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Prepares the claim rewards campaign object with all necessary data for contract interaction\n * @param userAddress The address of the user claiming rewards\n * @param chainId The chain ID where the campaign exists\n * @param campaignId Optional campaign ID to filter claims\n * @returns Promise resolving to an object containing all necessary data for claiming rewards\n * \n * @example\n * ```typescript\n * // Get the prepared claim data\n * const claimData = await smartRewards.prepareClaimRewardsCampaign(userAddress, chainId, campaignId);\n * \n * if (claimData.success) {\n * // Use the data with your own contract interaction methods\n * const { address, abi, functionName, args } = claimData.data;\n * // Execute the contract call using your preferred method\n * }\n * ```\n */\n public async prepareClaimRewardsCampaign(\n userAddress: Address,\n chainId: number,\n campaignId?: number\n ): Promise<SteerResponse<{\n address: Address;\n abi: {\n type: string;\n inputs: {\n name: string;\n internalType: string;\n type: string;\n }[];\n name: string;\n outputs: never[];\n stateMutability: string;\n }[];\n functionName: string;\n args: readonly [\n readonly Address[],\n readonly bigint[],\n readonly bigint[],\n readonly (readonly `0x${string}`[])[]\n ];\n }>> {\n try {\n const normalizedUser = userAddress.toLowerCase() as Address;\n \n // Get claim proofs\n const claimProofsResponse = await this.getClaimProofs(normalizedUser, chainId, campaignId);\n if (!claimProofsResponse.data || claimProofsResponse.data.edges.length === 0) {\n return {\n data: null,\n status: 400,\n success: false,\n error: 'No claim proofs found'\n };\n }\n\n // Filter claim proofs by campaignId if specified\n let filteredClaimProofs = claimProofsResponse.data;\n if (campaignId !== undefined) {\n filteredClaimProofs = {\n ...claimProofsResponse.data,\n edges: claimProofsResponse.data.edges.filter(edge => edge.node.campaignId === campaignId)\n };\n \n // If no matching campaign proofs found after filtering\n if (filteredClaimProofs.edges.length === 0) {\n return {\n data: null,\n status: 400,\n success: false,\n error: `No claim proofs found for campaign ID ${campaignId}`\n };\n }\n }\n\n // Get smart rewarder contract\n const rewarderResponse = await this.getSmartRewarderContracts();\n const rewarder = rewarderResponse.data?.find(r => r.chainId === chainId);\n if (!rewarder) {\n return {\n data: null,\n status: 400,\n success: false,\n error: `No smart rewarder contract found for chain ${chainId}`\n };\n }\n\n // Prepare claim data\n const claimData = this.prepareClaimData(filteredClaimProofs);\n\n // Prepare the complete contract interaction data\n return {\n data: {\n address: rewarder.address as Address,\n abi: [{\n type: 'function',\n inputs: [\n { name: 'users', internalType: 'address[]', type: 'address[]' },\n { name: 'campaignIds', internalType: 'uint256[]', type: 'uint256[]' },\n { name: 'amounts', internalType: 'uint256[]', type: 'uint256[]' },\n { name: 'proofs', internalType: 'bytes32[][]', type: 'bytes32[][]' }\n ],\n name: 'claim',\n outputs: [],\n stateMutability: 'nonpayable'\n }],\n functionName: 'claim',\n args: [\n claimData.users,\n claimData.campaignIds,\n claimData.amounts,\n claimData.proofs\n ] as const\n },\n status: 200,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Checks if a chain is supported by checking if it has a subgraph URL\n * @param chainId The chain ID to check\n * @returns boolean indicating if the chain is supported\n */\n public supportsChain(chainId: number): boolean {\n return getSubgraphUrlByChainId(chainId) !== undefined;\n }\n} "]}
|
|
1
|
+
{"version":3,"file":"SmartRewards.js","sourceRoot":"","sources":["../../../src/base/SmartRewards.ts"],"names":[],"mappings":";;;AAEA,+BAAmC;AAEnC,sDAA+D;AA4H/D,MAAsB,YAAY;IAKhC,YACE,MAAuC,EACvC,YAA0B,EAC1B,YAA0B;QAE1B,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;QACjC,IAAI,CAAC,YAAY,GAAG,YAAY,CAAC;IACnC,CAAC;IAEM,KAAK,CAAC,YAAY,CAAC,OAAe;QACvC,MAAM,SAAS,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,CAAC;YAC5C,MAAM,EAAE;gBACN,OAAO;aACR;SACF,CAAC,CAAC;QAEH,OAAO;YACL,IAAI,EAAE,CAAC,SAAS,CAAC,IAAI,EAAE,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;gBACpD,GAAG,IAAI,CAAC,IAAI;gBACZ,MAAM,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;oBACtC,GAAG,KAAK;oBACR,UAAU,EAAE,KAA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dk';\nimport type { Address, Hash, PublicClient, WalletClient } from 'viem';\nimport { formatUnits } from 'viem';\nimport { SteerResponse } from '../types.js';\nimport { getSubgraphUrlByChainId } from '../const/subgraph.js';\n\n/**\n * Represents a node in the claim proof data structure\n * @property chainId - The ID of the chain where the claim exists\n * @property lastBlockUpdatedTo - The last block number this claim was updated to\n * @property user - The address of the user who can claim\n * @property campaignId - The ID of the campaign this claim belongs to\n * @property amount - The claimable amount as a string (may include decimals)\n * @property proof - The merkle proof array required for claiming\n */\nexport interface ClaimProofNode {\n chainId: number;\n lastBlockUpdatedTo: number;\n user: string;\n campaignId: number;\n amount: string;\n proof: readonly string[];\n}\n\nexport interface ClaimProofEdge {\n node: ClaimProofNode;\n cursor: string;\n}\n\n/**\n * Represents a historical claim reward record\n * @property id - Unique identifier for the claim\n * @property user - Address of the user who claimed\n * @property amount - Amount that was claimed (may include decimals)\n * @property campaign - Campaign identifier\n * @property chainId - Chain ID where the claim occurred\n * @property timestamp - Unix timestamp of when the claim occurred\n */\nexport interface ClaimRewardNode {\n id: string;\n user: string;\n amount: string;\n campaign: string;\n chainId: number;\n timestamp: number;\n}\n\nexport interface ClaimRewardEdge {\n cursor: string;\n node: ClaimRewardNode;\n}\n\n/**\n * Pagination information for paginated queries\n * @property hasNextPage - Whether there are more results available\n * @property endCursor - Cursor to use for fetching next page, if available\n */\nexport interface PageInfo {\n hasNextPage: boolean;\n endCursor: string | null | undefined;\n}\n\n/**\n * Connection type for claim rewards, following the Relay specification\n * @property edges - Array of claim reward records with cursors\n * @property pageInfo - Pagination information\n * @property totalCount - Total number of records available\n */\nexport interface ClaimRewardsConnection {\n edges: readonly ClaimRewardEdge[];\n pageInfo: PageInfo;\n totalCount: number;\n}\n\nexport interface ClaimProofsPageInfo {\n hasNextPage: boolean;\n endCursor?: string;\n}\n\nexport interface ClaimProofsResponse {\n totalCount: number;\n edges: readonly ClaimProofEdge[];\n pageInfo: ClaimProofsPageInfo;\n}\n\nexport interface SmartRewarderContract {\n chainId: number;\n address: string;\n}\n\n/**\n * Parameters required for claiming rewards\n * @property users - Array of user addresses who are claiming\n * @property campaignIds - Array of campaign IDs corresponding to each claim\n * @property amounts - Array of amounts to claim\n * @property proofs - Array of merkle proofs for verification\n * @property rewarderAddress - Address of the smart rewarder contract\n */\nexport interface ClaimRewardParams {\n users: readonly Address[];\n campaignIds: readonly bigint[];\n amounts: readonly bigint[];\n proofs: readonly (readonly `0x${string}`[])[];\n rewarderAddress: Address;\n}\n\n/**\n * Represents a reward balance with both native and formatted values\n * @property formatted - Human-readable string format with proper decimals\n * @property native - Raw bigint value\n */\nexport interface RewardBalance {\n formatted: string;\n native: bigint;\n}\n\n/**\n * Comprehensive summary of a user's reward status\n * @property totalEarned - Total rewards earned (claimed + claimable)\n * @property totalClaimed - Total rewards already claimed\n * @property claimable - Rewards available to claim\n */\nexport interface RewardSummary {\n totalEarned: RewardBalance;\n totalClaimed: RewardBalance;\n claimable: RewardBalance;\n}\n\nexport abstract class SmartRewards {\n protected readonly client: ReturnType<typeof createClient>;\n protected readonly publicClient: PublicClient;\n protected readonly walletClient: WalletClient;\n\n constructor(\n client: ReturnType<typeof createClient>,\n publicClient: PublicClient,\n walletClient: WalletClient\n ) {\n this.client = client;\n this.publicClient = publicClient;\n this.walletClient = walletClient;\n }\n\n public async getCampaigns(chainId: number): Promise<SteerResponse<Campaign[]>> {\n const campaigns = await this.client.campaigns({\n filter: {\n chainId,\n },\n });\n\n return {\n data: (campaigns.data?.campaigns.edges.map((edge) => ({\n ...edge.node,\n vaults: edge.node.vaults?.map(vault => ({\n ...vault,\n beaconName: vault.beaconName || '',\n name: vault.name || '',\n protocol: vault.protocol || '',\n protocolBaseType: vault.protocolBaseType || '',\n targetProtocol: vault.targetProtocol || ''\n })) || []\n })) || []) as Campaign[],\n status: campaigns.status,\n success: true,\n };\n }\n\n /**\n * Retrieves campaigns associated with a specific pool address\n * @param poolAddress - The address of the pool to get campaigns for\n * @param chainId - Chain ID where the pool exists\n * @returns Promise resolving to an array of campaigns associated with the pool\n * \n * @example\n * ```typescript\n * // Get campaigns for a pool on a specific chain\n * const campaigns = await smartRewards.campaignsByPool('0x...', 1);\n * ```\n */\n public async campaignsByPool(\n poolAddress: string,\n chainId: number\n ): Promise<SteerResponse<Campaign[]>> {\n try {\n const campaigns = await this.client.campaignsByPool({\n pool: poolAddress,\n chainId\n });\n\n return {\n data: (campaigns.data?.campaignsByPool?.map(campaign => campaign ? {\n ...campaign,\n vaults: campaign.vaults?.map(vault => vault ? {\n ...vault,\n beaconName: vault.beaconName || '',\n name: vault.name || '',\n protocol: vault.protocol || '',\n protocolBaseType: vault.protocolBaseType || '',\n targetProtocol: vault.targetProtocol || ''\n } : null).filter((v): v is NonNullable<typeof v> => v !== null) || []\n } : null).filter((c): c is NonNullable<typeof c> => c !== null) || []) as Campaign[],\n status: campaigns.status,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Retrieves claim proofs for a user that can be used to claim rewards\n * @param user - Address of the user to get proofs for\n * @param chainId - Chain ID where the claims exist\n * @param campaignId - Optional campaign ID to filter claims\n * @returns Promise resolving to claim proof data with pagination support\n */\n public async getClaimProofs(\n user: Address,\n chainId: number,\n campaignId?: number\n ): Promise<SteerResponse<ClaimProofsResponse>> {\n try {\n const normalizedUser = user.toLowerCase() as Address;\n const response = await this.client.claimProofs({\n user: normalizedUser,\n filter: {\n chainId,\n campaignId\n }\n });\n\n if (!response.data?.claimProofs) {\n return {\n data: null,\n status: response.status,\n success: true\n };\n }\n\n const transformedResponse: ClaimProofsResponse = {\n totalCount: response.data.claimProofs.totalCount,\n pageInfo: {\n hasNextPage: response.data.claimProofs.pageInfo.hasNextPage,\n endCursor: response.data.claimProofs.pageInfo.endCursor || undefined\n },\n edges: response.data.claimProofs.edges.map(edge => ({\n cursor: edge.cursor,\n node: {\n ...edge.node,\n proof: edge.node.proof?.filter((p): p is string => p !== null) || []\n }\n }))\n };\n\n return {\n data: transformedResponse,\n status: response.status,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Retrieves historical claim data for a specific pool\n * @param chainId - Chain ID where the pool exists\n * @param pool - Address or identifier of the pool\n * @param user - Optional user address to filter claims\n * @returns Promise resolving to paginated claim history data\n * \n * @example\n * ```typescript\n * // Get all claims for a pool\n * const allClaims = await smartRewards.getClaimRewardsByPool(1, poolAddress);\n * \n * // Get claims for a specific user in a pool\n * const userClaims = await smartRewards.getClaimRewardsByPool(1, poolAddress, userAddress);\n * ```\n */\n public async getClaimedRewardsByPool(\n chainId: number,\n pool: string,\n user?: Address\n ): Promise<SteerResponse<ClaimRewardsConnection>> {\n try {\n const normalizedPool = pool.toLowerCase();\n const normalizedUser = user ? user.toLowerCase() as Address : undefined;\n \n const response = await this.client.claimRewards({\n poolId: normalizedPool,\n chainId,\n filter: normalizedUser ? { user: normalizedUser } : undefined\n });\n\n if (!response.data?.claimRewards) {\n return {\n data: null,\n status: response.status,\n success: true\n };\n }\n\n const transformedResponse: ClaimRewardsConnection = {\n totalCount: response.data.claimRewards.totalCount,\n pageInfo: {\n hasNextPage: response.data.claimRewards.pageInfo.hasNextPage,\n endCursor: response.data.claimRewards.pageInfo.endCursor\n },\n edges: response.data.claimRewards.edges.map(edge => ({\n cursor: edge.cursor,\n node: {\n ...edge.node,\n timestamp: Number(edge.node.timestamp)\n }\n }))\n };\n\n return {\n data: transformedResponse,\n status: response.status,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n \n\n /**\n * Gets a comprehensive summary of a user's reward status\n * @param user - Address of the user\n * @param chainId - Chain ID to check rewards on\n * @param campaignId - Optional campaign ID to filter rewards\n * @param decimals - Number of decimals for formatting (default: 18)\n * @returns Promise resolving to reward summary with both native and formatted values\n * \n * @example\n * ```typescript\n * const summary = await smartRewards.getRewardSummary(userAddress, chainId);\n * console.log('Total earned:', summary.data.totalEarned.formatted);\n * console.log('Available to claim:', summary.data.claimable.formatted);\n * ```\n */\n public async getRewardSummary(\n user: Address,\n poolAddress: string,\n chainId: number,\n campaignId: number,\n decimals: number = 18\n ): Promise<SteerResponse<RewardSummary>> {\n try {\n // Lowercase addresses\n const normalizedUser = user.toLowerCase() as Address;\n const normalizedPoolAddress = poolAddress.toLowerCase();\n\n // Get claimable rewards\n const claimProofs = await this.getClaimProofs(normalizedUser, chainId, campaignId);\n\n // Filter claim proofs by campaignId for additional safety\n const filteredClaimProofs = claimProofs.data?.edges.filter(\n edge => edge.node.campaignId === campaignId\n ) || [];\n\n const totalAmount = filteredClaimProofs.reduce(\n (sum, edge) => sum + BigInt(edge.node.amount.split('.')[0]),\n 0n\n ) || 0n;\n\n // Get claimed rewards\n const claimedRewards = await this.getClaimedRewardsByPool(chainId, normalizedPoolAddress, normalizedUser);\n\n // Filter claimed rewards by campaign ID\n const filteredClaimedRewards = claimedRewards.data?.edges.filter(\n edge => Number(edge.node.campaign) === campaignId\n ) || [];\n\n const claimedAmount = filteredClaimedRewards.reduce(\n (sum, edge) => sum + BigInt(edge.node.amount.split('.')[0]),\n 0n\n ) || 0n;\n\n // Calculate totals\n const claimableAmount = totalAmount - claimedAmount;\n\n const summary: RewardSummary = {\n totalEarned: {\n native: totalAmount,\n formatted: formatUnits(totalAmount, decimals)\n },\n totalClaimed: {\n native: claimedAmount,\n formatted: formatUnits(claimedAmount, decimals)\n },\n claimable: {\n native: claimableAmount,\n formatted: formatUnits(claimableAmount, decimals)\n }\n };\n\n return {\n data: summary,\n status: 200,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n public async getSmartRewarderContracts(): Promise<SteerResponse<readonly SmartRewarderContract[]>> {\n try {\n const response = await this.client.smartRewarderContracts();\n\n return {\n data: response.data?.smartRewarderContracts || [],\n status: response.status,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Claims rewards from the smart rewarder contract\n * @param params - Parameters required for claiming rewards\n * @returns Promise resolving to transaction hash if successful\n * \n * @remarks\n * This method handles the low-level interaction with the smart contract.\n * For a higher-level interface, consider using {@link claimCampaignRewards} instead.\n * \n * @example\n * ```typescript\n * // Get claim proofs\n * const claimProofs = await smartRewards.getClaimProofs(userAddress, chainId, campaignId);\n * \n * // Get smart rewarder contract\n * const rewarders = await smartRewards.getSmartRewarderContracts();\n * const rewarder = rewarders.data?.find(r => r.chainId === chainId);\n * \n * if (claimProofs.data && rewarder) {\n * // Prepare claim data\n * const claimData = smartRewards.prepareClaimData(claimProofs.data);\n * claimData.rewarderAddress = rewarder.address as Address;\n * \n * // Claim rewards\n * const tx = await smartRewards.claimReward(claimData);\n * }\n * ```\n * \n * @throws Will throw an error if no wallet account is found\n * @throws Will throw an error if contract simulation fails\n */\n public async claimReward(params: ClaimRewardParams): Promise<SteerResponse<Hash>> {\n try {\n const account = await this.walletClient.getAddresses();\n if (!account[0]) throw new Error('No account found');\n\n // Normalize addresses\n const normalizedParams = {\n ...params,\n users: params.users.map(user => user.toLowerCase() as Address),\n rewarderAddress: params.rewarderAddress.toLowerCase() as Address\n };\n\n const { request } = await this.publicClient.simulateContract({\n address: normalizedParams.rewarderAddress,\n abi: [{\n type: 'function',\n inputs: [\n { name: 'users', internalType: 'address[]', type: 'address[]' },\n { name: 'campaignIds', internalType: 'uint256[]', type: 'uint256[]' },\n { name: 'amounts', internalType: 'uint256[]', type: 'uint256[]' },\n { name: 'proofs', internalType: 'bytes32[][]', type: 'bytes32[][]' }\n ],\n name: 'claim',\n outputs: [],\n stateMutability: 'nonpayable'\n }],\n functionName: 'claim',\n args: [\n normalizedParams.users,\n normalizedParams.campaignIds,\n normalizedParams.amounts,\n normalizedParams.proofs\n ],\n account: account[0]\n });\n\n const hash = await this.walletClient.writeContract(request);\n\n return {\n data: hash,\n status: 200,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Helper function to prepare claim data from claim proofs\n * @param proofs - The claim proofs response from getClaimProofs\n * @returns ClaimRewardParams object ready for use with claimReward\n * \n * @remarks\n * This helper function transforms the claim proofs into the format required by the smart contract.\n * Note that the returned object's rewarderAddress is empty and must be set before using with claimReward.\n * \n * @example\n * ```typescript\n * // Get claim proofs and rewarder contract\n * const proofs = await smartRewards.getClaimProofs(userAddress, chainId);\n * const rewarders = await smartRewards.getSmartRewarderContracts();\n * const rewarder = rewarders.data?.find(r => r.chainId === chainId);\n * \n * if (proofs.data && rewarder) {\n * // Prepare the claim data\n * const claimData = smartRewards.prepareClaimData(proofs.data);\n * \n * // Set the rewarder address (required)\n * claimData.rewarderAddress = rewarder.address as Address;\n * \n * // Now the data is ready for claiming\n * const tx = await smartRewards.claimReward(claimData);\n * }\n * ```\n */\n public prepareClaimData(proofs: ClaimProofsResponse): ClaimRewardParams {\n return {\n users: proofs.edges.map(edge => edge.node.user.toLowerCase() as Address),\n campaignIds: proofs.edges.map(edge => BigInt(edge.node.campaignId)),\n amounts: proofs.edges.map(edge => BigInt(edge.node.amount.split('.')[0])),\n proofs: proofs.edges.map(edge => edge.node.proof as readonly `0x${string}`[]),\n rewarderAddress: '' as Address\n };\n }\n\n /**\n * Convenience function to handle the entire claim process\n * @param userAddress The address of the user claiming rewards\n * @param chainId The chain ID where the campaign exists\n * @param campaignId Optional campaign ID to filter claims\n * @returns Transaction hash if successful, or error details if failed\n */\n public async claimCampaignRewards(\n userAddress: Address,\n chainId: number,\n campaignId?: number\n ): Promise<SteerResponse<Hash>> {\n try {\n const normalizedUser = userAddress.toLowerCase() as Address;\n \n // Get claim proofs\n const claimProofsResponse = await this.getClaimProofs(normalizedUser, chainId, campaignId);\n if (!claimProofsResponse.data || claimProofsResponse.data.edges.length === 0) {\n return {\n data: null,\n status: 400,\n success: false,\n error: 'No claim proofs found'\n };\n }\n\n // Filter claim proofs by campaignId if specified\n let filteredClaimProofs = claimProofsResponse.data;\n if (campaignId !== undefined) {\n filteredClaimProofs = {\n ...claimProofsResponse.data,\n edges: claimProofsResponse.data.edges.filter(edge => edge.node.campaignId === campaignId)\n };\n \n // If no matching campaign proofs found after filtering\n if (filteredClaimProofs.edges.length === 0) {\n return {\n data: null,\n status: 400,\n success: false,\n error: `No claim proofs found for campaign ID ${campaignId}`\n };\n }\n }\n\n // Get smart rewarder contract\n const rewarderResponse = await this.getSmartRewarderContracts();\n const rewarder = rewarderResponse.data?.find(r => r.chainId === chainId);\n if (!rewarder) {\n return {\n data: null,\n status: 400,\n success: false,\n error: `No smart rewarder contract found for chain ${chainId}`\n };\n }\n\n // Prepare claim data\n const claimData = this.prepareClaimData(filteredClaimProofs);\n claimData.rewarderAddress = rewarder.address as Address;\n\n // Execute claim\n return await this.claimReward(claimData);\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Prepares the claim rewards campaign object with all necessary data for contract interaction\n * @param userAddress The address of the user claiming rewards\n * @param chainId The chain ID where the campaign exists\n * @param campaignId Optional campaign ID to filter claims\n * @returns Promise resolving to an object containing all necessary data for claiming rewards\n * \n * @example\n * ```typescript\n * // Get the prepared claim data\n * const claimData = await smartRewards.prepareClaimRewardsCampaign(userAddress, chainId, campaignId);\n * \n * if (claimData.success) {\n * // Use the data with your own contract interaction methods\n * const { address, abi, functionName, args } = claimData.data;\n * // Execute the contract call using your preferred method\n * }\n * ```\n */\n public async prepareClaimRewardsCampaign(\n userAddress: Address,\n chainId: number,\n campaignId?: number\n ): Promise<SteerResponse<{\n address: Address;\n abi: {\n type: string;\n inputs: {\n name: string;\n internalType: string;\n type: string;\n }[];\n name: string;\n outputs: never[];\n stateMutability: string;\n }[];\n functionName: string;\n args: readonly [\n readonly Address[],\n readonly bigint[],\n readonly bigint[],\n readonly (readonly `0x${string}`[])[]\n ];\n }>> {\n try {\n const normalizedUser = userAddress.toLowerCase() as Address;\n \n // Get claim proofs\n const claimProofsResponse = await this.getClaimProofs(normalizedUser, chainId, campaignId);\n if (!claimProofsResponse.data || claimProofsResponse.data.edges.length === 0) {\n return {\n data: null,\n status: 400,\n success: false,\n error: 'No claim proofs found'\n };\n }\n\n // Filter claim proofs by campaignId if specified\n let filteredClaimProofs = claimProofsResponse.data;\n if (campaignId !== undefined) {\n filteredClaimProofs = {\n ...claimProofsResponse.data,\n edges: claimProofsResponse.data.edges.filter(edge => edge.node.campaignId === campaignId)\n };\n \n // If no matching campaign proofs found after filtering\n if (filteredClaimProofs.edges.length === 0) {\n return {\n data: null,\n status: 400,\n success: false,\n error: `No claim proofs found for campaign ID ${campaignId}`\n };\n }\n }\n\n // Get smart rewarder contract\n const rewarderResponse = await this.getSmartRewarderContracts();\n const rewarder = rewarderResponse.data?.find(r => r.chainId === chainId);\n if (!rewarder) {\n return {\n data: null,\n status: 400,\n success: false,\n error: `No smart rewarder contract found for chain ${chainId}`\n };\n }\n\n // Prepare claim data\n const claimData = this.prepareClaimData(filteredClaimProofs);\n\n // Prepare the complete contract interaction data\n return {\n data: {\n address: rewarder.address as Address,\n abi: [{\n type: 'function',\n inputs: [\n { name: 'users', internalType: 'address[]', type: 'address[]' },\n { name: 'campaignIds', internalType: 'uint256[]', type: 'uint256[]' },\n { name: 'amounts', internalType: 'uint256[]', type: 'uint256[]' },\n { name: 'proofs', internalType: 'bytes32[][]', type: 'bytes32[][]' }\n ],\n name: 'claim',\n outputs: [],\n stateMutability: 'nonpayable'\n }],\n functionName: 'claim',\n args: [\n claimData.users,\n claimData.campaignIds,\n claimData.amounts,\n claimData.proofs\n ] as const\n },\n status: 200,\n success: true\n };\n } catch (error) {\n return {\n data: null,\n status: 500,\n success: false,\n error: error instanceof Error ? error.message : 'Unknown error occurred'\n };\n }\n }\n\n /**\n * Checks if a chain is supported by checking if it has a subgraph URL\n * @param chainId The chain ID to check\n * @returns boolean indicating if the chain is supported\n */\n public supportsChain(chainId: number): boolean {\n return getSubgraphUrlByChainId(chainId) !== undefined;\n }\n} "]}
|
|
@@ -1,7 +1,10 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.StakingClient = void 0;
|
|
4
|
+
const SubgraphClient_js_1 = require("./SubgraphClient.js");
|
|
5
|
+
const index_js_1 = require("./vault/withdraw/index.js");
|
|
6
|
+
const protocol_js_1 = require("../const/protocol.js");
|
|
7
|
+
const decimal_js_1 = require("decimal.js");
|
|
5
8
|
// ABIs for staking contracts
|
|
6
9
|
const SINGLE_REWARD_ABI = [
|
|
7
10
|
{
|
|
@@ -87,13 +90,13 @@ const ERC20_ABI = [
|
|
|
87
90
|
"type": "function"
|
|
88
91
|
}
|
|
89
92
|
];
|
|
90
|
-
|
|
93
|
+
class StakingClient extends SubgraphClient_js_1.SubgraphClient {
|
|
91
94
|
constructor(client) {
|
|
92
95
|
super(client);
|
|
93
96
|
this.stakingPoolsEndpoint = 'https://9i52h964s3.execute-api.us-east-1.amazonaws.com/dev/staking-pools';
|
|
94
97
|
this.publicClient = client;
|
|
95
98
|
this.walletClient = client;
|
|
96
|
-
this.withdrawClient = new VaultWithdrawClient(client, client);
|
|
99
|
+
this.withdrawClient = new index_js_1.VaultWithdrawClient(client, client);
|
|
97
100
|
}
|
|
98
101
|
/**
|
|
99
102
|
* Fetches and filters staking pools based on provided criteria
|
|
@@ -108,10 +111,10 @@ export class StakingClient extends SubgraphClient {
|
|
|
108
111
|
const rawPools = (await response.json()).pools;
|
|
109
112
|
// Convert and validate protocols in the response
|
|
110
113
|
let pools = rawPools
|
|
111
|
-
.filter((pool) => isValidStakingProtocol(pool.protocol))
|
|
114
|
+
.filter((pool) => (0, protocol_js_1.isValidStakingProtocol)(pool.protocol))
|
|
112
115
|
.map((pool) => ({
|
|
113
116
|
...pool,
|
|
114
|
-
protocol: normalizeProtocol(pool.protocol)
|
|
117
|
+
protocol: (0, protocol_js_1.normalizeProtocol)(pool.protocol)
|
|
115
118
|
}));
|
|
116
119
|
// Apply filters if provided
|
|
117
120
|
if (filter) {
|
|
@@ -470,11 +473,11 @@ export class StakingClient extends SubgraphClient {
|
|
|
470
473
|
})
|
|
471
474
|
]);
|
|
472
475
|
// Use Decimal.js for precise calculations
|
|
473
|
-
const token0Amount = new Decimal(tokensResponse.data.token0Val.toString())
|
|
474
|
-
.div(new Decimal(10).pow(token0Decimals))
|
|
476
|
+
const token0Amount = new decimal_js_1.Decimal(tokensResponse.data.token0Val.toString())
|
|
477
|
+
.div(new decimal_js_1.Decimal(10).pow(token0Decimals))
|
|
475
478
|
.mul(params.token0UsdPrice);
|
|
476
|
-
const token1Amount = new Decimal(tokensResponse.data.token1Val.toString())
|
|
477
|
-
.div(new Decimal(10).pow(token1Decimals))
|
|
479
|
+
const token1Amount = new decimal_js_1.Decimal(tokensResponse.data.token1Val.toString())
|
|
480
|
+
.div(new decimal_js_1.Decimal(10).pow(token1Decimals))
|
|
478
481
|
.mul(params.token1UsdPrice);
|
|
479
482
|
const totalValueUsd = token0Amount.plus(token1Amount).toNumber();
|
|
480
483
|
const token0ValueUsd = token0Amount.toNumber();
|
|
@@ -495,8 +498,8 @@ export class StakingClient extends SubgraphClient {
|
|
|
495
498
|
abi: ERC20_ABI,
|
|
496
499
|
functionName: 'decimals'
|
|
497
500
|
});
|
|
498
|
-
const tokenValueUsd = new Decimal(params.amount.toString())
|
|
499
|
-
.div(new Decimal(10).pow(stakingDecimals))
|
|
501
|
+
const tokenValueUsd = new decimal_js_1.Decimal(params.amount.toString())
|
|
502
|
+
.div(new decimal_js_1.Decimal(10).pow(stakingDecimals))
|
|
500
503
|
.mul(params.token0UsdPrice)
|
|
501
504
|
.toNumber();
|
|
502
505
|
return {
|
|
@@ -656,4 +659,5 @@ export class StakingClient extends SubgraphClient {
|
|
|
656
659
|
}
|
|
657
660
|
}
|
|
658
661
|
}
|
|
662
|
+
exports.StakingClient = StakingClient;
|
|
659
663
|
//# sourceMappingURL=StakingClient.js.map
|