"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.EthereumBalancerV1PoolTokenFetcher = void 0;
const common_1 = require("@nestjs/common");
const graphql_request_1 = require("graphql-request");
const lodash_1 = require("lodash");
const app_toolkit_interface_1 = require("../../../app-toolkit/app-toolkit.interface");
const position_template_decorator_1 = require("../../../app-toolkit/decorators/position-template.decorator");
const display_item_present_1 = require("../../../app-toolkit/helpers/presentation/display-item.present");
const image_present_1 = require("../../../app-toolkit/helpers/presentation/image.present");
const the_graph_helper_1 = require("../../../app-toolkit/helpers/the-graph.helper");
const app_token_template_position_fetcher_1 = require("../../../position/template/app-token.template.position-fetcher");
const contracts_1 = require("../contracts");
const balancer_v1_volume_data_loader_1 = require("./balancer-v1.volume.data-loader");
const getPoolsQuery = (0, graphql_request_1.gql) `
  query getPools($tsYesterday: Int) {
    pools(first: 1000, orderBy: liquidity, orderDirection: desc, where: { active: true, liquidity_gte: 10000 }) {
      id
    }
  }
`;
let EthereumBalancerV1PoolTokenFetcher = class EthereumBalancerV1PoolTokenFetcher extends app_token_template_position_fetcher_1.AppTokenTemplatePositionFetcher {
    constructor(appToolkit, contractFactory, volumeDataLoaderBuilder) {
        super(appToolkit);
        this.appToolkit = appToolkit;
        this.contractFactory = contractFactory;
        this.volumeDataLoaderBuilder = volumeDataLoaderBuilder;
        this.groupLabel = 'Pools';
    }
    getContract(address) {
        return this.contractFactory.balancerPoolToken({ address, network: this.network });
    }
    getAddresses() {
        return __awaiter(this, void 0, void 0, function* () {
            this.volumeDataLoader = this.volumeDataLoaderBuilder.getLoader();
            const poolsFromSubgraph = yield (0, the_graph_helper_1.gqlFetch)({
                endpoint: 'https://api.thegraph.com/subgraphs/name/balancer-labs/balancer',
                query: getPoolsQuery,
            });
            return poolsFromSubgraph.pools.map(v => v.id);
        });
    }
    getUnderlyingTokenDefinitions({ contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            const tokenAddresses = yield contract.getCurrentTokens();
            return tokenAddresses.map(address => ({ address, network: this.network }));
        });
    }
    getPricePerShare({ contract, appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            if (appToken.supply === 0)
                return appToken.tokens.map(() => 0);
            const reservesRaw = yield Promise.all(appToken.tokens.map(t => contract.getBalance(t.address)));
            const reserves = reservesRaw.map((r, i) => Number(r) / Math.pow(10, appToken.tokens[i].decimals));
            const pricePerShare = reserves.map(r => r / appToken.supply);
            return pricePerShare;
        });
    }
    getReserves({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return appToken.pricePerShare.map(pps => pps * appToken.supply);
        });
    }
    getLiquidity({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            const reserves = appToken.pricePerShare.map(pps => pps * appToken.supply);
            const liquidity = (0, lodash_1.sum)(reserves.map((r, i) => r * appToken.tokens[i].price));
            return liquidity;
        });
    }
    getApy({ appToken, contract }) {
        return __awaiter(this, void 0, void 0, function* () {
            const fee = (Number(yield contract.getSwapFee()) / Math.pow(10, 18)) * 100;
            const volume = yield this.volumeDataLoader.load(appToken.address);
            const yearlyFees = volume * fee * 365;
            const reserves = appToken.pricePerShare.map(pps => pps * appToken.supply);
            const liquidity = (0, lodash_1.sum)(reserves.map((r, i) => r * appToken.tokens[i].price));
            const apy = yearlyFees / liquidity;
            return apy;
        });
    }
    getDataProps(params) {
        const _super = Object.create(null, {
            getDataProps: { get: () => super.getDataProps }
        });
        return __awaiter(this, void 0, void 0, function* () {
            const defaultDataProps = yield _super.getDataProps.call(this, params);
            const { appToken, contract } = params;
            const fee = (Number(yield contract.getSwapFee()) / Math.pow(10, 18)) * 100;
            const weightsRaw = yield Promise.all(appToken.tokens.map(t => contract.getNormalizedWeight(t.address)));
            const weight = weightsRaw.map(w => Number(w) / Math.pow(10, 18));
            const volume = yield this.volumeDataLoader.load(appToken.address);
            return Object.assign(Object.assign({}, defaultDataProps), { fee, volume, weight });
        });
    }
    getLabel({ appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            return appToken.tokens.map(v => (0, image_present_1.getLabelFromToken)(v)).join(' / ');
        });
    }
    getSecondaryLabel({ appToken, }) {
        return __awaiter(this, void 0, void 0, function* () {
            const { liquidity, reserves } = appToken.dataProps;
            const reservePercentages = appToken.tokens.map((t, i) => reserves[i] * (t.price / liquidity));
            return reservePercentages.map(p => `${Math.round(p * 100)}%`).join(' / ');
        });
    }
    getStatsItems({ appToken }) {
        return __awaiter(this, void 0, void 0, function* () {
            return [
                { label: 'Liquidity', value: (0, display_item_present_1.buildDollarDisplayItem)(appToken.dataProps.liquidity) },
                { label: 'Supply', value: (0, display_item_present_1.buildNumberDisplayItem)(appToken.supply) },
                { label: 'Volume', value: (0, display_item_present_1.buildDollarDisplayItem)(appToken.dataProps.volume) },
                { label: 'Fee', value: (0, display_item_present_1.buildPercentageDisplayItem)(appToken.dataProps.fee) },
                { label: 'Ratio', value: appToken.dataProps.weight.map(p => `${Math.round(p * 100)}%`).join(' / ') },
            ];
        });
    }
};
EthereumBalancerV1PoolTokenFetcher = __decorate([
    (0, position_template_decorator_1.PositionTemplate)(),
    __param(0, (0, common_1.Inject)(app_toolkit_interface_1.APP_TOOLKIT)),
    __param(1, (0, common_1.Inject)(contracts_1.BalancerV1ContractFactory)),
    __param(2, (0, common_1.Inject)(balancer_v1_volume_data_loader_1.EthereumBalancerV1PoolSubgraphVolumeDataLoader)),
    __metadata("design:paramtypes", [Object, contracts_1.BalancerV1ContractFactory,
        balancer_v1_volume_data_loader_1.EthereumBalancerV1PoolSubgraphVolumeDataLoader])
], EthereumBalancerV1PoolTokenFetcher);
exports.EthereumBalancerV1PoolTokenFetcher = EthereumBalancerV1PoolTokenFetcher;
//# sourceMappingURL=balancer-v1.pool.token-fetcher.js.map