"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.CurvePoolGaugeContractPositionFetcher = exports.GaugeType = void 0;
const common_1 = require("@nestjs/common");
const ethers_1 = require("ethers");
const lodash_1 = require("lodash");
const moment_1 = __importDefault(require("moment"));
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const address_1 = require("../../../app-toolkit/constants/address");
const image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const position_interface_1 = require("../../../position/position.interface");
const position_utils_1 = require("../../../position/position.utils");
const contract_position_template_position_fetcher_1 = require("../../../position/template/contract-position.template.position-fetcher");
const contracts_1 = require("../contracts");
var GaugeType;
(function (GaugeType) {
    GaugeType["SINGLE"] = "single";
    GaugeType["DOUBLE"] = "double";
    GaugeType["N_GAUGE"] = "n-gauge";
    GaugeType["GAUGE_V4"] = "gauge-v4";
    GaugeType["CHILD"] = "child-chain";
    GaugeType["REWARDS_ONLY"] = "rewards-only";
})(GaugeType = exports.GaugeType || (exports.GaugeType = {}));
let CurvePoolGaugeContractPositionFetcher = class CurvePoolGaugeContractPositionFetcher extends contract_position_template_position_fetcher_1.ContractPositionTemplatePositionFetcher {
    constructor(appToolkit, contractFactory) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
    }
    getContract(address) {
        return this.contractFactory.curveGauge({ address, network: this.network });
    }
    getDefinitions({ multicall }) {
        return __awaiter(this, void 0, void 0, function* () {
            const contract = multicall.wrap(this.resolveRegistry(this.registryAddress));
            const poolCount = yield this.resolvePoolCount({ contract, multicall });
            const poolRange = (0, lodash_1.range)(0, Number(poolCount));
            const gaugeDefinitions = yield Promise.all(poolRange.map((poolIndex) => __awaiter(this, void 0, void 0, function* () {
                const swapAddress = yield this.resolveSwapAddress({ contract, poolIndex, multicall });
                const tokenAddress = yield this.resolveTokenAddress({ contract, swapAddress, multicall });
                const gaugeAddresses = yield this.resolveGaugeAddresses({ contract, swapAddress, multicall });
                const realGaugeAddresses = gaugeAddresses.filter(v => v !== address_1.ZERO_ADDRESS);
                return yield Promise.all(realGaugeAddresses.map((gaugeAddress) => __awaiter(this, void 0, void 0, function* () {
                    return ({
                        address: gaugeAddress.toLowerCase(),
                        swapAddress: swapAddress.toLowerCase(),
                        tokenAddress: tokenAddress.toLowerCase(),
                        gaugeType: yield this.resolveGaugeType(gaugeAddress),
                    });
                })));
            })));
            return gaugeDefinitions.flat();
        });
    }
    resolveGaugeType(gaugeAddress) {
        return __awaiter(this, void 0, void 0, function* () {
            const provider = this.appToolkit.getNetworkProvider(this.network);
            let bytecode = yield provider.getCode(gaugeAddress);
            const minimalProxyMatch = /0x363d3d373d3d3d363d73(.*)5af43d82803e903d91602b57fd5bf3/.exec(bytecode);
            if (minimalProxyMatch)
                bytecode = yield provider.getCode(`0x${minimalProxyMatch[1]}`);
            const doubleGaugeMethod = ethers_1.ethers.utils.id('rewarded_token()').slice(2, 10);
            const nGaugeMethod = ethers_1.ethers.utils.id('reward_tokens(uint256)').slice(2, 10);
            const gaugeV4Method = ethers_1.ethers.utils.id('claimable_reward_write(address,address)').slice(2, 10);
            if (bytecode.includes(gaugeV4Method))
                return GaugeType.GAUGE_V4;
            if (bytecode.includes(nGaugeMethod))
                return GaugeType.N_GAUGE;
            if (bytecode.includes(doubleGaugeMethod))
                return GaugeType.DOUBLE;
            return GaugeType.SINGLE;
        });
    }
    getTokenDefinitions({ address, definition, multicall, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const definitions = [
                { metaType: position_interface_1.MetaType.SUPPLIED, address: definition.tokenAddress, network: this.network },
                { metaType: position_interface_1.MetaType.CLAIMABLE, address: this.crvTokenAddress, network: this.network },
            ];
            if (definition.gaugeType === GaugeType.DOUBLE) {
                const doubleGauge = this.contractFactory.curveDoubleGauge({ address, network: this.network });
                const rewardTokenAddress = yield multicall.wrap(doubleGauge).rewarded_token();
                definitions.push({ metaType: position_interface_1.MetaType.CLAIMABLE, address: rewardTokenAddress, network: this.network });
            }
            if ([GaugeType.GAUGE_V4, GaugeType.N_GAUGE].includes(definition.gaugeType)) {
                const nGauge = this.contractFactory.curveNGauge({ address, network: this.network });
                const rewardTokenAddresses = yield Promise.all((0, lodash_1.range)(0, 4).map(i => multicall.wrap(nGauge).reward_tokens(i)));
                const filtered = rewardTokenAddresses.filter(v => v !== address_1.ZERO_ADDRESS);
                filtered.forEach(v => definitions.push({ metaType: position_interface_1.MetaType.CLAIMABLE, address: v, network: this.network }));
            }
            return definitions;
        });
    }
    getDataProps({ address, contract, multicall, contractPosition, definition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const stakedToken = contractPosition.tokens.find(position_utils_1.isSupplied);
            const rewardTokens = contractPosition.tokens.filter(position_utils_1.isClaimable);
            const stakedTokenContract = this.contractFactory.erc20(stakedToken);
            const reserveRaw = yield multicall.wrap(stakedTokenContract).balanceOf(address);
            const reserve = Number(reserveRaw) / Math.pow(10, stakedToken.decimals);
            const liquidity = reserve * stakedToken.price;
            const gaugeType = definition.gaugeType;
            const controller = this.contractFactory.curveController({
                address: this.controllerAddress,
                network: this.network,
            });
            const inflationRateRaw = yield contract.inflation_rate();
            const workingSupplyRaw = yield contract.working_supply();
            const relativeWeightRaw = yield multicall.wrap(controller)['gauge_relative_weight(address)'](address);
            const inflationRate = Number(inflationRateRaw) / Math.pow(10, 18);
            const workingSupply = Number(workingSupplyRaw) / Math.pow(10, 18);
            const relativeWeight = Number(relativeWeightRaw) / Math.pow(10, 18);
            const secondsPerYear = moment_1.default.duration(1, 'year').asSeconds();
            const ratePerSecond = (inflationRate * relativeWeight * 0.4) / workingSupply;
            const apy = ((ratePerSecond * secondsPerYear) / stakedToken.price) * rewardTokens[0].price * 100;
            const isActive = Number(inflationRate) > 0;
            return { gaugeType, liquidity, apy, isActive };
        });
    }
    getLabel({ contractPosition, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return `Staked ${(0, image_present_1.getLabelFromToken)(contractPosition.tokens[0])}`;
        });
    }
    getTokenBalancesPerPosition({ address, contractPosition, contract, multicall, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const rewardTokens = contractPosition.tokens.filter(position_utils_1.isClaimable);
            const balances = [yield contract.balanceOf(address), yield contract.claimable_tokens(address)];
            if (contractPosition.dataProps.gaugeType === GaugeType.DOUBLE && rewardTokens.length > 1) {
                const doubleGauge = this.contractFactory.curveDoubleGauge(contractPosition);
                const [secondaryRewardBalanceTotal, secondaryRewardBalanceClaimed] = yield Promise.all([
                    multicall.wrap(doubleGauge).claimable_reward(address),
                    multicall.wrap(doubleGauge).claimed_rewards_for(address),
                ]);
                const secondaryRewardBalance = secondaryRewardBalanceTotal.sub(secondaryRewardBalanceClaimed);
                balances.push(secondaryRewardBalance);
            }
            if (contractPosition.dataProps.gaugeType === GaugeType.N_GAUGE) {
                const nGauge = this.contractFactory.curveNGauge(contractPosition);
                const rewardTokenBalances = yield Promise.all(rewardTokens.slice(1).map(t => multicall.wrap(nGauge).claimable_reward(address, t.address)));
                balances.push(...rewardTokenBalances);
            }
            if (contractPosition.dataProps.gaugeType === GaugeType.GAUGE_V4) {
                const nGauge = this.contractFactory.curveGaugeV2(contractPosition);
                const rewardTokenBalances = yield Promise.all(rewardTokens.slice(1).map(t => multicall.wrap(nGauge).claimable_reward_write(address, t.address)));
                balances.push(...rewardTokenBalances);
            }
            return balances;
        });
    }
};
CurvePoolGaugeContractPositionFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.CurveContractFactory)),
    __metadata("design:paramtypes", [Object, contracts_1.CurveContractFactory])
], CurvePoolGaugeContractPositionFetcher);
exports.CurvePoolGaugeContractPositionFetcher = CurvePoolGaugeContractPositionFetcher;
//# sourceMappingURL=curve.pool-gauge.contract-position-fetcher.js.map