.github
    workflows
        deployment.yml
CHANGES.md
README.md
|  :------: |
apps
    README.md
    dex-dashboard
        .streamlit
            config.toml
        CustomCharts
            Bar.py
            Line.py
            Pie.py
            __init__.py
        README.md
        app.py
        config.py
        metrics.py
        requirements.txt
        tables.py
        utils.py
    makerdao-analytics
        README.md
        makerdao.py
        requirements.txt
        utilities
            __init__.py
            coingecko.py
    uniswap-analytics
        README.md
        app.py
        requirements.txt
    whale-watcher
        README.md
        app.py
        requirements.txt
dashboard
    .prettierrc.json
    README.md
    package.json
    public
        deployments.json
        index.html
        manifest.json
        robots.txt
    src
        constants.ts
        deployments
            DeploymentsContext.ts
            types.ts
        graphs
            types.ts
        index.css
        logo.svg
        queries
            dex
                poolOverview.ts
                schema.ts
            lending
                poolOverview.ts
                schema.ts
            protocolQuery.ts
            schema.ts
            subgraphStatusQuery.ts
            yield
                poolOverview.ts
                schema.ts
        react-app-env.d.ts
        reportWebVitals.ts
        styled.ts
        theme.ts
        types.ts
        utils
            index.ts
    tsconfig.json
deployment
    README.md
    deployment.js
    deploymentConfigurations.json
    execution.js
    package.json
docs
    Mapping.md
    Oracles.md
    Perf.md
    Schema.md
mscutil
    _reference_
        .prettierrc.json
        README.md
        abis
            Ethereum
                ERC20.json
        config
            default.json
            priceOracleABIs.json
        package-lock.json
        package.json
        tsconfig.json
    package-lock.json
    package.json
    src
        index.js
package-lock.json
package.json
subgraphs
    _reference_
        README.md
        abis
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            UniswapV2Factory.json
            UniswapV2Pair.json
        package-lock.json
        package.json
        src
            common
                constants.ts
                getters.ts
                metrics.ts
                rewards.ts
                tokens.ts
                utils
                    arrays.ts
                    datetime.ts
                    numbers.ts
                    strings.ts
            mappings
                handlers.ts
                helpers.ts
            prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrumOne.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
        tsconfig.json
    aave-v2-forks
        .eslintrc.json
        .prettierrc.json
        README.md
        abis
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            IPriceOracleGetter.json
            LendingPool.json
            LendingPoolAddressesProvider.json
            LendingPoolConfigurator.json
            StableDebtToken.json
            VariableDebtToken.json
            aave-v2
                AToken.json
                AaveIncentivesController.json
            geist-finance
                ChefIncentivesController.json
                GToken.json
                GeistIncentivesController.json
                SpookySwapOracle.json
        package-lock.json
        package.json
        protocols
            aave-v2
                README.md
                config
                    networks
                        avalanche
                            avalanche.json
                        mainnet-amm
                            mainnet-amm.json
                        mainnet-arc
                            mainnet-arc.json
                        mainnet-rwa
                            mainnet-rwa.json
                        mainnet
                            mainnet.json
                        matic
                            matic.json
                src
                    constants.ts
                    mapping.ts
            geist-finance
                README.md
                config
                    networks
                        fantom
                            fantom.json
                src
                    constants.ts
                    mapping.ts
        src
            constants.ts
            helpers.ts
            mapping.ts
            token.ts
        tsconfig.json
    aave-v3
        README.md
        abis
            AToken.json
            AaveOracle.json
            IERC20Detailed.json
            IERC20DetailedBytes.json
            Pool.json
            PoolAddressesProvider.json
            PoolAddressesProviderRegistry.json
            PoolConfigurator.json
            RewardsController.json
            StableDebtToken.json
            VariableDebtToken.json
        package.json
        protocols
            aave-v3
                config
                    networks
                        arbitrum
                            arbitrum.json
                        avalanche
                            avalanche.json
                        fantom
                            fantom.json
                        harmony
                            harmony.json
                        matic
                            matic.json
                        optimism
                            optimism.json
                src
                    entities
                        event.ts
                        market.ts
                        price.ts
                        protocol.ts
                        rate.ts
                        reserve.ts
                        token.ts
                        usage.ts
                    mappings
                        AToken.ts
                        Pool.ts
                        PoolAddressesProvider.ts
                        PoolAddressesProviderRegistry.ts
                        PoolConfigurator.ts
                        RewardsController.ts
                        StableDebtToken.ts
                        VariableDebtToken.ts
        src
            utils
                constants.ts
                numbers.ts
                strings.ts
        tsconfig.json
    abracadabra-ext
        README.md
        abis
            BentoBox.json
            Cauldron.json
            DegenBox.json
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            OffchainAggregator.json
            PriceOracle.json
        package-lock.json
        package.json
        protocols
            abracadabra
                config
                    networks
                        arbitrum
                            arbitrum.json
                        avalanche
                            avalanche.json
                        bsc
                            bsc.json
                        fantom
                            fantom.json
                        mainnet
                            mainnet.json
        src
            common
                constants.ts
                getters.ts
                metrics.ts
                prices
                    prices.ts
                setters.ts
                tokens.ts
                utils
                    arrays.ts
                    datetime.ts
                    numbers.ts
                    strings.ts
                    utils.ts
            mapping.ts
            positions.ts
            staking.ts
        tsconfig.json
    abracadabra
        README.md
        abis
            BentoBox.json
            Cauldron.json
            DegenBox.json
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            OffchainAggregator.json
            PriceOracle.json
        package-lock.json
        package.json
        protocols
            abracadabra
                config
                    networks
                        arbitrum
                            arbitrum.json
                        avalanche
                            avalanche.json
                        bsc
                            bsc.json
                        fantom
                            fantom.json
                        mainnet
                            mainnet.json
        src
            common
                constants.ts
                getters.ts
                metrics.ts
                prices
                    prices.ts
                setters.ts
                tokens.ts
                utils
                    arrays.ts
                    datetime.ts
                    numbers.ts
                    strings.ts
                    utils.ts
            mapping.ts
            staking.ts
        tsconfig.json
    alchemix
        README.md
    autofarm
        README.md
    badgerdao
        README.md
    balancer-forks
        .prettierrc.json
        README.md
        abis
            ConvergentCurvePool.json
            ERC20.json
            LinearPool.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            Vault.json
            WeightedPool.json
            masterchef
                MasterChefV2.json
        package.json
        protocols
            balancer-v2
                config
                    networks
                        arbitrum
                            arbitrum.json
                        mainnet
                            mainnet.json
                        matic
                            matic.json
            beethoven-x
                config
                    networks
                        fantom
                            fantom.json
                        optimism
                            optimism.json
        src
            common
                constants.ts
                creators.ts
                getters.ts
                metrics.ts
                pricing.ts
                tokens.ts
                utils
                    utils.ts
                weight.ts
            mappings
                handlers.ts
                masterchef.ts
            prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrumOne.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
        tsconfig.json
    bancor-v2
        README.md
    bancor-v3
        README.md
        abis
            BNTPool.json
            BancorNetwork.json
            BancorNetworkInfo.json
            ERC20.json
            NetworkSettings.json
            PoolCollection.json
            PoolToken.json
            PoolTokenFactory.json
            StandardRewards.json
        package.json
        protocols
            bancor-v3
                config
                    networks
                        mainnet
                            mainnet.json
        src
            constants.ts
            mapping.ts
        tsconfig.json
    beefy-finance
        BEEFY_INTERACTION_CHART.md
        README.md
        abis
            BeefiVaultRegistryMATIC.json
            BeefyStrategy.json
            BeefyVault.json
            Chainlink.json
            ERC20.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    FeeRouter.json
                    Pair.json
                    Router.json
                YearnLens.json
        package.json
        protocols
            beefy-finance
                config
                    networks
                        aurora
                            aurora.json
        setup
            scripts
                getStartBlock.js
                publicRpcs.js
            setup.js
        src
            mappings
                deposit.ts
                protocol.ts
                token.ts
                vault.ts
                withdraw.ts
            prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrum_one.ts
                    aurora.ts
                    avalanche.ts
                    bsc.ts
                    celo.ts
                    cronos.ts
                    fantom.ts
                    fuse.ts
                    harmony.ts
                    heco.ts
                    mainnet.ts
                    matic.ts
                    metis.ts
                    moonbeam.ts
                    moonriver.ts
                    oasis.ts
                index.ts
                oracles
                    ChainLinkAddresses.js
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                    oracles.ts
                    scripts
                        asset_finder.js
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
            utils
                getters.ts
                helpers.ts
                metrics.ts
                snapshots.ts
                time.ts
        tsconfig.json
    belt-finance
        .vscode
            settings.json
        README.md
        abis
            Chainlink.json
            ChainlinkBNB.json
            ERC20.json
            Strategy.json
            Vault.json
        package.json
        protocols
            belt-finance
                config
                    networks
                        bsc
                            bsc.json
        src
            constant.ts
            entities
                Metrics.ts
                Protocol.ts
                Strategy.ts
                Token.ts
                Transaction.ts
                Vault.ts
            handlers
                common.ts
                deposit.ts
                price.ts
                vault.ts
                withdraw.ts
            utils
                contracts.ts
                numbers.ts
                strings.ts
        tests
            constants.ts
            mocks
                chainlink.ts
                strategy.ts
                token.ts
                vault.ts
            vault.test.ts
        tsconfig.json
    compound-forks-ext
        .prettierrc.json
        README.md
        abis
            CToken.json
            Comptroller.json
            ERC20.json
            PriceOracle.json
            aurigami
                CToken.json
            banker-joe
                CToken.json
            benqi
                CToken.json
                Comptroller.json
                JoePair.json
                OldComptroller.json
            compound-v2
                CTokenNew.json
                CTokenOld.json
                PriceOracle1.json
                PriceOracle2.json
            dforce
                CToken.json
                Comptroller.json
                PriceOracle.json
                RewardDistributor.json
                stablecoin.json
            moonwell
                CToken.json
                Comptroller.json
                SolarBeamLPToken.json
            prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            rari-fuse
                CToken.json
                FuseComptroller.json
                FusePoolDirectory.json
                RewardsDistributorDelegator.json
        package-lock.json
        package.json
        protocols
            aurigami
                config
                    networks
                        aurora
                            aurora.json
                src
                    constants.ts
                    mapping.ts
            banker-joe
                config
                    networks
                        avalanche
                            avalanche.json
                src
                    constants.ts
                    mapping.ts
            bastion-protocol
                config
                    networks
                        aurora
                            aurora.json
                src
                    constants.ts
                    mapping.ts
            benqi
                config
                    networks
                        avalanche
                            avalanche.json
                src
                    constants.ts
                    mapping.ts
            compound-v2
                README.md
                config
                    networks
                        mainnet
                            mainnet.json
                src
                    constants.ts
                    mapping.ts
                    prices.ts
                    prices
                        README.md
                        calculations
                            CalculationsCurve.ts
                            CalculationsSushiswap.ts
                        common
                            constants.ts
                            types.ts
                            utils.ts
                        config
                            arbitrum_one.ts
                            fantom.ts
                            mainnet.ts
                        index.ts
                        oracles
                            ChainLinkFeed.ts
                            YearnLensOracle.ts
                        routers
                            CurveRouter.ts
                            SushiSwapRouter.ts
                            UniswapRouter.ts
                    rewards.ts
            cream-finance
                config
                    networks
                        arbitrum
                            arbitrum.json
                        bsc
                            bsc.json
                        mainnet
                            mainnet.json
                        matic
                            matic.json
                src
                    constants.ts
                    mapping.ts
            dforce
                README.md
                config
                    networks
                        arbitrum
                            arbitrum.json
                        avalanche
                            avalanche.json
                        bsc
                            bsc.json
                        mainnet
                            mainnet.json
                        matic
                            matic.json
                        optimism
                            optimism.json
                src
                    constants.ts
                    mapping.ts
            iron-bank
                config
                    networks
                        avalanche
                            avalanche.json
                        fantom
                            fantom.json
                        mainnet
                            mainnet.json
                src
                    constants.ts
                    mapping.ts
            moonwell
                config
                    networks
                        moonriver
                            moonriver.json
                src
                    constants.ts
                    mapping.ts
            rari-fuse
                README.md
                config
                    networks
                        arbitrum
                            arbitrum.json
                        mainnet
                            mainnet.json
                src
                    constants.ts
                    mappings.ts
                    prices
                        README.md
                        calculations
                            CalculationsCurve.ts
                            CalculationsSushiswap.ts
                        common
                            constants.ts
                            types.ts
                            utils.ts
                        config
                            arbitrum_one.ts
                            fantom.ts
                            mainnet.ts
                        index.ts
                        oracles
                            ChainLinkFeed.ts
                            YearnLensOracle.ts
                        routers
                            CurveRouter.ts
                            SushiSwapRouter.ts
                            UniswapRouter.ts
                    rewards.ts
            scream
                config
                    networks
                        fantom
                            fantom.json
                src
                    constants.ts
                    mapping.ts
            venus
                config
                    networks
                        bsc
                            bsc.json
                src
                    constants.ts
                    mapping.ts
        src
            constants.ts
            mapping.ts
        tsconfig.json
    compound-forks
        .prettierrc.json
        .vscode
            settings.json
        README.md
        abis
            CToken.json
            Comptroller.json
            ERC20.json
            PriceOracle.json
            aurigami
                CToken.json
            banker-joe
                CToken.json
            benqi
                CToken.json
                Comptroller.json
                JoePair.json
                OldComptroller.json
            compound-v2
                CTokenModified.json
                PriceOracle1.json
                PriceOracle2.json
            dforce
                CToken.json
                Comptroller.json
                PriceOracle.json
                RewardDistributor.json
                stablecoin.json
            moonwell
                CToken.json
                Comptroller.json
                SolarBeamLPToken.json
            prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            rari-fuse
                CToken.json
                FuseComptroller.json
                FusePoolDirectory.json
                RewardsDistributorDelegator.json
        package-lock.json
        package.json
        protocols
            aurigami
                config
                    networks
                        aurora
                            aurora.json
                src
                    constants.ts
                    mapping.ts
            banker-joe
                config
                    networks
                        avalanche
                            avalanche.json
                src
                    constants.ts
                    mapping.ts
            bastion-protocol
                config
                    networks
                        aurora
                            aurora.json
                src
                    constants.ts
                    mapping.ts
            benqi
                config
                    networks
                        avalanche
                            avalanche.json
                src
                    constants.ts
                    mapping.ts
            compound-v2
                README.md
                config
                    networks
                        mainnet
                            mainnet.json
                src
                    constants.ts
                    mapping.ts
                    prices.ts
                    prices
                        README.md
                        calculations
                            CalculationsCurve.ts
                            CalculationsSushiswap.ts
                        common
                            constants.ts
                            types.ts
                            utils.ts
                        config
                            arbitrum_one.ts
                            fantom.ts
                            mainnet.ts
                        index.ts
                        oracles
                            ChainLinkFeed.ts
                            YearnLensOracle.ts
                        routers
                            CurveRouter.ts
                            SushiSwapRouter.ts
                            UniswapRouter.ts
                    rewards.ts
            cream-finance
                config
                    networks
                        arbitrum
                            arbitrum.json
                        bsc
                            bsc.json
                        mainnet
                            mainnet.json
                        matic
                            matic.json
                src
                    constants.ts
                    mapping.ts
            dforce
                README.md
                config
                    networks
                        arbitrum
                            arbitrum.json
                        avalanche
                            avalanche.json
                        bsc
                            bsc.json
                        mainnet
                            mainnet.json
                        matic
                            matic.json
                        optimism
                            optimism.json
                src
                    constants.ts
                    mapping.ts
            iron-bank
                config
                    networks
                        avalanche
                            avalanche.json
                        fantom
                            fantom.json
                        mainnet
                            mainnet.json
                src
                    constants.ts
                    mapping.ts
            moonwell
                config
                    networks
                        moonriver
                            moonriver.json
                src
                    constants.ts
                    mapping.ts
            rari-fuse
                README.md
                config
                    networks
                        arbitrum
                            arbitrum.json
                        mainnet
                            mainnet.json
                src
                    constants.ts
                    mappings.ts
                    prices
                        README.md
                        calculations
                            CalculationsCurve.ts
                            CalculationsSushiswap.ts
                        common
                            constants.ts
                            types.ts
                            utils.ts
                        config
                            arbitrum_one.ts
                            fantom.ts
                            mainnet.ts
                        index.ts
                        oracles
                            ChainLinkFeed.ts
                            YearnLensOracle.ts
                        routers
                            CurveRouter.ts
                            SushiSwapRouter.ts
                            UniswapRouter.ts
                    rewards.ts
            scream
                config
                    networks
                        fantom
                            fantom.json
                src
                    constants.ts
                    mapping.ts
            venus
                config
                    networks
                        bsc
                            bsc.json
                src
                    constants.ts
                    mapping.ts
        src
            constants.ts
            mapping.ts
        tsconfig.json
    convex-finance
        README.md
        abis
            Ethereum
                BaseRewardPool.json
                Booster.json
                ERC20.json
                Pool.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                Custom
                    ChainLinkAggregator.json
                    CurvePool.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
        package.json
        protocols
            convex-finance
                config
                    networks
                        mainnet
                            mainnet.json
        src
            Prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                custom
                    ForexTokens.ts
                    common.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
            common
                constants.ts
                initializer.ts
                types.ts
                utils.ts
            mappings
                boosterMappings.ts
                rewardMappings.ts
            modules
                Deposit.ts
                Fees.ts
                Metric.ts
                Rewards.ts
                Tokens.ts
                Vault.ts
                Withdraw.ts
        tsconfig.json
    curve-finance
        README.md
        abis
            AddressProvider.json
            CLAggregator.json
            CrvERC20.json
            CryptoFactory.json
            CryptoRegistry.json
            CurveLendingPool.json
            CurveLendingPoolCoin128.json
            CurvePool.json
            CurvePoolAvax.json
            CurvePoolCoin128.json
            CurvePoolV2.json
            CurveRewards.json
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            Gauge.json
            GaugeController.json
            GaugeV2.json
            GaugeV3.json
            MainRegistry.json
            MetaPool.json
            RedeemableKeep3r.json
            RewardsOnlyGauge.json
            StableFactory.json
            UniswapV2Factory.json
            UniswapV2Pair.json
            UniswapV3Factory.json
            UniswapV3Quoter.json
            prices
                Atoken.json
                BalancerPoolToken.json
                Ctoken.json
                IdleToken.json
                Iearn.json
                YearnTokenV2.json
        package-lock.json
        package.json
        protocols
            curve-finance
                config
                    networks
                        arbitrum
                            arbitrum.json
                        avalanche
                            avalanche.json
                        fantom
                            fantom.json
                        mainnet
                            mainnet.json
                        matic
                            matic.json
                        optimism
                            optimism.json
                        xdai
                            xdai.json
        src
            common
                constants.ts
                constants
                    index.template.ts
                    index.ts
                getters.ts
                metrics.ts
                prices
                    aave.ts
                    balancer.ts
                    compound.ts
                    idle.ts
                    underlying.ts
                    yearn.ts
                pricing.ts
                setters.ts
                tokens.ts
                utils
                    arrays.ts
                    datetime.ts
                    numbers.ts
                    strings.ts
            mapping.template.ts
            mapping.ts
            mappingV2.ts
            services
                catchup.ts
                factory.ts
                gauges
                    helpers.ts
                liquidity.ts
                platform.ts
                pools.ts
                rewards.ts
                snapshots.ts
                swaps.ts
    dodo-v2
        README.md
    ellipsis-finance
        .prettierrc.json
        README.md
        abis
            BasePool2.json
            BasePool3.json
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            Factory.json
            IERC20.json
            Pair.json
            PancakeFactory.json
            RewardToken.json
            StableSwap.json
            prices
                Atoken.json
            staking
                LpStaking.json
                LpStakingV2.json
        package.json
        protocols
            ellipsis-finance
                config
                    networks
                        bsc
                            bsc.json
        src
            common
                constants.ts
                getters.ts
                metrics.ts
                prices
                    aave.ts
                    pricing.ts
                    underlying.ts
                setters.ts
                tokens.ts
                utils
                    arrays.ts
                    datetime.ts
                    numbers.ts
                    strings.ts
            mappings
                basepool2.ts
                basepool3.ts
                factory.ts
                staking.ts
            services
                liquidity.ts
                platform.ts
                pool.ts
                snapshots.ts
                swaps.ts
        tsconfig.json
    erc20
        README.md
        package.json
        tsconfig.json
    gamma-strategies
        README.md
        abis
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            HypeRegistry.json
            Hypervisor.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            UniswapV2Factory.json
            UniswapV2Pair.json
        package.json
        protocols
            gamma-strategies
                config
                    networks
                        arbitrum
                            arbitrum.json
                        mainnet
                            mainnet.json
                        matic
                            matic.json
                        optimism
                            optimism.json
        src
            common
                constants.ts
                getters.ts
                tokens.ts
                utils
                    arrays.ts
                    datetime.ts
                    numbers.ts
                    strings.ts
            mappings
                handlers.ts
                helpers
                    events.ts
                    financials.ts
                    pricing.ts
                    usageMetrics.ts
                    vaults.ts
            prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrum_one.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
    geist-finance
        README.md
    gmx
        README.md
    governance
        README.md
        ens-governance
            README.md
            abis
                ENSGovernor.json
                ENSToken.json
            networks.json
            package.json
            src
                ens-governor.ts
                ens-token.ts
                helpers.ts
            tsconfig.json
        fei-governance
            abis
                FeiDAO.json
                Tribe.json
            networks.json
            package.json
            src
                fei-dao.ts
                helper.ts
                tribe.ts
            tsconfig.json
        silo-governance
            abis
                SiloGovernanceToken.json
                SiloGovernor.json
            networks.json
            package.json
            src
                helpers.ts
                silo-governance-token.ts
                silo-governor.ts
            tsconfig.json
    harvest-finance
        README.md
    inverse-finance
        .prettierrc.json
        README.md
        abis
            CErc20.json
            DOLA.json
            ERC20.json
            INV.json
            JumpRateModelV2.json
            Stablizer.json
            comptroller.json
            priceOracle.json
        package.json
        protocols
            inverse-finance
                config
                    networks
                        mainnet
                            mainnet.json
        src
            common
                constants.ts
                getters.ts
                helpers.ts
                utils.ts
            core.ts
            dola.ts
            factory.ts
            rewardtoken.ts
            stablizer.ts
        tsconfig.json
    lido
        README.md
    liquity
        README.md
        abis
            ActivePool.json
            BorrowerOperations.json
            CollSurplusPool.json
            PriceFeed.json
            StabilityPool.json
            TroveManager.json
        package.json
        protocols
            liquity
                config
                    networks
                        mainnet
                            mainnet.json
        src
            entities
                event.ts
                market.ts
                protocol.ts
                rate.ts
                token.ts
                trove.ts
            mapping
                ActivePool.ts
                BorrowerOperations.ts
                CollSurplusPool.ts
                PriceFeed.ts
                StabilityPool.ts
                TroveManager.ts
            utils
                arrays.ts
                constants.ts
                datetime.ts
                numbers.ts
                strings.ts
        tsconfig.json
    makerdao
        README.md
        abis
            Cat.json
            CdpManager.json
            DSProxy.json
            DSProxyFactory.json
            Deploy.json
            Dog.json
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            GemJoin.json
            IlkRegistry.json
            Jug.json
            Spot.json
            Vat.json
        package-lock.json
        package.json
        protocols
            makerdao
                config
                    networks
                        mainnet
                            mainnet.json
        src
            common
                constants.ts
                getters.ts
                metrics.ts
                prices
                    prices.ts
                setters.ts
                tokens.ts
                utils
                    arrays.ts
                    datetime.ts
                    numbers.ts
                    strings.ts
            mapping.ts
            mappings
                core
                    cat.ts
                    spot.ts
                rates
                    jug.ts
                users
                    users.ts
        tsconfig.json
    maple-finance
        .prettierrc.json
        README.md
        abis
            BalancerPool.json
            Calculations
                Curve.json
                SushiSwap.json
            ChainLinkOracle.json
            Curve
                Factory.json
                PoolRegistry.json
                Registry.json
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            LoanV1.json
            LoanV2.json
            LoanV3.json
            MapleGlobals.json
            MapleRewardsFactory.json
            MplRewards.json
            Pool.json
            PoolFactory.json
            PoolLib.json
            StakeLocker.json
            SushiSwap
                Factory.json
                Pair.json
                Router.json
            Uniswap
                Factory.json
                Pair.json
                Router.json
            YearnOracle.json
        package.json
        src
            common
                constants.ts
                mappingHelpers
                    getOrCreate
                        markets.ts
                        protocol.ts
                        snapshots.ts
                        supporting.ts
                        transactions.ts
                    update
                        intervalUpdate.ts
                        usage.ts
                prices
                    calculations
                        CalculationsCurve.ts
                        CalculationsSushiswap.ts
                    common
                        constants.ts
                        types.ts
                        utils.ts
                    config
                        arbitrumOne.ts
                        fantom.ts
                        mainnet.ts
                    oracles
                        chainlink.ts
                        maple.ts
                        yearn.ts
                    prices.ts
                    routers
                        CurveRouter.ts
                        SushiSwapRouter.ts
                        UniswapRouter.ts
                types.ts
                utils.ts
            mappings
                loanV1.ts
                loanV2.ts
                loanV3.ts
                mapleGlobals.ts
                mapleRewardsFactory.ts
                mplRewards.ts
                pool.ts
                poolFactory.ts
                stakeLocker.ts
    moola-market
        README.md
    platypus-finance
        .vscode
            extensions.json
        README.md
        abis
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                TraderJoe
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            asset.json
            masterPlatypus.json
            masterPlatypusFactory.json
            masterPlatypusOld.json
            pool.json
            router.json
            secondaryPool.json
            simpleRewarder.json
        package-lock.json
        package.json
        src
            common
                constants.ts
                getters.ts
                metrics.ts
                rewards.ts
                tokens.ts
                utils
                    arrays.ts
                    datetime.ts
                    numbers.ts
                    strings.ts
            mappings
                asset.ts
                helpers.ts
                masterPlatypus.ts
                pool.ts
            prices
                README.md
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrum_one.ts
                    avalanche.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                routers
                    SushiSwapRouter.ts
                    TraderJoeRouter.ts
        tsconfig.json
    pooltogether
        README.md
    qidao
        README.md
        abis
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            QiStablecoin.json
            QiStablecoinDecimals.json
            erc20QiStablecoin.json
        package.json
        prepare.sh
        protocols
            qidao
                config
                    networks
                        arbitrum
                            arbitrum.json
                        avalanche
                            avalanche.json
                        bsc
                            bsc.json
                        fantom
                            fantom.json
                        matic
                            matic.json
                        moonriver
                            moonriver.json
                        optimism
                            optimism.json
                        xdai
                            xdai.json
        src
            entities
                event.ts
                market.ts
                price.ts
                protocol.ts
                rate.ts
                token.ts
                usage.ts
            mappings
                QiStablecoin.ts
                erc20QiStablecoin.ts
            utils
                constants.ts
                numbers.ts
                strings.ts
        tsconfig.json
    rari-vaults
        README.md
        abis
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            ether-pool
                RariEtherFundManager.json
            stables-pool
                RariStableFundManager.json
            yield-pool
                RariYieldFundManager.json
        package-lock.json
        package.json
        protocols
            rari-vaults
                config
                    networks
                        mainnet
                            mainnet.json
        src
            common
                getters.ts
                metrics.ts
                utils
                    constants.ts
                    tokens.ts
                    utils.ts
            mappings
                helpers.ts
                mappings.ts
            prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrumOne.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
        tsconfig.json
    saddle-finance
        README.md
        abis
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            MiniChefV2.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            SimpleRewarder.json
            Swap.json
            SwapDeployer.json
            SwapV1.json
        package.json
        protocols
            saddle-finance
                config
                    networks
                        arbitrum
                            arbitrum.json
                        fantom
                            fantom.json
                        mainnet
                            mainnet.json
                        optimism
                            optimism.json
        src
            entities
                event.ts
                fee.ts
                pool.ts
                protocol.ts
                token.ts
            mappings
                miniChef.ts
                swap.ts
                swapDeployer.ts
            prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrumOne.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
            utils
                arrays.ts
                constants.ts
                datetime.ts
                numbers.ts
                price.ts
                strings.ts
        tsconfig.json
    stakedao
        README.md
        abis
            Ethereum
                ERC20.json
                StableMaster.json
                TreasuryVault.json
                controller.json
                gauge.json
                governance.json
                strategy.json
                vault.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
        package.json
        protocols
            stakedao
                config
                    networks
                        mainnet
                            mainnet.json
        src
            Prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrumOne.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
            common
                constants.ts
                initializers.ts
                utils.ts
            mappings
                controllerMappings.ts
                gaugeMappings.ts
                strategyMappings.ts
                vaultMappings.ts
            modules
                Deposit.ts
                Metrics.ts
                Price.ts
                Reward.ts
                Strategy.ts
                Withdraw.ts
        tsconfig.json
    tokemak
        .prettierrc.json
        README.md
        abis
            ERC20Detailed.json
            Manager.json
            OnChainVote.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
            Rewards.json
            Vault.json
        package-lock.json
        package.json
        protocols
            tokemak
                config
                    networks
                        mainnet
                            mainnet.json
        src
            common
                account.ts
                constants.ts
                financial.ts
                protocol.ts
                tokens.ts
                usage.ts
                utils.ts
                vaults.ts
            mappings
                managerMappings.ts
                rewardMappings.ts
                vaultMappings.ts
                voteMappings.ts
            prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrumOne.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
        tsconfig.json
    treasuredao
        README.md
    truefi
        README.md
    uniswap-forks
        README.md
        abis
            apeswap
                Factory.json
                IERC20.json
                MasterChef.json
                MasterChefApeswap.json
                MasterChefV2Apeswap.json
                Pair.json
            quickswap
                ERC20.json
                Factory.json
                Pair.json
            solarbeam
                ERC20.json
                Factory.json
                MasterChefSolarbeam.json
                Pair.json
            spiritswap
                ERC20.json
                Factory.json
                MasterChefSpiritSwap.json
                Pair.json
            spookyswap
                Factory.json
                IERC20.json
                MasterChefSpookyswap.json
                MasterChefV2Spookyswap.json
                Pair.json
            sushiswap
                ERC20.json
                Factory.json
                MasterChefSushiswap.json
                MasterChefV2Sushiswap.json
                MiniChefSushiswap.json
                Pair.json
            trader-joe
                ERC20.json
                Factory.json
                MasterChefV2TraderJoe.json
                MasterChefV3TraderJoe.json
                Pair.json
            trisolaris
                ERC20.json
                Factory.json
                MasterChefTrisolaris.json
                MasterChefV2Trisolaris.json
                Pair.json
            ubeswap
                ERC20.json
                ERC20NameBytes.json
                ERC20SymbolBytes.json
                Factory.json
                Pair.json
                PoolManager.json
                StakingRewards.json
                UniswapV2Pair.json
            uniswap-v2
                ERC20.json
                ERC20NameBytes.json
                ERC20SymbolBytes.json
                Factory.json
                Pair.json
            vvs-finance
                Craftsman.json
                ERC20.json
                Factory.json
                Pair.json
        configurations
            configurations
                README.md
                configurations.ts
                deploy.ts
                interface.ts
            configure.template.ts
            configure.ts
        package-lock.json
        package.json
        protocols
            apeswap
                config
                    networks
                        bsc
                            bsc.json
                            bsc.ts
                        matic
                            matic.json
                            matic.ts
                src
                    common
                        constants.ts
                        handlers
                            handleReward.ts
                            handleRewardV2.ts
                    mappings
                        masterchef
                            reward.ts
                            rewardV2.ts
            quickswap
                config
                    networks
                        matic
                            matic.json
                            matic.ts
                src
                    common
                        constants.ts
            solarbeam
                config
                    networks
                        moonriver
                            moonriver.json
                            moonriver.ts
                src
                    common
                        constants.ts
                        handlers
                            handleReward.ts
                    mappings
                        masterchef
                            reward.ts
            spiritswap
                config
                    networks
                        fantom
                            fantom.json
                            fantom.ts
                src
                    common
                        constants.ts
                        handlers
                            handleReward.ts
                    mappings
                        masterchef
                            reward.ts
            spookyswap
                config
                    networks
                        fantom
                            fantom.json
                            fantom.ts
                src
                    common
                        constants.ts
                        handlers
                            handleReward.ts
                            handleRewardV2.ts
                    mappings
                        masterchef
                            reward.ts
                            rewardV2.ts
            sushiswap
                config
                    networks
                        arbitrum
                            arbitrum.json
                            arbitrum.ts
                        avalanche
                            avalanche.json
                            avalanche.ts
                        bsc
                            bsc.json
                            bsc.ts
                        celo
                            celo.json
                            celo.ts
                        fantom
                            fantom.json
                            fantom.ts
                        fuse
                            fuse.json
                            fuse.ts
                        mainnet
                            mainnet.json
                            mainnet.ts
                        matic
                            matic.json
                            matic.ts
                        moonbeam
                            moonbeam.json
                            moonbeam.ts
                        moonriver
                            moonriver.json
                            moonriver.ts
                        xdai
                            xdai.json
                            xdai.ts
                src
                    common
                        constants.ts
                        handlers
                            handleReward.ts
                            handleRewardMini.ts
                            handleRewardV2.ts
                        helpers.ts
                    mappings
                        masterchef
                            reward.ts
                            rewardMini.ts
                            rewardV2.ts
            trader-joe
                config
                    networks
                        avalanche
                            avalanche.json
                            avalanche.ts
                src
                    common
                        constants.ts
                        handlers
                            handleRewardV2.ts
                            handleRewardV3.ts
                        helpers.ts
                    mappings
                        masterchef
                            rewardV2.ts
                            rewardV3.ts
            trisolaris
                config
                    networks
                        aurora
                            aurora.json
                            aurora.ts
                src
                    common
                        constants.ts
                        handlers
                            handleReward.ts
                            handleRewardV2.ts
                    mappings
                        masterchef
                            reward.ts
                            rewardV2.ts
            ubeswap
                config
                    networks
                        celo
                            celo.json
                            celo.ts
                src
                    common
                        constants.ts
                        handlers
                            handelCreatePool.ts
                            handleReward.ts
                    mappings
                        stakingrewards
                            createpool.ts
                            reward.ts
            uniswap-v2
                config
                    networks
                        mainnet
                            mainnet.json
                            mainnet.ts
                src
                    common
                        constants.ts
            vvs-finance
                config
                    networks
                        cronos
                            cronos.json
                            cronos.ts
                src
                    common
                        constants.ts
                        handlers
                            handleReward.ts
                    mappings
                        craftsman
                            reward.ts
        src
            common
                constants.ts
                creators.ts
                getters.ts
                handlers.ts
                masterChef
                    apeswap
                        handleReward.ts
                        handleRewardV2.ts
                    sushiswap
                        handleReward.ts
                        handleRewardMini.ts
                        handleRewardV2.ts
                rewards.ts
                updateMetrics.ts
                utils
                    utils.ts
            mappings
                factory.ts
                pool.ts
            price
                price.ts
        tsconfig.json
    uniswap-v3
        README.md
        abis
            ERC20.json
            ERC20NameBytes.json
            ERC20SymbolBytes.json
            Factory.json
            NonfungiblePositionManager.json
            pool.json
        configurations
            configurations
                README.md
                configurations.ts
                deploy.ts
                interface.ts
            configure.template.ts
            configure.ts
        package-lock.json
        package.json
        protocols
            uniswap-v3
                config
                    networks
                        arbitrum
                            arbitrum.json
                            arbitrum.ts
                        mainnet
                            mainnet.json
                            mainnet.ts
                        matic
                            matic.json
                            matic.ts
                        optimism
                            optimism.json
                            optimism.ts
                src
                    common
                        constants.ts
        src
            common
                constants.ts
                creators.ts
                getters.ts
                price
                    price.ts
                updateMetrics.ts
                utils
                    utils.ts
            mappings
                Factory.ts
                core.ts
        tsconfig.json
    vesper-finance
        README.md
    yearn-v2
        README.md
        abis
            Ethereum
                Controller.json
                ERC20.json
                Registry_v1.json
                Registry_v2.json
                Strategies
                    Strategy_v0.2.2.json
                    Strategy_v0.3.0.json
                    Strategy_v0.3.1.json
                    Strategy_v0.3.2.json
                    Strategy_v0.3.3.json
                    Strategy_v0.3.5.json
                    Strategy_v0.4.2.json
                    Strategy_v0.4.3.json
                    _strategy_.json
                Vaults
                    Vault_v0.2.2.json
                    Vault_v0.3.0.json
                    Vault_v0.3.1.json
                    Vault_v0.3.2.json
                    Vault_v0.3.3.json
                    Vault_v0.3.5.json
                    Vault_v0.4.2.json
                    Vault_v0.4.3.json
                    _vault_.json
                    vaultStrategies_v1.json
                    vaultStrategies_v2.json
            Prices
                Calculations
                    Curve.json
                    SushiSwap.json
                ChainLink.json
                Curve
                    Factory.json
                    PoolRegistry.json
                    Registry.json
                ERC20.json
                SushiSwap
                    Factory.json
                    Pair.json
                    Router.json
                Uniswap
                    Factory.json
                    Pair.json
                    Router.json
                YearnLens.json
        package.json
        protocols
            yearn-v2
                config
                    networks
                        arbitrum
                            arbitrum.json
                        fantom
                            fantom.json
                        mainnet
                            mainnet.json
        src
            Prices
                README.md
                calculations
                    CalculationsCurve.ts
                    CalculationsSushiswap.ts
                common
                    constants.ts
                    types.ts
                    utils.ts
                config
                    arbitrumOne.ts
                    fantom.ts
                    mainnet.ts
                index.ts
                oracles
                    ChainLinkFeed.ts
                    YearnLensOracle.ts
                routers
                    CurveRouter.ts
                    SushiSwapRouter.ts
                    UniswapRouter.ts
            common
                constants.ts
                initializers.ts
                types.ts
                utils.ts
            mappings
                registryMappings.ts
                strategyMappings.ts
                vaultMappings.ts
            modules
                Deposit.ts
                Metrics.ts
                Price.ts
                Strategy.ts
                Vault.ts
                Withdraw.ts
        tsconfig.json
    yield-yak
        README.md

# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)      | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24)  | `Calculations` | `3808222`  |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)      |    `Router`    | `5655918`  |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957) |    `Router`    | `3796241`  |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506)  |    `Router`    | `2457904`  |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                              |      Type      | StartBlock | MultiCall | Status |
| ----------------------------------------------------------------------------------- | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603`  |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120`  |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056`  |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    |    `73`    |    ✅     |   🛠    |
# Compound Fork Subgraph

## Quickstart

### Setup

Setting up a new subgraph will require mimicing what is done currently.

- Under `./protocols` will be the fork in a new folder
- Any protocol-specific mappings will live in `./protocols/$(protocol)/src`
- Setup a config folder in `./protocols/$(protocol)/config` for the supported networks and the manifest template
- Lastly you need to add your configuration to [deploymentConfigurations.json](../../deployment/deploymentConfigurations.json)
- You can also reference the deployment [README](../../deployment/README.md) for help

### Deployment

Once everything is setup properly deploying is very easy.

```bash
# This example will deploy rari-fuse on all networks to the hosted service under "dmelotik" in deploymentConfigurations.json
npm run deploy --SUBGRAPH=compound-forks --PROTOCOL=rari-fuse --LOCATION=dmelotik

# This will do the same, but only deploying the mainnet subgraph
npm run deploy --SUBGRAPH=compound-forks --PROTOCOL=rari-fuse --NETWORK=mainnet --LOCATION=dmelotik
```

> Setting `deploy-on-merge` to `true` in [deploymentConfigurations.json](../../deployment/deploymentConfigurations.json) will run the above commands on subgraphs that have changed to messari's hosted service.

### Development Commands

During development you probably won't want to fully deploy the subgraph every time. Follow this guide to do each step incrementally.

To setup the subgraph manifest from the template:

```bash
# Use rari fuse as an example
npm run prepare:yaml --PROTOCOL=rari-fuse --NETWORK=mainnet --TEMPLATE=rari-fuse.template.yaml
```

To codegen and build:

```bash
graph codegen
graph build
```

> If you are working on multiple subgraphs you may want to delete `./generated/**` before `codegen` so no old files are left behind.

To deploy follow the steps above. You may put your hosted service endpoint in [deploymentConfigurations.json](../../deployment/deploymentConfigurations.json) just how messari's is set to take advantage of the commands.

## Project Layout

### schema.graphql

Shared schema for all Compound forks.

### abis

Standard Compound abis.

### src

Shared logic among the forks.

### queries

Useful queries to run against a Compound fork subgraph.

### protocols

Protocol-specific subgraph definition, abis and implementations.

**Notice**: Some forks have different abis from Compound. For example, Moonwell:

1. renames cToken to mToken
1. rename supplyRatePerBlock to supplyRatePerTimestamp because it accrues interest every second, not block
1. add supplyRewardSpeeds and borrowRewardSpeeds

Therefore we need to use Moonwell-specific abis, see moonwell/subgraph.yaml (note the dots!):

```yaml
- name: CToken
    file: ./abis/CToken.json
- name: Comptroller
    file: ./abis/Comptroller.json
- name: ERC20
    file: ../abis/ERC20.json
- name: PriceOracle
    file: ../abis/PriceOracle.json
- name: SolarBeamLPToken
    file: ./abis/SolarBeamLPToken.json
```
# Uniswap v3 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools: 

`Liquidity Pool TVL`

### Total Revenue USD

Sum across all Pools:

`(Pool Swap Trading Volume * Pool Fee Tier)`

Note that Pool Fee Tiers vary by pool and more tiers could be added by Governance (04/07/22)

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Pool Swap Trading Volume * Pool Fee Tier * Protocol Fee)`

Note that the Protocol Fee for Uniswap is currently 0% but could be changed via Governance (04/07/22)

https://uniswap.org/blog/uniswap-v3

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Pool Swap Trading Volume * Pool Fee Tier * (1 - Protocol Fee))`

Note that Pool Fee Tiers vary by pool and more tiers could be added by Governance (04/07/22)

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Swaps`

`Deposits`

`Withdraws`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added

## References and Useful Links

Other existing subgraph
https://thegraph.com/hosted-service/subgraph/uniswap/uniswap-v3

## Smart Contracts Interactions

![Uniswap v3](../../docs/images/protocols/uniswap-v3.png "Uniswap v3")
# Convex Protocol Metrics Subgraph Methodology v1.1.2

## Convex Finance Introduction

Convex Finance is a DeFi platform which allows Curve.fi liquidity providers to earn trading fees and claim boosted CRV without locking CRV themselves. 

Convex Finance has a similar operating model like group buy startups while small Curve.fi liquidity providers can enjoy a better boosted CRV rewards by staking their LP tokens together on Convex Finance.

Besides the native token rewards from Curve.fi, liquidity providers on Convex Finance also receive rewards in the form of CVX token.

Note:

* Convex is currently running on Ethereum.
* Convex is supporting Curve Finance and Frax Finance

## Useful Links

* Protocol
    * [https://www.convexfinance.com/](https://www.convexfinance.com/)
* Docs
    * [https://docs.convexfinance.com/](https://docs.convexfinance.com/)
* Smart contracts
    * [https://docs.convexfinance.com/convexfinance/faq/contract-addresses](https://docs.convexfinance.com/convexfinance/faq/contract-addresses)
* Tokenomics
    * [https://docs.convexfinance.com/convexfinance/general-information/tokenomics](https://docs.convexfinance.com/convexfinance/general-information/tokenomics)
* Fees
    * [https://docs.convexfinance.com/convexfinance/faq/fees](https://docs.convexfinance.com/convexfinance/faq/fees)
* Governance forum
    * [https://vote.convexfinance.com/#/](https://vote.convexfinance.com/#/)
* Medium
    * [https://convexfinance.medium.com](https://convexfinance.medium.com)

## Usage Metrics

**Active Users, Total Unique Users & Daily Transaction Count**

Transactions of interest on Convex Finance include:

1. Staking Curve LP Tokens
2. Converting CRV to cvxCRV
3. Staking cvxCRV
4. Staking CVX
5. Vote Locking CVX
6. Claiming Rewards
7. Claiming Airdrop
8. Converting FXS to cvxFXS
9. Staking cvxFXS
10. Staking Frax LP Tokens
11. Providing liquidity on Curve

Any address which conducts one of the transactions above should be considered a User.

## Financial Metrics

**Total Value Locked USD**

The Total Value Locked (TVL) on Convex Finance can be calculated by summing:

1. The TVL of cvxCRV pool
2. The TVL across Curve LP pools
3. The TVL of CVX pool
4. The TVL of CVX Vote Locking pool
5. The TVL of cvxFXS
6. The TVL of across Frax LP pools

Obviously, to calculate the TVL of each pool, we need to use this formula:

```
TVL (in USD) = The number of token in pool * the price of each token in USD
```

**Protocol Controlled Value USD**

Convex Finance has a Treasury but not Protocol Controlled Value.

**Total Revenue USD**

Total Revenue generated on Convex Finance is the combination of:

1. Yield generated and harvested from Curve LP pools (excluding base Curve yield)
    - CRV token rewards
    - CVX token rewards
    - Additional rewards (if any)
2. Yield generated and harvested from staked cvxCRV
    - CRV token rewards
    - CVX token rewards
    - 3crv token rewards
3. Yield generated and harvested from staked CVX
    - cvxCRV token rewards
4. Yield generated and harvested from Locked CVX
    - cvxCRV token rewards
5. Yield generated and harvested from Frax LP pools (excluding base Curve yield if any)
    - CRV token rewards (if applicable)
    - CVX token rewards (if applicable)
    - FXS token rewards
    - Other token rewards (depend on the pool)
6. Yield generated and harvested from cvxFXS/FXS liquidity pool (excluding base Curve yield if any)
    - CRV token rewards
    - CVX token rewards
    - Additional rewards (if any)

The total reward in USD shall be calculated by using this formula: 

```
Rewards (in USD) = The number of token * the price of each token in USD
```

The total revenue in USD shall be calculated by using this formula: 

```
Total Revenue = 1+2+3+4+5+6
```

**Supply Side Revenue USD**

Supply-side revenue on Convex Finance is the total revenue minus the performance fee. The performance fee is only applied for CRV revenue generated by Curve LP pool and Frax LP pool on the platform.

```
Supply Side Revenue = Total Revenue - (Performance fee rate * CRV token rewards from Curve LP pool and Frax LP pool)
```

**Protocol Revenue USD**

Protocol revenue on Convex Finance is the sum of performance fees on all CRV revenue generated by Curve LP pool and Frax LP pool on the platform.

```
Protocol Revenue = Performance fee rate * CRV token rewards from Curve LPs
```

The current performance fee is 17% for all pools.

The structure of the performance fee for Curve LP pool is as below:

1. 10% goes to cvxCRV stakers. This is paid out as CRV.
2. 5% goes to CVX stakers, which includes vote-locked CVX. This is paid out as cvxCRV.
3. 1% goes exclusively to vote-locked CVX. This is paid out as cvxCRV. 
4. 1% goes to the harvest caller. This is paid out as CRV.

The structure of the performance fee for Frax LP pool is as below:

1. 10% goes to cvxFXS/FXS stakers
2. 7% goes to CVX lockers

## Pool-Level Metrics

**Pool Total Value Locked USD**

The TVL of a Curve LP pool shall be calculated by using this formula: 

```
Number of LP token* Price of the LP token
```

On the Convex Finance UI, this is shown as “TVL” by Pool

**Reward Tokens & Reward Token Emissions Amount**

For Curve Finance

* veCRV holders as of block 12296676 are entitled to a portion of the $CVX token supply in the form of an airdrop.
* Additionally, all veCRV holders who voted to whitelist Convex Finance on the Curve.fi platform are entitled to an additional portion of the $CVX token supply.
* Start date: April 23rd, 2021
* End date: No end date
* References:

[https://docs.convexfinance.com/convexfinance/guides/claiming-your-airdrop](https://docs.convexfinance.com/convexfinance/guides/claiming-your-airdrop)

[https://convexfinance.medium.com/cvx-airdrop-details-a20ff7448075](https://convexfinance.medium.com/cvx-airdrop-details-a20ff7448075)
# Maple Finance Subgraph

## Calculation Methodology v1.0.0

Below, the methodologies for key fields in the protocol are surfaced for convenience.

Note that all cumulatives USD values are origination values (i.e values at the time the accumulation occurred), they are not current values. This means that the cumulative values are monotonically increasing over time. If current values are desired for the cumulatives, they can be derived from the cumulative token values.

In depth methodologies for every parameter in the protocol can be found here: [Schema Map](https://fluffy-cobalt-78d.notion.site/Schema-Map-59607afc87ac4891a7dc8c407e18f48d)

### Total Value Locked (TVL) USD

Total amount on the supply side that is earning interest

Sum across all Markets:

`Total Deposit Balance USD + Total Stake Balance USD + Total Unclaimed Supplier Interest USD`

This does not include accrued staking rewards.

### Total Deposit Balance USD

Sum across all Markets:

`Cumulative Deposit USD - Cumulative Withdraw USD - Cumulative Pool Losses USD`

Pool Losses occur when a default is suffered by the pool, it is absorbed by the deposit amount.

### Total Borrow Balance USD

Sum across all Markets:

`Cumulative Withdraw USD - Cumulative Principal Repay USD - Loan Defaults USD`

Liquidated collateral is interpreted the same as paying principal since from the pool perspective there is no difference. Defaults to the Stake Locker and Pool are absorbed and removed from total borrow.

### Cumulative Liquidate USD

Sum across all Markets:

`Cumulative Stake Locker Losses USD + Cumulative Pool Losses USD`

Collateral liquidation is not counted towards cumulative liquidate, and is instead considered the same as a principal repayment since from the pool perspective there is no difference.

### Cumulative Supply Side Revenue USD

Sum across all Markets:

`Cumulative Establishment Fees To Pool Delegate USD + Cumulative Interest To Market USD`

Interest To Market USD is all interest going to the Suppliers and the Stake Locker, this doesn't include MPL token distribution.

### Cumulative Protocol Side Revenue USD

Sum across all Markets:

`Cumulative Establishment Fees To Maple Treasury USD`

Establishment Fees To Maple Treasury USD is a percentage of the drawdown amount; lump sum for V1 and V2 loans and amortized over repayments for V3 loans.

### Cumulative Total Revenue USD

Sum across all Markets:

`Cumulative Supply Side Revenue USD + Cumulative Protocol Side Revenue USD`

### Total Unique Users

The number of Unique Addresses that interacted with the protocol through these transactions:

`Deposit`

`Borrow`

`Withdraw`

`Repay`

`Stake`

`Unstake`

## Protocol Diagrams

Diagrams of the protocol, specifically focusing on key things needed for the Subgraph. Each diagram follows this legend:

![Legend](./docs/Legend.jpg)

### Protocol Map

![Protocol Map](./docs/ProtocolMap.jpg)

### Providing Liquidity Flow

![Providing Liquidity Flow](./docs/ProvidingLiquidity.jpg)

### Staking Flow

![Staking](./docs/Staking.jpg)

### Taking Loan Flow

![Taking a loan](https://user-images.githubusercontent.com/9797920/175491683-de0cae25-58fd-4f05-a579-eb02fea2297e.jpg)

### Repaying Loan (Principal and Interest)

![Repay Loan](./docs/RepayLoan.jpg)

### Liquidation Flow

![Liquidation](./docs/Liquidation.jpg)

## Validation

Validation done for this subgraph against other data sources can be found here: [Validation Spreadsheet](https://docs.google.com/spreadsheets/d/1viyui7nAzUXMx68EJSW61xC251uS8zpKePzV2xijjGQ/edit?usp=sharing)

Validation for subgraph self-consistency, and some helper queries for the Validation Spreadsheet are here: [Notebooks](./validation)
# Ellipsis Finance (DEX) Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Coin balances`

### Total Revenue USD

`(Swap Trading Volume * Pool Swap Fee)`

Note: The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool
### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Swap Trading Volume * Pool Swap Fee * Pool Admin Fee)`

Note: The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Swap Trading Volume * Pool Swap Fee * (1 - Pool Admin Fee))`

Note: The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Swaps`

`Deposits`

`Withdraws`

### Reward Token Emissions Amount

Staking Rewards: 
 
`V1 = EPS inflation rate per second * pool relative weight`

`V2 = EPX inflation rate per second * pool relative weight`

## References and Useful Links

- Protocol: https://ellipsis.finance/
- Analytics: https://defillama.com/protocol/ellipsis-finance
- Docs: https://docs.ellipsis.finance/ellipsis-2.0/a-new-ellipsis
- Smart contracts: https://github.com/ellipsis-finance/ellipsis-v2
- Deployed addresses: https://docs.ellipsis.finance/ellipsis-2.0/deployment-links

## Smart Contracts Interactions

![Ellipsis-Finance](../../docs/images/protocols/ellipsis-finance.png "Ellipsis-Finance")

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`
# Curve Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Coin balances`

### Total Revenue USD

Sum across all Pools:

`(Swap Trading Volume * Pool Swap Fee)`

Note: The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Swap Trading Volume * Pool Swap Fee * Pool Admin Fee)`

Note: The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Swap Trading Volume * Pool Swap Fee * (1 - Pool Admin Fee))`

Note: The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Swaps`

`Deposits`

`Withdraws`

### Reward Token Emissions Amount

Rewards are measure in emissions per day. All pools with a Gauge Contract earn CRV as reward token.

Curve Rewards:
`Curve inflation rate per second * gauge relative weight * seconds in a day`

Extra Rewards:
`Reward token emissions rate per second * seconds in a day`

## References and Useful Links

- Protocol: https://curve.fi/
- Analytics: https://dune.com/mrblock_buidl/Curve.fi
- Docs: https://curve.readthedocs.io/
- Smart contracts: https://github.com/curvefi/curve-contract
- Deployed addresses: https://curve.readthedocs.io/ref-addresses.html
- Other Existing subgraph: https://thegraph.com/hosted-service/subgraph/curvefi/curve

## Additonal Notes

- Curve gauge rewards are technically allocated for pools across all chains that Curve is deployed on. Unfortunately, this allocation data based on pool type is only available on ethereum mainnet. Gauge rewards data for Curve on alternate chains will need to be manually integrated at another stage of the data ETL pipeline.

- Some withdraw events do not have the amount of pool input tokens removed, as it is impossible to get that information without access to transaction trace

## Smart Contracts Interactions

![Curve](../../docs/images/protocols/curve.png "Curve")

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`
# Uniswap v2 Subgraph

> This is a reference subgraph used to demonstrate some of the common patterns  
> you should use in your subgraph. It should help you bootstrap your subgraph  
> quickly, improve the readability and maintainability of your code, and  
> provide some common functions/modules that you can leverage. Specifically,  
> here are some guidelines:
>
> - Make sure you include this README (but without this section) in the  
>   subgraph, with links to protocol-related resource and build instruction.
> - Note that after you init the subgraph with `graph init`, it would create  
>   another git repo inside of the existing one. You should remove that with  
>   `rm -rf .git` and not check it in as a submodule.
> - Make sure you run `npm run format` to format your code before committing.
> - Try to follow the same folder structure inside of `src` for your subgraph.
> - There is a set of useful functions in `src/common` that you can leverage.
>  
> Note: this subgraph is just a reference is not meant to be built and deployed  
> Note: since Uniswap v2 is a DEX (AMM), the `schema.graphql` used here is  
> derived from `schema-dex-amm.graphql` in the repo root.

## Links

- Protocol: https://uniswap.org/
- Analytics: https://v2.info.uniswap.org/
- Docs: https://docs.uniswap.org/protocol/V2/introduction
- Smart contracts: https://github.com/Uniswap/v2-core
- Deployed addresses: https://docs.uniswap.org/protocol/V2/reference/smart-contracts/factory
- Official subgraph: https://github.com/Uniswap/v2-subgraph

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`
# Abracadabra Lending Protocol Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Markets:

`Total Collateral Tokens in USD from deposits and withdrawals`

### Total Revenue USD

Sum across all Markets:

`Borrow Opening Fee * MIM Borrwed + Interest Rate * Amount MIM Borrowed + Liquidation Fee * Collateral Liquidated`

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

`25% of Total Revenue USD is allocated to the Protocol Treasury`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

`75% of Total Revenue USD is awarded backed to Spell Stakers`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Borrows`

`Repays`

`Deposits`

`Withdraws`

`Liquidations`

`Staking`

### Total Volume USD

Sum across all Markets:

`Amount of Borrows and Repays`

### Input Token Balances

Amount of collateral for each Market

`Sum of Deposits and Withdrawals`

### Output Token Supply

Amount of MIM tokens minted for each Market

`Sum of Borrows minus Repays`

### NO Reward Token Emissions

## References and Useful Links

- Protocol: https://abracadabra.money/
- Analytics: http://dashboard.abracadabra.money/
- Docs: https://wizard69.gitbook.io/abracadabra-money/
- Smart contracts: https://github.com/Abracadabra-money/bentobox-strategies
- Deployed addresses: https://docs.abracadabra.money/our-ecosystem/our-contracts

## Smart Contracts Interactions

![Abracadabra](../../docs/images/protocols/abracadabra.png "Abracadabra")

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`
# Uniswap Forks

## Protocols:

- Apeswap
  - BSC, Matic
    - The two chains use the code from uniswap V2. Additionally, there is a Masterchef and MasterchefV2 contract. BSC only uses the Masterchef contract, while MasterchefV2 is used on the Matic chain. The masterchef contracts are slightly different for Apeswap vs. Sushiswap in the naming of certain functions. It looks like Apeswap forked from Pancakeswap. This is why they each have a separate folder for Masterchef.
- Quickswap
  - Matic
    - Uses the same codebase as Uniswap-V2 for the factory and pools stored in the uniswap-forks/src folder
- Solarbeam
  - Moonriver
    - Uses the uniswap-v2 codebase as Uniswap V2 for factory and pools. Additionally, it uses a masterchef contract that is templated from Sushiswap's implementation.
- Spiritswap
  - Moonbeam
    - Uses the uniswap-v2 codebase as Uniswap V2 for factory and pools. Additionally, it uses a masterchef contract that is templated from Sushiswap's implementation.
- Sushiswap
  - Mainnet
    - The only code that differs between uniswap is the use of the masterchef contract. This contract allows users to deposit LP tokens to earn rewards. Mainnet usees both the Masterchef and MasterchefV2 contract for these purposes.
  - Arbitrum, Celo, Fantom, Fuse, Matic, Moonbeam, Moonriver, Xdai
    - Similarly, these chains inherit the same code from uniswap. However, these chains only use the Miniswap contract for staking LP and earning rewards. It works very similar to the Masterchef contracts.
  - BSC, Avalanche
    - These two sushiswap chains deploy in just the same way as Uniswap V2. Just with different configurations.
- Trader Joe
  - Avalanche
    - Uses the uniswap-v2 codebase as Uniswap V2 for factory and pools. Additionally, it uses a masterchefV2 contract that is templated from Sushiswap's implementation and a masterchefV3 contract that is deployed at a later start block.
- Uniswap V2
  - Mainnet
    - Uniswap V2 serves as a base for the deployment of the other subgraphs. The others are forks of uniswap and inherit the baseline functionality for pool creation, pool management, and events like swaps, deposits, and withdraws. The code for these functionailities are the same code used for all forks specified.
- VVS
  - Cronos
    - Uses the uniswap-v2 codebase as Uniswap V2 for factory and pools. Additionally, it uses a masterchef contract that is templated from Sushiswap's implementation.
    - This is not deployed on the hosted service. It is deployed on cronos. This is the query URL https://graph.cronoslabs.com/subgraphs/name/vvs-finance-cronos/first-subgraph

## Project Layout:

### schema.graphql

- Shared schema for all Uniswap forks.

### abis

- ABI's for all forks. There are folders to contain ABIs for each protocol

### src

- Contains all logic for deploying all subgraphs. When the logic is not shared accross protocols, create a separate folder for each - See Masterchef.

### config

- Config folder contains folders for each protocol. In these folders, add the configurations for each network. These configurations include constants to be used in the main program, and the template with .json configurations for the subgraph.yaml file

### deployment

- This folder contains the code and configurations for deploying according to the **Deployment Instructions** section.
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)      | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24)  | `Calculations` | `3808222`  |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)      |    `Router`    | `5655918`  |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957) |    `Router`    | `3796241`  |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506)  |    `Router`    | `2457904`  |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                              |      Type      | StartBlock | MultiCall | Status |
| ----------------------------------------------------------------------------------- | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603`  |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120`  |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056`  |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    |    `73`    |    ✅     |   🛠    |
# Vesper Finance Subgraph
## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools (Grow Pools + Earn Pools + Governance Pools): 

`Deposit TVL`

### Total Revenue USD

Sum across all Pools (Grow Pools + Earn Pools + Governance Pools):

`Total Yield + Withdrawal Fees * Withdrawal Amount`

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Withdrawal Fees * Withdrawal Amount) + (Platform Fee * Yield)`

Note (04/07/22): 
- Grow Pools have 0.6% fee on withdrawals, and a 20% platform fee on yield.
- Earn Pools have 25% platform fee on yield and no withdrawal fee
- 5% goes to developer / strategist but is to be included in Protocol-side Revenue

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`Total Yield - Platform Fee * Total Yield`

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added

## Useful Links

Existing Subgraph 

https://thegraph.com/explorer/subgraph?id=0x9520b477aa81180e6ddc006fc09fb6d3eb4e807a-0&view=Playground	

https://github.com/vesperfi/vesper-subgraph
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1 
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)     | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24) | `Calculations` | `3808222` |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)     |    `Router`    | `5655918` |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957)   |    `Router`    | `3796241` |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    | `2457904` |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603` |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120` |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056` |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    | `73` |    ✅     |   🛠    |
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)      | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24)  | `Calculations` | `3808222`  |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)      |    `Router`    | `5655918`  |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957) |    `Router`    | `3796241`  |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506)  |    `Router`    | `2457904`  |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                              |      Type      | StartBlock | MultiCall | Status |
| ----------------------------------------------------------------------------------- | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603`  |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120`  |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056`  |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    |    `73`    |    ✅     |   🛠    |
# Moola Market - Lending Protocol Subgraph

## Useful Links

- https://moola.market/
- https://docs.moola.market/
- https://app.moola.market/
- Add here

## Calculation Methodology v0.0.1

### Total Value Locked (TVL) USD

Sum across all Pools:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Revenue USD

Sum across all Pools:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Repays`

`Liquidations`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)      | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24)  | `Calculations` | `3808222`  |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)      |    `Router`    | `5655918`  |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957) |    `Router`    | `3796241`  |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506)  |    `Router`    | `2457904`  |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                              |      Type      | StartBlock | MultiCall | Status |
| ----------------------------------------------------------------------------------- | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603`  |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120`  |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056`  |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    |    `73`    |    ✅     |   🛠    |
# Dodo V2 (DEX) Subgraph Methodology v1.0.0

DODO is a decentralized trading platform that uses an innovative Proactive Market Maker (PMM) algorithm to provide efficient on-chain liquidity for Web3 assets.

When the quantity of an asset becomes low, the algorithm automatically increases the price quoted for this asset in anticipation of buying back the missing inventory from the market. 

Besides this, DODO also lets you issue your own tokens, and provides a set of tools and smart contracts for NFT creation, trading, and fragmentation.

## Useful Links

* Exchange
    * [https://dodoex.io/](https://dodoex.io/) 
* Docs
    * [https://docs.dodoex.io/english/](https://docs.dodoex.io/english/)
* Smart contracts and subgraph 
    * [https://github.com/DODOEX/contractV2](https://github.com/DODOEX/contractV2)
    * [https://github.com/DODOEX/graph-node](https://github.com/DODOEX/graph-node) 
    * [https://github.com/DODOEX/dodoex_v2_subgraph](https://github.com/DODOEX/dodoex_v2_subgraph) 
* Deployed addresses
    * Ethereum:
        * [https://docs.dodoex.io/english/developers/contracts-address/ethereum](https://docs.dodoex.io/english/developers/contracts-address/ethereum) 
    * BSC:
        * [https://docs.dodoex.io/english/developers/contracts-address/bsc](https://docs.dodoex.io/english/developers/contracts-address/bsc) 
    * Polygon:
        * [https://docs.dodoex.io/english/developers/contracts-address/polygon](https://docs.dodoex.io/english/developers/contracts-address/polygon) 
    * Arbitrium:
        * [https://docs.dodoex.io/english/developers/contracts-address/arbitrum](https://docs.dodoex.io/english/developers/contracts-address/arbitrum) 
    * Avalanche:
        * [https://docs.dodoex.io/english/developers/contracts-address/avalanche](https://docs.dodoex.io/english/developers/contracts-address/avalanche) 
    * MoonRiver:
        * [https://docs.dodoex.io/english/developers/contracts-address/moonriver](https://docs.dodoex.io/english/developers/contracts-address/moonriver) 
    * Aurora:
        * [https://docs.dodoex.io/english/developers/contracts-address/aurora](https://docs.dodoex.io/english/developers/contracts-address/aurora) 
    * Boba:
        * [https://docs.dodoex.io/english/developers/contracts-address/boba](https://docs.dodoex.io/english/developers/contracts-address/boba) 
    * HECO:
        * [https://docs.dodoex.io/english/developers/contracts-address/heco](https://docs.dodoex.io/english/developers/contracts-address/heco) 
    * OKChain:
        * [https://docs.dodoex.io/english/developers/contracts-address/okchain](https://docs.dodoex.io/english/developers/contracts-address/okchain) 
    * Rinkeby Test Network:
        * [https://docs.dodoex.io/english/developers/contracts-address/rinkeby-test-network](https://docs.dodoex.io/english/developers/contracts-address/rinkeby-test-network) 
* Token Transparency Project
    * [https://docs.dodoex.io/english/tokenomics/token-transparency-project](https://docs.dodoex.io/english/tokenomics/token-transparency-project) 

## Usage Metrics

**Active Users, Total Unique Users & Daily Transaction Count**

Any address (EOA) which conducts one of the transactions below should be considered a User:

* Swap Tokens using a Liquidity Pool
* Adding LP
* Removing LP
* Create a Pool (LP or Crowdpooling)

Reference: [https://docs.dodoex.io/english/dodo-dex-intro/how-to-participate](https://docs.dodoex.io/english/dodo-dex-intro/how-to-participate)

## Core Metrics

Some core metrics as explained by DODO on their documentation. All the data of core metrics come from Subgraph, and the data of Subgraph comes from the events thrown when the contract is called. 

**Trading volume**

We use PairDayData to track the data of each trading pair for the day, and TokenDayData to track the trading data of each Token for the day, with daily trading volume data being the trading volume of each Token for the day multiplied by the fiat price of that Token.

**Market Capitalization**: Get all pools from Subgraph and read the BaseReserve and QuoteReserve (i.e. the balance of BaseToken and QuoteToken on the contract) from each pool, multiply it by the Token's current fiat price, and the sum of the dollar value of both Tokens is recorded as the market capitalization. Tokens not accepted by Coingecko, Coinmarket, or Debank are not included in the market capitalization display.

**Number of user addresses**: the number of addresses that have interacted with DODO's smart contracts

**Number of transactions**: the number of transactions that occurred on DODO

**Smart contracts Pools**: Number of pools created in DODO

**Number of pairs**: the number of pairs traded on DODO

Reference: [https://docs.dodoex.io/english/developers/dashboard](https://docs.dodoex.io/english/developers/dashboard)

## Financial Metrics

**Total Value Locked USD**

TVL for DODO should be calculated by summing the LP deposited on all pools. You can calculate the total across all chains, and also the total for each chain.

Ex: If there are only two pools, one with $1M deposited in ETH/DAI and other with $2M deposited on ETH/USDC, the TVL for the protocol is $3M.

**Protocol Controlled Value USD**

Not relevant for this protocol

**Total Revenue USD - waiting on DODO’s feedback**

Each liquidity pool’s trading fees on DODO are set and configured by its creator and may vary from one another. Although the default trading fee for a pair on DODO is 0.3%, with the exception of DODO Classic Pool’s single-sided liquidity pools, which have a default trading fee of 0.01%.

Also, vDODO holders have a discount on transaction fees.

DODO trading fees distribution is as follows:

* 80% for Liquidity Providers
* 15% to Buyback DODO tokens & redistribute them to all vDODO holders
* 5% for the Community treasure

After the [DIP-8](https://snapshot.org/#/dodobird.eth/proposal/0x0e10c3820b2252ece6567a291d9a12f90a481c4160518390211e01c312c538c5) proposal passed, the USDC-USDT (ETH) and BUSD-USDT (BSC) pools fee were reduced to 0.002%, of which 75% is used to repurchase DODOs and distribute them to vDODO holders in the form of vDODOs, and 25% is used for the community vault.

Besides trading fees, DODO also charges a service fee for each token created on the platform. The token creation service fee rates on different networks are as follows:

<span style="text-decoration:underline;">Ethereum</span>: 0.02 ETH

<span style="text-decoration:underline;">BNBChain</span>: 0.05 BNB

<span style="text-decoration:underline;">HECO</span>: 0.5 HT

<span style="text-decoration:underline;">Polygon</span>: 1 MATIC

<span style="text-decoration:underline;">Arbitrium</span>: 0.002 ETH

<span style="text-decoration:underline;">Moonriver</span>: 0.05 MOVR \
<span style="text-decoration:underline;">Boba</span>: 0.002 ETH

<span style="text-decoration:underline;">OKChain</span>: 0.1 OKT

<span style="text-decoration:underline;">Optimism</span>: 0.002 ETH

<span style="text-decoration:underline;">Aurora</span>: 0.002 ETH

<span style="text-decoration:underline;">Avalanche</span>: 0.1 AVAX

**Total Revenue USD** = Fees from all pools + Service fees from token creation

References: 

* [https://docs.dodoex.io/english/tokenomics/vdodo](https://docs.dodoex.io/english/tokenomics/vdodo)
* [https://snapshot.org/#/dodobird.eth/proposal/QmeRQ4DTcBzAETWycrH43WVEj2MXovqgA7gPwSmQpavV8W](https://snapshot.org/#/dodobird.eth/proposal/QmeRQ4DTcBzAETWycrH43WVEj2MXovqgA7gPwSmQpavV8W)
* [https://dodoexhelp.zendesk.com/hc/en-us/articles/4721769913497-How-to-Create-Tokens-on-DODO-](https://dodoexhelp.zendesk.com/hc/en-us/articles/4721769913497-How-to-Create-Tokens-on-DODO-)

**Supply Side Revenue USD**

Supply-side revenue on DODO is the fees generated for Liquidity Providers (80%) and the Buyback of DODO tokens and redistribution to all vDODO holders (15%).

Regarding vDODO holders, the redemption of a vDODO into a DODO requires the payment of a pro-rata refund fee. 50% of this refund fee will be immediately distributed to all non-exiting vDODO holders in the form of vDODO, and the remaining 50% will be permanently destroyed (see [DIP-2](https://snapshot.org/#/dodobird.eth/proposal/QmZon8LttMoD2oJoov8vAMiS6m26AbK18ePBevMUDo99DS) for more details).

**Supply Side Revenue USD** = LP fees + DODO redistribution - vDODO exit fees

**Protocol Revenue USD**

Protocol revenue for DODO is the 5% distribution from the LP fees.

## Pool-Level Metrics

**Pool Total Value Locked USD**

The TVL for DODO is the number of assets deposited in the pool * the price of each asset.

**Pool TVL USD** = (Asset1 amount * Asset1 price) + (Asset2 amount * Asset2 price)

<code> \
</code>[Link for dashboard with general and pairs overviews](https://info.dodoex.io/overview)

**Reward Tokens & Reward Token Emissions Amount**

As previously stated, after the [DIP-8](https://snapshot.org/#/dodobird.eth/proposal/0x0e10c3820b2252ece6567a291d9a12f90a481c4160518390211e01c312c538c5) proposal passed, the USDC-USDT (ETH) and BUSD-USDT (BSC) pools fee were reduced to 0.002%, of which 75% is used to repurchase DODOs and distribute them to vDODO holders in the form of vDODOs, and 25% is used for the community vault.

Since the LPs of both pools will no longer receive a portion of the trading fees, DIP-8 proposes to compensate the LPs by increasing the DODO token rewards for both pairs to cover the LPs’ reduction in fee revenue. Specifically, the token rewards for both pools were increased by 10%, as follows:

* The USDC-USDT (ETH) rewards were increased from 2 DODO per block (1 DODO for USDC and USDT respectively) to 2.2 DODO per block.
* The BUSD-USDT (BSC) rewards were increased from 0.4 DODO per block (0.2 DODO for BUSD and USDT, respectively) to 0.44 DODO per block.

**Liquidity Mining**

DODO has a Liquidity Mining contract with two versions. The first version of the contract is mainly for the DODO V1 type pool, which provides liquidity LP for single coins and carries out DODO token rewards. In the second version of the mining contract, a pledge token corresponds to a contract and supports multiple mining.

**V1 - Current mining projects conducted by the first version of the contract[​](https://docs-next.vercel.app/zh/docs/5_5_mining#%E5%BD%93%E5%89%8D%E7%AC%AC%E4%BA%8C%E7%89%88%E5%90%88%E7%BA%A6%E8%BF%9B%E8%A1%8C%E7%9A%84%E6%8C%96%E7%9F%BF%E9%A1%B9%E7%9B%AE)**

ETH

* Mining Contract Address:[ 0xaed7384f03844af886b830862ff0a7afce0a632c](https://etherscan.io/address/0xaed7384f03844af886b830862ff0a7afce0a632c)
* currently releasing 4.2 DODO rewards per block
* Start date: Oct-01-2020
* Block: [10970196](https://etherscan.io/block/10970196)

BSC

* Mining contract address:[ 0x01f9BfAC04E6184e90bD7eaFD51999CE430Cc750](https://bscscan.com/address/0x01f9BfAC04E6184e90bD7eaFD51999CE430Cc750)
* Currently releasing 0.54DODO reward per block
* Start date: Feb-19-2021
* Block: [5007474](https://bscscan.com/block/5007474)

Arbitrum One

* Mining contract address:[ 0xE3C10989dDc5Df5B1b9c0E6229c2E4e0862fDe3e](https://arbiscan.io/address/0xE3C10989dDc5Df5B1b9c0E6229c2E4e0862fDe3e)
* Currently releasing 1.5DODO rewards per block
* Start date: Sep-02-2021
* Block: [254374](https://arbiscan.io/block/254374)

Aurora

* Mining Contract Address：[0xDBFaF391C37339c903503495395Ad7D6B096E192](https://explorer.mainnet.aurora.dev/address/0xDBFaF391C37339c903503495395Ad7D6B096E192)
* Currently Releasing 0.1 DODO Rewards Per Block
* Start date: Dec-26-2021
* Block: [56001129](https://explorer.mainnet.aurora.dev/block/56001129/transactions)

Polygon

* Mining Contract Address:[ 0xB14dA65459DB957BCEec86a79086036dEa6fc3AD](https://polygonscan.com/address/0xB14dA65459DB957BCEec86a79086036dEa6fc3AD)
* Currently Releasing 0.44 DODO Rewards Per Block
* Start date: Jan-20-2022
* Block: [23937470](https://polygonscan.com/block/23937470)

MoonRiver

* Mining Contract Address:[ 0x6b3518E0260aE1515976A30FA67513C760De2570](https://moonriver.moonscan.io/address/0x6b3518E0260aE1515976A30FA67513C760De2570)
* Currently Releasing 0.005 WMOVR Rewards Per Block
* Start date: Jan-27-2022
* Block: [1379589](https://moonriver.moonscan.io/block/1379589)

Boba

* Mining Contract Address:[ 0x2d8349E957A69E4cC7B4ef225A4B6a85Be57FBF3](https://blockexplorer.boba.network/address/0x2d8349E957A69E4cC7B4ef225A4B6a85Be57FBF3)
* Currently Releasing 3 DODO Rewards Per Block
* Start date: Feb-09-2022
* Block: [320754](https://blockexplorer.boba.network/blocks/320754/transactions)

**V2 - Current mining projects conducted by the second version of the contract[​](https://docs-next.vercel.app/zh/docs/5_5_mining#%E5%BD%93%E5%89%8D%E7%AC%AC%E4%BA%8C%E7%89%88%E5%90%88%E7%BA%A6%E8%BF%9B%E8%A1%8C%E7%9A%84%E6%8C%96%E7%9F%BF%E9%A1%B9%E7%9B%AE)**

ETH[​](https://docs-next.vercel.app/zh/docs/5_5_mining#eth)

* Pledged Token DAI-USDT DLP (0x3058ef90929cb8180174d74c507176cca6835d73)
* Mining Contract 0x1A4F8705E1C0428D020e1558A371b7E6134455A2
* Bonus Token DODO (1.25 per block)
* Start date: May-14-2021
* Block: [12429771](https://etherscan.io/block/12429771)

BSC[​](https://docs-next.vercel.app/zh/docs/5_5_mining#bsc)

* Pledged Token DODO-BNB DLP (0xd534fae679f7f02364d177e9d44f1d15963c0dd7)
* Mining Contract 0x322B43e406D1B4Df9Bc36d058317Dd1cd3b0385F
* Bonus Token DODO (0.3 per block)
* Start date: May-06-2021
* Block: [ 7183883](https://bscscan.com/block/7183883)

Arbitrum One[​](https://docs-next.vercel.app/zh/docs/5_5_mining#arbitrum-one)

* Pledged Token DODO-USDC DLP (0x6a58c68ff5c4e4d90eb6561449cc74a64f818da5)
* Mining Contract 0x38Dbb42C4972116c88E27edFacD2451cf1b14255
* Bonus Token DODO (0.5 per block)
* Start date: Sep-02-2021
* Block: [254535](https://arbiscan.io/block/254535)

Aurora

* Pledged Token DODO-USDC DLP (0xc7689e5315a8b237ac7ab62119df299dd8c4b6d5)
* Mining Contract 0x10353A2e2EeAE8369c685526FC724137002BBDF9
* Bonus Token DODO (0.1 DODO Per Block)
* Bonus Token NEAR (0.007 DF Per Block)
* Start date: Dec-27-2021
* Block: [56104331](https://explorer.mainnet.aurora.dev/block/56104331/transactions)

Polygon

* Pledged Token DODO-USDT DLP (0x581c7DB44F2616781C86C331d31c1F09db87A746)
* Mining Contract 0x738aba1389C5e37d24b5B669F07CBEa594c733E4
* Bonus Token DODO (0.11 per block)
* Start date: Jan-20-2022
* Block: [23949001](https://polygonscan.com/block/23949001)

Boba

* Pledged Token DODO-USDT DLP (0xb55c56541dceef41322b5d7a7880594afcd9711c)
* Mining Contract 0xb69e388c678d6b5aed323e3ef2f22d5fef8fb1ec
* Start date: Feb-07-2022
* Block: [316096](https://blockexplorer.boba.network/blocks/316096/transactions)

Reference: [https://docs.dodoex.io/english/developers/liquidity-mining#current-mining-projects-conducted-by-the-first-version-of-the-contract](https://docs.dodoex.io/english/developers/liquidity-mining#current-mining-projects-conducted-by-the-first-version-of-the-contract)
# Inverse Finance Lending Protocol Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Markets:

`Sum of Deposits on Anchor`

`= CToken.get_cash() * priceOracle.getUnderlyingPrice(CToken)`

`CToken.get_cash()` returns the deposits (inputTokenBalance), which is then converted to USD by
multiplying with the underlying token price (including ETH) returned from the price Oracle contract.

### Total Revenue USD

Sum across all Markets:

`Sum of Interest paid by borrowers + Fees earned by Stabilizer`

`= AccrueInterest.interestAccumulated * priceOracle.getUnderlyingPrice(CToken) + Buy/Sell fees on Stablizer`

The `AccrueInterest` event is emitted when interest (revenue) is accrued in the underlying token. The interest (revenue) is converted to USD by multiplying with the underlying token price (including ETH) returned from the price Oracle contract.

Currenltly borrowing is paused after an exploit. Stabilizer is a backstop for DOLA peg that takes 0.4% for buying and 0.1% for selling DOLA.

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol. The total interest (revenue) is split between depositors (supply-side) and the protocol based on the value of the `reserveFactor`.

Sum across all Markets:

`(Sum of Interest paid by borrowers) * Protocol Share + Fees earned by Stabilizer`

`= total revenue * reserveFactorMantissa / 10 ^ MANTISSA + Buy/Sell fees on Stablizer`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side. The total interest (revenue) is split between depositors (supply-side) and the protocol based on the value of the `reserveFactor`.

Sum across all Markets:

`Sum of Interest paid by borrowers * (1 - Protocol Share)`

`= Total Revenue USD - Protocol-Side Revenue USD`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Repays`

`Liquidations`

### Reward Token Emissions Amount

The inverse-finance comptroller computes the rewards emissions to lenders and borrowers when users interacts with the contracts, and emit `DistributedSupplierComp` and `DistributedBorrowerComp` event when emissions are rewarded. The event paramater `compDelta` contains the amount of emissions. Since the emissions happen irregularly, to normalize the emssions to a daily amount, a HelperStore entity keeps tract the block number of the last emissions, and is used to computed `deltaBlocks` between two emissions. The normalized daily emissions = `compDelta / deltaBlock * BLOCKS_PER_DAY`.

Reward emissions for lenders: `DistributedSupplierComp.compDelta * priceOracle.getUnderlyingPrice(CToken) * BLOCKS_PER_DAY / deltaBlocks`

Reward emissions for borrowers: `DistributedBorrowerComp.compDelta * priceOracle.getUnderlyingPrice(CToken) * BLOCKS_PER_DAY / deltaBlocks`

### Protocol Controlled Value

Not applicable.

## Links

- Protocol: https://www.inverse.finance/
- Analytics: https://dune.xyz/naoufel/inverse-dao
- Docs: https://docs.inverse.finance/inverse-finance/about-inverse
- Smart contracts: https://github.com/InverseFinance/anchor
- Deployed addresses: https://docs.inverse.finance/inverse-finance/technical/smart-contracts
- Official subgraph: https://thegraph.com/studio/subgraph/inverse-subgraph/

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`

## Hosted Subgraph

- Hosted subgraph: https://thegraph.com/hosted-service/subgraph/tnkrxyz/inverse-finance

## Smart Contracts Interactions

![inverse-finance](../../docs/images/protocols/inverse-finance.png "inverse-finance")

## Inverse Finance Lending Protocol

## Deposit, Borrow, and Liquidate in Markets

The Inverse Finance Lending Protocol is controled by a [comptroller contract](https://etherscan.io/address/0x4dCf7407AE5C07f8681e1659f626E114A7667339), which controls 11 markets represented by an Anchor ERC20 token with a corresponding underlying/input token, including anDOLA/DOLA, anETH/ETH, anWBTC/WBTC, anxShushi/xSushi, anYFI/YFI, xINV/INV (an old and new contract), anStETH/stETH, anDOLA3POOL-CRV/DOLA3POOL CRV LP Token, anINV-DOLA SLP/INV-DOLA Sushi LP Token, and anFLOKI/FLOKI (deprecated). When a user deposits underlying (input) tokens in a market, they mint the corresponding Anchor token. As a depositor, the user will receive interest and INV token emissions as reward. An depositor can also borrow underlying tokens from any of the markets. The ratio between total borrow amount and collateral amount across all markets must be below a specified collateral factor. If a borrower's loan-to-collateral ratio is above the collateral factor, a liquidator can invoke the `LiquidateBorrow` function, repay all or part of the borrower's debt, and seize the borrower's Anchor tokens (which can then be redeemed for the underlying token).

## DOLA stablecoin and the Fed

The Inverse DAO also manages the DOLA stablecoin. The DOLA's peg to \$1 is maintained through [the Fed contract](https://etherscan.io/address/0x5e075e40d01c82b6bf0b0ecdb4eb1d6984357ef7) and through [the stablizer](https://etherscan.io/address/0x7ec0d931affba01b77711c2cd07c76b970795cdd), an exhange allowing users to arbitrage the differential between DAI and DOLA by swapping between them. When the demand for DOLA is high (price is above \$1), the Fed contract expands (increases) the DOLA supply by minting more DOLA and anDOLA tokens; vice versa, it contracts (reduces) the DOLA supply by burning the DOLA and anDOLA tokens. During expansion, the Fed contract is the supplier of liquidity in the anDOLA/DOLA market and earns a profit (interest) from its deposit.

Besides the Anchor Fed, separate Fed contracts also supplies DOLA to the lending pools of serval lending partners, including Yearn, Bagder, 0xb1, Fuse, and Scream (Fantom). The Fed contract behaves similar to Anchor Fed, with customization to make it work with the contract of each lending partner.
# Aave V3 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Reserves:

`Pool Deposit TVL`

Includes supply interest earned

### Total Revenue USD

Sum across all Reserves:

`Borrow interest + Flash loan premium + Bridge fee + Liquidation bonus`

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Reserves:

`(Borrow interest * reserve factor) + Flash loan protocol premium + Bridge protocol fee + Liquidation protocol bonus`

Calculated using:

- aToken transfers to treasury address (liquidation bonus)
- `Pool.getReserveData(asset).accruedToTreasury`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Reserves:

`Supply APY + Flash loan LP premium + Bridge LP fee + Liquidation LP bonus`

Calculated using:

- `(aToken liquidity index change * scaled total supply)`
- Liquidate.profitUSD

### Total Borrow Balance

Sum across all Reserves:

`VariableDebtToken total supply + StableDebtToken total supply`

Includes accrued interest

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

### Reward Token Emissions Amount

`Emissions per second * seconds per day`

### Protocol Controlled Value

N/A

## References and Useful Links

- Protocol website: https://aave.com
- Protocol documentation: https://docs.aave.com/developers/getting-started/readme
- Smart contracts: https://github.com/aave/aave-v3-core
  - Rewards contracts: https://github.com/aave/aave-v3-periphery
- Deployed addresses: https://docs.aave.com/developers/deployed-contracts/v3-mainnet
- Existing Subgraph: https://github.com/aave/protocol-subgraphs

## Usage

### Prepare

`npm run prepare:yaml --TEMPLATE=aave-v3.template.yaml --PROTOCOL=aave-v3 --NETWORK=matic`

## Smart Contracts Interactions

![Aave V3](../../docs/images/protocols/aave-v3.png "Aave V3")
## Deployment Instructions:

- Additional dependencies:
  - minimist - install at ./subgraphs at head of repository
    - `npm install minimist`
  - mustache
    - `npm install mustache`

```
# Deploys uniswap-v2 from the uniswap-forks to mainnet in my hosted service.
npm run deploy --SUBGRAPH=uniswap-forks --PROTOCOL=uniswap-v2 --NETWORK=mainnet --LOCATION=steegecs

# Deploys uniswap-v2 from the uniswap-forks to all networks in my hosted service.
npm run deploy --SUBGRAPH=uniswap-forks --PROTOCOL=uniswap-v2 --LOCATION=steegecs

# Deploys protocols from the uniswap-forks and networks in my hosted service.
npm run deploy --SUBGRAPH=uniswap-forks --LOCATION=steegecs
```

- 2 required parameters:

  - --SUBGRAPH
  - --LOCATION

- 2 Additional Parameters for specifying particular deployments from a subgraph directory.
  - --PROTOCOL
  - --NETWORK
- 2 Options (Leaving null means 'F')

  - --PRINTLOGS
    - T/F - Set PRINTLOGS to 't' or 'true' to print all logs to the console instead of just to results.txt
  - --MERGE
    - T/F - Specifies whether this deployment is triggered by a merge. Should only be set to merge in the deployment action unless for testing.

- This works by taking the inputs from `npm run deploy` and using them to configure the subgraph.yaml, and optionally, configurations/configure.ts with a particulalar set of constants, and subsequently deploying to the specified hosted service account.

## How CI/CD deployment works:

- The CI/CD deployment scripts and actions allow you to deploy multiple subgraphs at a time and deploy on merge if specified in the deployment/deploymentConfigurations.json file.
- The subgraphs that get deployed on merge depend upon 2 conditions:
  - The `deploy-on-merge` variable in the `deploymentConfigurations.json` should be present and set to `true` for that particular protocol and network deployment.
  - A change in the codebase is detected that is relevant to a particular subgraph. For example:
    - A change in the `src/` folder has an expected impact on all subgraphs in the directory, so all subgraphs will satisfy this condition and deploy on merge if the above condition met.
    - A change in a particular Protocols/`protocol`/src/ folder, will trigger all deployments for a particular protocol if the above condition is met.
    - A change in a particular Protocols/`protocol`/config/networks/`network` folder will deploy that specific protocol and network if the above condition is met.
- Be careful to set the deploy-on-merge to its proper configuration each time you create a PR and merge it to the remote repository.

## How to set up:

### Directory Structure (See uniswap-forks as example):

- Using these scripts requires a particular directory structure. This is because when the `npm` scripts are executed, the deployment scripts should know where to look for configuration files and templates. Also, for the deploy-on-merge actions, the specific structure allows us to detect changes that may apply to specific subgraph (root directory of subgraph e.g. uniswap-forks), a specific subgraph and protocol, a specific subgraph protocol, and network, or some combination. This is then used to execute the particular subgraph deployments that have relevant changes if specified in `deployment/deploymentConfigurations.json` to the Hosted Service.

- The folder structure is a minimum **requirement**. You can add additional folders and files as long as the general pattern is adhered to:

  - First, you should have a `src/` folder and add any code or constants that applies to all subgraphs.

    - Example Strucure:
      - src/
        - common/
          - constants.ts
        - mappings/
          - ...
        - price/
          - ...
    - This constants file should contain all constants that do not conflict accross protocols and networks. See subgraphs/uniswap-forks/src/common/constants.ts as an example.

  - Additionally, within the particular subgraph folder, you should have a `Protocols/` folder. The directory structure should have each of these folders and files (configured by `protocol` and `network`).

    - Protocols/ (contains a list of all protocols developed in this directory)

      - `protocol`/
        - config/
          - networks/
            - `network1`/
              - `network1`.json
            - `network2`/
              `network2`.json
          - templates/ (make sure there are not dashes (-) in `protocol` to help with programmatically accessing the file)
            - `protocol`.template.yaml
        - src/
          - common/
            - constants.ts
          - mappings/
            - ...

    - Protocols/`protocol`/config/networks/`network`/`network`.json contains all parameters used to configure the proper template in Protocols/`protocol`/config/templates using mustache

  - (Option) If you want to introduce protocol and network specific configurations for use by the program, add a `configurations` folder and add `network.ts` file to Protocols/`protocol`/config/networks/`network`/:
    - configurations/
      - configurations/
        - configurations.ts
        - deploy.ts
        - interface.ts
      - configure.template.ts

### Necessary Files

- _Protocols/`protocol`/config/networks/`network`/`network`.json_
  - ![plot](./images/network-json.png)
  - Add all necessary mustache configurations for Protocols/`protocol`/config/templates/`template`.yaml and configurations/configure.template.ts
  - If using a configurations/ folder for protocol and network specific constants, add a constant of the form to the `network`.json file:
    - "deployment": "{PROTOCOL*SLUG}*{NETWORK}"
- _Protocols/`protocol`/config/networks/`network`/`network`.ts_
  - ![plot](./images/network-ts.png)
  - Add an object containing configurations for a specific protocol/network deployment. Recommended to use Protocols/`protocol`/src/constants.ts and src/constants.ts for imports if applicable (e.g. for importing PROTOCOL_SUBGRAPH_VERSION or PROTOCOL_FACTORY_ADDRESS).
- _Protocols/`protocol`/config/templates/`protocol`.template.yaml_
  - ![plot](./images/subgraph-template-yaml.png)
  - Contains the template that will be used to create the subgraph.yaml in the subgraph directory - usually 1 per protocol but not always.
- _package.json_
  - Contains the `npm` scripts necessary to succesfully run the deployment scripts as shown in the instructions above.
  - Should contain at least:
    - `prepare:yaml`
    - `prepare:constants` (Option)
      - Use if you added a configuration/ folder
    - `prepare:build`
    - `deploy:subgraph`
    - `deploy`
  - See `deployment/package.template.json` at the head of the repo to get the scripts.
  - The `prepare:yaml` and `prepare:constants` scripts take arguments the tell them the proper locations to look for configurations and configurable files and generates configurations from templates. The `subgraph:deploy` script takes a deployment location as an argument and deploys to the Hosted Service at that location.
  - All you have to do is pass the relavent paramters to the `deploy` script described in the instructions above, and other scripts are configured and run as needed.
- _configurations/_

  - _configurations/_
    - _configurations.ts_
      - ![plot](./images/configurations-configurations-ts.png)
      - Contains imports for instantiated configuration objects in Protocols/`protocol`/config/networks/`network`/`network`.ts.
      - Import a configuration object for each particular protocol and network and add to switch case
    - _deploy.ts_
      - ![plot](./images/configurations-deploy-ts.png)
      - Contains a namespace for {PROTOCOL*SLUG}*{NETWORK} used in configure.template.ts
      - Add a namespace value for each deployment that uses the configurations/ folder.
    - _interface.ts_
      - ![plot](./images/configurations-interface-ts.png)
      - Contains an interface used to describe all configuration fields used by the program for all subgraphs in the directory.
      - Add or delete fields as necessary.
  - configure.template.ts
    - ![plot](./images/configurations-configure-ts.png)
    - This file is used to generate configure.ts which selects the proper configurations for a protocol/network deployment.

- _HEAD:/deployment/deploymentConfigurations.json_
  - This file contains deployment configurations for each protocol and network deployment.
  - Add an entry to this file for each protocol and network deployment
  - ![plot](./images/deploymentConfigurations-json.png)
  - Stick to the current structure of the json file
    - `subgraph folder` (e.g. uniswap-forks)
      - `protocol` (e.g. uniswap-v2)
        - `network` (e.g. mainnet)
          - template (Required)
            - file name of the template used for this deployment (e.g. uniswap.v2.template.yaml)
          - `location` (Optional)
            -Specify the deployment location in the hosted service if the deployment location name does not follow the Messari standard (account/protocol-network)
          - deploy-on-merge (Optional)
            - true/false/null
            - Set to true if you want to deploy upon merging your branch with remote repo
            - Does not deploy unless true
          - prepare:constants (Optional)
            - true/false/null
            - Set to true if you are configuring constants in the configurations/ folder.
            - Does not use unless true
# Yearn Finance Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Vaults: 

`Vault Deposit TVL`

### Total Revenue USD

Sum across all Vaults:

`Harvested Yield`

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Vaults:

`(Vault TVL * Management Fees) + (Harvested Yield * Performance Fees)`

Partly shared with Strategist / Referring Protocol but to be included in Protocol-Side Revenue

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Vaults

`Harvested Yield - (Vault TVL * Management Fees) - (Harvested Yield * Performance Fees)`

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be confirmed

## Links

Protocol
- https://yearn.finance/

Docs
- https://docs.yearn.finance/
- https://docs.yearn.finance/vaults/smart-contracts/vault

Smart contracts
- https://github.com/yearn/yearn-vaults

Deployed addresses
- https://andrecronje.gitbook.io/yearn-finance/developers/deployed-contracts-registry

ROI Calculation
- https://docs.yearn.finance/getting-started/guides/how-to-understand-yvault-roi
# dForce Network Lending Protocol Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum deposits on dForce Lending, that is, sum across all Markets:

`iToken.get_cash() * priceOracle.getUnderlyingPrice(iToken)`

`iToken.get_cash()` returns the deposits (inputTokenBalance), which is then converted to USD by
multiplying with the underlying token price (including ETH) returned from the price Oracle contract.

### Total Revenue USD

Sum across all Pools:

Sum of Interest paid by borrowers, or `UpdateInterest.interestAccumulated * priceOracle.getUnderlyingPrice(iToken)`

The `UpdateInterest` event is emitted when interest (revenue) is accrued in the underlying token. The interest (revenue) is converted to USD by multiplying with the underlying token price (including ETH) returned from the price Oracle contract.

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol. The total interest (revenue) is split between depositors (supply-side) and the protocol based on the value of the `reserveRatio`.

Sum across all Markets: `Total Revenue USD * reserveRatio / 10 ^ MANTISSA`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side. The total interest (revenue) is split between depositors (supply-side) and the protocol based on the value of the `reserveRatio`.

Sum across all Markets:`Total Revenue USD - Protocol-Side Revenue USD`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Repays`

`Liquidations`

### Reward Token Emissions Amount

The dForce lending RewardDistributor contract computes the rewards emissions to lenders and borrowers when users interacts with the contracts, and emit `RewardDistributed` event when emissions are distributed to user account. Since there is no event for market-level emissions, the daily emissions for a market have to be computed using the `distributionSpeed` storage in the RewardDistributor contract multiplied with `BLOCKS_PER_DAY`:

Reward emissions for lenders: `distributionSupplySpeed * priceOracle.getUnderlyingPrice(iToken) * BLOCKS_PER_DAY`

Reward emissions for borrowers: `distributionSpeed * priceOracle.getUnderlyingPrice(iToken) * BLOCKS_PER_DAY`

### Protocol Controlled Value

Not applicable.

## Links

- Protocol: https://dforce.network/
- Analytics: [Not found]
- Docs: https://docs.dforce.network/
- Smart contracts: https://github.com/dforce-network/LendingContractsV2
- Deployed addresses: https://developers.dforce.network/lend/lend-and-synth/deployed-contracts
- Official subgraph: [Not found]

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`

## Hosted Subgraph

- Arbitrum: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-arbitrum
- Avalanche: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-avalanche
- BSC: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-bsc
- Mainnet: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce
- Optimism: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-optimism
- Polygon: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-polygon

## Smart Contracts Interactions

![dforce-lending](../../docs/images/protocols/dforce.png "dforce-lending")

(Credit: [dForce Network](https://developers.dforce.network/lend/lend-and-synth))

## dForce Network Lending Protocol

### Deposit, Borrow, and Liquidate in Markets

The dForce Network Lending Protocol is controled by a [controller contract](https://etherscan.io/address/0x8B53Ab2c0Df3230EA327017C91Eb909f815Ad113), which controls 24 lending markets, each represented by an iToken (a dForce ERC20 token) with a corresponding underlying/input token, including iUSX/USX, iETH/ETH, iWBTC/WBTC, etc ([A complete list of all markets/iTokens](https://developers.dforce.network/lend/lend-and-synth/deployed-contracts)). When a user deposits underlying (input) tokens in a market, they mint the corresponding iToken. As a depositor, the user will receive interest and DF token emissions as reward. An depositor can also borrow underlying tokens from any of the (unpaused) markets. The ratio between total borrow amount and collateral amount across all markets must be below a specified collateral factor. If a borrower's loan-to-collateral ratio is above the collateral factor, a liquidator can invoke the `LiquidateBorrow` function, repay all or part of the borrower's debt, and seize the borrower's iTokens (which can then be redeemed for the underlying tokens).

### USX/EUX stablecoin

The dForce Network also manages the USX and EUX stablecoin. The USX is pegged to \$1, and the peg is maintained through controling the interest rate via [Protocol-Direct-Liquidity-Provision](https://docs.dforce.network/protocols/usx/price-stability). When the demand for USX is high (price is above \$1), the pool increases the USX supply by minting more USX tokens; vice versa.
# ERC20-Subgraph
# dForce Network Lending Protocol Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum deposits on dForce Lending, that is, sum across all Markets:

`iToken.get_cash() * priceOracle.getUnderlyingPrice(iToken)`

`iToken.get_cash()` returns the deposits (inputTokenBalance), which is then converted to USD by
multiplying with the underlying token price (including ETH) returned from the price Oracle contract.

### Total Revenue USD

Sum across all Pools:

Sum of Interest paid by borrowers, or `UpdateInterest.interestAccumulated * priceOracle.getUnderlyingPrice(iToken)`

The `UpdateInterest` event is emitted when interest (revenue) is accrued in the underlying token. The interest (revenue) is converted to USD by multiplying with the underlying token price (including ETH) returned from the price Oracle contract.

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol. The total interest (revenue) is split between depositors (supply-side) and the protocol based on the value of the `reserveRatio`.

Sum across all Markets: `Total Revenue USD * reserveRatio / 10 ^ MANTISSA`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side. The total interest (revenue) is split between depositors (supply-side) and the protocol based on the value of the `reserveRatio`.

Sum across all Markets:`Total Revenue USD - Protocol-Side Revenue USD`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Repays`

`Liquidations`

### Reward Token Emissions Amount

The dForce lending RewardDistributor contract computes the rewards emissions to lenders and borrowers when users interacts with the contracts, and emit `RewardDistributed` event when emissions are distributed to user account. Since there is no event for market-level emissions, the daily emissions for a market have to be computed using the `distributionSpeed` storage in the RewardDistributor contract multiplied with `BLOCKS_PER_DAY`:

Reward emissions for lenders: `distributionSupplySpeed * priceOracle.getUnderlyingPrice(iToken) * BLOCKS_PER_DAY`

Reward emissions for borrowers: `distributionSpeed * priceOracle.getUnderlyingPrice(iToken) * BLOCKS_PER_DAY`

### Protocol Controlled Value

Not applicable.

## Links

- Protocol: https://dforce.network/
- Analytics: [Not found]
- Docs: https://docs.dforce.network/
- Smart contracts: https://github.com/dforce-network/LendingContractsV2
- Deployed addresses: https://developers.dforce.network/lend/lend-and-synth/deployed-contracts
- Official subgraph: [Not found]

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`

## Hosted Subgraph

- Arbitrum: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-arbitrum
- Avalanche: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-avalanche
- BSC: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-bsc
- Mainnet: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce
- Optimism: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-optimism
- Polygon: https://thegraph.com/hosted-service/subgraph/tnkrxyz/dforce-polygon

## Smart Contracts Interactions

![dforce-lending](../../docs/images/protocols/dforce.png "dforce-lending")

(Credit: [dForce Network](https://developers.dforce.network/lend/lend-and-synth))

## dForce Network Lending Protocol

### Deposit, Borrow, and Liquidate in Markets

The dForce Network Lending Protocol is controled by a [controller contract](https://etherscan.io/address/0x8B53Ab2c0Df3230EA327017C91Eb909f815Ad113), which controls 24 lending markets, each represented by an iToken (a dForce ERC20 token) with a corresponding underlying/input token, including iUSX/USX, iETH/ETH, iWBTC/WBTC, etc ([A complete list of all markets/iTokens](https://developers.dforce.network/lend/lend-and-synth/deployed-contracts)). When a user deposits underlying (input) tokens in a market, they mint the corresponding iToken. As a depositor, the user will receive interest and DF token emissions as reward. An depositor can also borrow underlying tokens from any of the (unpaused) markets. The ratio between total borrow amount and collateral amount across all markets must be below a specified collateral factor. If a borrower's loan-to-collateral ratio is above the collateral factor, a liquidator can invoke the `LiquidateBorrow` function, repay all or part of the borrower's debt, and seize the borrower's iTokens (which can then be redeemed for the underlying tokens).

### USX/EUX stablecoin

The dForce Network also manages the USX and EUX stablecoin. The USX is pegged to \$1, and the peg is maintained through controling the interest rate via [Protocol-Direct-Liquidity-Provision](https://docs.dforce.network/protocols/usx/price-stability). When the demand for USX is high (price is above \$1), the pool increases the USX supply by minting more USX tokens; vice versa.
# Compound Fork Subgraph

## Quickstart

### Setup

Setting up a new subgraph will require mimicing what is done currently.

- Under `./protocols` will be the fork in a new folder
- Any protocol-specific mappings will live in `./protocols/$(protocol)/src`
- Setup a config folder in `./protocols/$(protocol)/config` for the supported networks and the manifest template
- Lastly you need to add your configuration to [deploymentConfigurations.json](../../deployment/deploymentConfigurations.json)
- You can also reference the deployment [README](../../deployment/README.md) for help

### Deployment

Once everything is setup properly deploying is very easy.

```bash
# This example will deploy rari-fuse on all networks to the hosted service under "dmelotik" in deploymentConfigurations.json
npm run deploy --SUBGRAPH=compound-forks --PROTOCOL=rari-fuse --LOCATION=dmelotik

# This will do the same, but only deploying the mainnet subgraph
npm run deploy --SUBGRAPH=compound-forks --PROTOCOL=rari-fuse --NETWORK=mainnet --LOCATION=dmelotik
```

> Setting `deploy-on-merge` to `true` in [deploymentConfigurations.json](../../deployment/deploymentConfigurations.json) will run the above commands on subgraphs that have changed to messari's hosted service.

### Development Commands

During development you probably won't want to fully deploy the subgraph every time. Follow this guide to do each step incrementally.

To setup the subgraph manifest from the template:

```bash
# Use rari fuse as an example
npm run prepare:yaml --PROTOCOL=rari-fuse --NETWORK=mainnet --TEMPLATE=rari-fuse.template.yaml
```

To codegen and build:

```bash
graph codegen
graph build
```

> If you are working on multiple subgraphs you may want to delete `./generated/**` before `codegen` so no old files are left behind.

To deploy follow the steps above. You may put your hosted service endpoint in [deploymentConfigurations.json](../../deployment/deploymentConfigurations.json) just how messari's is set to take advantage of the commands.

## Project Layout

### schema.graphql

Shared schema for all Compound forks.

### abis

Standard Compound abis.

### src

Shared logic among the forks.

### queries

Useful queries to run against a Compound fork subgraph.

### protocols

Protocol-specific subgraph definition, abis and implementations.

**Notice**: Some forks have different abis from Compound. For example, Moonwell:

1. renames cToken to mToken
1. rename supplyRatePerBlock to supplyRatePerTimestamp because it accrues interest every second, not block
1. add supplyRewardSpeeds and borrowRewardSpeeds

Therefore we need to use Moonwell-specific abis, see moonwell/subgraph.yaml (note the dots!):

```yaml
- name: CToken
    file: ./abis/CToken.json
- name: Comptroller
    file: ./abis/Comptroller.json
- name: ERC20
    file: ../abis/ERC20.json
- name: PriceOracle
    file: ../abis/PriceOracle.json
- name: SolarBeamLPToken
    file: ./abis/SolarBeamLPToken.json
```
# Whale Watcher

![Whale Watcher](../../docs/images/apps/whale-watcher.png "Whale Watcher")

## Development

Install venv

```
python3 -m venv venv
```

Activate venv

```
source venv/bin/activate
```

Install dependencies

```
pip3 install -r requirements.txt
```

Run locally

```
streamlit run app.py
```
# Tokemak Subgraph

## Links

- Protocol website: https://www.tokemak.xyz/
- Protocol documentation: https://docs.tokemak.xyz/
- Smart contracts: https://github.com/Tokemak/tokemak-smart-contracts-public
- Deployed addresses: https://docs.tokemak.xyz/protocol-information/contract-interactions
# Beefy Finance - Yield Protocol Subgraph

![Beefy](../../docs/images/protocols/beefy-finance.png)

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Vaults:

`Vault total value locked`

### Total Revenue USD

Sum across all Vaults:

`Amount harvested * price of token harvested`

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Vaults:

`Total revenue * performanceFee / 100`

PerformanceFee is set as maxFee of the vault (which is usually 10%) minus strategist and harvester fee (which are set by the deployer)

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Vaults

`Total revenue * (1 - performanceFee/100 - strategistFee/100 - harvesterFee/100)`

PerformanceFee is set as maxFee of the vault (which is usually 10%) minus strategist and harvester fee (which are set by the deployer)

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

### Reward Token Emissions Amount

To be added

### Protocol Controlled Value

Sum across all valuts:

`Vault controlled value`

## Useful Links and references

- https://beefy.finance/
- https://app.beefy.com/#/
- https://docs.beefy.com/
- https://dashboard.beefy.finance/
- https://api.beefy.finance/
- https://defillama.com/protocol/beefy-finance

## Deploying

Before deploying, run

`yarn write-yaml ${network}`

to build the yaml file for the correct chain; than you can deploy using

`yarn deploy ${githubuser/subgraphname}`
# Streamlit Demo

## Development

Install venv

```
python3 -m venv venv
```

Install dependencies

```
python3 install -r requirements.txt
```

Run locally

```
streamlit run makerdao.py
```

## TODO

- async https://gql.readthedocs.io/en/stable/advanced/async_advanced_usage.html#async-advanced-usage
- less verbose logging https://gql.readthedocs.io/en/stable/advanced/logging.html
# Configurations
- This folder contains the general configurations to use for the deployed networks/protocols

## deploy.ts
- Include a nameswap value for each protocol/network deployement. Structure these values as `PROTOCOL_NETWORK` as seen in the file as an example. 
- Set the namespace value to a number. This is so the namespace value works in the case/switch in the configurations.ts file
- Also, add the to the `PROTOCOL_NETWORK` like "deployment": "PROTOCOL_NETWORK" in the network specific conficuration .json file. 
## interface.ts
- The interface contains all of the fields and data types that will be stored in the Configurations class for use in the program
## configurations.ts
- This file is just used to select the proper configurations per protocol/network.
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1 
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)     | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24) | `Calculations` | `3808222` |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)     |    `Router`    | `5655918` |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957)   |    `Router`    | `3796241` |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    | `2457904` |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603` |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120` |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056` |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    | `73` |    ✅     |   🛠    |
# TreasureDAO Protocol Metrics Subgraph Methodology v1.0.0

## Useful Links

* Protocol
    * [https://www.treasure.lol/](https://www.treasure.lol/)
* Docs/Whitepaper
    * [https://docs.treasure.lol/about-treasure/readme](https://docs.treasure.lol/about-treasure/readme)
* GitHub
    * [https://github.com/TreasureProject](https://github.com/TreasureProject)
* Marketplace
    * [https://marketplace.treasure.lol/](https://marketplace.treasure.lol/)
* Contracts
    * [https://docs.treasure.lol/references/contracts](https://docs.treasure.lol/references/contracts)

## Introduction

TreasureDAO is an Arbitrum based NFT marketplace with a focus on metaverse projects. Their native token, MAGIC, is the base currency for transactions throughout their platform and partnered NFT projects. They are actively working towards bootstrapping new metaverse projects and solidifying MAGIC as the reserve currency for all their current and future connected metaverses. 

## Usage Metrics

**Active Users, Total Unique Users & Daily Transaction Count**

**Usage**

* Mining Actions
    * Deposits
    * Withdrawals
    * Harvesting
* Interactions with NFT contracts
    * Bridgeworld
    * Legions
* Treasure Marketplace NFT transactions
    * (Treasures, Keys, Extra Life, Legions, etc.)

**Additional Metrics for consideration**

* Liquidity Pairs Swap Volume
    * **[Sushiswap MAGIC-ETH LP Pair](https://app.sushi.com/analytics/pools/0xb7e50106a5bd3cf21af210a755f9c8740890a8c9?chainId=42161)**
    * **[Sushiswap MAGIC-gOHM Pair](https://app.sushi.com/analytics/pools/0xac75a1a0c4933e6537eafb6af3d402f82a459389?chainId=42161)**
* Bond Volume
    * **[Olympus MAGIC-ETH SLP Bond ](https://pro.olympusdao.finance/#/bond/magic_eth_slp) **

## Financial Metrics

**Total Value Locked USD**

The TVL for TreasureDAO should be calculated as follows: 
```
TVL (USD) = Total Mine TVL + LP Pools Value TVL
```
This can be checked against DefiLlama which follows this for TreasureDAO’s TVL.

Some useful reference links:

* **[Atlas mine contract](https://arbiscan.io/address/0xa0a89db1c899c49f98e6326b764bafcf167fc2ce) **
* **[Sushiswap MAGIC-ETH LP Pair](https://app.sushi.com/analytics/pools/0xb7e50106a5bd3cf21af210a755f9c8740890a8c9?chainId=42161)**
* **[Sushiswap MAGIC-gOHM Pair](https://app.sushi.com/analytics/pools/0xac75a1a0c4933e6537eafb6af3d402f82a459389?chainId=42161)**
* **[Olympus MAGIC-ETH SLP Bond ](https://pro.olympusdao.finance/#/bond/magic_eth_slp) **
* **[TreasureDAO Ecofund](https://arbiscan.io/address/0x482729215AAF99B3199E41125865821ed5A4978a) **

**Protocol Controlled Value USD**

TreasureDAO utilizes Olympus Pro to offer bonds on their native $MAGIC token. 

They currently offer a single bond for the MAGIC-ETH LP pair. They are staking the MAGIC-ETH LP they have accumulated in their treasury multisig.

[TreasureDAO Marketplace Multisig](https://arbiscan.io/address/0xDb6Ab450178bAbCf0e467c1F3B436050d907E233) 

The PCV is equal to the LP positions they hold. 
```
Protocol Controlled Value = Sum of LP Positions Held (USD)
```
**Total Revenue USD**

TreasureDAO generates revenue from three main sources: 

1. **Atlas Mine Emissions**
2. **LP Fees**
3. **NFT Royalty**

Adding these together we can get the total revenue. 
```
Total Revenue (USD) = Total Mining Revenue + Total LP Revenue + Total Royalty Revenue
```
where
```
Total Royalty Revenue = Creatory Royalty Revenue + DAO Swap Fee Revenue
```
**Supply Side Revenue USD**
```
Supply Side Revenue (USD) = Mining Supply Revenue + (Total LP Revenue - PCV Yield Revenue) + Marketplace Creator Royalty Revenue
```
where
```
Marketplace Creator Royalty Revenue (USD) = Swap Volume (USD) * Creator Fee (%)
```
TreasureDAO does not hold any MAGIC in the Atlas Mine or charge a fee. All MAGIC and mining rewards are paid to token holders. Mining rewards emissions are detailed in the rewards token section. 
```
Mining Supply Revenue = Emissions Amount * Price of MAGIC (USD)
```
**The DAO holds a LP position as PCV.**

With the implementation of TIP-12, the maximum cap for the creator fee was increased from 5% to 20%. As this was quite recent, NFT transactions on the marketplace have mostly stayed at 5% swap fees with 2.5% allocated to the creator. 

**Protocol Revenue USD**
```
Protocol Revenue (USD) = PCV Yield Revenue + Marketplace DAO Swap Fee Revenue
```
where
```
PCV Yield Revenue = LP Position (USD) * LP Yield (%)
```
and
```
Marketplace DAO Swap Fee Revenue (USD) = Swap Volume (USD) * DAO Swap Fee(%)
```
TreasureDAO currently takes 2.5% on all NFT swaps, so the DAO Swap Fee = 2.5% until changed. See [TreasureDAO TIP - 12](https://treasuredao.freeflarum.com/d/33-tip-12-creator-royalties-on-the-treasure-marketplace)

## Pool-Level Metrics

**Pool Total Value Locked USD**

The only two pools containing TreasureDAO’s native token; MAGIC-ETH and MAGIC-gOHM on Sushiswap Arbitrum. The value in these pools can be calculated as follows:
```
Pool TVL (USD) = (Sum of Magic Tokens * Price of MAGIC) + (Sum of Paired Token * Price of Token)
```

**Atlas mine TVL:**
```
Mine TVL = Sum of MAGIC tokens locked * Price of MAGIC
```
Reward Tokens & Reward Token Emissions Amount

The max supply of MAGIC is 347,714,007.

33% (115,904,669) was distributed through the treasure farm fair launch on September 6, 2021 over 30 days. 25% (86,928,502) is allocated to mining emissions over 10 years with a yearly halvening.

Of the first year (Y1) allocation, 20m was distributed in 90 days for the Genesis mine beginning 2021-10-26 14:00 UTC. With the close of the Genesis mine on 2022-01-24, emissions moved to the currently operational Atlas mine (started 2022-01-26) for the remaining 23,464,251 MAGIC in emissions.

On 2021-12-13 15:00 UTC, staking rewards for the MAGIC-ETH LP on Arbitrum were transferred to SushiSwap under the Onsen farm program, where LP providers can earn dual rewards in MAGIC and SUSHI tokens.

17% (59,111,381) of supply is allocated to LP Staking emissions.

Current MAGIC-ETH LP Emissions schedule after TIP-11 which passed on 2022-04-09.

<table>
  <tr>
   <td><strong>End December 2021 - April 2022</strong>
   </td>
   <td><strong>1,000,000 MAGIC per month</strong>
   </td>
  </tr>
  <tr>
   <td><strong>End April 2022 - June 2022</strong>
   </td>
   <td><strong>800,000 MAGIC per month</strong>
   </td>
  </tr>
  <tr>
   <td><strong>End June 2022 - August 2022</strong>
   </td>
   <td><strong>650,000 MAGIC per month</strong>
   </td>
  </tr>
</table>

Team and ecosystem fund emissions schedule was unable to be found.

## References: 

* **[https://docs.treasure.lol/getting-started/what-is-magic#tokenomics](https://docs.treasure.lol/getting-started/what-is-magic#tokenomics)**
* **[https://docs.treasure.lol/bridgeworld/bridgeworld-litepaper/magic-mining](https://docs.treasure.lol/bridgeworld/bridgeworld-litepaper/magic-mining)**
* **[TreasureDAO TIP - 11](https://treasuredao.freeflarum.com/d/31-tip-11-next-stage-of-magic-lp-emissions)**
* **[TreasureDAO TIP - 12](https://treasuredao.freeflarum.com/d/33-tip-12-creator-royalties-on-the-treasure-marketplace)**
* **[TreasureDAO Discord](https://discord.gg/treasuredao)**
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)      | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24)  | `Calculations` | `3808222`  |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)      |    `Router`    | `5655918`  |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957) |    `Router`    | `3796241`  |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506)  |    `Router`    | `2457904`  |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                              |      Type      | StartBlock | MultiCall | Status |
| ----------------------------------------------------------------------------------- | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603`  |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120`  |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056`  |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    |    `73`    |    ✅     |   🛠    |
# Gamma Strategies Subgraph

### Vault Input Token, Pirce per share
Gamma Strategies vaults work with two input tokens that corresponds to the underlying Uniswap v3 pool. To track this using our standardised schema, the `inputToken` is set as the `outputToken` of the vault.  The `_UnderlyingToken` entity tracks the actual two tokens used.
Due to the above, the pricePerShare has been set to null in this subgraph.

### Total Value Locked (TVL) USD

Sum across all Vaults: 

`Vault TVL`

### Total Revenue USD
The source of revenue from each vault comes from trading fees collected by providing liquidity to the underlying uniswap v3 pool. Trading fees are collected whenever `rebalance` is called on the hypervisor vault.

Sum across all Vaults:

'`Total Fees collected`'

### Protocol-Side Revenue USD
Gamma Strategies takes a 10% performance fee from the trading fees collected by its vaults. This fee is hardcoded in the vault contract. The performance fee collected is used to buyback GAMMA and distributed to GAMMA stakers. In this subgraph we only consider the USD value of the fees collected pre-GAMMA buyback.

Sum across all Vaults:

`(Vault Revenue * Vault Performance Fee)`

### Supply-Side Revenue USD
The remain 90% of the of trading fees are accrued to LPs of the vault and re-invested automatically during each `rebalance` call.  The USD value of this is calculated at the time of the rebalance call.

Sum across all Vaults

`((Vault Revenue * (1 - Vault annualized Performance Fee))`

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol vaults via the following functions:

`Deposit`

`Withdraw`

###  Reward Token Emissions Amount

No reward tokens are provided

###  Protocol Controlled Value

To be added

## Links

- Protocol website: https://gamma.xyz/
# Data Apps

Here are some simple data apps built using [Subgrounds](https://github.com/Protean-Labs/subgrounds) and [Streamlit](https://streamlit.io/) in Python.

- **DEXs Dashboard**: A python dashboard for Decentralized Exchanges such as Sushiswap, Curve, Uniswap etc.
- **Uniswap Analytics**: A dashboard breaking down various metrics of Uniswap v3 across different networks
- **Whale Watcher**: A real-time tracker for large transactions on Uniswap v3
# Abracadabra Lending Protocol Subgraph (Extended)

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Markets:

`Total Collateral Tokens in USD from deposits and withdrawals`

### Total Revenue USD

Sum across all Markets:

`Borrow Opening Fee * MIM Borrwed + Interest Rate * Amount MIM Borrowed + Liquidation Fee * Collateral Liquidated`

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

`25% of Total Revenue USD is allocated to the Protocol Treasury`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

`75% of Total Revenue USD is awarded backed to Spell Stakers`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Borrows`

`Repays`

`Deposits`

`Withdraws`

`Liquidations`

`Staking`

### Total Volume USD

Sum across all Markets:

`Amount of Borrows and Repays`

### Input Token Balances

Amount of collateral for each Market

`Sum of Deposits and Withdrawals`

### Output Token Supply

Amount of MIM tokens minted for each Market

`Sum of Borrows minus Repays`

### NO Reward Token Emissions

## References and Useful Links

- Protocol: https://abracadabra.money/
- Analytics: http://dashboard.abracadabra.money/
- Docs: https://wizard69.gitbook.io/abracadabra-money/
- Smart contracts: https://github.com/Abracadabra-money/bentobox-strategies
- Deployed addresses: https://docs.abracadabra.money/our-ecosystem/our-contracts

## Smart Contracts Interactions

![Abracadabra](../../docs/images/protocols/abracadabra.png "Abracadabra")

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)      | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24)  | `Calculations` | `3808222`  |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)      |    `Router`    | `5655918`  |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957) |    `Router`    | `3796241`  |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506)  |    `Router`    | `2457904`  |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                              |      Type      | StartBlock | MultiCall | Status |
| ----------------------------------------------------------------------------------- | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603`  |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120`  |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056`  |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    |    `73`    |    ✅     |   🛠    |
# Subgraphs

This repo contains subgraphs defined using a set of standardized schemas. These subgraphs are used to extract raw blockchain data and transform them into meaningful metrics, for products and analytics. Our goal is to build a subgraph for every DeFi protocol in the space.

## Contribution Guidelines

- Decide which protocol you want to build a subgraph for.
- Fork this repository.
- Add a folder under `subgraphs` with the name of the protocol you want to work on.
- Copy over the corresponding schema from the root folder. For example, if you are working on a yield aggregator, you should copy over `schema-yield.graphql` to your folder and rename it to `schema.graphql`. Note `schema-common.graphql` is used for schema design and reference, and should never be used for implementation.
- Build the subgraph within that folder. Feel free to use the [reference subgraph](./subgraphs/_reference_/) as a reference.
- Submit a PR (pull request) to this repo after you are done. Make sure you submit your PR as a draft if it's a work-in-progress. Include a link to your deployment in your PR description.

## Recommended Development Workflow

- Start with understanding the protocol. An easy start could be interacting with the protocol UI on testnets, check transaction details on Etherscan and pay attention to key events that are emitted.
- Go over the smart contracts. Identify the ones that we need to pull data from.
  - Usually each protocol has a factory contract that's responsible for tracking other contracts (e.g. Uniswap's Factory contract, Aave's Lending Pool Registry, Yearn's Registry).
  - Also a pool/vault contract that's responsible for pool level bookkeeping and transactions (e.g. Uniswap's Pair contract, Yearn's Vault contract, Aave's Lending Pool contract).
- Go over the schema and think about what data are needed from smart contract events/calls to map to the fields in each entity.
  - It's easiest to start with more granular entities and build up to aggregated data.
  - For example, usually it's easier to start writing mappings for transactions and usage metrics.
- Go over the documents in the `docs` folder. That should answer lots of questions you may have.
- Implement the mappings, deploy and test your data using either Hosted Service or The Graph Studio.
- For metrics calculation (e.g. revenue, fees, TVL), please refer to the `README.md` in the protocol's subgraph folder for methodology. There is also a broader explanation of how different fields are defined in the schema in `docs/Schema.md`. Feel free to reach out to me if anything isn't clear.
- We've built a handy debugging/validation dashboard for you to quickly visualize the data in your subgraph. It's deployed to [subgraphs.xyz](https://subgraphs.xyz/) and the source code is under `dashboard` if you want to spin it up locally.
- Verify your subgraph against other sources and include specific links to these sources in the README. Below are some common sources:
  - Project's official analytics dashboard
  - [DeFi Llama](https://defillama.com/) (for TVL)
  - [Dune Analytics](https://dune.xyz/)
  - [TokenTerminal](https://www.tokenterminal.com/terminal)

## Resources

### Introductory

- Learn the basics of GraphQL: [https://graphql.org/learn/](https://graphql.org/learn/)
- Query subgraphs using GraphQL: https://thegraph.com/docs/en/developer/graphql-api/
- Get familiar with The Graph: [https://thegraph.academy/developers/](https://thegraph.academy/developers/)
- Defining a subgraph: [https://thegraph.academy/developers/defining-a-subgraph/](https://thegraph.academy/developers/defining-a-subgraph/)
- Creating a subgraph: https://thegraph.com/docs/en/developer/create-subgraph-hosted/
- Deploying a subgraph using The Graph Studio: [https://thegraph.com/docs/en/studio/deploy-subgraph-studio/](https://thegraph.com/docs/en/studio/deploy-subgraph-studio/)

### Intermediate

- [AssemblyScript API](https://thegraph.com/docs/en/developer/assemblyscript-api/)
- [Unit Test Using Matchstick](https://thegraph.com/docs/en/developer/matchstick/)
- [Building a Subgraph for Sushiswap](https://docs.simplefi.finance/subgraph-development-documentation/sushiswap-subgraph-development)
- [Building a Subgraph for Loopring](https://www.youtube.com/watch?v=SNmzhwlQqgU)
  - Using templates (dynamic data sources)
  - Indexing proxies

### Advanced

- Building ambitious subgraphs (Part I): https://www.youtube.com/watch?v=4V2o5YJooOM
  - Schema design
  - Error handling
  - Interface and union types
- Building ambitious subgraphs (Part II) https://www.youtube.com/watch?v=1-8AW-lVfrA
  - Performance tips and tricks (for both mappings and queries)
- [Documentation for the graph-node](https://github.com/graphprotocol/graph-node/tree/master/docs)

## Development Status

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.  
✅ = Production-ready.  

| Protocol |  Status | Versions † | Deployments |
| ------- |  :------: | --- | --- |
| **DEX AMM** |    | |
| [Apeswap](https://apeswap.finance/) | 🛠 | 1.3.0 / 1.1.1 / 1.0.0 | [![Apeswap BSC](./docs/images/chains/bsc.png)](https://thegraph.com/hosted-service/subgraph/messari/apeswap-bsc) [![Apeswap Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/apeswap-polygon) |
| [Balancer v2](https://balancer.fi/) | 🛠 | 1.3.0 / 1.1.2 / 1.0.0 | [![Balancer V2 Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/balancer-v2-ethereum) [![Balancer V2 Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/balancer-v2-arbitrum) [![Balancer V2 Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/balancer-v2-polygon)|
| [Bancor v3](https://try.bancor.network/) | 🛠 | 1.3.0 / 1.0.0 / 1.0.0 | [![Bancor V3 Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/bancor-v3-ethereum) |
| [Beethoven X](https://beets.fi/) | 🛠 | 1.3.0 / 1.1.2 / 1.0.0 | [![Beethoven X Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/beethoven-x-fantom) [![Beethoven X Optimism](./docs/images/chains/optimism.png)](https://thegraph.com/hosted-service/subgraph/messari/beethoven-x-optimism)  |
| [Curve](https://curve.fi/) | 🛠 | 1.2.1 / 1.0.0 / 1.0.0 | [![Curve Finance Gnosis](./docs/images/chains/xdai.png)](https://thegraph.com/hosted-service/subgraph/messari/curve-finance-gnosis) [![Curve Finance Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/curve-finance-polygon) [![Curve Finance Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/curve-finance-arbitrum) [![Curve Finance Optimism](./docs/images/chains/optimism.png)](https://thegraph.com/hosted-service/subgraph/messari/curve-finance-optimism) [![Curve Finance Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/curve-finance-fantom) [![Curve Finance Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/curve-finance-avalanche) [![Curve Finance Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/curve-finance-ethereum) |
| DODO v2 | 🔨 | | |
| [Ellipsis Finance](https://ellipsis.finance/) | 🛠 | 1.2.1 / 1.0.0 / 1.0.0 | [![Ellipsis Finance BSC](./docs/images/chains/bsc.png)](https://thegraph.com/hosted-service/subgraph/messari/ellipsis-finance-bsc) |
| [Quickswap](https://quickswap.exchange/#/swap) | 🛠 | 1.3.0 / 1.0.0 / 1.0.0 | [![Quickswap Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/quickswap-polygon) |
| Platypus Finance | 🔨 | | |
| [Saddle Finance](https://saddle.finance/#/) | 🛠 | 1.3.0 / 1.1.0 / 1.0.0 | [![Saddle Finance Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/saddle-finance-ethereum) [![Saddle Finance Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/saddle-finance-arbitrum) [![Saddle Finance Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/saddle-finance-fantom) [![Saddle Finance Optimism](./docs/images/chains/optimism.png)](https://thegraph.com/hosted-service/subgraph/messari/saddle-finance-optimism) |
| [Solarbeam](https://solarbeam.io/) | 🛠 | 1.3.0 / 1.0.0 / 1.0.0 | [![Solarbeam Moonriver](./docs/images/chains/moonriver.png)](https://thegraph.com/hosted-service/subgraph/messari/solarbeam-moonriver) |
| [SpiritSwap](https://www.spiritswap.finance/) | 🛠 | 1.3.0 / 1.0.0 / 1.0.0 | [![SpiritSwap Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/spiritswap-fantom) |
| [SpookySwap](https://spooky.fi/) | 🛠 | 1.3.0 / 1.1.1 / 1.0.0 | [![SpookySwap Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/spookyswap-fantom) |
| [Ubeswap](https://ubeswap.org/) | 🛠 | 1.3.0 / 1.1.1 / 1.0.0 | [![Ubeswap Celo](./docs/images/chains/celo.png)](https://thegraph.com/hosted-service/subgraph/messari/ubeswap-celo) |
| [VVS Finance](https://vvs.finance/) | 🛠 | 1.3.0 / 1.1.1 / 1.0.0 | [![VVS Finance Cronos](./docs/images/chains/cronos.png)](https://graph.cronoslabs.com/subgraphs/name/messari/vvs-finance) |
| [SushiSwap](https://www.sushi.com/) | 🛠 | 1.3.0 / 1.1.1 / 1.0.0 | [![SushiSwap Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-ethereum) [![SushiSwap Celo](./docs/images/chains/celo.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-celo) [![SushiSwap Fuse](./docs/images/chains/fuse.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-fuse) [![SushiSwap Moonriver](./docs/images/chains/moonriver.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-moonriver) [![SushiSwap Moonbeam](./docs/images/chains/moonbeam.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-moonbeam) [![SushiSwap Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-avalanche) [![SushiSwap BSC](./docs/images/chains/bsc.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-bsc) [![SushiSwap Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-arbitrum) [![SushiSwap Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-fantom) [![SushiSwap Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-polygon) [![SushiSwap Gnosis](./docs/images/chains/xdai.png)](https://thegraph.com/hosted-service/subgraph/messari/sushiswap-gnosis) |
| [Trader Joe](https://traderjoexyz.com/home#/) | 🛠 | 1.3.0 / 1.0.0 / 1.0.0 | [![Trader Joe Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/trader-joe-avalanche) |
| [Uniswap v2](https://uniswap.org/) | 🛠 | 1.3.0 / 1.1.1 / 1.0.0 | [![Uniswap V2](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/uniswap-v2-ethereum) |
| [Uniswap v3](https://uniswap.org/) | 🛠 | 1.3.0 / 1.1.1 / 1.0.0 | [![Uniswap V3](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/uniswap-v3-ethereum) [![Uniswap V3 Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/uniswap-v3-polygon) [![Uniswap V3 Optimism](./docs/images/chains/optimism.png)](https://thegraph.com/hosted-service/subgraph/messari/uniswap-v3-optimism) [![Uniswap V3 Arbtitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/uniswap-v3-arbitrum)|
| **Lending Protocols** |    | |
| [Aave v2](https://aave.com/) | 🛠 | 1.3.0 / 1.2.3 / 1.0.0 | [![Aave V2 Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v2-ethereum) [![Aave V2 Ethereum ARC](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-arc-ethereum) [![Aave V2 Ethereum RWA](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-rwa-ethereum) [![Aave V2 Ethereum AMM](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-amm-ethereum) [![Aave V2 Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v2-avalanche) [![Aave V2 Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v2-polygons) |
| [Aave v3](https://aave.com/) | 🔨 | 1.3.0 / 1.0.0 / 1.0.0 | [![Aave V3 Optimism](./docs/images/chains/optimism.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v3-optimism) [![Aave V3 Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v3-polygon) [![Aave V3 Harmony](./docs/images/chains/harmony.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v3-harmony) [![Aave V3 Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v3-fantom) [![Aave V3 Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v3-avalanche) [![Aave V3 Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/aave-v3-arbitrum) |
| [Aurigami](https://www.aurigami.finance/) | 🛠 | 1.3.0 / 1.0.6 / 1.0.0  | [![Aurigami Aurora](./docs/images/chains/aurora.png)](https://thegraph.com/hosted-service/subgraph/messari/aurigami-aurora) |
| [Bastion Protocol](https://bastionprotocol.com/) | 🛠 | 1.3.0 / 1.0.9 / 1.0.0 | [![Bastion Protocol Aurora](./docs/images/chains/aurora.png)](https://thegraph.com/hosted-service/subgraph/messari/bastion-protocol-aurora) |
| [Banker Joe](https://traderjoexyz.com/lending#/) | 🛠 | 1.3.0 / 1.0.5 / 1.0.0 | [![Banker Joe Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/banker-joe-avalanche) |
| [BENQI](https://benqi.fi/) | 🛠 | 1.3.0 / 1.0.6 / 1.0.0 | [![BENQI Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/benqi-avalanche) |
| [Compound](https://compound.finance/) | 🛠 | 1.3.0 / 1.6.6 / 1.0.0 | [![Compund Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/compound-ethereum) |
| [CREAM Finance](https://cream.finance/) | 🛠 | 1.3.0 / 1.0.6 / 1.0.0 | [![CREAM Finance Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/cream-finance-arbitrum) [![CREAM Finance Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/cream-finance-polygon) [![CREAM Finance BSC](./docs/images/chains/bsc.png)](https://thegraph.com/hosted-service/subgraph/messari/cream-finance-bsc) [![CREAM Finance Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/cream-finance-ethereum)|
| [dForce](https://dforce.network) | 🛠 | 1.3.0 / 1.0.2 / 1.0.0 | [![dforce Arbitrum](./docs/images/chains/arbitrum.png)]() [![dforce Avalanche](./docs/images/chains/avalanche.png)]() [![dforce BSC](./docs/images/chains/bsc.png)]() [![dforce Ethereum](./docs/images/chains/ethereum.png)]() [![dforce Optimism](./docs/images/chains/optimism.png)]() [![dforce Polygon](./docs/images/chains/matic.png)]() |
| Euler Finance | 🔨 | | |
| [Geist](https://geist.finance/markets) | 🛠 | 1.3.0 / 1.0.1 / 1.0.0 | [![Geist Protocl](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/geist-fantom) |
| [Iron Bank](https://app.ib.xyz/) | 🛠 | 1.3.0 / 1.0.8 / 1.0.0 | [![Iron Bank Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/iron-bank-fantom) [![Iron Bank Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/iron-bank-avalanche) [![Iron Bank Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/iron-bank-ethereum) |
| [Maple Finance](https://www.maple.finance/) | 🛠 | 1.2.1 / 1.1.0 / 1.0.0 | [![Maple Finance Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/maple-finance-ethereum) |
| [Moonwell Finance](https://moonwell.fi/) | 🛠 | 1.3.0 / 1.0.10 / 1.0.0 | [![Moonwell Moonriver](./docs/images/chains/moonriver.png)](https://thegraph.com/hosted-service/subgraph/messari/moonwell-moonriver)  |
| Notional Finance | 🔨 | | |
| [Rari Fuse](https://app.rari.capital/fuse) | 🔨 | 1.3.0 / 1.0.16 / 1.0.0 | [![Rari Fuse Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/rari-fuse-ethereum) [![Rari Fuse Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/rari-fuse-arbitrum) |
| [SCREAM](https://scream.sh/) | 🛠 | 1.3.0 / 1.0.6 / 1.0.0 | [![SCREAM Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/scream-fantom)  |
| [Venus Protocol](https://venus.io/) | 🛠 | 1.3.0 / 1.0.6 / 1.0.0 | [![Venus Protocol BSC](./docs/images/chains/bsc.png)](https://thegraph.com/hosted-service/subgraph/messari/venus-protocol-bsc) |
| [Yeti Finance](https://yeti.finance/) | 🔨 | | |
| **CDPs** |    | |
| [Abracadabra](https://abracadabra.money/) | 🛠 | 1.3.0 / 1.0.5 / 1.0.0| [![Abracadabra Money](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/abracadabra-money-ethereum) [![Abracadabra Money](./docs/images/chains/bsc.png)](https://thegraph.com/hosted-service/subgraph/messari/abracadabra-money-bsc) [![Abracadabra Money](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/abracadabra-money-arbitrum) [![Abracadabra Money](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/abracadabra-money-fantom) [![Abracadabra Money](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/abracadabra-money-avalanche) |
| Alchemix |   | | |
| [Inverse Finance](https://www.inverse.finance/) | 🛠 | 1.3.0 / 1.2.2 / 1.0.0  | [![Inverse Finance Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/inverse-finance-ethereum)|
| [Liquity](https://www.liquity.org/) | 🛠 | 1.3.0 / 1.1.4 / 1.0.1 | [![Liquity Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/liquity-ethereum) |
| [MakerDAO](https://makerdao.com/en/) | 🛠 | 1.3.0 / 1.1.0 / 1.0.0 | [![MakerDAO Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/makerdao-ethereum?selected=playground) |
| [QiDAO](https://app.mai.finance/) | 🛠 | 1.3.0 / 1.1.0 / 1.0.0 | [![QiDAO Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/qidao-arbitrum) [![QiDAO Avalanche](./docs/images/chains/avalanche.png)](https://thegraph.com/hosted-service/subgraph/messari/qidao-avalanche) [![QiDAO BSC](./docs/images/chains/bsc.png)](https://thegraph.com/hosted-service/subgraph/messari/qidao-bsc) [![QiDAO Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/qidao-fantom) [![QiDAO Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/qidao-polygon) [![QiDAO Moonriver](./docs/images/chains/moonriver.png)](https://thegraph.com/hosted-service/subgraph/messari/qidao-moonriver) [![QiDAO Optimism](./docs/images/chains/optimism.png)](https://thegraph.com/hosted-service/subgraph/messari/qidao-optimism) [![QiDAO Gnosis](./docs/images/chains/xdai.png)](https://thegraph.com/hosted-service/subgraph/messari/qidao-gnosis) |
| **Yield Aggregators** |     | |
| [Arrakis Finance](https://www.arrakis.finance/) |  | | |
| [Badger DAO](https://badger.com/) | 🔨 | 1.3.0 / 1.0.0 / 1.0.0 | [![Badger Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/badgerdao-ethereum) |
| Beefy Finance | 🛠 | | |
| [Belt Finance](https://belt.fi/landing) | 🛠 | 1.2.1 / 1.0.0 / 1.0.0 | [![Belt BSC](./docs/images/chains/bsc.png)](https://thegraph.com/hosted-service/subgraph/messari/belt-finance-bsc) |
| [Convex Finance](https://www.convexfinance.com/) | 🛠 | 1.3.0 / 1.1.1 / 1.0.0 | [![Convex Finance Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/convex-finance-ethereum) |
| [Gamma Strategy](https://www.gamma.xyz/) | 🛠 | 1.2.1 / 1.0.0 / 1.0.0 | [![Gamma Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/gamma-ethereum) [![Gamma Polygon](./docs/images/chains/matic.png)](https://thegraph.com/hosted-service/subgraph/messari/gamma-polygon) |
| Harvest Finance | 🔨  | | |
| Liquid Driver | 🔨  | | |
| [Rari Vaults](https://rari.capital/) | 🛠 | 1.2.1 / 1.3.13 / 1.0.0 | [![Rari Vaults Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/rari-vaults-ethereum)|
| [Stake DAO](https://stakedao.org/) | 🛠 | 1.3.0 / 1.3.0 / 1.0.0 | [![Stake DAO](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/stake-dao-ethereum)|
| [Tokemak](https://www.tokemak.xyz/) | 🛠 | 1.2.1 / 1.0.0 / 1.0.0 | [![Tokemak](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/tokemak-ethereum) |
| Vesper Finance | 🔨 | | |
| Yield Yak | 🔨 | | |
| [Yearn v2](https://yearn.fi/) | 🛠 | 1.3.0 / 1.2.0 / 1.0.0 | [![Yearn V2 Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/yearn-v2-ethereum) [![Yearn V2 Arbitrum](./docs/images/chains/arbitrum.png)](https://thegraph.com/hosted-service/subgraph/messari/yearn-v2-arbitrum) [![Yearn V2 Fantom](./docs/images/chains/fantom.png)](https://thegraph.com/hosted-service/subgraph/messari/yearn-v2-fantom) |
| **Governance** |    | |
| ENS Governor | 🛠 | 1.0.0 / 1.0.0 / 1.0.0 | [![ENS Governor](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/ens-governance) |
| FEI Governor | 🔨 | | |
| Silo Finance Governor | 🔨 | | |
| Hop Protocol Governor | 🔨 | | |
| **Network Subgraph** |    | |
| EVM | 🔨 | | |
| Cosmos | 🔨 | | |
| NEAR | 🔨 | | |
| Arweave | 🔨 | | |
| **ERC20 Subgraph** |    | |
| ERC20 | 🔨 | 1.0.0 / 1.0.0 / 1.0.0 | [![ERC20 Ethereum](./docs/images/chains/ethereum.png)](https://thegraph.com/hosted-service/subgraph/messari/erc20-ethereum) |
| **ERC721 Subgraph** |    | |
| TBD | 🔨 | | |

† Versions are schema version, subgraph version, methodology version respectively
# BadgerDAO Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Vaults: 

`Vault TVL`

### Total Revenue USD

Sum across all Vaults:

`Total Yield`

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Note that BadgerDAO applies a Variable Withdrawal Fee and Variable Performance Fee

Sum across all Vaults:

`(Vault Revenue * Vault Annualized Performance Fee) + (Withdraw Amount * Vault Withdraw Fee)`

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Note that this is the remaining Yield after Protocol Fees

Sum across all Vaults

`((Vault Revenue * (1 - Vault annualized Performance Fee)) - (Withdraw Amount * Vault Withdraw Fee)`

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposit`

`Withdraw`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added

## Links

- Protocol website: https://badger.com/
- Protocol documentation: https://badger-finance.gitbook.io/badger-finance/
- Smart contracts: https://github.com/Badger-Finance/badger-system
- Deployed addresses: https://docs.badger.com/badger-finance/contract-addresses
- Existing subgraphs: https://github.com/Badger-Finance/badger-subgraph
# GMX Protocol Subgraph Metrics Methodology v1.0.0

Introduction:

GMX is a decentralized spot and perpetual exchange featuring a unique multi-asset pool that earns fees for liquidity providers. The platform supports swaps with minimal fees and trades without price impact.

Note:

* GMX is currently running on Arbitrum and Avalanche.
* Before its rebranding to “GMX” the protocol was called “Gambit” and ran on Binance Smart Chain. After the rebranding Gambit has been phased out and there is no noteworthy activity anymore which is why BSC was not considered in this report.

## Useful Links

* Protocol
    * [https://gmx.io/](https://gmx.io/)
* Docs
    * [https://gmxio.gitbook.io/gmx/](https://gmxio.gitbook.io/gmx/)
    * [https://gmx-io.notion.site/gmx-io/GMX-Technical-Overview-47fc5ed832e243afb9e97e8a4a036353](https://gmx-io.notion.site/gmx-io/GMX-Technical-Overview-47fc5ed832e243afb9e97e8a4a036353)
* Smart contracts
    * [https://github.com/gmx-io](https://github.com/gmx-io)
* Deployed addresses
    * [https://gmxio.gitbook.io/gmx/contracts](https://gmxio.gitbook.io/gmx/contracts)
* Protocol stats
    * [https://stats.gmx.io/](https://stats.gmx.io/)
    * [https://gmx.io/dashboard](https://gmx.io/dashboard)
* Governance forum
    * [https://gov.gmx.io](https://gov.gmx.io)
* GMX Medium
    * [https://medium.com/@gmx.io](https://medium.com/@gmx.io)

## Usage Metrics

**Active Users, Total Unique Users & Daily Transaction Count**

Transactions of interest on GMX include:

* Swapping (excluding swaps of the protocol token)
* Opening a position (long / short)
* Closing a position (long / short; 3 options: manual closing, stop-loss, liquidations)
* Staking GMX
* Minting GLP
* Redeeming GLP
* Depositing collateral
* Withdrawing collateral
* Compounding esGMX
* Claiming esGMX
* Staking GLP should not be considered because after buying GLP, these tokens will be automatically staked so this is not a transaction actively triggered by users.

## Financial Metrics

**Total Value Locked USD**

TVL = GMX staked (all chains) + GLP supply * GLP price

Note that GLP is specific to the network and the price & supply will differ between Arbitrum & Avalanche. So for TVL among all chains, it should be calculated as follows: \

TVL = GMX staked (all chains) + (GLP supply on Arbitrum * GLP price on Arbitrum) + (GLP supply on Avalanche * GLP price on Avalanche)

GMX has a Floor Price Fund (FPF). The assets in the FPF were not deposited in the protocol and should therefore not be included in the TVL calculation. 

Assets in the FPF are accumulated by: 

* provision of GMX/ETH liquidity that is provided and owned by the protocol
* 50% of funds received through[ Olympus bonds](https://pro.olympusdao.finance/#/partners/GMX) 

**Protocol Controlled Value USD**

There is a sale of 10,000 GMX each month through Olympus bonds Olympus Pro-Bond marketplace for protocol-owned liquidity, 50% goes to the floor price fund, and 50% for marketing activities. The starting price is at 0.9 * GMX market price at the time.

Source: https://gov.gmx.io/t/treasury-diversification-through-the-sale-of-esgmx-tokens/73/29

**Total Revenue USD**

Total Revenue generated on GMX is the sum of:

1. Fees generated from swapping
2. Fees generated from minting GLP
3. Fees generated from burning GLP
4. Fees from liquidations
5. Fees from margin trading

As a calculation, this could be described as:

Total Revenue = Fees from swapping + Fees from minting GLP + Fees from burning GLP + Fees from liquidations + Fees from margin trading

Total Revenue for GMX can be described as the sum of all Platform Fees.

**Supply Side Revenue USD**

In general fees for GMX are split 30/70 between staked GMX/GLP and paid out in either wETH or wAVAX depending on which chain the user staked their assets. 

The two assets GMX and GLP can be defined as follows:

* GMX: The utility and governance token, accrues 30% of the platform's generated fees (if staked).
* GLP: The platform's liquidity provider token. Holders of the GLP token earn Escrowed GMX rewards and 70% of platform fees distributed in ETH/AVAX.

For GMX the supply side revenue can be calculated as the share of trading fees that goes to the liquidity providers:

Supply Side Revenue = (Total Revenue - Costs of Keepers - Referral Rewards)  * Supply Side Fees

  \
Supply Side Fees in this case would be equal to a fixed parameter of 70%. Platform Fees in the case of GMX are equal to Total Revenues (see the formula in the respective section) since all fees are distributed between staked GMX & GLP holders. Referral Rewards are further explained in the section ‘Reward Tokens & Reward Token Emissions Amount’.

**Protocol Revenue USD**

For GMX protocol revenue can be calculated as the share of trading fees that goes to the stakers of the protocol token. Staked GMX receives three types of rewards:

* Escrowed GMX
* Multiplier Points
* ETH / AVAX Rewards (Platform Fees)

Protocol Revenue = (Total Revenue - Costs of Keepers - Referral Rewards) * (1- Supply Side Fees) \
 \
Supply Side Fees in this case would be equal to a fixed parameter of 70%. Platform Fees in the case of GMX are equal to Total Revenues (see the formula in the respective section) since all fees are distributed between staked GMX & GLP holders.

## Pool-Level Metrics

**Pool Total Value Locked USD**

The Pool TVL of GMX is the No. of Assets Deposited in the GLP * Price of the Asset. On the GMX dashboard (https://gmx.io/dashboard), this is shown as “GLP Index Composition”. Please note that there are two GLP: One for Arbitrum and one for Avalanche. 

Pool Total Value Locked = No. of Assets Deposited in the GLP * Price of the Asset

**Reward Tokens & Reward Token Emissions Amount**

**Escrowed GMX:**

Escrowed GMX was and will be distributed at the following rate starting from 1 Sep 2021:

* 100,000 Escrowed GMX tokens per month to GMX stakers
* 100,000 Escrowed GMX tokens per month to GLP holders on Arbitrum
* 50,000 Escrowed GMX tokens per month to GLP holders on Avalanche from Jan 2022 - Mar 2022
* 25,000 Escrowed GMX tokens per month to GLP holders on Avalanche from Apr 2022 - Dec 2022

Escrowed GMX rewards are distributed every second to staked tokens and can be converted into GMX tokens through vesting. Note for future maintenance of the subgraph: A very recent governance decision will update esGMX emissions from fixed to dynamic starting from June 2022. 

(Source: https://snapshot.org/#/gmx.eth/proposal/0xb370249628b2226c6a7e771b2959c3b2e80eada36ad3618a7fc39f964213643e)

**Multiplier Points: **

GMX stakers receive Multiplier Points every second at a fixed rate of 100% APR. Example: 1000 GMX staked for one year would earn 1000 Multiplier Points. Multiplier points can be staked for fee rewards. Each multiplier point will earn the same amount of ETH / AVAX rewards as a regular GMX token. 

When GMX or Escrowed GMX tokens are unstaked, the proportional amount of Multiplier Points is burnt. For example, if 1000 GMX is staked and 500 Multiplier Points have been earned so far, then unstaking 300 GMX would burn 150 (300 / 1000 * 500) Multiplier Points. The burn will apply to the total amount of Multiplier Points which includes both staked and unstaked Multiplier Points.

**Referral Rewards:**

The GMX Referral Program provides fee discounts and the earning of rebates. In the course of this program, esGMX is paid out to Tier 3 referrers. The payout price of esGMX is based on the 7-day TWAP of GMX. Note that there is a cap of 5000 esGMX distributed per week. If the price of GMX is $30 the full 5% bonus can be paid for total Tier 3 referral volumes up to $3 billion per week. esGMX tokens distributed for this program do not require GMX or GLP to vest. The discounts and rebates are distributed as ETH on Arbitrum and AVAX on Avalanche every Wednesday.

**ETH Rewards:**

In their launch announcement on Medium, additional ETH rewards were mentioned. They read as follows: With the start of GMX on Arbitrum, $72,072.62 USD worth of ETH that has been collected from trading fees on BSC was distributed to GMX stakers over 4 weeks. However, these rewards are not mentioned in the official documentation.  \
(Source: https://medium.com/@gmx.io/gmx-launch-plan-8ecf60254410)
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)      | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24)  | `Calculations` | `3808222`  |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)      |    `Router`    | `5655918`  |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957) |    `Router`    | `3796241`  |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506)  |    `Router`    | `2457904`  |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                              |      Type      | StartBlock | MultiCall | Status |
| ----------------------------------------------------------------------------------- | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603`  |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120`  |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056`  |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    |    `73`    |    ✅     |   🛠    |
# Compound v2 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Pool Deposit TVL`

### Total Revenue USD

Sum across all Pools:

`(Pool Borrow Amount * Pool Borrow Rate)`

Note: This currently excludes Liquidations

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Pool Oustanding Borrow Amount * Pool Borrow Rate) * (Pool Reserve Factor)`

Note: This currently excludes Liquidations

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Pool Outstanding Borrows * Pool Borrow Rate) * (1 - Pool Reserve Factor)`

Note: This currently excludes Liquidations

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

### Reward Token Emissions Amount

Amount of reward tokens (COMP) distributed each day.

Following calculation gives the COMP distributed (in COMP) to suppliers OR borrowers

`COMP per block * 4 * 60 * 24`

### Protocol Controlled Value

Not applicable to Compound v2

## Reference and Useful Links

Protocol: https://compound.finance/

Docs: https://compound.finance/docs

Smart contracts: https://github.com/compound-finance/compound-protocol

Deployed addresses: https://compound.finance/docs#networks

Existing subgraphs: https://github.com/graphprotocol/compound-v2-subgraph

Existing Subgraph in Studio: https://thegraph.com/hosted-service/subgraph/graphprotocol/compound-v2

Explanation of lending metrics: https://docs.aave.com/risk/asset-risk/risk-parameters

Dune Dashboard for Testing: https://dune.xyz/messari/Messari:-Compound-Macro-Financial-Statements
# Bancor V3 Subgraph Methodology v1.0.0

## Contract Details

![Bancor V3 Interaction](../../docs/images/protocols/bancor-v3.png)

Edit the chart [here](https://excalidraw.com/#json=8pcmLXt3KH0HR1BmvGgc4,xXC-0PZvj5s1kGpIX4Fwhw).

## Useful Links

* Bancor V3: [https://try.bancor.network/](https://try.bancor.network/)
* Bancor V3 Proposal Document: 
* Bancor V3 Technical Docs: [Bancor V3 Technical Docs](https://docs.bancor.network/about-bancor-network/bancor-v3)
* Introducing Bancor V3: [Introducing Bancor 3](https://blog.bancor.network/introducing-bancor-3-962a3c601c25)
* Bancor V3 Useful Resources: [Resources - Bancor V3 Technical Docs](https://docs.bancor.network/about-bancor-network/resources)
* Bancor V3 Presentation by Mark Richardson (Head of Bancor Research): https://www.youtube.com/watch?v=qi1geks1n8A

## Bancor V3 Deployment

**Last Update: 13/05/22**

Bancor V3 was deployed on the 11th May 2022 on the Ethereum mainnet. 

This is currently the only chain where Bancor V3 is deployed.

All metrics in this document are for** _Ethereum mainnet_** only.

## 

## Usage Metrics

**Active Users, Total Unique Users & Daily Transaction Count**

Bancor V3 has a number of transactions that users can execute. 

The transactions of interest according to the Usage Metrics guidelines are:

* Swapping tokens using liquidity pools
* Providing liquidity using liquidity pools (adding and removing liquidity)
* Flashloan trading

These transactions are explained in the table below.

<table>
  <tr>
   <td><strong>Transaction Type</strong>
   </td>
   <td><strong>Transaction Description</strong>
   </td>
   <td><strong>Example</strong>
   </td>
  </tr>
  <tr>
   <td>Swap
   </td>
   <td>When a user (address) swaps one token for the equivalent in value of another
   </td>
   <td>User A swapped 1 ETH for 2000 USDC
   </td>
  </tr>
  <tr>
   <td>Add Liquidity
   </td>
   <td>When a user (address) adds liquidity to a liquidity pool in the protocol
   </td>
   <td>User A added 100 LINK to the LINK pool protocol
   </td>
  </tr>
  <tr>
   <td>Remove Liquidity
   </td>
   <td>When a user (address) removes liquidity from a liquidity pool in the protocol
   </td>
   <td>User A removed 100 LINK from the LINK pool in the protocol
   </td>
  </tr>
  <tr>
   <td>Flashloan
   </td>
   <td>When a user (address) borrows an amount of an asset from the protocol which needs to be repaid within 1 block
   </td>
   <td>User A flashloaned 100 ETH from the protocol
   </td>
  </tr>
</table>

### Usage Metrics Definitions

Any address that executes one of the transaction types listed in the table above (Swap, Add/Remove Liquidity or Flashloan) should be considered a user of the protocol.

The core usage metrics of interest are:

* Active Users
* Total Unique Users
* Daily Transaction Count

These metrics are defined and explained in the table below.

**Core Usage Metrics Table**

<table>
  <tr>
   <td><strong>Name</strong>
   </td>
   <td><strong>Description</strong>
   </td>
   <td><strong>Calculation</strong>
   </td>
   <td><strong>Example</strong>
   </td>
  </tr>
  <tr>
   <td>Active Users
   </td>
   <td>Any user (address) that executed one of the transactions (Swap, Add Liquidity, Remove Liquidity or Flashloan)
<p>
There may be a temporal element that is applied to this metric
<p>
E.g Active Users in the last 30 days would be any user (address) that has executed one of the transactions (Swap, Add Liquidity, Remove Liquidity or Flashloan) in the last 30 days
   </td>
   <td>Active Users = Count of distinct users (addresses) that executed one of the transactions (Swap, Add Liquidity, Remove Liquidity or Flashloan)
   </td>
   <td>The following is a list of transactions and the addresses that executed them in the last 1 day:
<ul>

<li>Swap - Address ABC

<li>Add Liquidity - Address DEF

<li>Flashloan - Address GHI

<p>
In this case the Active Users for the last 1 day would be 3
</li>
</ul>
   </td>
  </tr>
  <tr>
   <td>Total Unique Users
   </td>
   <td>The total distinct number of users (addresses) that have ever executed one of the transactions (Swap, Add Liquidity, Remove Liquidity or Flashloan)
   </td>
   <td>Total Unique Users = Count of distinct users (addresses) that have ever executed one of the transactions (Swap, Add Liquidity, Remove Liquidity or Flashloan)
   </td>
   <td>The following is a list of transactions that have occurred in a protocol since launch:
<ul>

<li>Swap - Address ABC

<li>Add Liquidity - Address DEF

<li>Flashloan - Address GHI

<li>Swap - Address ABC

<p>
In this case the Total Unique Users would be 3
</li>
</ul>
   </td>
  </tr>
  <tr>
   <td>Daily Transaction Count
   </td>
   <td>The total distinct number of successful transactions (Swap, Add Liquidity, Remove Liquidity or Flashloan) that occurred in 1 day
   </td>
   <td>Daily Transaction Count = Count of distinct transactions that occurred in 1 day 
   </td>
   <td>The following transactions were recorded for a single day:
<ul>

<li>Swap - Tx Id: 123

<li>Add Liquidity - Tx Id: 456

<li>Flashloan - Tx Id: 789

<li>Swap - Tx Id: 234

<p>
The daily transaction count in this case would be 4
</li>
</ul>
   </td>
  </tr>
</table>

There are additional breakdowns that may facilitate further drill-down analysis if required. These suggested metrics are listed below:

* Active Traders
* Unique Traders
* Daily Swap Transactions
* Active Liquidity Providers
* Total Unique Liquidity Providers
* Daily Liquidity Actions Count
* Active Flashloaners
* Unique Flashloaners
* Daily Flashloaners Count

## Financial Metrics

**Total Value Locked USD**

The Total Value Locked USD on Bancor V3 is calculated by summing the TVL USD across each individual liquidity pool in the protocol.

_TVL USD = SUM of TVL USD IN ALL LIQUIDITY POOLS IN PROTOCOL_

Example:

Let’s assume that there are 4 liquidity pools in the Bancor V3 protocol which are: ETH, BNT, DAI and LINK.

The pools have the following TVL USD each:

* ETH: $1,000,000 USD
* BNT: $1,800,000 USD
* DAI: $2,000,000 USD
* LINK: $1,500,000 USD

In this case, the Total Value Locked USD for the protocol would be: 

_TVL USD = ETH TVL USD + BNT TVL USD + DAI TVL USD + LINK TVL USD = $6,300,000_

**Protocol Controlled Value USD**

There are two metrics worth noting here:

1. BNT locked forever
2. Protocol-owned BNT

About 1:
BNT is locked forever in the protocol as vBNT is burnt. This is because vBNT is needed to unstake BNT.

On Bancor 2.1, vBNT is emitted 1:1 with BNT stakes, and is needed in a 1:1 ratio in order to unstake BNT.
On Bancor 3, vBNT is emitted 1:1 with bnBNT, and is needed in a 1:1 ratio with bnBNT in order to unstake BNT. How much BNT can be unstaked with 1 vBNT can be calculated by using the poolTokenToUnderlying in the BancorNetworkInfo contract.

One can expect the vBNT:BNT price to stabilise around the poolTokenToUnderlying value of vBNT in BNT, but this isn't necessarily true and thus doesn't exactly translate to how much BNT is actually locked forever. As the vBNT and bnBNT are needed 1:1 to unstake poolTokenToUnderlying(BNT, bnBNT), the amount of BNT locked forever can be calculated as follows:

_BNT locked forever = poolTokenToUnderlying(BNT, Amount of vBNT Burned)_

Note: This BNT isn't necessarily protocol controlled. As an example, the protocol could theoretically control no BNT and some BNT would still be locked forever.

About 2:
Protocol controlled BNT can be calculated based on how much bnBNT the protocol owns, by checking the BNTpool balance and using the poolTokenToUnderlying function in BancorNetworkInfo contract.

_Protocol Controlled BNT = poolTokenToUnderlying(BNT, bnBNT in the BNTPool contract)_

Relevant SC addresses:
BNTpool: https://etherscan.io/address/0x02651e355d26f3506c1e644ba393fdd9ac95eaca
BancorNetworkInfo: https://etherscan.io/address/0x8E303D296851B320e6a697bAcB979d13c9D6E760#readProxyContract

Reference links

* Dune Analytics Dashboard: [https://dune.com/Bancor/Bancor-3-Beta](https://dune.com/Bancor/bancor_1)
* Dune Analytics BNT Value Locked Forever Query: [https://dune.com/queries/30032/73935](https://dune.com/queries/30032/73935)
* Bancor Vortex Burner: [Bancor Vortex Burner](https://docs.bancor.network/guides/triggering-the-bancor-vortex-burner)
* Bancor V3 Proposal Document - see Bancor Vortex section: [Bancor V3 Proposal Document](https://docs.google.com/document/d/11UeMYaI_1CWdf_Nu6veUO-vNB5uX-FcVRqTSU-ziDRk/edit#)

**Total Revenue USD**

_Total Revenue USD = Supply Side Revenue USD + Protocol Revenue USD_
_Total Revenue USD = Total Trading Fees USD + Total Flash Loan Fees USD (LP side) + Total Exit Fees USD + Total Flash Loan Fees (Protocol Side) + Total Vortex Fees USD_

**Supply Side Revenue USD**

_Total Supply Side Revenue USD = Total Trading Fees USD + Total Flash Loan Fees USD_

_Total Supply Side Revenue USD = Total BNT to TKN Trading Fees USD + Total TKN to BNT Trading Fees USD + Total TKN to TKN Trading Fees USD + Total Flash Loan Fees USD_

**Protocol Revenue USD**

_Protocol Revenue USD = Total Exit Fees from Liquidity Pools USD + Total Flash Loan Fees USD + Total Vortex Fees USD_

## Pool-Level Metrics

**Pool Total Value Locked USD**

Pool Total Value Locked USD is calculated summing the total USD value of the tokens in a given liquidity pool

_Pool Total Value Locked USD = Number of tokens in liquidity pool * price of token in USD_

Example:

Let’s assume that there are 1,500,000 LINK in the LINK liquidity pool on Bancor V3 and the current price of LINK at the time of calculation is $8.

_Pool Total Value Locked USD (LINK Liquidity Pool) = Number of tokens in liquidity pool * price of token USD = 1,500,000 * $8 = $12,000,000 USD_

**Reward Tokens & Reward Token Emissions Amount**

Breakdown of total BNT rewards:

30M BNT will be distributed over an infinite time period to BNT LPs

10M BNT to be distributed to TKN LPs, not necessarily under an exponential decay emission model i.e. over an infinite time period, as we also have the flat/linear emissions model mentioned below

**BNT Pool Reward Token Emissions**

In Bancor V3 there will be a maximum of 40,000,000 BNT that will be distributed over an infinite time period. 

The start date and end date of the rewards is still to be decided.

The distribution rate of the rewards will follow an _exponential decay curve_.

See the “Rewards Schedules” section of the [Bancor 3 Proposal document](https://docs.google.com/document/d/11UeMYaI_1CWdf_Nu6veUO-vNB5uX-FcVRqTSU-ziDRk/edit#) for more information and examples. 

**Third Party Reward Token Emissions**

For third party reward token emissions, the third party can use the same mechanism (_exponential decay curve)_ as described in the “BNT Pool Reward Token Emissions”. The only difference being the rewards will be in TKN rather than BNT.

There will also be a Flat Alternative emissions program where project teams may not wish to use the exponential decay function equation as described above. 

In this case, a constant emissions rate will be possible similar to what is currently done on Bancor V 2.1 (a constant rate of emissions over a period of time).

For more detailed information see “Third Party TKN Staking Rewards” in the [Bancor V3 proposal document](https://docs.google.com/document/d/11UeMYaI_1CWdf_Nu6veUO-vNB5uX-FcVRqTSU-ziDRk/edit#).

**Non-Identical TKN Emission Programs**

In the case where the incentivised asset is being rewarded with the asset of the same type (e.g BNT rewards for BNT LPs) then the above described emission programs would work. 

If however the rewarded asset is different to the asset that is being incentivised then the above will not work. 

Bancor V3 has addressed this by allowing users to manually claim rewards.

For more detailed information see “Non-Identical TKN Emission Programs” in the [Bancor V3 proposal document](https://docs.google.com/document/d/11UeMYaI_1CWdf_Nu6veUO-vNB5uX-FcVRqTSU-ziDRk/edit#)

**Historical Reward Incentive Programs**

As Bancor V3 has only gone live on 11th May 2022, there are currently no historical reward incentive programs to date. This section can be updated in the future.
# DEX Subgraphs Dashboard

Demo: <https://share.streamlit.io/harsh9200/protocol-dashboard/app.py>

## Development

Install venv

```
python3 -m venv venv
```

Activate venv

```
source venv/bin/activate
```

Install dependencies

```
pip3 install -r requirements.txt
```

Run locally

```
streamlit run app.py
```

## Requirements

Only supports Python3.10+
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
#############################################
############## Price Oracle #################
#############################################
- name: ERC20
  file: ./abis/Ethereum/ERC20.json
- name: CurveRegistry
  file: ./abis/Oracles/Curve/Registry.json
- name: CalculationsCurve
  file: ./abis/Oracles/Calculations/Curve.json
- name: YearnLensContract
  file: ./abis/Oracles/YearnLens.json
- name: ChainLinkContract
  file: ./abis/Oracles/ChainLink.json
- name: UniswapRouter
  file: ./abis/Oracles/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Oracles/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Oracles/Uniswap/Pair.json
- name: SushiSwapRouter
  file: ./abis/Oracles/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Oracles/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Oracles/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Oracles/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1 
// Using function getUsdPricePerToken(tokenAddr: Address)

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);
if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimals.toBigDecimal()
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |
# Geist Finance Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Pool Deposit TVL`

### Total Revenue USD

Sum across all Pools:

`(Pool Variable Borrow Amount * Variable Pool Borrow Rate) + (Pool Stable Borrow Amount * Stable Pool Borrow Rate)`

Note: This currently excludes Flash Loans

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Pool Oustanding Borrow Amount * Pool Borrow Rate) * (Pool Reserve Factor)`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Pool Outstanding Borrow Amount * Pool Borrow Rate) * (1 - Pool Reserve Factor)`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

### Reward Token Emissions Amount

Emissions Per Day = (`emissionsPerSecond` \* `SECONDS_PER_DAY`)

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

### Protocol Controlled Value

Not applicable to Geist Finance

## Links

Protocol: [geist.finance](https://geist.finance/)

Analytics: [geist.finance/stats](https://geist.finance/stats/)

Docs: [docs.geist.finance](https://docs.geist.finance/)

Smart contracts: [github.com/geist-finance/geist-protocol](https://github.com/geist-finance/geist-protocol)

Deployed addresses: [docs.geist.finance/useful-info/deployments-addresses](https://docs.geist.finance/useful-info/deployments-addresses)
# Platypus Subgraph Methodology v1.0

The Platypus Finance protocol is a single-side AMM (decentralized exchange) designed for exchanging stable cryptocurrencies (ERC20 tokens) on the Avalanche blockchain.

The protocol is implemented as a set of smart contracts; designed to prioritize censorship resistance, security, self-custody and maximum capital efficiency. Platypus takes the early innovations of Curve Finance (ETH mainnet) and adds the twist of single-token staking and asset-liability management, in an attempt to fix issues related to impermanent loss and slippage.

## Useful Links

- Main Page
  - [https://www.platypus.finance/](https://www.platypus.finance/)
- Protocol
  - AMM: [https://app.platypus.finance/swap](https://app.platypus.finance/swap)
  - LPs: [https://app.platypus.finance/pool?pool_group=main](https://app.platypus.finance/pool?pool_group=main)
  - Staking (vePTP): [https://app.platypus.finance/stake](https://app.platypus.finance/stake)
- Docs
  - Liquidity Mining Yellow Paper: [https://cdn.platypus.finance/Platypus_Liquidity_Mining_Paper.pdf](https://cdn.platypus.finance/Platypus_Liquidity_Mining_Paper.pdf)
  - AMM Technical Specification Yellow Paper: [https://cdn.platypus.finance/Platypus_Liquidity_Mining_Paper.pdf](https://cdn.platypus.finance/Platypus_Liquidity_Mining_Paper.pdf)
  - [https://docs.platypus.finance/platypus-finance-docs/](https://docs.platypus.finance/platypus-finance-docs/)
  - [https://docs.platypus.finance/platypus-finance-docs/developers/contracts](https://docs.platypus.finance/platypus-finance-docs/developers/contracts)
- Smart contracts
  - [https://github.com/platypus-finance](https://github.com/platypus-finance)
- Deployed addresses
  - [https://docs.platypus.finance/platypus-finance-docs/developers/contract-addresses](https://docs.platypus.finance/platypus-finance-docs/developers/contract-addresses)
- Airdrop Site
  - [https://airdrop.platypus.finance/](https://airdrop.platypus.finance/)
- Treasury
  - [https://gnosis-safe.io/app/avax:0x068e297e8FF74115C9E1C4b5B83B700FdA5aFdEB/balances](https://gnosis-safe.io/app/avax:0x068e297e8FF74115C9E1C4b5B83B700FdA5aFdEB/balances)
- Coverage Ratio & APR Example
  - [https://docs.platypus.finance/platypus-finance-docs/concepts/platypus-interest-rate-model](https://docs.platypus.finance/platypus-finance-docs/concepts/platypus-interest-rate-model)
- Medium
  - [https://medium.com/platypus-finance](https://medium.com/platypus-finance)
- Messari Profile
  - [https://messari.io/asset/platypus-finance](https://messari.io/asset/platypus-finance)

## Usage Metrics

**Active Users, Total Unique Users & Daily Transaction Count**

Transactions of interest on Platypus include:

- Depositing any token into its liquidity pool to gain LP Token
- Staking LP token to Liquidity Mine PTP
- Staking PTP for vePTP
- Swapping one stablecoin for another (Stableswap)

Any address which conducts one of the transactions above should be considered a User.

All unique addresses that have participated in any of the above accounts should be considered in the Total Unique Users Calculation. Furthermore, a 24-hour lookback period should be used to determine Daily Transaction Count.

**Total Swap Volume**

Total Volume on Platypus would be total amount (in USD) swapped across all assets available.

`Sum of swap volume across liqudity pools.`

**Total LP Volume**

Given that Platypus allows users to add single-sided (as opposed to paired liquidity), Total LP Volume would be total deposits into any asset liquidity pool (across Main, Alt and Factory Pools) on the Platypus platform.
Sum of LP volume across liqudity pools

**Total Staked Volume (PTP and vePTP)**

In order to mine the PTP token, users must stake their LP tokens after depositing into a liquidity pool. Process is as follows:

User deposits USDC into Main Pool-> User received single-sided LP Token (USDC on Main Pool) -> User stakes single-sided LP Token-> User receives emissions in PTP based on volume, coverage ratio of asset and APR

Total Staked Volume (PTP) would be total LP tokens staked in on Platypus. This will likely be a % of Total LP Volume, and a **% of Staked/LP** would be an interesting metric as well.

Discussed under Reward Tokens below, but Platypus incorporates a veCRV model to boost PTP emissions at the pool level. After a user receives PTP from the LP staking process outlined above, they have the ability to further stake their PTP tokens to generate voting-escrowed PTP (vePTP). vePTP is non-tradeable or transferable and is used to boost PTP-rewards for LP stakers.

The amount of staked vePTP changes the total PTP rewards given to each pool. Our implementation uses `AdjustedAllocationPoints` from the `MasterPlatypusContract` which is updated whenever the staked vePTP balance changes.
However we are not tracking the amount of vePTP staked or its balances, as it is non-transferable and doenst have any market value.

## Financial Metrics

**Total Value Locked USD**

The Total Value Locked (TVL) on Platypus can be calculated by summing the total deposits across all pools (Main, Alt & Factory Pools) on Platypus. We leverage the LP-Pools from [this list](https://docs.platypus.finance/platypus-finance-docs/developers/contract-addresses).

\_Note: \_DeFi Llama utilizes the above calculation; **however, **user’s can toggle TVL to include staking. If Messari were to want TVL both inclusive and exclusive of staking, they would take the TVL calculation laid out above and add Total Staked Volume metrics shown under Usage.

_TVL (non-staking): All LP deposits across main, alt and factory pools_

\_TVL (staking): TVL (non-staking) + Total Staked Volume (PTP)\_

**Protocol Controlled Value USD**

As a DEX, and more specifically a StableSwap protocol, Platypus does not require a PCV to back its token. Token price should be based on total trading volume, fees, etc.
The the Protocol Controlled Value is thus the same as Protocol Side Revenue, which stays in the liquidity pool but is yet to be distributed to either the protocol admin or the supply side.

**Supply Side Revenue**

As with most DEXs, supply side revenue is generated for LPs through a % of transaction fees as a function of one’s % of total liquidity added to a pool. By depositing liquidity, an individual may farm the PTP governance token once liquidity mining, or share the **haircut fee** of the transaction fee collected from each asset swap depending on the retention ratio.

The split between Supply Side revenue and Protocol Side revenue depends on the retention ratio, the ratio for each pool is 100% meaning the supply side revenue is 0 unless the team changes it in the future.

\_SupplySideRevenue = Total Revenue \* (( 100 - Retention Ratio ) / 100)\_

**Protocol Revenue:**

_Swap Fees_

Within its main function as a DEX, Platypus charges a transaction fee on all swaps on the platform. This relatively small fee can be changed via governance.

For each type of pool there is a different haircut according to the docs, but this may vary from the haircut rate set on the contracts. Our implementation uses the retention ratio and haircut rate from the actual deployed contracts.

In order to calculate the total swap revenue for the protocol you would perform the following calculation:

\_SwapFees = Total Revenue \* ( Retention Ratio / 100 )

_Withdrawal / Deposit Fees_

Given the nature of Platypus’ single-side LPs, they opened themselves up to unique arbitrage risk, outlined [here](https://medium.com/platypus-finance/withdrawal-arbitrage-the-risk-of-platypus-attacks-bc3e43e69fcb). To combat this arbitrage, they have instituted withdrawal and deposit fees, which also provides a _small_ source of revenue.

Our implementation doesnt track the withdrawal and deposit fee charged as the contracts provide no simple way to get this information and a lots of computation would be required to calculate the dynamic fee based on slippage and coverage ratio of each asset in a pool.

These fees are based on the coverage ratio of the pools. For Example:

<table>
  <tr>
   <td>Coverage Ratio
   </td>
   <td>Withdrawal Fee
   </td>
  </tr>
  <tr>
   <td>>=1
   </td>
   <td>-0.0000%
   </td>
  </tr>
  <tr>
   <td>0.9
   </td>
   <td>-0.0011%
   </td>
  </tr>
  <tr>
   <td>0.8
   </td>
   <td>-0.0093%
   </td>
  </tr>
  <tr>
   <td>0.7
   </td>
   <td>-0.0518%
   </td>
  </tr>
  <tr>
   <td>0.6
   </td>
   <td>-0.2731%
   </td>
  </tr>
</table>

_Protocol Revenue = Transaction Fees \* (Retention Ratio /100) + Withdrawal Fees + Deposit Fees_

Since we are not tracking Withdrawal and Deposit Fees

_Protocol Revenue = Transaction Fees \* (Retention Ratio /100)_

**Treasury Yield Revenue:**

Platypus also generates revenue by yield farming its treasury. This is currently mostly composed

of its native token, PTP. Platypus can deploy these assets to generate yield and increase the existing treasury.

## Pool-Level Metrics

**Coverage Ratio **

_not tracked_
Ratio of single-sided asset to each other in every pool
The higher the coverage ratio, the greater the PTP emission is to the stablecoin account.

**Pool Total Value Locked USD**

Total deposits in a pool
`` Calculated as the sum of `cash` across each asset. ``

**Reward Tokens & Reward Token Emissions Amount**

Platypus delivers its native token PTP through three different pool for liquidity mining: namely the **Base Pool, Boosting Pool and AVAX-PTP Pool (Pool 2)**, accounted for 30%, 50%, and 20% of the liquidity emission, respectively.

**Base Pool:**

The Base Pool issues PTP tokens to a deposit at an amount that is positively proportional to its share of the aggregate deposit. The token emission for a deposit in the base pool is defined as:

    _Token Emissions (per Deposit) = Emissions Allocated to the Account * (Deposit Amount / Aggregate Deposits in Account)(_

**Boosting Pool:**

The Boosting Pool utilizes an additional token, voting escrow PTP (vePTP), inspired by voting escrow CRV ([veCRV](https://resources.curve.fi/base-features/understanding-crv)) of Curve Finance. Have a look at the below vePTP attributes :

- 1 staked PTP generates 0.014 vePTP every hour
- Maximum vePTP held with a deposit equals to 100 times PTP staked for the deposit
- Upon unstaking PTP, vePTP drops to 0
- vePTP is non-transferable and non-tradeable due to the design of the smart contract, i.e. vePTP token will be locked in the private wallet of the user

The weight function and number of PTP token emission for the boosting pool is defined as:

_w=sqrt{deposit\*vePTP}_

_PTP token emission for a deposit=Emission Allocated to the account∗(Deposit Weight/Aggregate Weights in the Account) _

We dont need to track the deposit for each account, as we are returning the overall PTP emitted for each Asset in each Pool.

## Various Types of Pools in Platypus

### Main Pool

This the main driver of TVL on the platform. It contains all the battle tested stablecoins like DAI.e, USDT.e, USDT, among others. MIM was a part of the main pool before it was moved to a Alt pool of its own. Our implementation tracks this effectivly.

### Alt Pool

These are pools that are spun up for compartivly risky assets such as UST and MIM. Each Alt pool contains 2 assets which are supposed to be of same value like the USDT/MIM Alt Pool and the sAVAX/wAVAX Alt Pool. ALthough these assets are risky, and a depeg of an asset in ALT would result in the pool not accepting new trades / deposits / withdraws.

### Factory Pool

Factory pools are like Alt pool as in they are created for risky assets, but they have the depeg protection turned off. This means that the pool will remian functional even if the asset depegs from its desired value. These are new pools that are additionally rewarded by external tokens (mostly by the creator of the risky stablecoin).
Currently there are 3 Factory Pools. (Eg: H20/USDC Pool)

#### Note abount deprecated and "False Pools"

The admin has for operational reasons changed the pool for an asset to their own address or the Platypus Multisig to carry out specific functions only allowed to be done by the pool. This causes "false pools" to be added to the subgraph. These pools are hardcoded to be ingored and do not contribute to the TVL or other metrics of the protocol. These are also not counted when we count the number of pools in the protocol.
Deprecated Pools (like an Old MIM pool) are also ignored and as named as "Withdraw Pools" in the subgraphs, as they only allow withdraws and no other functions.

## Interaction Diagram

![Platypus Finance](./interaction-diagram.jpg "Platypus Finance")
# MakerDAO Lending Protocol Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Markets:

`Total Collateral Tokens in USD after accounting deposits and withdrawals`

Total collateral is counted by dink during frob events

### Total Deposit USD

Sum across all Markets:

`Sum dink values emitted during Frob events from Vat address per Market`

'ink' is considered the market's collateral, dink stands for Δink, contract emits signed values

### Total Borrow USD

Sum across all Markets:

`Sum dart values emitted during Frob events from Vat address per Market`

'art' is considered the market's debt, dart stands for Δart, contract emits signed values

### Total Revenue USD

Sum across all Markets:

`(Change in market debt multiplier rate value from Vat Fold event * market total borrow usd) + (Liquidations per market * liquidation penalty per market)`

### Protocol-Side Revenue USD

### Protocol-Side Revenue USD

Sum across all Markets:

`(Change in market debt multiplier rate value from Vat Fold event * market total borrow usd) + (Liquidations per market * liquidation penalty per market)`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Markets

`Change in dai savings rate * total dai in the pot contract`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`'Frob' events emitted by CDP proxy addresses which include deposits withdrawals + 'Give' events emitted during a CDP swap to a new owner + from address from 'Grab' events emitted by Vat during liquidations`

### NO Reward Token Emissions

## References and Useful Links

- Protocol: https://makerdao.com/en/
- Analytics: https://makerburn.com/#/
- Docs: https://docs.makerdao.com/
- Smart contracts: https://github.com/makerdao/dss
- Deployed addresses: https://changelog.makerdao.com/releases/mainnet/active/contracts.json

## Smart Contracts Interactions

![Makerdao](../../docs/images/protocols/makerdao.png "Makerdao")

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`
# Autofarm - Yield Protocol Subgraph

## Useful Links

- https://autofarm.network/
- https://autofarm.gitbook.io/autofarm-network/
- Add here

## Calculation Methodology v0.0.1

### Total Value Locked (TVL) USD

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Revenue USD

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Vaults

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added
# Trufi Protocol Subgraph
## Calculation Methodology v0.0.1

### Total Value Locked (TVL) USD

Sum across all Pools:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Revenue USD

Sum across all Pools:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Repays`

`Liquidations`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added
# PoolTogether v4 Subgraph Methodology v1.0.0
(Ethereum, Polygon, Avalanche)
Briefly, PoolTogetherv4 is a lottery where users deposit their funds into a prize pool, 
the funds in said prize pool are put into protocols like Compound and Aave to generate yield, 
and then the yield (+ some protocol treasury) is distributed as prizes to the users. Users also get their original deposits back.

## Calculation Methodology v1.0.0

### Total Value Locked USD

On PoolTogetherv4, the total value locked is equal to the amount of deposits currently in the prize pool + DAO treasury incentives + the yield earned on these two. There is a new prize pool every 24 hours generated by the execution of a Prize Pool Instance (also known as a Draw), after which users are able to claim their winnings.

`TVL_Eth = (Deposits (USDC) since last Prize Pool Instance +  Pool Yield Earned) on Ethereum`
`TVL_Avax = (Deposits (USDC) since last Prize Pool Instance + Pool Yield Earned) on Avax`
`TVL_Matic = (Deposits (USDC) since last Prize Pool Instance + Pool Yield Earned) on Polygon`

`TVL = TVL_Eth + TVL_Avax + TVL_Matic`

### Protocol Controlled Value USD

This is not applicable to PoolTogether.

### Total Revenue USD

Total Revenue is the yield generated on the Deposits into the Prize Pool across Ethereum, Polygon, and Avalanche.

`Total Revenue = Pool Yield Earned on Ethereum, Avalanche, and Polygon`

### Supply Side Revenue USD

`Supply Side Revenue = Total Revenue`

### Protocol Revenue USD

PoolTogether does not have any Protocol Revenue at this time.

## Pool-Level Metrics

### Pool Total Value Locked USD

There are no Pools outside of the Prize Pools in PoolTogether, so

Pool Total Value Locked = Total Value Locked 

### Reward Tokens & Reward Token Emissions Amount

The V4 Design requires that prize liquidity reserves are maintained to fulfill all prizes that are awarded. Prize distributions are targeted to specific amounts, but do have variance. Similarly Aave yields vary. However this treasury is not held in the POOL token, so it’s not relevant, but for completeness:
A ~6k USDC per day burn of the treasury subsidy was seen up until at least March 22nd, 2022, after which a PTIP was passed to reduce this to ~2K USDC per day. More details can be found here: https://gov.pooltogether.com/t/rfc-prize-liquidity/2102
And here: https://gov.pooltogether.com/t/prize-adjustment-3/2097

## Links 
Protocol
https://app.pooltogether.com/deposit

Docs
https://v4.docs.pooltogether.com/

Smart Contracts
https://v4.docs.pooltogether.com/protocol/contracts/

Messari Reports (a bit dated)
https://messari.io/article/how-pooltogether-is-building-a-sustainable-lottery-at-the-protocol-level (Oct, 2020)
https://messari.io/article/pooltogether-launches-new-no-loss-protocol (Oct, 2020)

Dune Dashboards 
https://dune.com/sarfang/PoolTogetherV4
# Saddle Finance (DEX) Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Liquidity Pool TVL`

### Total Revenue USD

Sum across all Pools:

`(Swap Trading Volume * Pool Swap Fee)`

Note:

- The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool
- Excludes flash loans

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Swap Trading Volume * Pool Swap Fee * Pool Admin Fee)`

Note: The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Swap Trading Volume * Pool Swap Fee * (1 - Pool Admin Fee))`

Note: The Pool Swap Fee + Pool Admin Fees can be dynamically updated from pool-to-pool

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Swaps`

`Deposits`

`Withdraws`

### Reward Token Emissions Amount

`Reward Token Emission Rate Per Second * (seconds in day)`

### Protocol Controlled Value

To be added

### Pool Output Token Price

`(Sum of input token balances in USD) / (LP token supply)`

Note: All pegged value asset prices are set to underlying asset price

## Smart Contract Interactions

![Saddle](../../docs/images/protocols/saddle.png "Saddle Finance")

## References and Useful Links

- Protocol website: https://saddle.finance/
- Protocol documentation: https://docs.saddle.finance
- Smart contracts: https://github.com/saddle-finance/saddle-contract/
- Deployed addresses: https://docs.saddle.finance/contracts
- Existing subgraph: https://thegraph.com/hosted-service/subgraph/saddle-finance/saddle
# Configurations

- This folder contains the general configurations to use for the deployed networks/protocols

## deploy.ts

- Include a nameswap value for each protocol/network deployement. Structure these values as `PROTOCOL_NETWORK` as seen in the file as an example.
- Set the namespace value to a number. This is so the namespace value works in the case/switch in the configurations.ts file
- Also, add the to the `PROTOCOL_NETWORK` like "deployment": "PROTOCOL_NETWORK" in the network specific conficuration .json file.

## interface.ts

- The interface contains all of the fields and data types that will be stored in the Configurations class for use in the program

## configurations.ts

- This file is just used to select the proper configurations per protocol/network.
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1 
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)     | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24) | `Calculations` | `3808222` |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)     |    `Router`    | `5655918` |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957)   |    `Router`    | `3796241` |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    | `2457904` |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603` |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120` |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056` |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    | `73` |    ✅     |   🛠    |
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)      | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24)  | `Calculations` | `3808222`  |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)      |    `Router`    | `5655918`  |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957) |    `Router`    | `3796241`  |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506)  |    `Router`    | `2457904`  |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                              |      Type      | StartBlock | MultiCall | Status |
| ----------------------------------------------------------------------------------- | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603`  |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120`  |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056`  |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    |    `73`    |    ✅     |   🛠    |
# Belt Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Vaults:

`Vault TVL`

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol.

Note that Belt applies a Withdrawal and Deposit Fees based on Strategy used at the time of deposit or withdraw.

Sum across all Vaults:

`(Withdraw Amount * Vault Withdraw Fee) + (Deposit Amount * Vault Deposit Fee)`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Note that this is the remaining Yield after Protocol Fees

Sum across all Vaults

`(Withdraw Amount - Withdraw Fee) + (Deposit Amount - Deposit Fee)`

## Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposit`

`Withdraw`

## Links

- Protocol website: https://belt.fi/landing
- Protocol documentation: https://docs.belt.fi/
- Deployed addresses: https://docs.belt.fi/contracts/contract-deployed-info

## Setup

1. Install all the dependencies

```
yarn add

# global packages
yarn global add @graphprotocol/graph-cli
yarn global add mustache
```

2. Generate types

```
yarn run prepare
yarn run codegen
```

3. Building the subgraph

```
yarn run prepare
yarn run build
```

5. Deploy

```
graph auth --product hosted-service <access-token>
graph deploy --product hosted-service <username/subgraph-name>
```
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
###########################################
############## Price Oracle ###############
###########################################
# ERC20
- name: _ERC20
  file: ./abis/Prices/ERC20.json
# Curve Contracts
- name: CurveRegistry
  file: ./abis/Prices/Curve/Registry.json
- name: CurvePoolRegistry
  file: ./abis/Prices/Curve/PoolRegistry.json
- name: CalculationsCurve
  file: ./abis/Prices/Calculations/Curve.json
# YearnLens Contracts
- name: YearnLensContract
  file: ./abis/Prices/YearnLens.json
# ChainLink Contracts
- name: ChainLinkContract
  file: ./abis/Prices/ChainLink.json
# Uniswap Contracts
- name: UniswapRouter
  file: ./abis/Prices/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Prices/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Prices/Uniswap/Pair.json
# SushiSwap Contracts
- name: SushiSwapRouter
  file: ./abis/Prices/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Prices/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Prices/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Prices/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1 
// Using function getUsdPricePerToken(tokenAddr: Address): CustomPriceType

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);

// fetchPrice.reverted: Bool
// fetchPrice.decimals: number
// fetchPrice.decimalsBaseTen: BigDecimal, returns 10**decimals

if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimalsBaseTen
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
│── README.md
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |

### Fantom

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://ftmscan.com/address/0x0b53e9df372e72d8fdcdbedfbb56059957a37128)     | `Calculations` | `27067399` |    ❎     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0xec7Ac8AC897f5082B2c3d4e8D2173F992A097F24) | `Calculations` | `3808222` |    ❎     |   🛠    |
| [Curve](https://ftmscan.com/address/0x0f854EA9F38ceA4B1c2FC79047E9D0134419D5d6)     |    `Router`    | `5655918` |    ✅     |   🛠    |
| [SpookySwap](https://ftmscan.com/address/0xbe4fc72f8293f9d3512d58b969c98c3f676cb957)   |    `Router`    | `3796241` |    ✅     |   🛠    |
| [SushiSwap](https://ftmscan.com/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    | `2457904` |    ✅     |   🛠    |

### Arbitrum-One

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [Curve](https://arbiscan.io/address/0x26f698491daf32771217abc1356dae48c7230c75)     | `Calculations` | `5287603` |    ❎     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x5EA7E501c9A23F4A76Dc7D33a11D995B13a1dD25) | `Calculations` | `2396120` |    ❎     |   🛠    |
| [Curve](https://arbiscan.io/address/0x445FE580eF8d70FF569aB36e80c647af338db351)     |    `Router`    | `1362056` |    ✅     |   🛠    |
| [SushiSwap](https://arbiscan.io/address/0x1b02da8cb0d097eb8d57a175b88c7d8b47997506) |    `Router`    | `73` |    ✅     |   🛠    |
# ENS Governance Subgraph

## Things that do not work well

1. The `quorum` changes per block since it relies on total token supply

```
function quorum(uint256 blockNumber) public view virtual override returns (uint256) {
  return (token.getPastTotalSupply(blockNumber) * quorumNumerator())  / quorumDenominator();
}
```

This makes it hard to keep it up to date in the subgraph. _Keep up to date via the subgraph ingestion process?_

2. Using the first `QuorumNumeratorUpdated` event to create `GovernanceFramework` which feels wrong. This may not always be the case depending on constructor ordering of OZ Governor contracts

```
constructor(ERC20Votes _token, TimelockController _timelock)
  Governor("ENS Governor")
  GovernorVotes(_token)
  GovernorVotesQuorumFraction(100) // 1% <-- event from here trigger creation
  GovernorTimelockControl(_timelock)
{}
```

[OZGovernor deployment logs](https://etherscan.io/tx/0x97cba35bb5b36409dc31f22f2cb31d0f947bd8d1145093f9a785aefa525fe269#eventlog)

It would be ideal if there was a handler for after constructor call or after the contract is successfully deployed...
# Rari Capital Yield Aggregator v1

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Vaults:

`Vault TVL`

### Total Revenue USD

Sum across all Vaults:

`Total Interest Accrued`

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Total Vault Revenue USD * Vault Performance Fee) + (Withdraw Amount * Withdraw Fee)`

Note that different fees are applied:

- Passive Vaults: Performance Fee + Withdrawal fee
- Option Vaults: Performance Fee + Withdrawal Fee
- (Fees can vary between vaults - standard is 15% performance, 0.5% withdrawal)

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Total Vault Revenue USD * (1-Vault Performance Fee))`

Note that this is the remaining yield after protocol fees

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdraw`

### Reward Token Emissions Amount

`Not applicable`

### Protocol Controlled Value

`Not applicable`

## Known Issues

- Eth vault revenues are weird
- Big spike in revenues around 10/21/2020 (may be okay since there is also a big spike in activity)
- *Note*: `OutputTokenSupply/Price` should be the same for each vault with the same contract addresses (ie, USDC pool mStable and USDC)
  - However, `pricePerShare` is a function of each individual vaults `inputTokenBalance` and the overall Pool's `outputTokenSupply`
- `DEFAULT_DECIMALS` is used in places where the `BigInt` value is offset by a factor of 1e18 on the contract-level
- *Note*: `pricePerShare` is very small for some vaults b/c the `outputTokenSupply` is aggregated and there is little of the `inputToken`

## Reference and Useful Links

Protocol: https://rari.capital/

Docs:

- https://docs.rari.capital/yag/
- https://info.rari.capital/products/earn/
- https://info.rari.capital/risk/earn/

Smart contracts:

- [Yield Pool](https://github.com/Rari-Capital/rari-yield-pool-contracts)
- [Ethereum Pool](https://github.com/Rari-Capital/rari-ethereum-pool-contracts)
- [Stables _ie_ USDC/DAI/USDT/TUSD/BUSD/mUSD Pool](https://github.com/Rari-Capital/rari-stable-pool-contracts)

Deployed addresses: https://docs.rari.capital/contracts

Existing subgraphs: `NA`
# Lido Subgraph
## Calculation Methodology v1.0.0

### stETH Supply:

`value`/1e18 FROM `stETH erc20."ERC20_evt_Transfer"`

WHERE `from` = '\x0000000000000000000000000000000000000000'

UNION ALL

-`value`/1e18 FROM `erc20."ERC20_evt_Transfer"`

WHERE `to` = '\x0000000000000000000000000000000000000000'

**Contract:** stETH erc20 0xae7ab96520de3a18e5e111b5eaab095312d7fe84

**Evt:** `ERC20_evt_Transfer`

**Parameters:** `value`, `from`, `to`

### stETH Price (ETH) from Curve:

`tokens_sold`/`tokens_bought` FROM `curvefi."steth_swap_evt_TokenExchange"`

WHERE `sold_id` = 0

UNION ALL 

`tokens_bought`/`tokens_sold` FROM `curvefi."steth_swap_evt_TokenExchange"`

WHERE `sold_id` = 1

**Contract:** curvefi steth 0xdc24316b9ae028f1497c275eb9192a3ea0f67022

**Evt:** `steth_swap_evt_TokenExchange`

**Parameters:** `tokens_sold`, `tokens_bough`, `sold_id`

### stETH Vol. (ETH) from Curve:

`tokens_sold`/1e18 FROM `curvefi."steth_swap_evt_TokenExchange"`

WHERE `sold_id` = 0

UNION ALL 

`tokens_bought`/1e18 FROM `curvefi."steth_swap_evt_TokenExchange"`

WHERE `sold_id` = 1

**Contract:** curvefi steth 0xdc24316b9ae028f1497c275eb9192a3ea0f67022

**Evt:** `steth_swap_evt_TokenExchange`

**Parameters:** `tokens_sold`, `tokens_bough`, `sold_id`

### stETH Vol. (USD)

`stETH Vol. (ETH)` * `ETH price (offchain)`

### stETH MCap. (USD)

`stETH Supply` * `stETH Price (ETH)` * `ETH price (offchain)`

### Number of Active Depositors:

COUNT(`sender`) FROM `lido."steth_evt_Submitted"`

**Contract:** lido steth 0xae7ab96520de3a18e5e111b5eaab095312d7fe84

**Evt:** `steth_evt_Submitted`

**Parameters:** `sender`  

### Unique Users:

COUNT (UNIQUE `sender`) OVER `time` FROM `lido."steth_evt_Submitted"`

**Contract:** lido steth 0xae7ab96520de3a18e5e111b5eaab095312d7fe84

**Evt:** `steth_evt_Submitted`

**Parameters:** `sender`  
    
### Deposits Amount (ETH)

SUM(`amount`)/1e18 FROM `lido."steth_evt_Submitted"`

**Contract:** lido steth 0xae7ab96520de3a18e5e111b5eaab095312d7fe84

**Evt:** `steth_evt_Submitted`

**Parameters:** `amount`

### Agg. Deposits (ETH)

SUM(`Deposits Amount (ETH)`) OVER `time`

### Agg. Deposits (USD)

`Agg. Deposits (ETH)` * `ETH price (offchain)`

### Total Staked (ETH):

SUM(SUM(`amount`)/1e18) OVER `time` FROM `lido."steth_evt_Unbuffered"`

**Contract:** lido steth 0xae7ab96520de3a18e5e111b5eaab095312d7fe84

**Evt:** `lido.steth_evt_Unbuffered`

**Parameters:** `amount`

### Total Pooled (ETH):

`postTotalPooledEther`/1e18 FROM `lido."LidoOracle_evt_PostTotalShares"`

**Contract:** lido LidoOracle 0x442af784a788a5bd6f42a01ebe9f287a871243fb

**Evt:** `LidoOracle_evt_PostTotalShares`

**Parameters:** `postTotalPooledEther`

### Lido Total Shares:

`totalShares`/1e18 FROM `lido."LidoOracle_evt_PostTotalShares"`

**Contract:** lido LidoOracle 0x442af784a788a5bd6f42a01ebe9f287a871243fb

**Evt:** `LidoOracle_evt_PostTotalShares`

**Parameters:** `totalShares`

### Beacon Chain Total Staked (ETH):

SUM(SUM(`amount`)/1e9) OVER `time` FROM `eth2."DepositContract_evt_DepositEvent"`
       
_Note_: `amount` is returned as little endian HEX num and needs to be decoded into INT

**Contract:** eth2 DepositContract 0x00000000219ab540356cbb839cbe05303d7705fa

**Evt:** `DepositContract_evt_DepositEvent`

**Parameters:** `amount`

### Others Total Staked (ETH):

`Beacon Chain Total Staked (ETH)` - `Total Staked (ETH)`

### Lido Participation (%):

`Total Staked (ETH)` / `Beacon Chain Total Staked (ETH)`

### Lido Global APY (%):

(1+(`postTotalPooledEther` - `preTotalPooledEther`)/`postTotalPooledEther`/(`timeElapsed`/(60 * 60 * 24)))^365-1 FROM `lido."LidoOracle_evt_PostTotalShares"`
        

**Contract:** lido LidoOracle 0x442af784a788a5bd6f42a01ebe9f287a871243fb

**Evt:** `LidoOracle_evt_PostTotalShares`

**Parameters:** `postTotalPooledEther`, `preTotalPooledEther`, `timeElapsed`

### Staking Rewards (ETH):

(`postTotalPooledEther`-`preTotalPooledEther`)/1e18 FROM `lido."LidoOracle_evt_PostTotalShares"`
        

**Contract:** lido LidoOracle 0x442af784a788a5bd6f42a01ebe9f287a871243fb

**Evt:** `LidoOracle_evt_PostTotalShares`

**Parameters:** `postTotalPooledEther`, `preTotalPooledEther`

### Staking Rewards (USD):

`Staking Rewards (ETH)` * `ETH price (offchain)`

### Agg. Staking Rewards (ETH)

SUM(`Staking Rewards (ETH)`) OVER `time`

### Treasury Revenue (ETH):

FOR every tx WITH triggered the evt `lido."LidoOracle_evt_PostTotalShares"`:

    SUM(`value`/1e18) FROM `stETH erc20."ERC20_evt_Transfer"`
    WHERE `to` = '\x3e40d73eb977dc6a537af587d48316fee66e9c8c'

_Note_:0x3e40d73eb977dc6a537af587d48316fee66e9c8c Treasury address

**Contract:** stETH erc20 0xae7ab96520de3a18e5e111b5eaab095312d7fe84

lido LidoOracle 0x442af784a788a5bd6f42a01ebe9f287a871243fb

**Evt:** `ERC20_evt_Transfer`

**Parameters:** `PostTotalShares`, `value`, `to`

### Node Operators Revenue (ETH):

FOR every tx WITH triggered the `evt lido."LidoOracle_evt_PostTotalShares"`:

    SUM(`value`/1e18) FROM `stETH erc20."ERC20_evt_Transfer"`
    WHERE "to" != '\x3e40d73eb977dc6a537af587d48316fee66e9c8c'     <---- !=

_Note_:0x3e40d73eb977dc6a537af587d48316fee66e9c8c Treasury address

**Contract:** stETH erc20 0xae7ab96520de3a18e5e111b5eaab095312d7fe84

lido LidoOracle 0x442af784a788a5bd6f42a01ebe9f287a871243fb

**Evt:** `ERC20_evt_Transfer`

**Parameters:** `PostTotalShares`, `value`, `to`

### Lido Protocol Revenue (ETH):

`Treasury Revenue (ETH)` + `Node Operators Revenue (ETH)`

### Supply-side Revenue (ETH):

`Staking Rewards (ETH)` - (`Treasury Revenue (ETH)` + `Node Operators Revenue (ETH)`)

### Agg. Protocol Revenue (ETH)

SUM(`Treasury Revenue (ETH)`) OVER `time` + SUM(`Node Operators Revenue (ETH)`) OVER `time`

## METRICS FOR UI

### Total Value Locked (TVL) USD

`Agg. Deposits (ETH)`

### Total Revenue USD

`Staking Rewards (ETH)`

### Protocol-Side Revenue USD

`Lido Protocol Revenue (ETH)`

### Supply-Side Revenue USD

`Supply-side Revenue (ETH)`

### Total Unique Users

`Unique Users`

## Useful links and references

https://docs.lido.fi/
# Rari Capital Fuse v1 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Pool Deposit TVL`

### Total Revenue USD

Sum across all Pools:

`(Pool Borrow Amount * Pool Borrow Rate)`

Note: This currently excludes Liquidations

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Pool Oustanding Borrow Amount * Pool Borrow Rate) * (Pool Reserve Factor + Fuse Fee + Admin Fee)`

Note: This currently excludes Liquidations

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Pool Outstanding Borrows * Pool Borrow Rate) * (1 - Pool Reserve Factor - Fuse Fee - Admin Fee)`

Note: This currently excludes Liquidations

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

### Reward Token Emissions Amount

`Reward Token Per Block * blocksPerDay`

### Protocol Controlled Value

`NA`

## Fuse Specific Additions

- There is a helper entity called `_FusePool` that tracks each fuse pool's market's, pool number, price oracle, liquidation incentive. This is needed in order to populate certain `Market` fields when a new market is added to an existing pool.
- Each market has additional `rates` added for the `Fuse Fee` and `Admin Fee`
  - `Fuse Fee` is the percentage of a market's accrued interest that is sent to the Rari Capital DAO
  - `Admin Fee` is the percentage of a market's accrued interest that is given to the admin of the pool.
  - Note: `Admin Fee` + `Fuse Fee` + `Reserve Factor` <= 100%

## Known Issues

- Ethereum:
  - _Note_: When OHM moved migrated to v2, pools that started with an `inputToken` of `sOHM` were migrated to `gOHM`. This is handled in `./src/mappings.ts`
- Arbitrum One:
  - Market `0xc0c997227922004da3a47185ac2be1d648db0062` has a very high TVL (~$100m). This is likely due to the fact that 10% of the total supply of the `inputToken` is in this vault and there are only 5 holders. Price of this asset is probably hard to calculate.
    - A potential fix is to recalculate TVL in every market each time `AccrueInterest` emits. This would slow down syncing as lots of contract calls would be introduced.

## Reference and Useful Links

Protocol: https://rari.capital/

Docs: https://docs.rari.capital/fuse/#fuse

Smart contracts: https://github.com/Rari-Capital/fuse-contracts

Deployed addresses: https://docs.rari.capital/contracts

Existing subgraphs: https://github.com/sharad-s/rari-fuse-subgraph
# Rari Capital Fuse v1 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Pool Deposit TVL`

### Total Revenue USD

Sum across all Pools:

`(Pool Borrow Amount * Pool Borrow Rate)`

Note: This currently excludes Liquidations

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Pool Oustanding Borrow Amount * Pool Borrow Rate) * (Pool Reserve Factor + Fuse Fee + Admin Fee)`

Note: This currently excludes Liquidations

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Pool Outstanding Borrows * Pool Borrow Rate) * (1 - Pool Reserve Factor - Fuse Fee - Admin Fee)`

Note: This currently excludes Liquidations

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

### Reward Token Emissions Amount

`Reward Token Per Block * blocksPerDay`

### Protocol Controlled Value

`NA`

## Fuse Specific Additions

- There is a helper entity called `_FusePool` that tracks each fuse pool's market's, pool number, price oracle, liquidation incentive. This is needed in order to populate certain `Market` fields when a new market is added to an existing pool.
- Each market has additional `rates` added for the `Fuse Fee` and `Admin Fee`
  - `Fuse Fee` is the percentage of a market's accrued interest that is sent to the Rari Capital DAO
  - `Admin Fee` is the percentage of a market's accrued interest that is given to the admin of the pool.
  - Note: `Admin Fee` + `Fuse Fee` + `Reserve Factor` <= 100%

## Known Issues

- Ethereum:
  - _Note_: When OHM moved migrated to v2, pools that started with an `inputToken` of `sOHM` were migrated to `gOHM`. This is handled in `./src/mappings.ts`
- Arbitrum One:
  - Market `0xc0c997227922004da3a47185ac2be1d648db0062` has a very high TVL (~$100m). This is likely due to the fact that 10% of the total supply of the `inputToken` is in this vault and there are only 5 holders. Price of this asset is probably hard to calculate.
    - A potential fix is to recalculate TVL in every market each time `AccrueInterest` emits. This would slow down syncing as lots of contract calls would be introduced.

## Reference and Useful Links

Protocol: https://rari.capital/

Docs: https://docs.rari.capital/fuse/#fuse

Smart contracts: https://github.com/Rari-Capital/fuse-contracts

Deployed addresses: https://docs.rari.capital/contracts

Existing subgraphs: https://github.com/sharad-s/rari-fuse-subgraph
# Compound v2 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Pool Deposit TVL`

### Total Revenue USD

Sum across all Pools:

`(Pool Borrow Amount * Pool Borrow Rate)`

Note: This currently excludes Liquidations

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Pool Oustanding Borrow Amount * Pool Borrow Rate) * (Pool Reserve Factor)`

Note: This currently excludes Liquidations

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Pool Outstanding Borrows * Pool Borrow Rate) * (1 - Pool Reserve Factor)`

Note: This currently excludes Liquidations

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

### Reward Token Emissions Amount

Amount of reward tokens (COMP) distributed each day.

Following calculation gives the COMP distributed (in COMP) to suppliers OR borrowers

`COMP per block * 4 * 60 * 24`

### Protocol Controlled Value

Not applicable to Compound v2

### Modified CToken ABI

CTokens have 2 different ABIs. They switch at block `8983575`, and the only difference is the `AccrueInterest` event params.

To handle this the `CTokenModifed` ABI just adds a new `AccrueInterest` event signature.

## Reference and Useful Links

Protocol: https://compound.finance/

Docs: https://compound.finance/docs

Smart contracts: https://github.com/compound-finance/compound-protocol

Deployed addresses: https://compound.finance/docs#networks

Existing subgraphs: https://github.com/graphprotocol/compound-v2-subgraph

Existing Subgraph in Studio: https://thegraph.com/hosted-service/subgraph/graphprotocol/compound-v2

Explanation of lending metrics: https://docs.aave.com/risk/asset-risk/risk-parameters

Dune Dashboard for Testing: https://dune.xyz/messari/Messari:-Compound-Macro-Financial-Statements
### Schema Discrepancy

Governor Alpha/Bravo:

- quorum: BigDecimal

OZ Governor:

- quorumNumerator: BigInt!
- quorumDenominator: BigInt!

Gov Specific:

- guardian: String (FEI)
- eta: BigInt (FEI)

## Things that do not work well

1. The `quorum` changes per block since it relies on total token supply

```
function quorum(uint256 blockNumber) public view virtual override returns (uint256) {
  return (token.getPastTotalSupply(blockNumber) * quorumNumerator())  / quorumDenominator();
}
```

This makes it hard to keep it up to date in the subgraph. _Keep up to date via the subgraph ingestion process?_

2. Using the first `QuorumNumeratorUpdated` event to create `GovernanceFramework` which feels wrong. This may not always be the case depending on constructor ordering of OZ Governor contracts

```
constructor(ERC20Votes _token, TimelockController _timelock)
  Governor("ENS Governor")
  GovernorVotes(_token)
  GovernorVotesQuorumFraction(100) // 1% <-- event from here trigger creation
  GovernorTimelockControl(_timelock)
{}
```

[OZGovernor deployment logs](https://etherscan.io/tx/0x97cba35bb5b36409dc31f22f2cb31d0f947bd8d1145093f9a785aefa525fe269#eventlog)

It would be ideal if there was a handler for after constructor call or after the contract is successfully deployed...
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
#############################################
############## Price Oracle #################
#############################################
- name: ERC20
  file: ./abis/Ethereum/ERC20.json
- name: CurveRegistry
  file: ./abis/Oracles/Curve/Registry.json
- name: CalculationsCurve
  file: ./abis/Oracles/Calculations/Curve.json
- name: YearnLensContract
  file: ./abis/Oracles/YearnLens.json
- name: ChainLinkContract
  file: ./abis/Oracles/ChainLink.json
- name: UniswapRouter
  file: ./abis/Oracles/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Oracles/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Oracles/Uniswap/Pair.json
- name: SushiSwapRouter
  file: ./abis/Oracles/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Oracles/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Oracles/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Oracles/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1 
// Using function getUsdPricePerToken(tokenAddr: Address)

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);
if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimals.toBigDecimal()
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |
# Geist Finance Subgraph

## Calculation Methodology v0.0.1

### Total Value Locked (TVL) USD

Sum across all Pools: 

`Pool Deposit TVL`

### Total Revenue USD

Sum across all Pools:

`(Variable Pool Borrow Amount * Variable Pool Borrow Rate) + (Stable Pool Borrow Amount * Stable Pool Borrow Rate)`

Note: This currently excludes Flash Loans

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`((Market Oustanding Borrow Amount * Market Borrow Rate) * (Pool Reserve Factor)) + ((Stable Pool Borrow Amount * Stable Pool Borrow Rate) * Pool Reserve Factor)`

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Market Outstanding Borrows * Market Borrow Rate) * (1 - Pool Reserve Factor) + ((Stable Pool Borrow Amount * Stable Pool Borrow Rate) * (1 - Pool Reserve Factor))`

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

Not applicable to Geist

## Links

- Protocol: https://geist.finance/
- Analytics: https://geist.finance/stats/
- Docs: https://docs.geist.finance/
- Smart contracts: https://github.com/geist-finance/geist-protocol
- Deployed addresses: https://docs.geist.finance/useful-info/deployments-addresses
# QiDAO Subgraph

## References and Useful Links

- Protocol website: https://mai.finance

- Protocol documentation: https://docs.mai.finance

- Smart contracts: https://github.com/0xlaozi/qidao

- Deployed addresses: https://docs.mai.finance/functions/smart-contract-addresses

## Smart Contracts Interactions

![QiDao](../../docs/images/protocols/qidao.png "QiDao")

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Collateral locked in Vaults`

### Total Revenue USD

Sum across all Pools:

`(Closing Fee + Liquidation Revenue)`

Closing fee is taken from collateral during either debt repayment or liquidation

Both closing fee and liquidation penalty can be changed by admin

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`Closing Fee`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`Liquidation Revenue`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdraws`

`Borrows`

`Repays`

`Liquidations`

### Reward Token Emissions Amount

Reward token emissions are calculated off-chain via snapshots

## Note

- Similar to Liquity, there is no interest rate, only a one-time closing fee, which is taken from collateral during repay. Market interest rate is set to 0.
- MAI price is fixed to $1.0.
- Vault ownership is tracked using NFTs, which can be transferred between addresses. This is not tracked in the subgraph.
- Vault reward token (Qi) emissions are calculated off-chain from snapshots and are not tracked.
- Masterchef contracts are not tracked.
- [Anchor](https://app.mai.finance/anchor) is not tracked.
# Alchemix Yield Protocol Subgraph

## Useful Links

- https://alchemix.fi/
- https://alchemix-finance.gitbook.io/v2/
- Add here

## Calculation Methodology v0.0.1

### Total Value Locked (TVL) USD

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Revenue USD

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Vaults

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added
# Uniswap v2 Subgraph

> This is a reference subgraph used to demonstrate some of the common patterns  
> you should use in your subgraph. It should help you bootstrap your subgraph  
> quickly, improve the readability and maintainability of your code, and  
> provide some common functions/modules that you can leverage. Specifically,  
> here are some guidelines:
>
> - Make sure you include this README (but without this section) in the  
>   subgraph, with links to protocol-related resource and build instruction.
> - Note that after you init the subgraph with `graph init`, it would create  
>   another git repo inside of the existing one. You should remove that with  
>   `rm -rf .git` and not check it in as a submodule.
> - Make sure you run `npm run format` to format your code before committing.
> - Try to follow the same folder structure inside of `src` for your subgraph.
> - There is a set of useful functions in `src/common` that you can leverage.
>  
> Note: this subgraph is just a reference is not meant to be built and deployed  
> Note: since Uniswap v2 is a DEX (AMM), the `schema.graphql` used here is  
> derived from `schema-dex-amm.graphql` in the repo root.

## Links

- Protocol: https://uniswap.org/
- Analytics: https://v2.info.uniswap.org/
- Docs: https://docs.uniswap.org/protocol/V2/introduction
- Smart contracts: https://github.com/Uniswap/v2-core
- Deployed addresses: https://docs.uniswap.org/protocol/V2/reference/smart-contracts/factory
- Official subgraph: https://github.com/Uniswap/v2-subgraph

## Build

- Initialize subgraph (Subgraph Studio):
  ```
  graph init --product subgraph-studio
  --from-contract <CONTRACT_ADDRESS> [--network <ETHEREUM_NETWORK>] [--abi <FILE>] <SUBGRAPH_SLUG> [<DIRECTORY>]
  ```
- Initialize subgraph (Hosted Service):
  ```
  graph init --product hosted-service --from-contract <CONTRACT_ADDRESS> <GITHUB_USER>/<SUBGRAPH_NAME>[<DIRECTORY>]
  ```
- Generate code from manifest and schema: `graph codegen`
- Build subgraph: `graph build`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Subgraph Studio: `graph deploy --studio <SUBGRAPH_NAME>`
- Deploy to Hosted Service: `graph deploy --product hosted-service <GITHUB_USER>/<SUBGRAPH_NAME>`
# StakeDAO Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Vaults: 

`Vault TVL`

### Total Revenue USD

Sum across all Vaults:

`Total Yield`

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Vault Revenue * Annualized Vault Performance Fee) + (Withdraw Amount * Vault Withdraw Fee)`

Note that different fees are applied:

- Passive Vaults: Performance Fee +  Withdrawal fee
- Option Vaults: Performance Fee + Withdrawal Fee 
- (Fees can vary between vaults - standard is 15% performance, 0.5% withdrawal)

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Vault Revenue * (1-Vault annualized Performance Fee)) - (Withdraw Amount * Vault Withdraw Fee)`

Note that this is the remaining yield after protocol fees

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposit`

`Withdraw`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added

## Links

- Protocol website: https://stakedao.org/
- Protocol documentation: https://stakedao.gitbook.io/stakedaohq/
- Smart contracts: https://github.com/StakeDAO/smart-contracts
- Deployed addresses: https://stakedao.gitbook.io/stakedaohq/platform/deployed-contracts
- Existing subgraphs: https://github.com/SimpleFi-finance/subgraphs/tree/master/stake-dao
# Liquity Lending Protocol Subgraph

## Links

- Protocol website: https://www.liquity.org
- Protocol documentation: https://docs.liquity.org
- Smart contracts: https://github.com/liquity/dev/tree/main/packages/contracts/contracts
- Deployed addresses: https://docs.liquity.org/documentation/resources#contract-addresses
- Existing subgraphs: https://thegraph.com/explorer/subgraph?id=2TmD7Fq3K2BQGmUXNPzrNMXb6PDNbcBWfAHa5o3gRJC8

## Calculation Methodology v1.0.1

### Total Value Locked (TVL) USD

Sum across all Pools:

`Collateral locked in Troves + LUSD and Collateral in stability pool`

Ignores LQTY staked. Currently, the only Collateral is ETH.

### Total Revenue USD

Sum across all Pools:

`Borrowing Fee + Redemption Fee + Liquidation Revenue (i.e. Liquidation reserve of 200 LUSD + Value of Collateral - Outstanding Loan Amount)`

Borrowing fee is 0.5% to 5% depending on amount borrowed, Redemption fee is Borrowing fee + 0.5%

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`Borrowing Fee + Redemption Fee + Part of Liquidation Revenue (Liquidation reserve of 200 LUSD + 0.5% of Collateral)`

Part of Liquidation Revenue (Liquidation reserve of 200 LUSD + 0.5% of Collateral) goes to Liquidator

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`Part of Liquidation Revenue (i.e. 99.5% of Collateral - Outstanding Loan Amount)`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Repays`

`Liquidations`

### Reward Token Emissions Amount

To be added

### Protocol Controlled Value

To be added

## Smart Contract Interactions

### Events included in the subgraph

![Liquity](../../docs/images/protocols/liquity.png "Liquity")

See also official documentation for more detailed charts:

https://github.com/liquity/dev#flow-of-ether-in-liquity
# Uniswap Analytics

![Uniswap Analytics](../../docs/images/apps/uniswap-analytics.png "Uniswap Analytics")

## Development

Install venv

```
python3 -m venv venv
```

Activate venv

```
source venv/bin/activate
```

Install dependencies

```
pip3 install -r requirements.txt
```

Run locally

```
streamlit run app.py
```
# Bancor v2.1 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Sum of Pool Assets`

do inlcude protocol-deposited BNT as TVL

https://bancor-network.gitbook.io/v2.1/guides/querying-a-pool-contract

### Total Revenue USD

Sum across all Pools:

`PoolFee * Pool Volume`

Note - Bancor supplies BNT liquidity. Fees on this liquidity go to covering IL losses of outside LPs. As such, this would still be considered revenue (and protocol revenue). Each pool can have its own fee 

https://bancor-network.gitbook.io/v2.1/guides/measuring-trading-volume

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`PoolFee * Pool Volume * (Protocol BNT / Total TVL)`

This should be the fee revenue attributed to Bancor-supplied BNT 
-- future note: LP fees are subsequently used to compensate users for IL. This should be a operating expense in the future. If Fee Income > IL payouts, then native tokens dumped for more BNT by the protocol. 

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`PoolFeeModel * Pool Volume * (1 - (Protocol BNT / Total TVL)`

This should be fee income not given to Bancor

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Swaps`

`Deposits`

`Withdraws`

###  Reward Token Emissions Amount

To be added

  

## Links

- Protocol website: https://www.bancor.network/
- Protocol documentation: https://docs.bancor.network/
- Version 2.1 Docs: https://bancor-network.gitbook.io/v2.1/faqs
- Smart contracts: https://github.com/bancorprotocol/contracts-solidity
- Deployed addresses: https://docs.bancor.network/ethereum-contracts/addresses
- Existing subgraphs: https://thegraph.com/hosted-service/subgraph/blocklytics/bancor
# Balancer v2 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Liquidity Pool TVL`

### Total Revenue USD

Sum across all Pools:

`Pool Swap Volume * Pool Swap Fee`

Note, does this not include

- Flash Loans (Flash Loan Amount \* Flash Loan Interest)
- Asset Manager Yield Generated

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`Pool Swap Volume * Pool Swap Fee * ProtocolSide Fee`

Note: 04/07/22 The ProtocolSideFee is currently 50% and has been changed twice. It can continue changing.

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`Pool Swap Volume * Pool Swap Fee * (1 - ProtocolSide Fee)`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Swaps`

`Deposits`

`Withdraws`

### Reward Token Emissions Amount

To be added

### Protocol Controlled Value

To be added

## Useful Links

- Protocol: https://balancer.fi/
- Analytics: https://dune.xyz/balancerlabs
- Docs: https://docs.balancer.fi/
- Smart contracts: https://github.com/balancer-labs/balancer-v2-monorepo
- Deployed addresses: https://github.com/balancer-labs/balancer-v2-monorepo/tree/master/pkg/deployments#past-deployments
- Official subgraph: https://github.com/balancer-labs/balancer-subgraph-v2

## Smart Contracts Interactions

![balancer-v2](../../docs/images/protocols/balancer-v2.png "balancer-v2")

## Build

- Generate code from manifest and schema: `yarn codegen`
- Build subgraph:
  - Mainnet: `yarn build:mainnet`
  - Polygon: `yarn build:polygon`
  - Arbitrum: `yarn build:arbitrum`
  - Beets: `yarn build:beets`
  - Beets-optimism: `yarn build:beetsop`

## Deploy

- Authenticate (just once): `graph auth --product hosted-service <ACCESS_TOKEN>`
- Deploy to Hosted Service:
  - Mainnet `yarn deploy:mainnet`
  - Polygon `yarn deploy:polygon`
  - Arbitrum `yarn deploy:arbitrum`
  - Beets: `yarn deploy:beets`
  - Beets-optimism: `yarn deploy:beetsop`
# Yield Yak Subgraph

## Calculation Methodology v0.0.1

### Total Value Locked (TVL) USD

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Revenue USD

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Vaults:

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Vaults

`Insert Calculation`

<Add notes to consider if any - delete if none>

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added

## Links

- Protocol website: https://yieldyak.com/
- Protocol documentation: https://docs.yieldyak.com/
- Smart contracts: https://github.com/yieldyak/smart-contracts
# Validation Dashboard

This document contains some instruction on the functionality of the Validation Dashboard

## Deployments Page

### Input Box

This input is used to pull up a subgraph to validate. This box accepts the Query URL specified for your deployment on its Graph page (Under the label `Queries (HTTP)` for the hosted service and under the label `TEMPORARY QUERY URL` for subgraph studio deployments). Alternatively for Hosted Service deployments, you can use the subgraph name string (constructed as `messari/PROTOCOL-VERSION-NETWORK`, for example `messari/uniswap-v3-ethereum`).

### Deployment Tiles

This section contains deployments from a hardcoded list of protocols deployed on the hosted service for easy access. Each protocol section is divided into each network the subgraph has a deployment for. The indexing status is pulled for each subgraph. If there was a fatal error in the indexing process, the deployment tile is highlighted in Red and provides a small amount of information about where/when the error occurred. If a subgraph deployment is not the latest schema version, it is highlighted in yellow. If a subgraph deployment is the latest schema version and has reached 100% indexed status, it is highlighted in green.

Clicking on a tile loads that subgraph into the validation dashboard. Subgraphs with fatal errors cannot validate any data, however clicking on these tiles gives a some more insight into the fatal error.

## Protocol Dashboard

Upon entering a subgraph to query/clicking on a deployment tile, the application loads a query param with the subgraph currently being validated. As the subgraph's data loads, you will see a header with subgraph metadata such as name, schema version, and protocol type. After the data is returned and processed, new header sections appear. If there are warnings/errors detected from the data returned, a box will appear with numbered messages about inconsistencies or issues with the data. Generally, the order of warnings are not based on priority but rather when they came up in execution. Error/warning handling is a work in progress and may miss some fields or show duplicate messages. The next header section are the page tabs. These toggle the view between Protocol level data, Pool level data, and event data. Because of the nature of loading all of the different data between tabs, if clicking on a tab is not immediately responsive wait a few seconds and it should load the correct page. If the Protocol Dashboard is loaded from the deployment screen or from being linked without a specified tab as a query param, the Protocol tab is loaded by default.

Unless the user is brought to the Validation dashboard by a link with a poolId query param speicified, there is no pool selected by default. If no pool is currently selected, switching to the Pool or Events tabs shows a pool selection input. It is a text input/drop down combo box. Once an option is selected, the query to pull the pool data is sent.

Amongst all of these tabs, every section contains a button with text along the lines of "Copy Link To financialsDailySnapshots-totalValueLockedUSD". This button copies a link to that specific section to make it easier to share and point to a specific chart or table. If this is on pool level/event data, the poolId is loaded into this link to bring the user directly to that element on the specified pool.

### Protocol Tab

Protocol level data involves subgraph data that does not apply to any specific pool. The table at the top of the page displays all of the data on the protocol entity (for DEXs "dexAmmProtocols", for lending "lendingProtocols", and for yield protocols "yieldAggregators"). The left side of the table is the field name followed by its specified type in the schema. The right side is the current value of that field in the protocol entity.

Below the table, timeseries data is divided into their own sections. On the Protocol level the timeseries entities are `financialsDailySnapshots`, `usageMetricsDailySnapshots`, and depending on the subgraph schema version possibly `usageMetricsHourlySnapshots`. All of the fields on these entities are mapped through and rendered into charts plotting each data point on a given snapshot.

### Pool Tab

Before a pool is selected, a text input/drop down box appears prompting selection. Once a pool is selected, a query is sent to pull the appropriate pool data.

Once pool data is loaded, the top of the page displays a table containing data on the pool entity (for DEXs "liquidityPool", for lending "market", and for yield protocols "vault"). The left side of the table is the field name followed by its specified type in the schema. The right side is the current value of that field in the pool entity.

Below the table, timeseries data is divided into their own sections. On the Pool level the timeseries entities are `...DailySnapshots`, and `...HourlySnapshots` for the given pool. All of the fields on these entities are mapped through and rendered into charts plotting each data point on a given snapshot. Data for fields with multiple indexes are broken down into their own charts. For example, timeseries data involving reward tokens are broken down into a chart for each reward token. The broken down charts are labeled by name or index in the array.

### Events Tab

Before a pool is selected, a text input/drop down box appears prompting selection. Once a pool is selected, a query is sent to pull the appropriate event data on the pool.

Once the pool data is loaded, a table for each event type is loaded. The table contains entries for each instance of an event. If an event type for the protocol type has no instances, a message is rendered in place of the event table.

## Troubleshooting

In the case of data appearing differently as expected, here are some things to do to verify and correct the data. If any issues arise or if you suspect something is erroneous on the dashboard, please leave a message in the 'Validation-Dashboard' Discord channel.

-Upon entering a subgraph to validate, if an error is received saying `Required schema fields are missing from this subgraph. Verify that your schema has all of the fields that are in the common ***** schema.`, the specified field is required for the protocol type but is missing from the subgraph.

-Check the schema for that data field and check that the data is being saved in the correct unit

-For data involving tokens, the Validation assumes that the token amount has not been converted with decimals. Make sure that the tokens on a pool have the correct value for decimals.

-For zero values in the timeseries tables, make sure that the field is being saved on the snapshot
# Aave V2 Forks

## Quickstart

### Deployment

Once everything is setup properly deploying is very easy.

```bash
# This example will deploy all forks of aave-v2 on all networks to the hosted service under "dmelotik" in deploymentConfigurations.json
npm run deploy --SUBGRAPH=aave-v2-forks --PROTOCOL=aave-v2 --LOCATION=dmelotik

# This will do the same, but only deploying the mainnet subgraph
npm run deploy --SUBGRAPH=aave-v2-forks --PROTOCOL=aave-v2 --NETWORK=mainnet --LOCATION=dmelotik
```

> Setting `deploy-on-merge` to `true` in [deploymentConfigurations.json](../../deployment/deploymentConfigurations.json) will run the above commands on subgraphs that have changed to messari's hosted service.

### Development Commands

During development you probably won't want to fully deploy the subgraph every time. Follow this guide to do each step incrementally.

To setup the subgraph manifest from the template:

```bash
# Use aave-v2 as an example
npm run prepare:yaml --PROTOCOL=aave-v2 --NETWORK=mainnet --TEMPLATE=aave.v2.template.yaml
```

To codegen and build:

```bash
graph codegen
graph build
```

> If you are working on multiple subgraphs you may want to delete `./generated/**` before `codegen` so no old files are left behind.

To deploy follow the steps above. You may put your hosted service endpoint in [deploymentConfigurations.json](../../deployment/deploymentConfigurations.json) just how messari's is set to take advantage of the commands.

## Aave Transaction Flow

When a transaction occurs in the `lendingPool` the following events are emitted in this order.

1. Next a `reserveDataUpdated` event is emitted
   1. This is equivalent to `AccrueInterest` in compound.
   2. New Revenue = ScaledTotalSupply \* (currentLiquidityIndex - lastLiquidityIndex)
   3. This event is used to update all of the rates, prices, and balances in the subgraph.
2. To get current supply balance we take use a contract call to `totalSupply()` in the respective aToken
3. To get the current borrow balance we call `totalSupply()` in both the VariableDebtToken and StableDebtToken
4. Finally we handle the actual transaction event (ie, deposit, borrow, repay, withdraw, liquidate)
   1. This handler is designed to only update the metrics that have to do with those events. ie, usage and daily/hourly event amounts

### Problems

- Unable to change `protocol.id` for multiple deployments on mainnet [see code](./protocols/aave-v2/src/constants.ts)

### Resources

- Aave V2 Contract Addresses: https://docs.aave.com/developers/v/2.0/deployed-contracts/deployed-contracts
- Aave V2 Permissioned Contract Addresses: https://aave-arc.gitbook.io/docs/deployed-contracts/arc
- Gesit Contract Addresses: https://docs.geist.finance/useful-info/deployments-addresses
# Aave v2 Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Pools:

`Pool Deposit TVL`

### Total Revenue USD

Sum across all Pools:

`(Pool Variable Borrow Amount * Variable Pool Borrow Rate) + (Pool Stable Borrow Amount * Stable Pool Borrow Rate)`

Note: This currently excludes Flash Loans

### Protocol-Side Revenue USD

Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`(Pool Oustanding Borrow Amount * Pool Borrow Rate) * (Pool Reserve Factor)`

### Supply-Side Revenue USD

Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`(Pool Outstanding Borrow Amount * Pool Borrow Rate) * (1 - Pool Reserve Factor)`

### Total Unique Users

Count of Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdrawals`

`Borrows`

`Liquidations`

`Repayments`

### Reward Token Emissions Amount

To be added

### Protocol Controlled Value

Not applicable to Aave

## Useful links and references

Existing Subgraph - https://thegraph.com/hosted-service/subgraph/aave/protocol-v2

https://docs.aave.com/risk/asset-risk/risk-parameters#reserve-factor
# Harvest Finance Subgraph

## Calculation Methodology v1.0.0

### Total Value Locked (TVL) USD

Sum across all Vaults: 

`Vault TVL`

### Total Revenue USD

Sum across all Vaults:

`Harvested Yield`

Note: This does not currently include investments https://harvest-finance.gitbook.io/harvest-finance/general-info/what-do-we-do/420-69-programm

### Protocol-Side Revenue USD
Portion of the Total Revenue allocated to the Protocol

Sum across all Pools:

`Harvested Yield * Protocol Share`

Note that the Protocol Share varies on the Network. 

e.g. As of 04/07/22, the Protocol Share on Ethereum is 30% and 8% on BNB Chain

### Supply-Side Revenue USD
Portion of the Total Revenue allocated to the Supply-Side

Sum across all Pools

`Harvested Yield * (1 - Protocol Share)`

### Total Unique Users

Count of  Unique Addresses which have interacted with the protocol via any transaction

`Deposits`

`Withdraws`

###  Reward Token Emissions Amount

To be added

###  Protocol Controlled Value

To be added

## Useful Links

Existing Subgraph

https://thegraph.com/hosted-service/subgraph/harvestfi/harvest-finance	

https://github.com/harvestfi/thegraph	

Documentation - https://harvest-finance.gitbook.io/harvest-finance/thegraph/harvest-finance-subgraph
# Price Oracle

## Configuration

- In `subgraph.yaml`, add the following code inside the `abis` section of the `datasources` which is going to fetch prices of token using the `Price Oracle`.
  **NOTE**: Include the following code in each of the datasources, that is dependent on the `Price Oracle` and update imports in each file inside oracle folder.

```
#############################################
############## Price Oracle #################
#############################################
- name: ERC20
  file: ./abis/Ethereum/ERC20.json
- name: CurveRegistry
  file: ./abis/Oracles/Curve/Registry.json
- name: CalculationsCurve
  file: ./abis/Oracles/Calculations/Curve.json
- name: YearnLensContract
  file: ./abis/Oracles/YearnLens.json
- name: ChainLinkContract
  file: ./abis/Oracles/ChainLink.json
- name: UniswapRouter
  file: ./abis/Oracles/Uniswap/Router.json
- name: UniswapFactory
  file: ./abis/Oracles/Uniswap/Factory.json
- name: UniswapPair
  file: ./abis/Oracles/Uniswap/Pair.json
- name: SushiSwapRouter
  file: ./abis/Oracles/SushiSwap/Router.json
- name: SushiSwapFactory
  file: ./abis/Oracles/SushiSwap/Factory.json
- name: SushiSwapPair
  file: ./abis/Oracles/SushiSwap/Pair.json
- name: CalculationsSushiSwap
  file: ./abis/Oracles/Calculations/SushiSwap.json
```

## Usage

Following are some ways through which you can get the prices of tokens:

```
import { BigDecimal } from "@graphprotocol/graph-ts";
import { getUsdPricePerToken, getUsdPrice } from "../Oracle";

// Method 1 
// Using function getUsdPricePerToken(tokenAddr: Address)

let tokenPrice: BigDecimal;
let fetchPrice = getUsdPricePerToken(tokenAddr);
if (!fetchPrice.reverted) {
  tokenPrice = fetchPrice.usdPrice.div(
    fetchPrice.decimals.toBigDecimal()
  );
} else {
  // default value of this variable, if reverted is BigDecimal Zero
  tokenPrice = fetchPrice.usdPrice
}

// Method 2
// Using function getUsdPrice(tokenAddr: Address, amount: BigInt)

let tokenPrice = getUsdPrice(tokenAddr, amount);
```

## Optimizations

- Reorder the methods present in `index.ts`, depending on which method works best for you.

## Folder Structure

```

Prices
├── calculations
│   ├── CalculationsCurve.ts
│   └── CalculationsSushiSwap.ts
├── common
│   ├── types.ts
│   ├── constants.ts
│   └── utils.ts
├── oracles
│   ├── ChainLinkFeed.ts
│   └── YearnLensOracle.ts
├── routers
│   ├── CurveRouter.ts
│   ├── SushiSwapRouter.ts
│   └── UniswapRouter.ts
└── index.ts
```

## Development Status

### Mainnet

🔨 = In progress.  
🛠 = Feature complete. Additional testing required.
`MultiCall` = If the method uses more than two `JSON RPC Call`.

| Method                                                                               |      Type      | StartBlock | MultiCall | Status |
| ------------------------------------------------------------------------------------ | :------------: | :--------: | :-------: | :----: |
| [YearnLens](https://etherscan.io/address/0x83d95e0d5f402511db06817aff3f9ea88224b030) |    `Oracle`    | `12242339` |    ❎     |   🛠    |
| [ChainLink](https://etherscan.io/address/0x47Fb2585D2C56Fe188D0E6ec628a38b74fCeeeDf) |    `Oracle`    | `12864088` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x25BF7b72815476Dd515044F9650Bf79bAd0Df655)     | `Calculations` | `12370088` |    ❎     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0x8263e161A855B644f582d9C164C66aABEe53f927) | `Calculations` | `12692284` |    ❎     |   🛠    |
| [Curve](https://etherscan.io/address/0x7D86446dDb609eD0F5f8684AcF30380a356b2B4c)     |    `Router`    | `11154794` |    ✅     |   🛠    |
| [Uniswap](https://etherscan.io/address/0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D)   |    `Router`    | `10207858` |    ✅     |   🛠    |
| [SushiSwap](https://etherscan.io/address/0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F) |    `Router`    | `10794261` |    ✅     |   🛠    |
