"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PickleJarUniv3TokenFetcher = void 0;
const common_1 = require("@nestjs/common");
const lodash_1 = require("lodash");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const uniswap_v3_liquidity_contract_position_builder_1 = require("../../../apps/uniswap-v3/common/uniswap-v3.liquidity.contract-position-builder");
const multicall_ethers_1 = require("../../../multicall/multicall.ethers");
const contract_interface_1 = require("../../../position/contract.interface");
const app_token_template_position_fetcher_1 = require("../../../position/template/app-token.template.position-fetcher");
const contracts_1 = require("../contracts");
const pickle_api_jar_registry_1 = require("./pickle.api.jar-registry");
let PickleJarUniv3TokenFetcher = class PickleJarUniv3TokenFetcher extends app_token_template_position_fetcher_1.AppTokenTemplatePositionFetcher {
    constructor(appToolkit, contractFactory, jarRegistry, uniswapV3LiquidityContractPositionBuilder) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.jarRegistry = jarRegistry;
        this.uniswapV3LiquidityContractPositionBuilder = uniswapV3LiquidityContractPositionBuilder;
    }
    getContract(address) {
        return this.contractFactory.pickleJarUniv3({ address, network: this.network });
    }
    getPositions() {
        return __awaiter(this, void 0, void 0, function* () {
            const multicall = this.appToolkit.getMulticall(this.network);
            const tokenLoader = this.appToolkit.getTokenDependencySelector({
                tags: { network: this.network, context: `${this.appId}__template` },
            });
            const definitions = yield this.getDefinitions({ multicall, tokenLoader });
            const addressesRaw = yield this.getAddresses();
            const addresses = addressesRaw.map(x => x.toLowerCase());
            const maybeSkeletons = yield Promise.all(addresses.map((address) => __awaiter(this, void 0, void 0, function* () {
                const definition = definitions.find(v => v.address.toLowerCase() === address);
                if (!definition)
                    return null;
                const contract = multicall.wrap(this.getContract(address));
                const context = { address, definition, contract, multicall, tokenLoader };
                const underlyingTokenDefinitions = yield this.getUnderlyingTokenDefinitions(context)
                    .then(v => v.map(t => ({ address: t.address.toLowerCase(), network: t.network })))
                    .catch(err => {
                    if ((0, multicall_ethers_1.isMulticallUnderlyingError)(err))
                        return null;
                    throw err;
                });
                if (!underlyingTokenDefinitions)
                    return null;
                const controllerAddr = yield contract.controller();
                const controller = multicall.wrap(this.contractFactory.pickleController({ address: controllerAddr, network: this.network }));
                const strategyAddr = yield controller.strategies(underlyingTokenDefinitions[0].address);
                const strategy = multicall.wrap(this.contractFactory.pickleStrategyUniv3({ address: strategyAddr, network: this.network }));
                const tokenId = yield strategy
                    .tokenId()
                    .then(x => x === null || x === void 0 ? void 0 : x.toString())
                    .catch(err => {
                    if ((0, multicall_ethers_1.isMulticallUnderlyingError)(err))
                        return null;
                    throw err;
                });
                if (!tokenId)
                    return null;
                return { address, definition, underlyingTokenDefinitions, tokenId };
            })));
            const skeletons = (0, lodash_1.compact)(maybeSkeletons);
            const tokens = yield Promise.all(skeletons.map(({ address, definition, tokenId }) => __awaiter(this, void 0, void 0, function* () {
                const uniV3Token = yield this.uniswapV3LiquidityContractPositionBuilder.buildPosition({
                    positionId: tokenId,
                    network: this.network,
                    multicall,
                    tokenLoader,
                    collapseClaimable: true,
                });
                if (!uniV3Token)
                    return null;
                const contract = multicall.wrap(this.getContract(address));
                const baseFragment = {
                    type: contract_interface_1.ContractType.APP_TOKEN,
                    appId: this.appId,
                    groupId: this.groupId,
                    network: this.network,
                    address,
                    tokens: uniV3Token.tokens,
                };
                const baseContext = { address, definition, contract, multicall, tokenLoader, appToken: baseFragment };
                const [symbol, decimals, totalSupplyRaw] = yield Promise.all([
                    this.getSymbol(baseContext),
                    this.getDecimals(baseContext),
                    this.getSupply(baseContext),
                ]);
                const supply = Number(totalSupplyRaw) / Math.pow(10, decimals);
                const pricePerShareStageFragment = Object.assign(Object.assign({}, baseFragment), { symbol, decimals, supply });
                const pricePerShareContext = Object.assign(Object.assign({}, baseContext), { appToken: pricePerShareStageFragment });
                const pricePerShare = yield this.getPricePerShare(pricePerShareContext).then(v => ((0, lodash_1.isArray)(v) ? v : [v]));
                const priceStageFragment = Object.assign(Object.assign({}, pricePerShareStageFragment), { pricePerShare });
                const price = uniV3Token.balanceUSD / supply;
                const dataPropsStageFragment = Object.assign(Object.assign({}, priceStageFragment), { price });
                const dataPropsStageParams = Object.assign(Object.assign({}, baseContext), { appToken: dataPropsStageFragment });
                let dataProps = yield this.getDataProps(dataPropsStageParams);
                dataProps = Object.assign(Object.assign({}, dataProps), { liquidity: uniV3Token.balanceUSD });
                const displayPropsStageFragment = Object.assign(Object.assign({}, dataPropsStageFragment), { dataProps });
                const displayProps = uniV3Token.displayProps;
                const appToken = Object.assign(Object.assign({}, displayPropsStageFragment), { displayProps });
                const key = this.appToolkit.getPositionKey(appToken);
                return Object.assign({ key }, appToken);
            })));
            const positionsSubset = (0, lodash_1.compact)(tokens).filter(v => {
                if (typeof v.dataProps.liquidity === 'number')
                    return Math.abs(v.dataProps.liquidity) >= this.minLiquidity;
                return true;
            });
            return (0, lodash_1.sortBy)(positionsSubset, t => {
                if (typeof t.dataProps.liquidity === 'number')
                    return -t.dataProps.liquidity;
                return 1;
            });
        });
    }
    getAddresses() {
        return __awaiter(this, void 0, void 0, function* () {
            const vaults = yield this.jarRegistry.getJarDefinitions({ network: this.network });
            return vaults.map(v => v.vaultAddress);
        });
    }
    getUnderlyingTokenDefinitions({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [{ address: yield contract.pool(), network: this.network }];
        });
    }
    getPricePerShare({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            return contract.getRatio().then(v => [Number(v) / Math.pow(10, 18)]);
        });
    }
    getLiquidity() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.minLiquidity;
        });
    }
    getReserves({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            const reserveRaw = yield contract.totalLiquidity();
            const reserve = Number(reserveRaw) / Math.pow(10, 18);
            return [reserve];
        });
    }
    getApy({ appToken }) {
        var _a;
        return __awaiter(this, void 0, void 0, function* () {
            const vaultDefinitions = yield this.jarRegistry.getJarDefinitions({ network: this.network });
            const vaultDefinition = vaultDefinitions.find(v => v.vaultAddress === appToken.address);
            return (_a = vaultDefinition === null || vaultDefinition === void 0 ? void 0 : vaultDefinition.apy) !== null && _a !== void 0 ? _a : 0;
        });
    }
};
PickleJarUniv3TokenFetcher = __decorate([
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.PickleContractFactory)),
    __param(2, (0, common_1.Inject)(pickle_api_jar_registry_1.PickleApiJarRegistry)),
    __param(3, (0, common_1.Inject)(uniswap_v3_liquidity_contract_position_builder_1.UniswapV3LiquidityContractPositionBuilder)),
    __metadata("design:paramtypes", [Object, contracts_1.PickleContractFactory,
        pickle_api_jar_registry_1.PickleApiJarRegistry,
        uniswap_v3_liquidity_contract_position_builder_1.UniswapV3LiquidityContractPositionBuilder])
], PickleJarUniv3TokenFetcher);
exports.PickleJarUniv3TokenFetcher = PickleJarUniv3TokenFetcher;
//# sourceMappingURL=pickle.jar-univ3.token-fetcher.js.map