"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
    return function (target, key) { decorator(target, key, paramIndex); }
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConvexFarmContractPositionFetcher = exports.claimedCrvToMintedCvx = void 0;
const common_1 = require("@nestjs/common");
const bignumber_js_1 = __importDefault(require("bignumber.js"));
const ethers_1 = require("ethers");
const lodash_1 = require("lodash");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const position_utils_1 = require("../../../position/position.utils");
const single_staking_dynamic_template_contract_position_fetcher_1 = require("../../../position/template/single-staking.dynamic.template.contract-position-fetcher");
const _types_1 = require("../../../types");
const contracts_1 = require("../contracts");
const claimedCrvToMintedCvx = (claimedCrvAmount, currentCvxSupply) => {
    const claimedCrvAmountBN = new bignumber_js_1.default(claimedCrvAmount);
    const currentCvxSupplyBN = new bignumber_js_1.default(currentCvxSupply);
    const tokensPerCliff = new bignumber_js_1.default(100000).times(1e18);
    const maxCliffCount = new bignumber_js_1.default(1000);
    const maxCvxSupply = new bignumber_js_1.default(100000000).times(1e18);
    const currentCliff = currentCvxSupplyBN.div(tokensPerCliff);
    if (currentCliff.gte(maxCliffCount))
        return ethers_1.ethers.BigNumber.from(0);
    const remainingCliffs = maxCliffCount.minus(currentCliff);
    const remainingCliffRatio = remainingCliffs.div(maxCliffCount);
    const remainingCvxToMint = maxCvxSupply.minus(currentCvxSupplyBN);
    const maybeCvxRewardTokenBalanceRaw = remainingCliffRatio.times(claimedCrvAmountBN);
    const cvxRewardTokenBalanceRaw = maybeCvxRewardTokenBalanceRaw.gt(remainingCvxToMint)
        ? remainingCvxToMint
        : maybeCvxRewardTokenBalanceRaw;
    return ethers_1.ethers.BigNumber.from(cvxRewardTokenBalanceRaw.toFixed(0));
};
exports.claimedCrvToMintedCvx = claimedCrvToMintedCvx;
let ConvexFarmContractPositionFetcher = class ConvexFarmContractPositionFetcher extends single_staking_dynamic_template_contract_position_fetcher_1.SingleStakingFarmDynamicTemplateContractPositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getContract(address) {
        return this.contractFactory.convexSingleStakingRewards({ address, network: this.network });
    }
    getStakedTokenAddress({ contract }) {
        return contract.stakingToken();
    }
    getRewardTokenAddresses({ multicall, contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            const primaryRewardTokenAddresses = [
                '0xd533a949740bb3306d119cc777fa900ba034cd52',
                '0x4e3fbd56cd56c3e72c1403e103b45db9da5b9d2b',
            ];
            const numExtraRewards = yield contract.extraRewardsLength();
            const extraRewardTokenAddresses = yield Promise.all((0, lodash_1.range)(0, Number(numExtraRewards)).map((v) => __awaiter(this, void 0, void 0, function* () {
                const vbpAddress = yield contract.extraRewards(v);
                const vbp = this.contractFactory.convexVirtualBalanceRewardPool({ address: vbpAddress, network: this.network });
                const rewardTokenAddressRaw = yield multicall.wrap(vbp).rewardToken();
                const rewardTokenAddress = rewardTokenAddressRaw.toLowerCase();
                if (rewardTokenAddress === primaryRewardTokenAddresses[1])
                    return null;
                return rewardTokenAddressRaw.toLowerCase();
            })));
            return [...primaryRewardTokenAddresses, ...(0, lodash_1.compact)(extraRewardTokenAddresses)];
        });
    }
    getRewardRates({ contract, contractPosition, multicall, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const rewardTokens = contractPosition.tokens.filter(position_utils_1.isClaimable);
            const [, cvxRewardToken] = rewardTokens;
            const cvxTokenContract = this.contractFactory.erc20(cvxRewardToken);
            const cvxSupplyRaw = yield multicall.wrap(cvxTokenContract).totalSupply();
            const crvRewardRate = yield multicall.wrap(contract).rewardRate();
            let cvxRewardRate = (0, exports.claimedCrvToMintedCvx)(crvRewardRate.toString(), cvxSupplyRaw.toString());
            const numExtraRewards = yield multicall.wrap(contract).extraRewardsLength();
            const extraRewardRates = yield Promise.all((0, lodash_1.range)(0, Number(numExtraRewards)).map((v) => __awaiter(this, void 0, void 0, function* () {
                const vbpAddress = yield multicall.wrap(contract).extraRewards(v);
                const vbpContract = this.contractFactory.convexVirtualBalanceRewardPool({
                    address: vbpAddress,
                    network: _types_1.Network.ETHEREUM_MAINNET,
                });
                const extraRewardRate = yield multicall.wrap(vbpContract).rewardRate();
                const extraRewardTokenAddressRaw = yield multicall.wrap(vbpContract).rewardToken();
                const extraRewardTokenAddress = extraRewardTokenAddressRaw.toLowerCase();
                if (extraRewardTokenAddress === cvxRewardToken.address) {
                    cvxRewardRate = cvxRewardRate.add(extraRewardRate);
                    return null;
                }
                return extraRewardRate;
            })));
            return [crvRewardRate, cvxRewardRate, ...(0, lodash_1.compact)(extraRewardRates)];
        });
    }
    getStakedTokenBalance({ address, contract, }) {
        return contract.balanceOf(address);
    }
    getRewardTokenBalances({ address, contract, multicall, contractPosition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const rewardTokens = contractPosition.tokens.filter(position_utils_1.isClaimable);
            const [, cvxRewardToken] = rewardTokens;
            const cvxTokenContract = multicall.wrap(this.contractFactory.erc20(cvxRewardToken));
            const currentCvxSupply = yield cvxTokenContract.totalSupply();
            const crvBalanceBN = yield contract.earned(address);
            const crvBalanceRaw = crvBalanceBN.toString();
            let cvxBalanceRaw = (0, exports.claimedCrvToMintedCvx)(crvBalanceRaw, currentCvxSupply.toString());
            const numExtraRewards = yield multicall.wrap(contract).extraRewardsLength();
            const extraRewardBalances = yield Promise.all((0, lodash_1.range)(0, Number(numExtraRewards)).map((_, i) => __awaiter(this, void 0, void 0, function* () {
                const vbpAddress = yield contract.extraRewards(i);
                const vbpContract = this.contractFactory.convexVirtualBalanceRewardPool({
                    address: vbpAddress,
                    network: this.network,
                });
                const earnedBN = yield multicall.wrap(vbpContract).earned(address);
                const extraRewardTokenAddressRaw = yield multicall.wrap(vbpContract).rewardToken();
                const extraRewardTokenAddress = extraRewardTokenAddressRaw.toLowerCase();
                if (extraRewardTokenAddress === cvxRewardToken.address) {
                    cvxBalanceRaw = cvxBalanceRaw.add(earnedBN);
                    return null;
                }
                return earnedBN;
            })));
            return [crvBalanceRaw, cvxBalanceRaw, ...(0, lodash_1.compact)(extraRewardBalances)];
        });
    }
};
ConvexFarmContractPositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.ConvexContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.ConvexContractFactory])
], ConvexFarmContractPositionFetcher);
exports.ConvexFarmContractPositionFetcher = ConvexFarmContractPositionFetcher;
//# sourceMappingURL=convex.farm.contract-position-fetcher.js.map